# Technical Documentation: dotnet/sdk

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/dotnet/sdk)

### Overview (README.md)

## Welcome to dotnet sdk

This repository contains core functionality needed to create .NET projects that are shared between Visual Studio and the [.NET CLI](https://learn.microsoft.com/dotnet/core/tools/).

* MSBuild tasks are under [/src/Tasks/Microsoft.NET.Build.Tasks/](src/Tasks/Microsoft.NET.Build.Tasks).

See [dotnet/project-system](https://github.com/dotnet/project-system) for the project system work that is specific to Visual Studio.

See the [dotnetup documentation](https://github.com/dotnet/sdk/tree/release/dnup/documentation/general/dotnetup)
for work on the .NET toolchain manager. Dotnetup changes should target the
`release/dnup` branch rather than `main`.

Common project and item templates are found in [template_feed](https://github.com/dotnet/sdk/tree/main/template_feed).

## Build status

Visibility|All jobs|
|:------|:------|
|Public|[](https://dev.azure.com/dnceng-public/public/_build?definitionId=101)|
|Microsoft Internal|[](https://dev.azure.com/dnceng/internal/_build?definitionId=140)|

## Installing the SDK

You can download the .NET SDK as either an installer (MSI, PKG) or a zip (zip, tar.gz). The .NET SDK contains both the .NET runtime and CLI tools.

- [Official builds](https://dotnet.microsoft.com/download/dotnet)
- [**.NET SDK latest builds table**](https://github.com/dotnet/dotnet/blob/main/docs/builds-table.md)

### Looking for dotnet-install sources?

Sources for dotnet-install.sh and dotnet-install.ps1 are in the [install-scripts repo](https://github.com/dotnet/install-scripts).

## How do I engage and contribute?

We welcome you to try things out, [file issues](https://github.com/dotnet/sdk/issues), make feature requests and join us in design conversations. Be sure to check out our [project documentation](documentation)

This project has adopted the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct) to clarify expected behavior in our community.

## How do I build the SDK?

Start with the [Developer Guide](documentation/project-docs/developer-guide.md).

## How do I test an SDK I have built?

To test your locally built SDK, run `eng\dogfood.cmd` after building. That script starts a new Powershell with the environment configured to redirect SDK resolution to your build.

From that shell your SDK is available in:

- any Visual Studio instance launched via `& devenv.exe`
- `dotnet build`
- `msbuild`

## How do I determine the timeline I must follow to get my changes in for a specific version of .NET?

Please see the [Pull Request Timeline Guide](documentation/project-docs/SDK-PR-guide.md).

## How we triage and review PRs

With the SDK repository being the home for many different areas, we've started trying to label incoming issues for the area they are related to using `Area-` labels.  Then we rely on the [codeowners](https://github.com/dotnet/sdk/blob/main/CODEOWNERS) to manage and triages issues in their areas. Feel free to contact the owners listed in that file if you're not getting a response on a particular issue or PR. Please try to label new issues as that'll help us route them faster.

For issues related to the central SDK team, typically they are assigned out to a team member in the first half of each week. Then each member is asked to review and mark those needing further discussion as "needs team triage" and otherwise setting a milestone for the issue. Backlog means we will consider it in the future if there is more feedback. Discussion means we have asked for more information from the filer. All other milestones indicate our best estimate for when a fix will be targeted for noting that not all issues will get fixed. If you are not getting a quick response on an issue assigned to a team member, please ping them.

The example query used for triage of .NET SDK issues can be viewed [here](https://github.com/dotnet/sdk/issues?q=is%3Aissue+is%3Aopen+-label%3AArea-NuGet+-label%3AArea-format+-label%3AArea-implicitusings+-label%3AArea-SourceBuild+-label%3AArea-Host+-label%3AArea-NativeAOT+-label%3AArea-readytorun+-label%3AArea-websdk+-label%3AArea-watch+-label%3AArea-illink+-label%3AArea-aspnetcore+-label%3AArea-compatibility+-label%3A%22Area-dotnet+test%22+-label%3AArea-FSharp+-label%3AArea-GenAPI+-label%3AArea-ApiCompat+label%3Auntriaged+no%3Amilestone+no%3Aassignee+)

For PRs, we assign a reviewer once a week on Wednesday, looking only at PRs that are green in the build.  If you are contributing:

* Get the PR green.
* Include a test if possible.
* Mention  `@dotnet-cli` if you want to raise visibility of the PR.

## License

The .NET SDK project uses the [MIT license](LICENSE.TXT).

The *LICENSE.txt* and *ThirdPartyNotices.txt* in any downloaded archives are authoritative.

---

### Documentation README (`documentation/README.md`)

Documents Index
===============

## Overview and general information

- [Intro to .NET Core CLI](general/intro-to-cli.md)
- [Publishing a solution and its pitfalls](general/solution-publish.md)
- [CLI UX Guidelines](general/cli-ux-guidelines.md)
- [.NET Core native pre-requisities document](https://github.com/dotnet/core/blob/main/Documentation/prereqs.md)
- [Roadmap and OS support](https://github.com/dotnet/core/blob/main/roadmap.md)
- [Comprehensive CLI documentation](https://docs.microsoft.com/en-us/dotnet/articles/core/preview3/tools/)
- [ASP.NET Core Command Line Tools](general/aspnetcore-tools.md)
- [Guidelines for how to introduce a new diagnostic or breaking change](project-docs/breaking-change-guidelines.md)

## Working with the CLI repo

- [Developer Guide](project-docs/developer-guide.md)
- [How to file issues](project-docs/issue-filing-guide.md)

## Troubleshooting and issues reporting

- [CLI Known Issues](https://github.com/dotnet/core/blob/main/release-notes/2.0/2.0.0-known-issues.md)
- [Filing migration issues](migration-issues.md)

## Specifications

- [CLI installation scenarios](specs/cli-installation-scenarios.md)
- [Runtime configuration file specification](specs/runtime-configuration-file.md)

---

### Documentation TemplateEngine README (`documentation/TemplateEngine/README.md`)

# .NET Template Engine

## Overview

The .NET Template Engine provides the libraries for template instantiation and template package management used in [`dotnet new`](https://learn.microsoft.com/dotnet/core/tools/dotnet-new), the [New Project Dialog](https://learn.microsoft.com/visualstudio/ide/create-new-project?view=vs-2022), and the New Item Dialog in Visual Studio. The source code is located in this repository under [`src/TemplateEngine/Microsoft.TemplateEngine.*`](../../src/TemplateEngine) and the libraries are distributed as NuGet packages on nuget.org.

> **Note:** The template engine was previously maintained in the [dotnet/templating](https://github.com/dotnet/templating) repository and has been merged into this repository (dotnet/sdk).

## Key Packages

| Package | Description |
|---|---|
| `Microsoft.TemplateEngine.Edge` | The template engine infrastructure: managing template packages, templates, components, and executing templates. Main API surface for products aiming to use the template engine. See the [Inside the Template Engine](api/Inside-the-Template-Engine.md) article for more information. |
| `Microsoft.TemplateEngine.Abstractions` | Contains the main contracts between `Edge` and components. |
| `Microsoft.TemplateEngine.Orchestrator.RunnableProjects` | The template generator based on `template.json` configuration. |
| `Microsoft.TemplateSearch.Common` | Facilitates template package search on nuget.org. |
| `Microsoft.TemplateEngine.IDE` | Lightweight API overlay over `Microsoft.TemplateEngine.Edge`. |
| `Microsoft.TemplateEngine.Authoring.Tasks` | Authoring tools: MSBuild tasks for template authoring. |
| `Microsoft.TemplateEngine.Authoring.CLI` | Authoring tools: dotnet CLI tool with utilities for template authoring. |
| `Microsoft.TemplateEngine.Authoring.TemplateVerifier` | Authoring tools: [snapshot testing framework](authoring-tools/Templates-Testing-Tooling.md) for templates. |

## `dotnet new`

The `dotnet new` CLI command is located in [`src/Cli/Microsoft.TemplateEngine.Cli`](../../src/Cli/Microsoft.TemplateEngine.Cli).

Issues for `dotnet new` CLI UX should be opened in this repository ([dotnet/sdk](https://github.com/dotnet/sdk)).

## Template Content Repositories

[.NET default templates](https://learn.microsoft.com/dotnet/core/tools/dotnet-new-sdk-templates) are located across several repositories:

| Templates | Repository |
|---|---|
| Common project and item templates | [dotnet/sdk](https://github.com/dotnet/sdk) |
| ASP.NET and Blazor templates | [dotnet/aspnetcore](https://github.com/dotnet/aspnetcore) |
| ASP.NET Single Page Application templates | [dotnet/spa-templates](https://github.com/dotnet/spa-templates) |
| Aspire templates | [dotnet/aspire](https://github.com/dotnet/aspire) |
| WPF templates | [dotnet/wpf](https://github.com/dotnet/wpf) |
| Windows Forms templates | [dotnet/winforms](https://github.com/dotnet/winforms) |
| Test templates | [dotnet/test-templates](https://github.com/dotnet/test-templates) |
| MAUI templates | [dotnet/maui](https://github.com/dotnet/maui) |

Issues for template content should be opened in the corresponding repository. Suggestions for new templates should be opened in the closest repository from the list above. For example, if you have a suggestion for a new web template, please create an issue in [dotnet/aspnetcore](https://github.com/dotnet/aspnetcore).

## How to Author Templates

The starting point tutorial on how to create new templates is available on [Microsoft Learn](https://learn.microsoft.com/dotnet/core/tutorials/cli-templates-create-project-template).

More advanced information can be found in the documentation in this folder:

- [Reference for template.json](Reference-for-template.json.md)
- [Conditional processing and comment syntax](Conditional-processing-and-comment-syntax.md)
- [Available symbols generators](Available-Symbols-Generators.md)
- [Post-action registry](Post-Action-Registry.md)
- [Constraints](Constraints.md)
- [Conditions](Conditions.md)
- [Binding and project context evaluation](Binding-and-project-context-evaluation.md)
- [Value forms](Value-Forms.md)
- [Using group identity](Using-Group-Identity.md)
- [Template samples](Samples/)

### Authoring Tools

In addition to the template engine implementation, there are various tools to help author templates. They are not shipped with the .NET SDK but are available on NuGet.org. More information can be found in the [Authoring Tools documentation](authoring-tools/Authoring-Tools.md).

## Contributing

We welcome contributions! You can contribute by:

- [Creating an issue](https://github.com/dotnet/sdk/issues/new/choose) in the dotnet/sdk repository
- Contributing a PR that fixes an issue or implements a new feature

See the [SDK developer guide](../project-docs/developer-guide.md) for details on how to build, run, and debug.

For template engine specific documentation on contributing, see the [contributing guide](contributing/).

---

### Documentation Issue Mappings README (`documentation/issue-mappings/README.md`)

Many of the issues in this repo were originally created in the dotnet/toolset and dotnet/cli repos, then migrated here to the dotnet/sdk repo.

In this process their ID numbers inevitably changed. If you have the old ID number, you can find the new ID number by simply navigating to the old URL: your browser will be redirected to the new URL.

For example, https://github.com/dotnet/cli/issues/10 redirects to https://github.com/dotnet/sdk/issues/4288.

In some circumstances you may have the new URL and want the old one. For example, if you are looking at a migrated issue and wish to search your email or chat logs for a discussion that referred to the old URL. In that case, you can use these mapping files to look up the old ID and find the old URL.

---

### Documentation TemplateEngine Samples README (`documentation/TemplateEngine/Samples/README.md`)

# .NET Template Samples

This folder contains samples of templates done for template engine.
These templates are supported by `dotnet new` and Visual Studio. 
For details, on how to configure the templates to be used in Visual Studio, refer to [this article]( https://aka.ms/netcore-templates).
The other examples of complex templates can be found in [Microsoft.TemplateEngine.TestTemplates](../../../test/TestAssets/TestPackages/TemplateEngine/test_templates) and [SDK.TestTemplates](../../../test/TestAssets/TestPackages/dotnet-new/test_templates) repositories.

For more general info on the authoring, see:
- [How to create custom templates](https://learn.microsoft.com/en-us/dotnet/core/tools/custom-templates)
- [Template authoring docs](..)

## Contributing

We would love community contributions here. Please feel free to open the PRs to add more examples or create an [issue](https://github.com/dotnet/sdk/issues/new) requesting a new example.

See the [SDK developer guide](../../project-docs/developer-guide.md) for information on contributing to this project.

## Template Content Repositories

[.NET default templates](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-new-sdk-templates) are located in several repositories. You can use them as examples of more complicated templates.

The templates are located in the following repositories:

| Templates | Repository |
|---|---|
|Common project and item templates|[dotnet/sdk](https://github.com/dotnet/sdk)|
|ASP.NET and Blazor templates|[dotnet/aspnetcore](https://github.com/dotnet/aspnetcore)|
|ASP.NET Single Page Application templates| [dotnet/spa-templates](https://github.com/dotnet/spa-templates)|
|WPF templates|[dotnet/wpf](https://github.com/dotnet/wpf)|
|Windows Forms templates|[dotnet/winforms](https://github.com/dotnet/winforms)|
|Test templates|[dotnet/test-templates](https://github.com/dotnet/test-templates)|
|MAUI templates|[dotnet/maui](https://github.com/dotnet/maui)|

---

### Documentation Format Docs README (`documentation/format/docs/README.md`)

# Welcome to the dotnet-format docs!

## .editorconfig options
- [Supported .editorconfig options](./Supported-.editorconfig-options.md)

## CLI options

### Specify a workspace (Required)

A workspace path is needed when running dotnet-format. By default, the current folder will be used as the workspace path. The workspace path and type of workspace determines which code files are considered for formatting.

- Solutions and Projects - By default dotnet-format will open the workspace path as a MSBuild solution or project.
- `--no-restore` - When formatting a solution or project the no restore option will stop dotnet-format from performing an implicit package restore.
- `--folder` - When the folder options is specified the workspace path will be treated as a folder of code files.

*Example:*

Format the code files used in the format solution.

```console
dotnet format ./format.sln
```

Format the code files used in the dotnet-format project.

```console
dotnet format ./src/dotnet-format.csproj
```

Format the code files from the  `./src` folder.

```console
dotnet format whitespace ./src --folder
```

### Whitespace formatting

Whitespace formatting includes the core .editorconfig settings along with the placement of spaces and newlines. The whitespace formatter is run by default when not running analysis. When only performing whitespace formatting, an implicit restore is not perfomed. When you want to run analysis and fix formatting issues you must specify both.

Whitespace formatting run by default along with code-style and 3rd party analysis.

```console
dotnet format ./format.sln
```

Running the whitespace formatter alone.

```console
dotnet format whitespace ./format.sln
```

### Running analysis

#### CodeStyle analysis

Running codestyle analysis requires the use of a MSBuild solution or project file as the workspace. By default an implicit restore on the solution or project is performed. Enforces the .NET [Language conventions](https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-language-conventions?view=vs-2019) and [Naming conventions](https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-naming-conventions?view=vs-2019).

- `dotnet format style --severity <severity>` - Runs analysis and attempts to fix issues with severity equal or greater than specified. If severity is not specified then severity defaults to warning.

*Example:*

Code-style analysis is run by default along with whitespace formatting and 3rd party analysis.

```console
dotnet format ./format.sln
```

Run code-style analysis alone against the dotnet-format project.

```console
dotnet format style ./src/dotnet-format.csproj --severity error
```

Errors when used with the `--folder` option. Analysis requires a MSBuild solution or project.

```console
dotnet format style ./src --folder
```

#### 3rd party analysis

Running 3rd party analysis requires the use of a MSBuild solution or project file as the workspace. By default an implicit restore on the solution or project is performed. 3rd party analyzers are discovered from the `<PackageReferences>` specified in the workspace project files.

- `dotnet format analyzers --severity <severity>` - Runs analysis and attempts to fix issues with severity equal or greater than specified. If no severity is specified then this defaults to warning.

#### Filter diagnostics to fix

Typically when running codestyle or 3rd party analysis, all diagnostics of sufficient severity are reported and fixed. The `--diagnostics` option allows you to target a particular diagnostic or set of diagnostics of sufficient severity.

- `--diagnostics <diagnostic ids>` - When used in conjunction with `style` or `analyzer` subcommands, allows you to apply targeted fixes for particular analyzers.

*Example:*

Run code-style analysis and fix unused using directive errors.

```console
dotnet format style ./format.sln --diagnostics IDE0005
```

### Filter files to format

You can further narrow the list of files to be formatted by specifying a list of paths to include or exclude. When specifying folder paths the path must end with a directory separator. File globbing is supported.

- `--include` - A list of relative file or folder paths to include in formatting.
- `--exclude` - A list of relative file or folder paths to exclude from formatting.

*Example:*

Other repos built as part of your project can be included using git submodules. These submodules likely contain their own .editorconfig files that are set as `root = true`. This makes it difficult to validate formatting for your project as formatting mistakes in submodules are treated as errors.

The following command sets the repo folder as the workspace. It then includes the `src` and `tests` folders for formatting. The `submodule-a` folder is excluded from the formatting validation.

```console
dotnet format whitespace --folder --include ./src/ ./tests/ --exclude ./src/submodule-a/ --verify-no-changes
```

### Logging and Reports

- `--verbosity` - Set the verbosity level. Allowed values are q[uiet], m[inimal], n[ormal], d[etailed], and diag[nostic]
- `--report` - Writes a json file to the given directory. Defaults to 'format-report.json' if no filename given.
- `--binarylog` - Writes a [binary log file](https://msbuildlog.com/) to help in diagnosing solution or project load errors. Defaults to 'format.binlog' if no filename given.

### Validate formatting

- `--verify-no-changes` - Formats files without saving changes to disk. Terminates with a non-zero exit code (`2`) if any files were formatted.

---

### Documentation General Dotnetup README (`documentation/general/dotnetup/README.md`)

# Get started with dotnetup

> [!IMPORTANT]
> `dotnetup` is in public preview. Its features and behavior might change
> before general availability.

`dotnetup` is a cross-platform toolchain manager for user-level .NET
installations. It installs, updates, and removes .NET SDKs and runtimes without
using a system package manager.

## Prerequisites

- One of the following operating systems and architectures:

  | Operating system | Architectures |
  | --- | --- |
  | Windows | x64, Arm64 |
  | macOS | x64, Arm64 |
  | Linux (glibc) | x64, Arm64 |
  | Linux (musl), such as Alpine Linux | x64, Arm64 |

- A terminal.
- Bash on macOS or Linux, or PowerShell on Windows, to run the download script.
- On macOS or Linux, `curl` or `wget` to download files, and `sha512sum` or
  `shasum` to verify them.

`dotnetup` has the same operating-system requirements as the .NET Runtime.
For OS-specific requirements, see
[Install .NET on Windows](https://learn.microsoft.com/dotnet/core/install/windows),
[Install .NET on macOS](https://learn.microsoft.com/dotnet/core/install/macos),
or [Install .NET on Linux](https://learn.microsoft.com/dotnet/core/install/linux).

> [!IMPORTANT]
> On Windows, the default setup uses the `everywhere` access mode. This mode:
>
> - Requires elevation to update the system `PATH`.
> - Makes the dotnetup-managed installation take precedence over machine-wide
>   .NET installations, such as the ones that Visual Studio installs. Projects
>   and apps that need a machine-wide SDK or runtime that isn't also installed
>   by `dotnetup` fail to build or run.
> - Changes the system `PATH`, which applies to all users. Elevated processes
>   that other users start might resolve .NET from your user profile.
>
> To avoid these effects, choose the `none` or `shell` access mode during setup.
> If you choose `everywhere`, migrate your existing installations when setup
> offers to. For details, see
> [Everywhere mode considerations](concepts/environment.md#everywhere-mode-considerations).

## Download dotnetup

The download scripts install the latest `preview` build by default. They verify
the downloaded executable with its SHA-512 checksum and install it in
`~/.dotnetup`.

On macOS or Linux, run:

```bash
curl -fsSL https://aka.ms/dotnetup/get-dotnetup.sh | bash
```

On Windows, run:

```powershell
irm https://aka.ms/dotnetup/get-dotnetup.ps1 | iex
```

To install the latest `daily` build on macOS or Linux, run:

```bash
curl -fsSL https://aka.ms/dotnetup/get-dotnetup.sh |
  bash -s -- --quality daily
```

To install the latest `daily` build on Windows, run:

```powershell
iex "& { $(irm https://aka.ms/dotnetup/get-dotnetup.ps1) } -Quality daily"
```

> [!IMPORTANT]
> Daily builds have not completed release validation and are not code-signed.
> Use daily builds only for short-lived testing.

The scripts print instructions to add `dotnetup` to `PATH`. Open a new terminal
after you apply the instructions.

## Run first-time setup

Run the interactive setup:

```dotnetcli
> dotnetup init
Welcome to dotnetup!

SDK Channel: latest
Mode: <recommended-mode> (Suggested)

<recommended-mode> modifies <configuration-target> to set PATH and DOTNET_ROOT to prefer <install-path>.

Would you like to install .NET with the recommended settings?
> Yes, proceed with defaults and install

Installing SDK <resolved-version> to <install-path>...
<download and installation progress>
Installed at <install-path>:
  SDK <resolved-version>
<mode-specific environment guidance>
Setup complete!
```

The paths, progress display, and environment guidance depend on your system and
the selected mode.

The recommended access mode is `everywhere` on Windows. On macOS and Linux, it
is `shell` when `dotnetup` detects a supported shell and `none` otherwise.

Select **No, customize setup** to choose the SDK channel, access mode, and
migration options.

### Choose an SDK channel

An SDK channel tells `dotnetup` which SDK to install and how to update it.

| Channel form | Example | Result |
| --- | --- | --- |
| Latest stable | `latest` | Latest active stable SDK |
| Latest LTS | `lts` | Latest active stable LTS SDK |
| Latest preview | `preview` | Latest preview SDK |
| Latest daily | `daily` | Latest available daily SDK |
| Major | `10` | Latest SDK for the specified major version |
| Major and minor | `10.0` | Latest SDK for the specified major and minor version |
| Feature band | `10.0.1xx` | Latest SDK in the specified feature band |
| Exact version | `10.0.103` | Only the specified SDK version |
| No initial SDK | `none` | Skip installation during setup |

Exact versions do not advance during updates. For all accepted forms, see
[dotnetup channels and versions](concepts/channels.md).

### Choose how to access .NET

The access mode controls how terminals and applications find the
dotnetup-managed .NET installation.

| Access mode | Behavior |
| --- | --- |
| `none` | Does not modify these environment variables. Run .NET with `dotnetup dotnet`. |
| `shell` | Modifies the shell profile to set these environment variables. Processes started from that shell use the .NET SDKs and Runtimes installed by dotnetup. |
| `everywhere` | Modifies the system `PATH` and sets the user-level `DOTNET_ROOT` environment variable. Only available on Windows. |

For more details and considerations for `everywhere` mode, see
[dotnetup environment configuration](concepts/environment.md).

### Migrate existing installations

Setup can offer to migrate existing machine-wide .NET SDK and Runtime
installations into the dotnetup-managed installation. See
[Everywhere mode considerations](concepts/environment.md#everywhere-mode-considerations)
for why migration is especially important with `everywhere` mode.

## Verify setup

Open a new terminal after setup changes your environment.

For `shell` or `everywhere` mode, run:

```dotnetcli
dotnet --version
dotnetup list
```

For `none` mode, run:

```dotnetcli
dotnetup dotnet -- --version
dotnetup list
```

Run `dotnetup init` again to change the setup.

## Public documentation

- [dotnetup overview](index.md)
- [When to use dotnetup](choose-dotnetup.md)
- [Table of contents](toc.yml)
- [Core concepts](concepts/how-dotnetup-works.md)
- [Download verification](concepts/download-verification.md)
- [Release channels](channels/preview.md)
- [Troubleshooting](troubleshooting.md)
- [Telemetry](telemetry.md)
- [CLI reference](reference/dotnetup.md)
- [Scenarios](usecases/install-with-global-json.md)
- [Update or remove dotnetup](usecases/manage-dotnetup.md)

## Maintainer documentation

- [Design notes](designs/)
- [How dotnetup is included in the SDK](dotnetup_in_sdk.md)
- [Release engineering](releasing.md)
- [Signature verification](signature-verification.md)

The command reference follows the generated runtime help. Command handlers and
tests verify product behavior. Hidden compatibility and elevation commands are
implementation details. They are not part of the public command reference.

---

### Documentation General Dotnetup Index (`documentation/general/dotnetup/index.md`)

---
title: dotnetup overview
description: Learn how dotnetup installs and manages user-level .NET SDKs and runtimes.
ms.topic: overview
ms.date: 08/07/2026
---

# dotnetup overview

> [!IMPORTANT]
> `dotnetup` is in public preview. Its features and behavior might change
> before general availability.

`dotnetup` is a cross-platform toolchain manager for user-level .NET
installations. It installs .NET SDKs and runtimes without writing to a
system-managed .NET directory. It also tracks the installation requirements
that you select so that it can update or remove the related files later.

Use `dotnetup` to:

- Install stable, preview, daily, or exact .NET versions.
- Keep multiple SDK and runtime requirements in one managed installation.
- Install the SDK required by the nearest `global.json` file.
- Update tracked channels without changing exact-version requirements.
- Configure how terminals and applications find the managed `dotnet`.
- Run the managed `dotnet` without changing `PATH`.

## Start

Run the interactive setup:

```dotnetcli
> dotnetup init
Welcome to dotnetup!

SDK Channel: latest
Mode: Terminal Mode (Suggested)

Would you like to install .NET with the recommended settings?
> Yes, proceed with defaults and install

Downloading SDK <resolved-version>
Installing SDK <resolved-version>
Installed SDK <resolved-version>
Setup complete!
```

The setup asks which SDK channel to install and how you want to access the
managed `dotnet` command.

For a concise, noninteractive setup, install an SDK and configure the current
shell:

```dotnetcli
> dotnetup install latest --interactive false
Downloading SDK <resolved-version>
Installing SDK <resolved-version>
Installed SDK <resolved-version>

> dotnetup env set shell
dotnet and dotnetup are on your PATH.
To apply the change to this terminal now, run:
<shell-specific command>
Or open a new terminal.

> dotnetup list
Installations (managed by dotnetup):

  <default-installation-root>

    Tracked channels:
      SDK latest  (source: explicit)

    Installed versions:
      SDK <resolved-version>  (<architecture>)

Total: 1

> dotnet --version
<resolved-version>
```

If you do not want to add the managed `dotnet` command to `PATH`, use the
forwarding command:

```dotnetcli
> dotnetup install latest --interactive false
Downloading SDK <resolved-version>
Installing SDK <resolved-version>
Installed SDK <resolved-version>

> dotnetup env set none
dotnetup is on your PATH. dotnet is not — run it with 'dotnetup dotnet <command>'.
Open a new terminal for the change to take effect.

> dotnetup dotnet --version
<resolved-version>
```

The mode, resolved version, architecture, installation path, and shell command
depend on your system and the available releases.

## How dotnetup manages .NET

`dotnetup` tracks the SDK installations that you request. This tracking lets
`dotnetup` update many installations at the same time. It also lets `dotnetup`
safely remove unused or out-of-support installations.

For more information, see [How dotnetup works](concepts/how-dotnetup-works.md).

## Choose what to read next

| Goal | Article |
| --- | --- |
| Decide whether dotnetup fits your scenario | [When to use dotnetup](choose-dotnetup.md) |
| Install dotnetup and run the first setup | [Get started with dotnetup](README.md) |
| Understand channels, installation roots, and tracking | [How dotnetup works](concepts/how-dotnetup-works.md) |
| Use a repository's `global.json` | [Manage repository SDK requirements](usecases/install-with-global-json.md) |
| Install SDKs and runtimes | [Install .NET components](usecases/install-components.md) |
| Update or remove installations | [Update installations](usecases/update-installations.md) |
| Update or remove dotnetup itself | [Update or remove dotnetup](usecases/manage-dotnetup.md) |
| Configure `PATH` and `DOTNET_ROOT` | [Manage the dotnetup environment](usecases/manage-environment.md) |
| Try preview or daily builds | [Use preview and daily builds](usecases/try-daily-builds.md) |
| Learn how downloads are verified | [How dotnetup verifies downloads](concepts/download-verification.md) |
| Fix common problems | [Troubleshoot dotnetup](troubleshooting.md) |
| Learn what data dotnetup collects | [dotnetup telemetry](telemetry.md) |
| Look up command syntax | [dotnetup command reference](reference/dotnetup.md) |

## Availability

`dotnetup` is available as a public preview. Commands, options, and behavior
might change between preview releases, and the support lifecycle for the
generally available release isn't final.

To install `dotnetup`, see [Get started with dotnetup](README.md). After you
install it, run `dotnetup --version` to confirm the version and
`dotnetup --help` to see the available commands.

---

### Documentation General Workloads README (`documentation/general/workloads/README.md`)

# .NET SDK Workloads

.NET SDK Workloads are optional components of the .NET SDK.

Some of the design docs for workloads are in the [dotnet/designs](https://github.com/dotnet/designs) repo:

- [.NET Optional SDK Workloads](https://github.com/dotnet/designs/blob/main/accepted/2020/workloads/workloads.md)
- [MSBuild SDK Resolvers and optional workloads](https://github.com/dotnet/designs/blob/main/accepted/2020/workloads/workload-resolvers.md)
- [.NET SDK Workload Manifests](https://github.com/dotnet/designs/blob/main/accepted/2020/workloads/workload-manifest.md)
- [Workload installation](https://github.com/dotnet/designs/pull/188)

Other documentation for workloads is in this repo:

- [.NET SDK Workload Rollback](workload-rollback.md)
- [User local workloads](user-local-workloads.md)
- [Workload manifest fallback](workload-fallback.md)
- [Preview feature bands](workload-preview-bands.md)
- [.NET SDK Installer Finalizer](workload-finalizer.md)
- [Workload description localization](https://github.com/dotnet/sdk/pull/21189)
- [Grouping multiple packs into one MSI](https://github.com/dotnet/sdk/issues/21741)
- [Handling workload assets across major .NET versions](cross-version-workloads.md)
- [Workload Clean Command](workload-clean.md)
- [Workload MSI Installation Tests](/test/dotnet-MsiInstallation.Tests/README.md)
- [Diagnosing workloads issues](workload-diagnosis.md)

---

### Documentation Manpages Tool README (`documentation/manpages/tool/README.md`)

# Manpage update tool

Utility to update dotnet-cli documentation from https://github.com/dotnet/docs.

## Docker Usage

If docker is installed, then simply execute `run_docker.sh` to update manpages.

## Prerequisites

* Unix OS
* `python` in PATH
* `pandoc` installed
* `pandocfilters` package installed
* `unzip`
* `wget` or `curl`

## Usage

```sh
./update-man-pages.sh
```

## Ubuntu example (from scratch)

```sh
apt update
apt install -y jq curl python python-pip wget unzip git < /dev/null
pip install pandocfilters

pandocVersion=$(curl -s https://api.github.com/repos/jgm/pandoc/releases/latest | jq -r ".tag_name")
pandocVersionedName="pandoc-$pandocVersion-1-amd64.deb"
curl -sLO https://github.com/jgm/pandoc/releases/download/$pandocVersion/$pandocVersionedName > /dev/null
dpkg -i $pandocVersionedName
rm $pandocVersionedName*

git clone https://github.com/dotnet/cli
./cli/Documentation/manpages/tool/update-man-pages.sh
```

---

### Src Microsoft.CodeAnalysis.NetAnalyzers Docs Netcore Getting Started (`src/Microsoft.CodeAnalysis.NetAnalyzers/docs/netcore-getting-started.md`)

# Getting started with .NET analyzers

The `CA####` analyzers live in `src/Microsoft.CodeAnalysis.NetAnalyzers`, migrated into
`dotnet/sdk` from the retired `dotnet/roslyn-analyzers` repo. PRs target `dotnet/sdk`;
servicing fixes target the relevant `release/<major>.<minor>.<band>xx` branch.

For the step-by-step authoring workflow — ID allocation, resource strings, release
tracking, tests — use the
[`add-net-analyzer`](../../../.github/skills/add-net-analyzer/SKILL.md) skill and
[`AGENTS.md`](../AGENTS.md). This document covers the parts that skill doesn't: the
definition of done, and validating a rule against real code.

## Background reading

1. The [.NET Compiler Platform SDK](https://learn.microsoft.com/dotnet/csharp/roslyn-sdk/)
   overview, for the Roslyn concepts (syntax nodes, tokens, trivia) and the factory APIs.
2. The [analyzer/code-fix tutorial](https://learn.microsoft.com/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix),
   which walks an analyzer, a fixer, and unit tests end to end.
3. [Guidelines about new rule ids and docs](guidelines-for-new-rules.md).

## Building

```powershell
./build.cmd -projects src/Microsoft.CodeAnalysis.NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.slnx -c Debug
```

Use `./build.sh` on Linux/macOS. Do **not** pass `-restore`/`-build` alongside `-projects`;
the driver already implies them and the combination fails. Output lands in
`artifacts/bin/Microsoft.CodeAnalysis.{,CSharp.,VisualBasic.}NetAnalyzers/<Configuration>/netstandard2.0/`.

## Definition of done

- Analyzer implemented to work for C# and VB.
  - Unit tests for C#:
    - All scenarios covered.
      - Prefer markup syntax for the majority of tests.
      - If your analyzer has placeholders in the diagnostic message and you want to test the arguments, write a smaller number of tests using the `VerifyCS.Diagnostic` syntax to construct specific diagnostic forms.
    - Unit tests for VB:
      - Obvious positive and negative scenarios covered.
      - If the implementation uses any syntax-specific code, then all scenarios must be covered.
- Fixer implemented for C#, using the language-agnostic APIs if possible.
  - If the fixer can be entirely implemented with language-agnostic APIs `(IOperation)`, then VB support is essentially free.
  - With a language-agnostic fixer, apply the attribute to indicate the fixer also applies to VB and add mainline VB tests.
  - If language-specific APIs are needed to implement the fixer, the VB fixer is not required.
  - Do not separate analyzer tests from code fix tests. If the analyzer has a code fix, then write all your tests as code fix tests.
    - Calling `VerifyCodeFixAsync(source, source)` verifies that the analyzer either does not produce diagnostics, or produces diagnostics where no code fix is offered.
    - Calling `VerifyCodeFixAsync(source, fixedSource)` verifies the diagnostics (analyzer testing) and verifies that the code fix on source produces the expected output.
  - Fix-all is part of the fixer. `WellKnownFixAllProviders.BatchFixer` applies every fix
    against the original document and merges the results, which produces a wrong tree when
    diagnostics overlap or nest. Derive from
    [`SyntaxEditorBasedCodeFixProvider`](../src/Microsoft.CodeAnalysis.NetAnalyzers/SyntaxEditorBasedCodeFixProvider.cs)
    instead, and cover the nested case in tests.
- Run the analyzer locally against `dotnet/runtime` and `dotnet/roslyn` ([instructions](#validating-against-a-real-codebase)).
  - Review each of the failures in those repositories and determine the course of action for each.
  - Use the failures to discover nuance and guide the implementation details.
  - Document for review: matching and non-matching scenarios, including any discovered nuance.
  - All warnings and errors in these repos are addressed (to prevent build failures).
    - `Info` level diagnostics do not need to be fully resolved or suppressed as they do not cause build failures.
- Document for review: severity, default, categorization, numbering, titles, messages, and descriptions.
- Create the appropriate documentation for [learn.microsoft.com](https://github.com/dotnet/docs/tree/main/docs/fundamentals/code-analysis/quality-rules) within **ONE WEEK**, instructions available on [Contribute docs for .NET code analysis rules to the .NET docs repository](https://learn.microsoft.com/contribute/dotnet/dotnet-contribute-code-analysis).
- PR merged into `dotnet/sdk`.
- Validate the analyzer's behavior with end-to-end testing using the command-line and Visual Studio:
  - Use `dotnet new console` and `dotnet build` from the command-line, updating the code to introduce diagnostics and ensuring warnings/errors are reported at the command-line.
  - Use Visual Studio to create a new project, introduce diagnostics, and observe the warnings/errors/info messages without invoking a build.

## Validating against a real codebase

Unit tests prove the rule fires. They say nothing about the false-positive rate, which is
what actually decides the `RuleLevel` and what reviewers will ask about.

Since the analyzers migrated into `dotnet/sdk` they ship *inside* the SDK, at
`<dotnet-root>/sdk/<version>/Sdks/Microsoft.NET.Sdk/analyzers/`, laid down by
`PublishNETAnalyzers` in
[`GenerateLayout.targets`](../../Layout/redist/targets/GenerateLayout.targets). A repo that
only sets `<AnalysisLevel>` consumes that copy, so overwriting the NuGet cache does nothing
for it. A repo that `PackageReference`s `Microsoft.CodeAnalysis.NetAnalyzers` is the
reverse: the package carries a props file setting `EnableNETAnalyzers=false`, which switches
the SDK copy off in its favour. `dotnet/runtime` does the latter, in
[`eng/Analyzers.targets`](https://github.com/dotnet/runtime/blob/main/eng/Analyzers.targets).
Work out which of the two applies before copying anything.

Either route below changes only what the **command line** uses. At design time Visual Studio
redirects `Microsoft.CodeAnalysis.NetAnalyzers.dll` out of the SDK to its own deployed copy
whenever the major and minor versions match, so VS keeps running the shipped analyzers and
your change appears to do nothing. Set `DOTNET_ANALYZER_REDIRECTING=0` before launching VS
to suppress it;
[`analyzer-redirecting.md`](../../../documentation/general/analyzer-redirecting.md) has the
matching rules.

### Point the target repo at a locally built SDK

The cleanest route. A full `build.cmd` produces a complete SDK containing your analyzers:

```powershell
./build.cmd -c Release
# -> artifacts/bin/redist/Release/dotnet
```

Then run the target repo's build against it, either by setting `DOTNET_ROOT` and putting
that `dotnet` first on `PATH`, or by pointing the target repo's `global.json` at the
version it contains.

### Overwrite the analyzers in an existing SDK

Faster inner loop, and it avoids a full redist build. Build only the analyzer solution,
then copy the three assemblies over the SDK the target repo actually uses — often that
repo's own `.dotnet`. The copy below is PowerShell; use `cp` on Linux/macOS.

```powershell
./build.cmd -projects src/Microsoft.CodeAnalysis.NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.slnx -c Release

$dest = "<target-repo>/.dotnet/sdk/<version>/Sdks/Microsoft.NET.Sdk/analyzers"
Copy-Item artifacts/bin/Microsoft.CodeAnalysis.CSharp.NetAnalyzers/Release/netstandard2.0/*.dll $dest -Force
Copy-Item artifacts/bin/Microsoft.CodeAnalysis.VisualBasic.NetAnalyzers/Release/netstandard2.0/Microsoft.CodeAnalysis.VisualBasic.NetAnalyzers.dll $dest -Force
```

If the target repo *does* pin the `Microsoft.CodeAnalysis.NetAnalyzers` package, copy into
`~/.nuget/packages/microsoft.codeanalysis.netanalyzers/<version>/analyzers/dotnet/` instead
— into **both** `cs` and `vb`, since the language-agnostic assembly is duplicated into each
— and build with `/p:AssemblyVersion=<version> /p:AutoGenerateAssemblyVersion=false
/p:OfficialBuild=true` so the assembly version matches what the package declares. Build the
target repo with `/bl` and
[read the binlog](https://github.com/dotnet/msbuild/blob/main/documentation/wiki/Binary-Log.md#replaying-a-binary-log)
if you are unsure which copy is in play.

### dotnet/runtime

Set your rule to `warning` in
[`eng/CodeAnalysis.src.globalconfig`](https://github.com/dotnet/runtime/blob/main/eng/CodeAnalysis.src.globalconfig)
— e.g. `dotnet_diagnostic.CA1234.severity = warning` — then build. If nothing fires,
introduce a violation to prove the rule actually ran; pick a project nothing else depends
on, so a deliberate error doesn't cascade.

Triage every hit. Reduce false positives in the analyzer, fix the genuine violations, and
suppress only in rare edge cases.

### dotnet/roslyn

`dotnet/roslyn` builds `AnalyzerRunner`, which reports diagnostics over a solution without
requiring an analyzer-enabled build of the whole repo.

1. Build `dotnet/roslyn`: `./Build.cmd -restore -Configuration Release` (their `build.sh` on
   Linux/macOS — see roslyn's own docs for its flags).
2. Build the analyzers here in `Debug`.
3. From the roslyn root, point `AnalyzerRunner` at the analyzer output directory. It
   multi-targets .NET and .NET Framework, so pick the .NET build rather than taking the
   first folder under `artifacts/bin/AnalyzerRunner/Release/`, and launch it through
   `dotnet exec` so the path is the same on every platform:

   ```powershell
   $runner = Get-ChildItem artifacts/bin/AnalyzerRunner/Release/*/AnalyzerRunner.dll |
       Where-Object { $_.Directory.Name -notlike 'net4*' } | Select-Object -First 1
   dotnet exec $runner <sdk-repo>/artifacts/bin/Microsoft.CodeAnalysis.CSharp.NetAnalyzers/Debug/netstandard2.0 `
       ./Roslyn.slnx /stats /concurrent /a <AnalyzerTypeName> /log Output.txt
   ```

   The `/a` value is the analyzer type name. Results land in `Output.txt`.

## Debugging an analyzer inside Visual Studio

1. Build the analyzers in `Debug` and copy them into the SDK the target project uses, as
   above.
2. Open the project you want to analyze in Visual Studio.
3. Analyzers run in `ServiceHub.RoslynCodeAnalysisService.exe`; note its process ID.
   **Code fixes run in `devenv.exe` instead** — attach to that one to debug a
   `CodeFixProvider`.
4. In a second Visual Studio instance, open
   `src\Microsoft.CodeAnalysis.NetAnalyzers\Microsoft.CodeAnalysis.NetAnalyzers.slnx`, set
   your breakpoints, and *Debug -> Attach to Process...* onto the ID from step 3.
5. Type in the first instance; the breakpoints should hit. If they don't, either the build
   you copied and the solution you attached from are out of sync, or VS redirected the
   analyzer — check `DOTNET_ANALYZER_REDIRECTING=0` is set.

---

### Documentation TemplateEngine Samples Content 01 Basic Template README (`documentation/TemplateEngine/Samples/content/01-basic-template/README.md`)

The sample in this folder demonstrates:

 - **How to create a basic template** 

See [`template.json`](./MyProject.Con/.template.config/template.json)

---

### Documentation TemplateEngine Samples Content 02 Add Parameters README (`documentation/TemplateEngine/Samples/content/02-add-parameters/README.md`)

The sample in this folder demonstrates:

 - **How to create a template with parameters** - The parameters are `copyrightName` and `title`

See [`template.json`](./MyProject.Con/.template.config/template.json)

---

### Documentation TemplateEngine Samples Content 03 Optional Page README (`documentation/TemplateEngine/Samples/content/03-optional-page/README.md`)

The sample in this folder demonstrates:

 - **How to have optional content** - The contact page is optional 

See [`template.json`](./MyProject.StarterWeb/.template.config/template.json)

---

### Documentation TemplateEngine Samples Content 04 Parameter From List README (`documentation/TemplateEngine/Samples/content/04-parameter-from-list/README.md`)

The sample in this folder demonstrates:

 - **Creating a parameter based on a list of options** - The parameter is used to set the background color of the website

See [`template.json`](./MyProject.Con/.template.config/template.json)

---

### Documentation TemplateEngine Samples Content 05 Multi Project README (`documentation/TemplateEngine/Samples/content/05-multi-project/README.md`)

The sample in this folder demonstrates:

 - **Multi-project template** - Console with an optional unit test project 

See [`template.json`](./.template.config/template.json)

---

### Documentation TemplateEngine Samples Content 06 Console Csharp Fsharp README (`documentation/TemplateEngine/Samples/content/06-console-csharp-fsharp/README.md`)

The sample in this folder demonstrates:

 - **Creating a template that supports multiple languages** - Using `groupIdentity` to create a console project in `C#` and `F#` 

In this sample there are two project templates, one using C# and the other F#.
By using `groupIdentiy` these templates will appear as the same template in the output of `dotnet new --list`.

To make more than one template appear as the same in `dotnet new --list` ensure the following:

 - Each has a unique value for `identity`
 - Each has the **same** value for `groupIdentity`
 - Each has the **same** value for `name`
 - Each has a `language` tag specifying the language supported

See 
 - [`template.json` (c#)](./MyProject.Con.CSharp/.template.config/template.json)
 - [`template.json` (f#)](./MyProject.Con.FSharp/.template.config/template.json)

---

### Documentation TemplateEngine Samples Content 07 Param With Custom Short Name README (`documentation/TemplateEngine/Samples/content/07-param-with-custom-short-name/README.md`)

The sample in this folder demonstrates:

 - Customizing parameter names on the CLI 

To customize parameter names for the command line (`dotnet new`), you will create a new file named `dotnetcli.host.json`.
In that file you can define the long and short name of the parameters, as well as other settings.

See 
 - [`dotnetcli.host.json`](./MyProject.Con/.template.config/dotnetcli.host.json)
 - [`template.json`](./MyProject.Con/.template.config/template.json)

Note: This sample is the same as [`02-add-parameters`](https://github.com/dotnet/dotnet-template-samples/tree/master/02-add-parameters) plus a `dotnetcli.host.json` file.

---

### Documentation TemplateEngine Samples Content 08 Restore On Create README (`documentation/TemplateEngine/Samples/content/08-restore-on-create/README.md`)

The sample in this folder demonstrates:

 - Run `dotnet restore` after create

Using a *post action* you can run `dotnet restore` after the project is created.
In this sample a parameter is configured so the user can skip the restore step if desired.

See 

 - [`template.json`](./MyProject.Con.CSharp/.template.config/template.json)
 - [`dotnetcli.host.json`](./MyProject.Con.CSharp/.template.config/dotnetcli.host.json)

Related

For more info on *post actions*, including the list of available ones, see ../../../Post-Action-Registry.md.

---

### Documentation TemplateEngine Samples Content 09 Replace Onlyif After README (`documentation/TemplateEngine/Samples/content/09-replace-onlyif-after/README.md`)

The sample in this folder demonstrates:

 - **`onlyIf`** - Shows how you can replace some text on the condition it's preceded by a specified string.

In this sample, we show how you can replace a 

From [`site.css`](./MyProject.Con/site.css)

```
body {
    padding-top: 50px;
    padding-bottom: 20px;
    background-color: black;
}

/* Set widths on the form inputs since otherwise they're 100% wide */
input,
select,
textarea {
    max-width: 280px;
    color: black;
}

/* Carousel */
.carousel-caption p {
    font-size: 20px;
    line-height: 1.4;
    color: black
}
```

The sample shows how you can update the `black` for background-color without impacting the values for color in the following elements.


See [`template.json`](./MyProject.Con/.template.config/template.json)

---

### Documentation TemplateEngine Samples Content 10 Symbol From Date README (`documentation/TemplateEngine/Samples/content/10-symbol-from-date/README.md`)

The sample in this folder demonstrates:

 - Creating a parameter from the current date/time.

See 

 - [`template.json`](./MyProject.Con/.template.config/template.json)
 - [`Program.cs`](./MyProject.Con/Program.cs)

Related
 - [Available parameter generators](../../../Available-Symbols-Generators.md)

---

### Documentation TemplateEngine Samples Content 11 Change String Casing README (`documentation/TemplateEngine/Samples/content/11-change-string-casing/README.md`)

The sample in this folder demonstrates:

 - Uppercasing a parameter value.
 - Lowercasing a parameter value.

See 

 - [`template.json`](./MyProject.Con/.template.config/template.json)
 - [`Program.cs`](./MyProject.Con/Program.cs)

Related
 - [Available parameter generators](../../../Available-Symbols-Generators.md)

---

### Documentation TemplateEngine Samples Content 12 Random Number README (`documentation/TemplateEngine/Samples/content/12-random-number/README.md`)

The sample in this folder demonstrates:

 - Creating a random int in a given range.

See 

 - [`template.json`](./MyProject.Con/.template.config/template.json)
 - [`Program.cs`](./MyProject.Con/Program.cs)

Related
 - [Available parameter generators](../../../Available-Symbols-Generators.md)

---

### Documentation TemplateEngine Samples Content 13 Constant Value README (`documentation/TemplateEngine/Samples/content/13-constant-value/README.md`)

The sample in this folder demonstrates:

 - Creating a value based on a constant.

See 

 - [`template.json`](./MyProject.Con/.template.config/template.json)
 - [`Program.cs`](./MyProject.Con/Program.cs)

Related
 - [Available parameter generators](../../../Available-Symbols-Generators.md)

---

### Documentation TemplateEngine Samples Content 14 Guid README (`documentation/TemplateEngine/Samples/content/14-guid/README.md`)

The sample in this folder demonstrates:

 - Creating guids in different formats and using those for replacements.
 - Replacing guids using the `guids` element in `template.json`

See 

 - [`template.json`](./MyProject.Con/.template.config/template.json)
 - [`Program.cs`](./MyProject.Con/Program.cs)
 - [`MyProject.Con.csproj`](./MyProject.Con/MyProject.Con.csproj)

Related
 - [Available parameter generators](../../../Available-Symbols-Generators.md)

---

### Documentation TemplateEngine Samples Content 15 Computed Symbol README (`documentation/TemplateEngine/Samples/content/15-computed-symbol/README.md`)

The sample in this folder demonstrates:

 - **How to create a computed symbol and use that for conditions**

In this sample we define a few parameter in the [`template.json`](./MyProject.Con/.template.config/template.json) file. There is also
a computed symbols `BackgroundGreyAndDisplayCopyright` which combines the value for two parameters. Then this symbol can be used
as a conditional in source files.

Try the sample with the following and compare the results.
 - `dotnet new sample15 -o Sam15 --DisplayCopywrite false`
 - `dotnet new sample15 -o Sam15 --DisplayCopywrite true --BackgroundColor aliceblue`

## See
  - [`template.json`](./MyProject.Con/.template.config/template.json)
  - [`Program.cs`](./MyProject.Con/Program.cs)

---

### Documentation TemplateEngine Samples Content 16 String Value Transform README (`documentation/TemplateEngine/Samples/content/16-string-value-transform/README.md`)

The sample in this folder demonstrates using `derived` parameter to:

 - PascalCase a parameter value.
 - camelCase a parameter value.
 - kebab-case a paremeter value.
 - Regex replace a parameter value.
 - Chain value forms.

See

 - [`template.json`](./MyProject.Con/.template.config/template.json)
 - [`Program.cs`](./MyProject.Con/Program.cs)

Details

 - A `derived` `type` with a value transformation is performed using [value forms](../../../Value-Forms.md) (`ValueForms` type).
 - The sample uses `replace`, `titleCase`, `kebabCase`, `firstLowerCaseInvariant` and `chain` value forms.
 - More value forms can be found in [the source code](../../../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms).

Related
 - [Change String Casing](../11-change-string-casing/README.md)

---

### Documentation TemplateEngine Samples Content 17 Rename File README (`documentation/TemplateEngine/Samples/content/17-rename-file/README.md`)

The sample in this folder demonstrates:

 - **How to rename a file and/or folder in your project template** 

See [`template.json`](./MyProject.Con/.template.config/template.json)
See [`FileToRename.cs`](./MyProject.Con/FileToRename.cs)

---

### Documentation ProjectJsonToCSProj (`documentation/ProjectJsonToCSProj.md`)

.NET CLI preview 3 is here, and with it comes the .csproj project file format and msbuild engine. The team has put a lot of focus on making the transition as seamless as possible, but as with any change of this magnitude there are some gotcha's to keep in mind. This issue explains how to use the .NET CLI during this transitional period.

# Overview
Starting with @coolcsh's great post [Changes to Project.json](https://blogs.msdn.microsoft.com/dotnet/2016/05/23/changes-to-project-json/) the team has been hard at work moving the .NET command line story from project.json to msbuild. Our plan was fairly straightforward:
- Create a preview3 fork of the CLI
- Temporarily support both project.json and msbuild in the preview3 fork
  - This allowed the team to use the CLI to build the new CLI
  - msbuild support lit up through `3` verbs such as `build3`, `publish3`, `restore3`
- Once the msbuild support matures enough to build working applications, remove project.json support

In addition to lighting up the msbuild scenario, the team also provided a migration tool called `dotnet migrate` that converts project.json files to csproj files.

# Where are we now?
The team is feature complete to the plan above. The transition to msbuild is done and the migration tool is already part of the preview3 CLI. Of course there are still many issues to address before we can claim that we're ready to drop the `preview` suffix, but the core functionality is in place.

# How do I...
Until we are ready to call the `preview3+` CLI ready for prime-time we find ourselves in a world where it is interesting to work on csproj, project.json, or both. How can we make that work?

## How do I keep working with project.json?
Developers who are waiting for the new CLI to ship will continue using the `preview2` CLI. As long as they don't install any `preview3` or later bits on their machine they will be able to continue using Visual Studio 2015 preview tooling and maintain their existing developer experience. 

The `preview3` CLI does not offer any benefits for developers that want to keep using `project.json` for the time being.

## How do I work with csproj only?
Developers who want to try out the new csproj / msbuild CLI and don't have project.json-based code to worry about can just install the `preview3` tooling. Any build starting at `1.0.0-preview3-004056` is sufficient to get started. Once installed, you can open a command prompt and:
- `dotnet new` to get a new csproj console application
- `dotnet restore` to get required nuget packages
- `dotnet build` to build the project
- `dotnet run` to run the project

## How do I work with project.json while trying out csproj?
This scenario presents a few options. First, you can use the `dotnet migrate` tool to migrate your existing `project.json` assets to csproj. Alternatively, you can maintain both workflows side-by-side with some care, described below.

### How do I migrate project.json to csproj?
I'll start with a warning. Migration is fairly complex and `preview3` is the first preview of this capability. The tool will be better in future releases, and it will need your project.json files in order to redo the migration in the future. `dotnet migrate` moves your `project.json` assets into a `backup` folder whose structure matches the layout of your solution. If you intend to migrate with newer tooling in the future then keep this folder in source control so you can put the files back when needed.

To migrate a project open a command prompt and go to the project's root directory. From here, type `dotnet migrate` and let the tool do its work. For most projects, that's it! There are some special cases where the tool will complain and ask for some help, however:
- Projects are expected to have been updated to the `preview2` format for `project.json`.  If you had noticed the previous CLI complaining about `deprecated` properties, these warnings will need to be cleaned up prior to migration.
- Some advanced capabilities, particularly some script variables, do not have an equivalent in the csproj world. The migration tool will ask you to remove these before migration can complete.

Once migration is done you can use the same verbs as before to build, run, publish, etc. your project.

### How do I work with project.json and csproj on the same machine?
This is an important scenario, as many folks will keep working with the existing tooling while experimenting with the preview3 implementations.

To work with both project.json and csproj a developer will install two CLIs: one `preview2` for project.json and one `preview3` for csproj. There will only be one `dotnet` on the PATH, of course, so the CLI will need some help knowing which version to choose. This is accomplished with the help of the `global.json` file.

When `preview2` shipped the Visual Studio new project templates included both a `project.json` file and a `global.json` file. The latter was fairly empty, including project locations and a `version` property. That `version` specified the `preview2` CLI that shipped with the tools.


```
{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-preview2-003121"
  }
}
```

We included this file by default as a future-proofing tactic. When the CLI launches it looks for this file in the current directory, or the nearest parent directory, and tries to find a matching version of itself. If an exact match is found then it is used. Otherwise, `dotnet.exe` picks the latest installed CLI. When there is no exact match AND preview3 is installed then we get into trouble because preview3 cannot reason about project.json files.

When working with `preview2` and `preview3` on the same machine we need to be sure that `preview2` projects have a global.json present and that the `version` property is set to an installed preview2 version. This will typically be `1.0.0-preview2-003121` or `1.0.0-preview2-003131`. You can check what is installed by looking in `%PROGRAM FILES%\dotnet\sdk` and checking the folder names.

---

### Documentation Migration Issues (`documentation/migration-issues.md`)

## Getting help on migration issues
You're using the new .NET Core tools that are MSBuild-based. You took your project.json project and ran `dotnet migrate` or migrated from Visual Studio 2017...and you maybe ran into problems. 

The best way to get help is to [file an issue](https://github.com/dotnet/cli/issues/new) on this repo and we will investigate and provide help and/or fixes as part of new CLI builds. Make sure to read the instructions below and to **add the [MIGRATION] prefix to the issue title**.

### Filing an migration issue 
CLI is a very high-traffic repository in terms of issues. In order to be able to respond fast to migration issues, we need the issue to be formatted in a certain way:

* Add `[MIGRATION]:` prefix to the title of the issue.
* Make sure that we can see your project.json
   * If you have a GH repo or this is an OSS project, share the URL to the repo.
   * Otherwise attach or paste the project.json contents into the issue.
 * Add all of the errors that any operation like `dotnet restore`, `dotnet build` or others reported. This will help us speedily triage where the potential problem will be. 
* Add output of `dotnet --info` to the issue so we know what build you are running. 
* Mention @blackdwarf and @livarcocc in the issue body. 

From there on, we will start investigating the issue and respond.

---

### Documentation MigrationPlan CLISDKPlan (`documentation/MigrationPlan/CLISDKPlan.md`)

Given the list from the main migration status page:
1.	Using Azure DevOps for CI (Done for all repos)
2.	Using shared toolset (Arcade SDK)
3.	Engineering dependency flow
4.	Internal builds from dnceng

CLI 
2.	Beginning Nov. (Under way)
3.	Mid Nov.
4.	Eng Nov.

Toolset
2.	Mid Nov (Will follow after CLI)
3.	Mid Nov
4.	Eng Nov

Core-sdk
2.	Beginning Nov. (Under way)
3.	Mid Nov.
4.	Eng Nov.

from @licavalc on 10/30

---

### Documentation TemplateEngine Available Symbols Generators (`documentation/TemplateEngine/Available-Symbols-Generators.md`)

Inside the `template.json` file, you can define custom symbols that will be used inside the template files. 
The supported symbol types are:
- Parameter - the value is typically provided by the user when creating the template. If not provided, the value is taken from host configuration, otherwise default value is used. 
- Derived - defines transformation of another symbol.  The value of this symbol is derived from the value of another symbol by applying the defined form.
- Computed - the boolean value is evaluated during the processing of the template based on the other symbol values.
- Generated - the value is computed by a built-in symbol value generator.
There are no restrictions on symbol order: e.g. generated/computed/derived symbols can be used in any type of other symbols. The only rule is in avoiding circular dependencies such as:
```json
"symbols": {
  "switchCheck": {
    "type": "generated",
    "generator": "switch",
    "datatype": "string",
    "parameters": {
      "evaluator": "C++",
      "cases": [
        {
          "condition": "(switchCheck2 == 'regions')",
          "value": "regions"
        }
      ]
    }
  },
  "switchCheck2": {
    "type": "generated",
    "generator": "switch",
    "datatype": "string",
    "parameters": {
      "evaluator": "C++",
      "cases": [
        {
          "condition": "(switchCheck == 'regions')",
          "value": "regions"
        }
      ]
    }
  }  
```
This article covers available generators for generated symbols.

To use a generated symbol inside your `template.json` file:
1. Add `"type": "generated"` to the symbol definition
1. Use the `"generator": ...` parameter to select the generator to use.    
This is a sample of definition of a generated symbol, the `port` generator, that generates a random number for an http port.    

```json
"IISExpressPortGenerated": {    
  "type": "generated",    
  "generator": "port",
  "parameters": {
    "fallback":"5000"
  }  
},   
```

Most of the generators need to be configured via parameters that let you select the source of the data and select among the options available. Below is a sample of a symbol that uses the `now` generator to replace a fixed year indication present in the source files with the current year.

```json
"copyrightYear": {
  "type": "generated",
  "generator": "now",
  "replaces": "1975",
  "parameters": {
    "format": "yyyy"
  }
},
```

Available built-in generators for computing generated symbols values are:

| Name     | Description   |
|----------|---------------|
| [casing](#casing) | Enables changing the casing of a string. |
| [coalesce](#coalesce) | Behaves like the C# `??` operator. |
| [constant](#constant) | Constant value |
| [port](#port) | Generate a port number that can be used by web projects. |
| [guid](#guid) | Create a new guid. |
| [now](#now) | Get the current date/time. |
| [random](#random) | Generate random int. |
| [regex](#regex) | Process a regular expression. |
| [regexMatch](#regexmatch) | Checks if the value matches the regex pattern. |
| [switch](#switch) | Behaves like a C# `switch` statement. |
| [join](#join) | Concatenates multiple symbols or constants. |

## Casing
Changes the case of the text of the source value to all upper-case or all lower-case.  It does not affect spaces (i.e. does not do any sort of Camel Casing).

#### Parameters
| Name     |Data Type| Description |Mandatory|
|----------|------|---------------|---|
|`source`|`string`| The name of symbol to use as the source of data.| yes |
|`toLower`|`bool`| applies lower case if `true`, upper case otherwise| no |

### Samples

In this sample three symbols are defined:     
 - `ownerName` is a parameter which can be set on the command line using `dotnet new` It has a default value of "John Doe", that will be used if the no value is received from the host. The value will be used to replace "John Smith (a)".
 - `nameUpper` and `nameLower` are the symbols that generate the upperCase and lowerCase version of `ownerName` that are used to replace any instance of "John Smith (U)" and "John Smith (l)". 

```json
"symbols":{
    "ownerName":{
      "type": "parameter",
      "datatype":"text",
      "replaces": "John Smith (a)",
      "defaultValue": "John Doe"
    },

    "nameUpper":{
      "type": "generated",
      "generator": "casing",
      "parameters": {
        "source":"ownerName",
        "toLower": false
      },
      "replaces":"John Smith (U)"
    },

    "nameLower":{
      "type": "generated",
      "generator": "casing",
      "parameters": {
        "source":"ownerName",
        "toLower": true
      },
      "replaces":"John Smith (l)"
    }
}
```

### Related

[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CaseChangeMacro.cs)
[`Sample`](https://github.com/dotnet/dotnet-template-samples/tree/master/11-change-string-casing)


## Coalesce
Behaves like the C# `??` operator. Note: the empty string value and default value of value type is treated as `null`.
The typical use of this generator is to check if the parameter was provided by user, otherwise set fallback generated value.

#### Parameters

|Name|Data Type|Description|Mandatory|
|---|---|---|---|
|`sourceVariableName`|`string`|the symbol name which is a primary source of data (left operand of `coalesce`)|yes|
|`fallbackVariableName`|`string`|the symbol name which is an alternate source of data(right operand of `coalesce`)|yes|
|`defaultValue`|`string`|The default value. In case it is specified, and primary source is equal to this value, the fallback value will be used.|no|

### Samples

In this sample three symbols are defined:
 - `MessageYear` - is a parameter set by the user when calling `dotnet new`.   
 - `ThisYear` - use the now generator to calculate the current year.
 - `YearReplacer` - ensures that any occurrence of "1234" is replaced. If `MessageYear` was passed in by the user that value will be used. Otherwise `ThisYear` will be used.

```json
  "symbols":{
    "MessageYear":{
      "type": "parameter",
      "datatype":"int"
    },
    "ThisYear":{
      "type": "generated",
      "generator": "now",
      "parameters": {
        "format": "yyyy"
      }
    },
    "YearReplacer": {
      "type": "generated",
      "generator": "coalesce",
      "parameters": {
        "sourceVariableName": "MessageYear",
        "fallbackVariableName": "ThisYear"
      },
      "replaces": "1234"
    }
  }
```

### Related
[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CoalesceMacro.cs)

## Constant

Uses constant value.

#### Parameters

|Name|Data Type|Description|Mandatory|
|----------|------|---------------|---|
|`value`|`string`|constant value|yes|


### Samples

`myConstant` is a symbol that replaces "1234" with "5001"

```json
"symbols":{
  "myConstant": {
    "type": "generated",
    "generator": "constant",
    "parameters": {
      "value":"5001"
    },
    "replaces":"1234"
  }
}
```

### Related

[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/ConstantMacro.cs)
[`Sample`](https://github.com/dotnet/dotnet-template-samples/tree/master/13-constant-value)


## Port
Gets an available port number on the machine.   
During evaluation looks for a valid free port number trying to create a socket, and in case of problems, returns the value defined in the `fallback` parameter.

#### Parameters

|Name|Data Type|Description|Mandatory|
|----------|------|---------------|---|
|`high`|`integer`|defined the high bound of range to select port from. The maximum value is `65535`. If greater value is specified, `65535` is used instead. |no, default: `65535`|
|`low`|`integer`|defined the low bound of range to select port from. The minimum value is `1024`. If less value is specified, `1024` is used instead.|no, default: `1024`|
|`fallback`|`integer`|fallback value|no, default: `0`|

Note: if `low` > `high`, the default values for `low` and `high` are used: 1024 - 65535.

The following ports are reserved:
- 1719 - H323 (RAS)
- 1720 - H323 (Q931)
- 1723 - H323 (H245)
- 2049 - NFS
- 3659 - apple-sasl / PasswordServer [Apple addition]
- 4045 - lockd
- 4190 - ManageSieve [Apple addition]
- 5060 - SIP
- 5061 - SIPS
- 6000 - X11
- 6566 - SANE
- 6665 - Alternate IRC [Apple addition]
- 6666 - Alternate IRC [Apple addition]
- 6667 - Standard IRC [Apple addition]
- 6668 - Alternate IRC [Apple addition]
- 6669 - Alternate IRC [Apple addition]
- 6679 - Alternate IRC SSL [Apple addition]
- 6697 - IRC+SSL [Apple addition]
- 10080 - amanda

### Samples
In this sample `KestrelPortGenerated` is a symbol that return the number of an available port or 5000.

```json
  "KestrelPortGenerated": {
    "type": "generated",
    "generator": "port"
    "parameters": {
      "fallback":"5000"
    }
  },
```

### Related
[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GeneratePortNumberMacro.cs)


## Guid

*Note:* [Guids section in `template.json`](Reference-for-template.json.md#guids) can be used to achieve same goals with easier configuration

Creates a formatted guid for a replacement. To configure the output format of the macro you can use the **defaultFormat** parameter that accepts a single value from **{'n', 'd', 'b', 'p', 'x'}** for lowercase output or **{'N', 'D', 'B', 'P', 'X'}** for uppercase output. The formats are defined in [`Guid.ToString()`  method documentation](https://msdn.microsoft.com/en-us/library/97af8hh4(v=vs.110).aspx)
#### Parameters
|Name|Data Type|Description|Mandatory|
|----------|------|---------------|---|
|`defaultFormat`|`string`|format descriptor|no, default: `D`|

### Samples
This sample creates different symbols showing the different formatting available for the generated guid.

```json
"symbols":{
  "id01":{
    "type": "generated",
    "generator": "guid",
    "replaces": "myid01",
    "parameters": {
      "defaultFormat":"N"
    }
  },
  "id02":{
    "type": "generated",
    "generator": "guid",
    "replaces": "myid02",
    "parameters": {
      "defaultFormat":"D"
    }
  },
  "id03":{
    "type": "generated",
    "generator": "guid",
    "replaces": "myid03",
    "parameters": {
      "defaultFormat":"B"
    }
  },
  "id04":{
    "type": "generated",
    "generator": "guid",
    "replaces": "myid04",
    "parameters": {
      "defaultFormat":"P"
    }
  },
  "id05":{
    "type": "generated",
    "generator": "guid",
    "replaces": "myid05",
    "parameters": {
      "defaultFormat":"X"
    }
  }
}
```

### Related 
[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/GuidMacro.cs)
[`Guid Format Documentation`](https://msdn.microsoft.com/en-us/library/97af8hh4(v=vs.110).aspx)
[Guids section in `template.json`](Reference-for-template.json.md#guids)


## Now

Creates a symbol from the current date/time. 

#### Parameters 
|Name|Data Type|Description|Mandatory|
|----------|------|---------------|---|
|`format`|`string`|[`DateTime.ToString()`](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings) format|no|
|`utc`|`bool`|UTC time if `true`, local time otherwise|no|

### Samples
In this sample a symbol is created showing the current data, and replacing any instance of "01/01/1999"    

```json
"symbols":{
  "createdDate": {
    "type": "generated",
    "generator": "now",
    "parameters": {
    "format": "MM/dd/yyyy"
    },
    "replaces":"01/01/1999"
  }
}
```

### Related
[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/NowMacro.cs)   
[`DateTime.ToString documentation`](https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx)     
[`Sample`](https://github.com/dotnet/dotnet-template-samples/tree/master/10-symbol-from-date)   

## Random

Creates a random integer value in a specified range. 

#### Parameters
|Name|Data Type|Description|Mandatory|
|----------|------|---------------|---|
|`low`|`integer`|lower inclusive bound|yes|
|`high`|`integer`|upper exclusive bound|no, default:`int.MaxValue`|

### Samples   
This sample shows a symbol that generates a value from `0` to `10000` excluded, and replace any instance of `4321`

```json
"symbols":{
  "myRandomNumber":{
    "type": "generated",
    "generator": "random",
    "parameters": {
    "low": 0,
    "high": 10000
    },
    "replaces": "4321"
  }
}
```

### Related 
[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RandomMacro.cs)    
[`Sample`](https://github.com/dotnet/dotnet-template-samples/tree/master/12-random-number)


## Regex
Defines a list of data manipulation steps based on regex expressions.     

#### Parameters
|Name|Data Type|Description|Mandatory|
|----------|------|---------------|---|
|`source`|`string`|the symbol to transform|yes|
|`steps`|`array`|replacement steps|yes|

`steps` element definition:     
|Name|Data Type|Description|Mandatory| 
|----------|------|---------------|---|
|`regex`|`string`, regex pattern|selection pattern|yes|
|`replacement`|`string`|the replacement value for matched pattern|yes|

### Samples

```json
"symbols": {
  "regexExample": {
    "type": "generated",
    "generator": "regex",
    "dataType": "string",
    "replaces": "A different message",  //The value to replace in the output
    "parameters": {
      "source": "message",              //The name of the symbol whose value should be operated on
      "steps": [
        {
          "regex": "^test",             //The regular expression whose matches will be replaced with '[Replaced]`
          "replacement": "[Replaced]"   //The value to replace matches of the expression '^test' with
        },
        {
          "regex": "test$",
          "replacement": "[/Replaced]"
        }
      ]
    }
  }
}
```

### Related
[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMacro.cs)
[`RegEx.Replace Documentation`](https://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx)     

## RegexMatch
Tries to match regex pattern against value of source symbol and returns `true` if matched, otherwise `false`.

#### Parameters
|Name|Data Type|Description|Mandatory|
|----------|------|---------------|---|
|`source`|`string`|the symbol to attempt to match value|yes|
|`pattern`|`string`, regex pattern|the regex match pattern|yes|

### Samples

```json
"symbols": {
  "isMatch": {
    "type": "generated",
    "generator": "regexMatch",
    "dataType": "bool",
    "replaces": "test.value1",
    "parameters": {
    "source": "name",
    "pattern": "^hello$"
    }
  }
}
```

### Related
[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/RegexMatchMacro.cs)
[`Regex.IsMatch Documentation`](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.ismatch)     

## Switch

Defines a set of conditions to be evaluated, and the value to return if the condition is met. The first condition to evaluate to true is used. To include a default case, add a condition that always evaluates to true as the last entry in `cases`.

#### Parameters
|Name|Data Type|Description|Mandatory|
|----------|------|---------------|---|    
|`cases`|`array`|choices to evaluate|yes|
|`evaluator`|`enum`: `C++2`, `C++`, `MSBuild`, `VB`|expression evaluation engine|no, default: `C++2`|

`cases` definition
|Name|Data Type|Description|Mandatory| 
|----------|------|---------------|---|    
|`condition`|`string`|the condition to evaluate, keep empty for default clause.|no|
|`value`|`string`|the value to return, if `condition` evaluates to `true`|yes|

### Samples

This sample shows how to change the replacement value based on evaluating conditions using other symbols:

```json
"symbols": {
  "test": {
    "type": "parameter",
    "datatype": "string"
  },
  "example": {
    "type": "generated",
    "generator": "switch",
    "replaces": "abc",
    "parameters": {
      "evaluator": "C++",
      "datatype": "string",
      "cases": [
        {
          "condition": "(test == '123')",
          "value": "456"
        },
        {
          "condition": "(test == '789')",
          "value": "012"
        }
      ]
    }
  }
}
```
In this case, if the user enters the value `123` as the value of the parameter `test`, `abc` in the content will be replaced with `456`, if the user enters `789`, `abc` is replaced with `012` instead.

### Related
[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/SwitchMacro.cs)

## Join

Concatenates multiple symbols or constants with the defined separator into a new symbol.

#### Parameters
|Name|Data Type|Description|Mandatory|   
|----------|---------|----------|-----|    
|`symbols`   |`array`    |defines the values to concatenate|yes|
|`separator` |`string`   |the value used as the separator between the values to be concatenated, notice that you can use `/` as folder separator also on Windows, since File API will convert it into `\` | no |
|`removeEmptyValues` |`bool`|indicates whether the empty values should be skipped or honored. By default this switch is off - leading to multiple consecutive separators in output string in case that same input values are null or empty| no |

`symbols` definition
|Name|Data Type|Description|Mandatory|   
|------|---------|---------------|---|
|`type`  |`enum`: `ref`, `const` |`ref` indicates that the value is referenced from another symbol </br> `const` - the value is a string constant|no, default: `const`|
|`value` |`string`   |either a name of another symbol or string constant|yes, should be not empty or whitespace when `type` is `ref`|

### Samples

This sample shows how to change the replacement value based on evaluating conditions using other symbols:

```json
"symbols": {
  "company": {
    "type": "parameter",
    "dataType": "string",
    "defaultValue": "Microsoft"
  },
  "product": {
    "type": "parameter",
    "dataType": "string",
    "defaultValue": "Visual Studio"
  },
  "joinedRename": {
    "type": "generated",
    "generator": "join",
    "fileRename": "Api",
    "parameters": {
      "symbols": [
        {
          "type": "const",
          "value": "Source"
        },
        {
          "type": "const",
          "value": "Api"
        },
        {
          "type": "ref",
          "value": "company"
        },
        {
          "type": "ref",
          "value": "product"
        }
      ],
      "separator": "/",
      "removeEmptyValues": true
    }
  }
}
```
This sample will rename folder called `Api` into `Source/Api/Microsoft/Visual Studio`. Notice that File API will automatically change `/` into `\` on Windows.

<a id="multichoice-join-sample"></a>Joining [multi-choice symbol](Reference-for-template.json.md#multichoice-symbols-specifics) values:

`template.json`:
```json
"symbols": {
  "Platform": {
    "type": "parameter",
    "description": "The target framework for the project.",
    "datatype": "choice",
    "allowMultipleValues": true,
    "choices": [
      {
        "choice": "Windows",
        "description": "Windows Desktop"
      },
      {
        "choice": "WindowsPhone",
        "description": "Windows Phone"
      },
      {
        "choice": "MacOS",
        "description": "Macintosh computers"
      },
      {
        "choice": "iOS",
        "description": "iOS mobile"
      },
      {
        "choice": "android",
        "description": "android mobile"
      },
      {
        "choice": "nix",
        "description": "Linux distributions"
      }
    ],
    "defaultValue": "MacOS|iOS"
  },
  "joinedRename": {
    "type": "generated",
    "generator": "join",
    "replaces": "SupportedPlatforms",
    "parameters": {
      "symbols": [
        {
          "type": "ref",
          "value": "Platform"
        }
      ],
      "separator": ", ",
      "removeEmptyValues": true,
    }
  }
}
```

`Program.cs`:
```C#
// This file is generated for platform: SupportedPlatforms
```

This sample will expand and join values of `Platform` argument and replace `SupportedPlatforms` string with `MacOS, iOS`:

`Program.cs`:
```C#
// This file is generated for platform: MacOS, iOS
```

### Related
[`Implementation class`](../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/JoinMacro.cs)

---

### Documentation TemplateEngine Available Templates For Dotnet New (`documentation/TemplateEngine/Available-templates-for-dotnet-new.md`)

To search for the templates available on NuGet.org, use [`dotnet new search`](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-new-search).
```
    dotnet new search web
    dotnet new search azure --type project
    dotnet new search azure --author Microsoft
```

To ensure that the template package appears in `dotnet new search` result, set [the NuGet package type](https://docs.microsoft.com/en-us/nuget/create-packages/set-package-type) to `Template`.

**Note:** In order to show templates preinstalled with SDK and installed manually run the [`dotnet new list`](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new-list).

```
    dotnet new list
    dotnet new list --author Microsoft
    dotnet new list web
    dotnet new list web --type project
```

Below is a list of selected NuGet.org templates which are available for use with `dotnet new`:

# C# Templates


| Name     | Quick Install |
|----------|:--------------|
| [.NET Boxed](https://github.com/Dotnet-Boxed/Templates) | `dotnet new install "Boxed.Templates"`|
| [Auth0 Templates](https://github.com/auth0/auth0-dotnet-templates) | `dotnet new install Auth0.Templates` |
| [AWS Lambda .NET Core Templates](https://github.com/aws/aws-lambda-dotnet/tree/master/Blueprints) | `dotnet new install "Amazon.Lambda.Templates"`|
| [Avalonia UI Templates](https://github.com/AvaloniaUI/Avalonia) - Avalonia is a framework for creating cross platform UI | `dotnet new install "Avalonia.Templates"`|
| [Blazor](http://blazor.net) - Full stack web development with C# and WebAssembly | `dotnet new install "Microsoft.AspNetCore.Blazor.Templates::3.0.0-*"`|
| [Cake.Frosting](https://github.com/cake-build/cake) | `dotnet new install "Cake.Frosting.Template"` |
| [Carter](https://github.com/CarterCommunity/Carter) - Carter is a library that allows Nancy-esque routing for use with ASP.Net Core. | `dotnet new install "CarterTemplate"`|
| [CleanBlazor](https://github.com/fvilches17/CleanBlazor) - Minimal Blazor projects. Standard Blazor project templates minus any boilerplate assets (e.g. Bootstrap, Counter.razor, etc.)  | `dotnet new install "FriscoVInc.DotNet.Templates.CleanBlazor"` |
| [cloudscribe](https://www.cloudscribe.com/docs/introduction) | `dotnet new install "cloudscribe.templates"` |
| [DotVVM](https://github.com/riganti/dotvvm) - Open source MVVM framework for line of business web applications | `dotnet new install "DotVVM.Templates"` |
| [Eto.Forms](https://github.com/picoe/Eto) | `dotnet new install "Eto.Forms.Templates"` |
| [GCC.Build](https://github.com/roozbehid/dotnet-vcxproj) - C/C++/CPP/VCXPROJ Build Template using GCC/G++/EMCC or your favorate compiler | `dotnet new install GCC.Build.Template` |
| [Geco](https://github.com/iQuarc/Geco) - C# 6 Interpolated strings based Code Generator | `dotnet new install "iQuarc.Geco.CSharp"` |
| [GtkSharp](https://github.com/GtkSharp/GtkSharp) | `dotnet new install "GtkSharp.Template.CSharp"` |
| [IdentityServer4.Templates](https://github.com/IdentityServer/IdentityServer4.Templates) | `dotnet new install "identityserver4.templates"` |
| [Kentico Cloud Boilerplate](https://github.com/Kentico/cloud-boilerplate-net) | `dotnet new install "KenticoCloud.CloudBoilerplateNet"` |
| [MonoGame (.NET Core)](https://github.com/MonoGame/MonoGame) | `dotnet new install "MonoGame.Templates.CSharp"` |
| [MSBuild extension](https://github.com/tintoy/msbuild-extension-template) | `dotnet new install "MSBuildExtensionTemplate"` |
| [MvxScaffolding Templates](https://github.com/Plac3hold3r/MvxScaffolding) - MvvmCross Xamarin native and Xamarin Forms templates. | `dotnet new install "MvxScaffolding.Templates"` |
| [NancyFX Template](https://github.com/jchannon/NancyTemplate) | not on nuget.org |
| [NSpec Templates](https://github.com/nspec/DotNetNewNSpec) | `dotnet new install "dotnet-new-nspec"` |
| [NUnit 3 Test Project Template](https://github.com/nunit/dotnet-new-nunit) | `dotnet new install "NUnit3.DotNetNew.Template"` |
| [Paulovich.Caju](https://github.com/ivanpaulovich/dotnet-new-caju) - .NET applications with Event Sourcing, Hexagonal or Clean Architectures styles | `dotnet new install "Paulovich.Caju"` |
| [Paulovich.Manga](https://github.com/ivanpaulovich/manga-clean-architecture) - Clean Architecture for .NET Applications! | `dotnet new install "Paulovich.Manga"` |
| [Particular Templates](https://docs.particular.net/nservicebus/dotnet-templates) - Templates targeting NServiceBus and other tools and libraries from [Particular Software](https://particular.net/) | `dotnet new install "ParticularTemplates"` |
| [Pioneer Console Boilerplate](https://github.com/PioneerCode/pioneer-console-boilerplate) - Boilerplated .NET Core console application that includes dependency injection, logging and configuration. | `dotnet new install "Pioneer.Console.Boilerplate"` |
| [PowerShell Core](https://github.com/tintoy/ps-core-module-template) | `dotnet new install "FiftyProtons.Templates.PSCore"` |
| [Prism Forms QuickStarts](https://github.com/dansiegel/Prism-Templates) - Empty &amp; QuickStart project Templates for Prism for Xamarin Forms. *Requires dotnet cli 2.0 pre3+* | `dotnet new install "Prism.Forms.QuickstartTemplates"` |
| [Raspberry Pi 3](https://github.com/jeremylindsayni/RaspberryPiTemplate) - C# template for .NET Core 2 IoT applications. | `dotnet new install "RaspberryPi.Template"` |
| [ServiceStack](https://github.com/NetCoreApps/templates) | `dotnet new install "ServiceStack.Core.Templates"` |
| [SpecFlow.Templates.DotNet](https://github.com/SpecFlowOSS/SpecFlow) - A project template for creating executable specifications with SpecFlow. You can choose from different .NET frameworks and test frameworks. |`dotnet new install "SpecFlow.Templates.DotNet"` |
| [Template templates](https://github.com/tintoy/dotnet-template-templates) - Templates to create new project and item templates. Requires `new3`. | `dotnet new install "FiftyProtons.Templates.DotNetNew"` |
| [Zahasoft Templates](https://github.com/zahasoft/skele) | `dotnet new install "Zahasoft.Skele"` |
| [ASP.NET Core Web API (extended)](https://github.com/popov1024/httpapi-template-sharp) | `dotnet new install "Popov1024.HttpApi.Template.CSharp"` |
| [ASP.NET Core Web API for AKS](https://github.com/robbell/dotnet-aks-api-template) - A template for creating a fully-featured, 12 Factor, ASP.NET Core Web API for AKS | `dotnet new install "RobBell.AksApi.Template"` |
| [HoNoSoFt.DotNet.Web.Spa.ProjectTemplates (VueJs + Picnic CSS)](https://github.com/Nordes/HoNoSoFt.DotNet.Web.Spa.ProjectTemplates) | `dotnet new install "HoNoSoFt.DotNet.Web.Spa.ProjectTemplates"` |
| [xUnit Test Template](https://github.com/gatewayprogrammingschool/xUnit.Template) - Adds a xUnit test file to an existing test project. | `dotnet new install GatewayProgrammingSchool.xUnit.CSharp`|
[RocketMod Plugin Templates](https://github.com/RocketMod/Rocket.Templates) RocketMod is a plugin framework for .NET based games. This template allows to quickly get started with a new RocketMod Plugin.| `dotnet new install "Rocket.Templates"` |
| [EISK Web Api](https://github.com/eisk/eisk.webapi) - ASP.NET Core templates with simple use cases to build scalable web api with architectural best practices (DDD, Onion Architecture etc). | `dotnet new install "eisk.webapi"` |
|[OpenMod Plugin Templates](https://github.com/openmod/openmod/tree/master/templates) - OpenMod is .NET plugin framework. These templates allow user to quickly get started with a new OpenMod Plugin.| `dotnet new install "OpenMod.Templates"` |

# F# Templates

| Name     | Quick Install |
|----------|:--------------|
| [ASP.NET Core WebAPI F# Template](https://github.com/MNie/FSharpNetCoreWebApiTemplate) | `dotnet new install "WebAPI.FSharp.Template"` |
| [Bolero: F# in WebAssembly](https://fsbolero.io/)| `dotnet new install Bolero.Templates`|
| [Eto.Forms](https://github.com/picoe/Eto) | `dotnet new install "Eto.Forms.Templates"` |
| [Expecto Template](https://github.com/MNie/Expecto.Template) | `dotnet new install "Expecto.Template"`|
| [F# TypeProvider Template](https://github.com/fsprojects/FSharp.TypeProviders.SDK#the-f-type-provider-sdk)| `dotnet new install FSharp.TypeProviders.Templates`|
| [Fable-elmish](https://github.com/fable-compiler/fable-elmish) | `dotnet new install "Fable.Template.Elmish.React"` |
| [Fable, F# \|> Babel](http://fable.io) | `dotnet new install "Fable.Template"` |
| [Fable Library](https://github.com/TheAngryByrd/Fable.Template.Library) - F# Template for creating and publishing Fable libraries | `dotnet new install "Fable.Template.Library"` |
| [Fabulous for Xamarin.Forms](https://github.com/fsprojects/Fabulous/tree/master/Fabulous.XamarinForms)| `dotnet new install Fabulous.XamarinForms.Templates`|
| [Freya](https://freya.io) | `dotnet new install "Freya.Template"` |
| [Giraffe Template](https://github.com/giraffe-fsharp/giraffe-template) | `dotnet new install "giraffe-template"` |
| [GtkSharp](https://github.com/GtkSharp/GtkSharp) | `dotnet new install "GtkSharp.Template.FSharp"` |
| [Interstellar](https://github.com/fsprojects/Interstellar) | `dotnet new install "Interstellar.Template"` |
| [MiniScaffold](https://github.com/TheAngryByrd/MiniScaffold) - F# Template for creating and publishing libraries targeting .NET Full (net45) and Core (netstandard1.6) | `dotnet new install "MiniScaffold"` |
| [NancyFx](https://github.com/MNie/NancyFxCore)| `dotnet new install "NancyFx.Core.Template"`|
| [SAFE Template](https://safe-stack.github.io/)| `dotnet new install "SAFE.Template"`|
| [vbfox's F# Templates](https://github.com/vbfox/FSharpTemplates)| `dotnet new install "BlackFox.DotnetNew.FSharpTemplates"`|
| [WebSharper](https://github.com/dotnet-websharper/core)| `dotnet new install "WebSharper.Templates"`

# VBNet Templates

| Name     | Quick Install |
|----------|:--------------|
| [GtkSharp](https://github.com/GtkSharp/GtkSharp) | `dotnet new install "GtkSharp.Template.VBNet"` |
| [InteXX Assorted Templates](https://github.com/InteXX/Templates) | `dotnet new install "Intexx.Templates"` |

---

### Documentation TemplateEngine Binding And Project Context Evaluation (`documentation/TemplateEngine/Binding-and-project-context-evaluation.md`)

# Binding and project context evaluation

## Overview

Since .NET SDK 7.0.100 template engine supports binding of symbols to various external sources, including MSBuild properties of the current project.
The feature is available for both `dotnet new` and Visual Studio.

## `bind` symbols

The symbol binds value from external sources. 
By default, the following sources are available:
- host parameters - parameters defined at certain host. For .NET SDK the following parameters are defined: `HostIdentifier: dotnetcli`, `GlobalJsonExists: true/false`, `WorkingDirectory: <dotnet_new_context_directory>`.  Binding syntax is `host:<param name>`, example: `host:HostIdentifier`. 
- environment variables - allows to bind environment variables. Binding syntax is `env:<environment variable name>`, example: `env:MYENVVAR`.

It is also possible to bind the parameter without the prefix as a fallback behavior: `HostIdentifier`, `MYENVVAR`.

The priority of the sources are following:
- host parameters: 100
- environment variables: 0

The higher value indicates higher priority.


|Name|Description|Mandatory|
|---|---|---|
|`type`|`bind`|yes|
|`binding`| Mandatory. The name of the source and parameter in the source to take the value from. The syntax follows: `<source prefix>:<parameter name>`.|yes|
|`replaces`|The text to be replaced by the symbol value in the template files content.|no|
|`fileRename`|The portion of template filenames to be replaced by the symbol value.|no| 	 
|`defaultValue`|The value assigned to the symbol if no value was provided from external source(s). Recommended to be used when `replaces` and/or `fileRename` is used. In case default value is not specified and no value was provided from external source(s) the replacement won't be performed. |no|
|`dataType`|The value assigned to the symbol if no value was provided from external source(s). Allowed values are: "bool", "float", "int", "hex", "text", "string". If not specified, the value type will be inferred. In case the type of values might be ambiguous, consider specifying the desired datatype for processing. In case the conversion of value to the type fails, the symbol will be skipped from further processing. For more information about supported data types and their restrictions, refer to [data type description](Reference-for-template.json.md#parameter-symbol) for parameter symbols. |no|
 
##### Example  

```json
"symbols": {
   "HostIdentifier": {
      "type": "bind",
      "binding": "host:HostIdentifier"
    },
   "WorkingDirectory": {
      "type": "bind",
      "binding": "host:WorkingDirectory"
    }
}
```  

### Binding to MSBuild properties

It is possible to bind symbols to MSBuild properties of the current project. The prefix to be used: `msbuild` and it is mandatory.
Commonly used with item templates to get the information about the project it is added to.

`dotnet new` attempts to find the closest project file using following rules:
- The project in current directory or `--output` directory (matching `*.*proj` extension).
- If not found, the parent of above and so on.
- The path to the project can be explicitly specified using `--project` instantiation option. This path takes precedence - so it can be used in case of ambiguity.

Once project is located, its MSBuild properties are evaluated. The project should be restored, otherwise evaluation fails.
Only .NET [SDK-style projects](https://docs.microsoft.com/en-us/dotnet/core/project-sdk/overview) are supported.

It is recommended to configure `defaultValue` for `bind` symbol that will be used in case evaluation fails. 
If applicable, it is also recommended to use [project capability constraint](Constraints.md#project-capabilities) to define the projects that the template can be added to.

Example - binds `DefaultNamespace` symbol to `RootNamespace` of the project:
```json
"symbols": {
  "DefaultNamespace": {
    "type": "bind",
    "binding": "msbuild:RootNamespace",
    "replaces": "%NAMESPACE%",
    "defaultValue": "TestNamespace"
  }
},
"constraints": {
  "csharp-only": {
    "type": "project-capability",
    "args": "CSharp + TestContainer" // only allowed in C# test project
  }
}
```


## Visual Studio specifics

Visual Studio supports binding to host parameters, environment variables and MSBuild properties.
In addition to that, there is additional `context` source supporting:
- `context:createsolutiondirectory` - indicates whether a solution directory is to be created as a result of project creation (Place solution and project in same directory is UNCHECKED in NPD).
- `context:isexclusive` - indicates whether the template instantiation is a result of a new project being created (true) vs result of adding to an existing solution (false).
- `context:solutionname` - the name of the solution, which may be different from the project name.

Visual Studio also provides a way to bind to "namespace" via host parameters source:
```json
  "type": "bind"
  "binding": "namespace"
```

or 

```json
  "type": "bind"
  "binding": "host:namespace"
```

---

### Documentation TemplateEngine Blog Posts (`documentation/TemplateEngine/Blog-posts.md`)

- [**How to create your own templates for `dotnet new`**](https://aka.ms/dotnetnew-create-templates) by @sayedihashimi
 - [Announcing .NET Core (includes how to use `dotnet new`)](https://blogs.msdn.microsoft.com/dotnet/2017/03/07/announcing-net-core-tools-1-0/) by @sayedihashimi
 - [Trying out "dotnet new" template updates and csproj with VS2017](https://www.hanselman.com/blog/TryingOutDotnetNewTemplateUpdatesAndCsprojWithVS2017.aspx) by @shanselman
 - [Custom Project Templates Using dotnet new](http://rehansaeed.com/custom-project-templates-using-dotnet-new/) by @RehanSaeed
 - [dotnet new Feature Selection](http://rehansaeed.com/dotnet-new-feature-selection/) by @RehanSaeed
 - [Building a Solution with dotnet cli nuget templates](https://motowilliams.com/2017-02-21-building-a-solution-with-dotnet-cli-nuget-templates/) by @motowilliams
- [Building And Debugging The dotnet new Templating Engine In Visual Studio](http://pioneercode.com/post/building-and-debugging-the-dot-net-new-templating-engine-in-visual-studio) by @chad-ramos
- [How To Create A dotnet new Project Template In .NET Core](http://pioneercode.com/post/how-to-create-a-dot-net-new-project-template-in-dot-net-core) - @chad-ramos

---

### Documentation TemplateEngine Conditional Processing And Comment Syntax (`documentation/TemplateEngine/Conditional-processing-and-comment-syntax.md`)

# Table of contents

- [Introduction](#introduction)
- [Known Issues](#known-issues)
- [Language Source Files](#language-source-files)
  - [Samples](#samples)
  - [Ignore conditions expressions in language files](#ignore-conditions-expressions-in-language-files)
  - [Related](#related)
- [JSON Files](#json-files)
  - [Samples](#samples)
  - [Related](#related)
- [XML Files](#xml-files)
  - [Samples](#samples)
  - [Related](#related)
- [MSBuild Files](#msbuild-files)
  - [Samples](#samples)
  - [Ignore conditions expressions in MSBuild files](#ignore-conditions-expressions-in-msbuild-files)
  - [Related](#related)
- [Single hash line comments](#single-hash-line-comments)
  - [Samples](#samples)
  - [Related](#related)
- [CSS Files](#css-files)
  - [Samples](#samples)
  - [Related](#related)
- [Command Files](#command-files)
  - [Samples](#samples)
  - [Related](#related)
- [Razor Views](#razor-views)
  - [Samples](#samples)
  - [Related](#related)
- [Haml Files](#haml-files)
  - [Samples](#samples)
  - [Related](#related)
- [Jsx Files](#jsx-files)
  - [Samples](#samples)
  - [Related](#related)
- [Other File Types](#other-file-types)
  - [Samples](#samples)
  - [Related](#related)
  

## Introduction

To add conditional, or dynamic, content you can add Template Engine expressions in your source files. The conditional expression lets you include or exclude part of the file according to a specified condition, and to do this you can use the familiar conditional expressions like **#if**, **#else**, **#elseif**, **#endif**.

To learn more about conditional expressions evaluation go to [Conditions](Conditions.md) description.


| Name     | Description   |   
|----------|---------------|  
|[Language files](#language-source-files)| Common Dotnet language source files.|
|[JSON files](#json-files) | Common Json type files. |
|[XML files](#xml-files) | Common Xml and *tml type files. |
|[MSBuild files](#msbuild-files)| MSBuild project files.|
|[Single hash line comments](#single-hash-line-comments)| Common file types that use single hash line comment syntax.|
|[Css files](#css-files)| Css Files.|
|[Command files](#command-files)| Windows command Files.|
|[Razor Views](#razor-views)| Razor View files.|
|[Haml Files](#haml-files)| Haml files.|
|[JSX Files](#jsx-files)| Jsx and Tsx files.|   
|[Other File](#other-file-types)| Default rules for file type not in this list.|  

## Known Issues

| Name     | Description   | Incorrect Use   | Correct Use    |  
|----------|---------------|-----------------|----------------| 
|[Conditional statement overlaps with Replacement functionality](https://github.com/dotnet/templating/issues/6536)| There is a problem with using different types of conditional comments in replacement statements. In order to workaround it avoid using comments (e.g. "//") as a part of the candidate string for replacing.| "http://localhost:"| "localhost:"|

#### File Extensions
`.cs`, `.fs`,`.cpp`, `.h`, `.hpp`, `.cake`.

In these file types you can use a preprocessor directive. 
   
### Samples

In this sample, according to the value of the `IndividualB2CAuth` and `OrganizationalAuth` the appropriate service is added.
 
```
#if (IndividualB2CAuth)
  services.AddAzureAdB2CBearerAuthentication();
#elseif (OrganizationalAuth)
  services.AddAzureAdBearerAuthentication();
#endif

```

#### C# Sample

In this sample, using the parameter symbol `addMethod` we include the definition of a new method, and its use inside the main function.

```csharp
namespace MyProject.Con
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World!");
#if( addMethod )
      HelloWordAgain();
#endif    
  }
    
#if( addMethod )
    static void HelloWordAgain() {
      Console.WriteLine("Hello World Again!");
    }
#endif    
  }
}
```

#### C++ Sample

In this sample, using the parameter symbol `addMethod` we include the definition of a new class, and its use inside the main function.

```cpp
#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;
#if( addMethod )

class HelloClass
{
public:
  HelloClass() {
  }
  ~HelloClass()
  {
  }

  void HelloWordAgain() {
    cout << "Hello World Again!";
  }
};
#endif

int main()
{
  cout << "Hello World!";

#if( addMethod )
  HelloClass *hello = new HelloClass();
  hello->HelloWordAgain();
#endif

  return 0;
}
```

#### F# Sample

In this sample, using the parameter symbol `addMethod` we include the definition of a new method, and its use inside the main function.

```fsharp
open System

#if( addMethod )

let helloWorldAgain =
  printfn "HelloAgain"
#endif    

[<EntryPoint>]
let main argv =
  printfn "Hello World from F#!"
#if( addMethod )
  helloWorldAgain
#endif    
  0 // return an integer exit code

```

#### File Extensions

`.vb`.

For Visual Basic file the expressions must be preceded by a `'` comment and conditional expressions are **#If**, **#ElseIf**, **#Else**, **#End If**. 

#### Visual Basic Sample

In this sample, using the parameter symbol `addMethod` we include the definition of a new method, and its use inside the main function.

```vb
Module Module1

  Sub Main()
    Console.WriteLine("Hello World!")
'#If( addMethod )    
    HelloWorldAgain()
'#End If
  End Sub

'#If( addMethod )    
  Sub HelloWorldAgain()
    Console.WriteLine("Hello World Again!")
  End Sub
'#End If
End Module
```

#### File Extensions

`.js`,`.ts`.

With these file types the expressions must be preceded by a `//` comment . 

#### JavaScript Sample

In this sample, using the parameter symbol `addMethod` we include the definition of a new method, and its use inside the main function.

```javascript
(function () {
  
//#if( addMethod )    
  function helloWorldAgain() {
    console.log("Hello World Again!");
  }
//#endif
  
  console.log("Hello World!");
//#if( addMethod )    
  helloWorldAgain();
//#endif
  
})();
```

#### TypeScript Sample

In this sample, using the parameter symbol `addMethod` we include the definition of a new method, and its use inside the constructor.

```typescript
class Student {

  constructor() {
  console.log("Hello World!");
//#if( addMethod )    
  this.helloWorldAgain();
//#endif
  }

//#if( addMethod )    
  public helloWorldAgain(): void {
  console.log("Hello World Again!");
  }
//#endif
}
```

### Ignore conditions expressions in language files
Template engine attempts to process all conditional statements in language files. In case conditions should not be processed by template engine, this should be explicitly specified.

There are two ways to do it:
- disable processing for the whole file
- disable processing for the part of the file

If the file should never be processed by template engine, it can be specified as `copyOnly` in the `sources` section of the `template.json`. For example:

```json
"sources": [
  {
    "modifiers": [
      {
        "copyOnly": [ "Directory.Build.props" ]
      }
    ]
  }
],
```

If template engine should not process only part of the file, but other parts should be processed, the conditional processing can be turned off for the section that should not be processed by using directives:

`//-:cnd:noEmit`

`//+:cnd:noEmit`

The part `//` is the prefix to use for turning operations on and off in language files. The name `cnd` is the name of the operation to turn on/off. The `-` and `+` near the beginning of these lines indicate that the operation should be turned off, and on, respectively. The `noEmit` part tells templating to not process this line.

For example:

```
#if DEBUG
Comet.Reload.Init();
#endif
//-:cnd:noEmit
#if DEBUG
Xamarin.Calabash.Start();
#endif
//+:cnd:noEmit
```
When invoking the template with the above content, the output looks like this:
```
#if DEBUG
Xamarin.Calabash.Start();
#endif
```
The first expression is not emitted because it is processed, and the condition evaluated to `false`. The second expression is copied as-is because the conditional processing is turned off for that part of the file. 

### Related
[C# Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.cs)  
[C++ Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.cpp)  
[F# Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.fs)  
[VB Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.vb)  
[JavaScript Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.js)  
[TypeScript Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.ts)  

## JSON Files

For .json files, the comment block starts with `//` or `////` to the end of the line. After this marker you can add the conditional expressions.
The choice between `//` or `////` is very important because it lets you choose between different actions to be executed when the condition is met: in the first case the content in the expression is simply rendered into the output files as is, while in the second a different action can be executed, by default uncommenting removing an eventual leading `//`.

#### File Extensions

`.json`, `.jsonld`, `.hjson`, `.json5`, `.geojson`, `.topojson`, `.bowerrc`, `.npmrc`, `.job`, `.postcssrc`, `.babelrc`, `.csslintrc`, `.eslintrc`, `.jade-lintrc`, `.pug-lintrc`, `.jshintrc`, `.stylelintrc`, `.yarnrc`.  

### Samples

In this sample, we see the difference between the two ways to define conditional expression.
If the initial `#if` condition is preceded by `//` so, if `param1 == true`, rows below are copied as is.  
second condition `#elseif`, is preceded by `////`, so if `param1 == false` and `param2 == true`, rows below will be copied after the leading `//` has been removed, resulting in

```jsonc
// comment related to the 'elseif' content
content for when param2 is true and param1 is false
```

the latest condition, `#else`, is preceded by `////`, so the comments will removed, resulting in 

```jsonc
// comment related to the 'else' content
content for when both param1 & param2 are false
```
Changing from `////#else` to `//#else` the result will be

```jsonc
//// comment related to the 'else' content
// content for when both param1 & param2 are false
```

```jsonc
//#if (param1)
  // comment related to the 'if' content
  default content // also appropriate if param1 is true
////#elseif (param2)
  //// comment related to the 'elseif' content
  //content for when param2 is true and param1 is false
////#else
  //// comment related to the 'else' content
  // content for when both param1 & param2 are false
//#endif
```

### Related
[Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.json)

## XML Files

#### File Extensions

`.*htm`, `.*html`, `.jsp`, `.asp`, `.aspx`, `.nuspec`, `.xslt`, `.xsd`, `.vsixmanifest`, `.vsct`, `.storyboard`, `.axml`, `.plist`, `.xib`, `.strings`, `.xml`, `.xaml`, `.axaml`, `.md`, `.appxmanifest`.

#### Well known XML file names

`app.config`, `web.config`, `web.\*.config`, `packages.config`, `nuget.config`.

the comment block starts with ``. Inside this block you can add your conditional expressions.   

### Samples

In this sample, conditional expression is inside the comment `` in the same line. According to the value of the `IndividualLocalAuth` and `UseLocalDB` symbol, an element is added.
 
```xml

  <SomeXmlHere>true</SomeXmlHere>

```
 
In this sample, conditional expression is inside the comment `` in a block.

```xml

```

### Related
[Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.xml)

## MSBuild Files

#### File Extensions

`.*proj`, `.proj.user`, `.msbuild`, `.targets`, `.props`

MSBuild files, in addition to the `#if`, `#else`, `#elseif`, `#endif` inside an xml type comment, a **Condition** expression could be added to an element.  
  
### Samples

In this sample, one **<TargetFramework>** element will be added according to the value of the **TargetFrameworkOverride** symbol. This syntax is more clear and lets you use a single conditional expression to rule the inclusion of a whole block of content inside the template

```xml
<TargetFramework Condition="'$(TargetFrameworkOverride)' == ''">netcoreapp2.0</TargetFramework>
<TargetFramework Condition="'$(TargetFrameworkOverride)' != ''">TargetFrameworkOverride</TargetFramework>
```

In this sample, we can see that if the **TargetFrameworkOverride** symbol is defined all the package references are added to the project file.

```xml
<ItemGroup Condition="'$(TargetFrameworkOverride)' == ''">
  <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0-preview2-final" />
  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0-preview2-final" PrivateAssets="All" Condition="'$(IndividualAuth)' == 'True'" />
  <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0-preview2-final" PrivateAssets="All" Condition="'$(IndividualAuth)' == 'True'" />
</ItemGroup>
```

In this snippet of MSBuild file, we see usage of conditional expression embedded inside a xml comment.

```xml

  <ItemGroup>
  <None Update="Company.WebApplication1.db" CopyToOutputDirectory="PreserveNewest" />
  </ItemGroup>

```

### Ignore conditions expressions in MSBuild files

 Template engine attempts to process all conditional statements in MSBuild files. In case conditions should not be processed by template engine, this should be explicitly specified.

There are two ways to do it:
- disable processing for the whole file
- disable processing for the part of the file

If the file should never be processed by template engine, it can be specified as `copyOnly` in the `sources` section of the `template.json`. For example:

```json
  "sources": [
  {
    "modifiers": [
    {
      "copyOnly": [ "Directory.Build.props" ]
    }
    ]
  }
  ],
```

If template engine should not process only part of the file, but other parts should be processed, the conditional processing can be turned off for the section that should not be processed by using directives:

``

``

The part `
    <Foo Condition="'$(OS)' != 'Windows_NT'">Bar</Foo>

  </PropertyGroup>

  <PropertyGroup>
    <Foo Condition="'$(OS)' != 'Windows_NT'">Bar</Foo>
  </PropertyGroup>
</Project>
```
When invoking the template with the above content in `Directory.Build.props`, the output looks like this:
```
<Project>
  <PropertyGroup>
    <Foo Condition="'$(OS)' != 'Windows_NT'">Bar</Foo>
  </PropertyGroup>

  <PropertyGroup>
  </PropertyGroup>
</Project>
```
The first `<Foo Condition...` is copied as-is because the `msbuild-conditional` processing is turned off for that part of the file. But the second one is not emitted because it is processed, and the condition evaluated to `false`.

### Related

[Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.csproj)

## Single hash line comments

#### File Extensions

`.sln`, `.yml`, `.yaml`, `.sh`, `.ps1`

#### Well-known file names

`.dockerignore`, `.gitignore`, `.gitattributes`, `.editorconfig`, `Dockerfile`, `nginx.conf`, `robots.txt`.

### Samples

For solution files, the comment block starts with # to the end of the line. After this marker you can add the conditional expressions.

```.gitignore
#if (symbol-name == "value")
stuff
#endif
```

In this sample, using the parameter `useSSL` add configuration for the 443 port inside nginx configuration

```
http {
  include  /etc/nginx/proxy.conf;
  limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
  server_tokens off;

  sendfile on;
  keepalive_timeout 29; # Adjust to the lowest possible value that makes sense for your use case.
  client_body_timeout 10; client_header_timeout 10; send_timeout 10;

  upstream hellomvc{
    server localhost:5000;
  }

  server {
    listen *:80;
    add_header Strict-Transport-Security max-age=15768000;
    return 301 https://$host$request_uri;
  }

#if( useSSL )  
  server {
    listen *:443  ssl;
    server_name   example.com;
    ssl_certificate /etc/ssl/certs/testCert.crt;
    ssl_certificate_key /etc/ssl/certs/testCert.key;
    ssl_protocols TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
    ssl_ecdh_curve secp384r1;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;
    ssl_stapling on; #ensure your cert is capable
    ssl_stapling_verify on; #ensure your cert is capable

    add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;

    #Redirects all traffic
    location / {
      proxy_pass  http://hellomvc;
      limit_req   zone=one burst=10;
    }
  }
#endif
}
```

### Related
[Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.yml)

## CSS Files

#### File Extensions

`.css`, `.css.min`

the comment block starts with `/*` and ends with `*/`. Inside this block you can add your conditional expressions.

### Samples
In this sample, according to the value of the `IndividualLocalAuth` symbol, a few classes are added to the css file.
 
```css
/*#if (IndividualLocalAuth)*/
/* buttons and links extension to use brackets: [ click me ] */
.btn-bracketed::before {
  display: inline-block;
  content: "[";
  padding-right: 0.5em;
}

.btn-bracketed::after {
  display: inline-block;
  content: "]";
  padding-left: 0.5em;
}

.dl-horizontal dt 
{
  white-space: normal;
}

/*#endif*/
```

### Related

[Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.css)

## Command Files

The comment block starts with `rem ` to the end of line. After this marker you can add the conditional expressions.

#### File Extensions

`.bat`, `.cmd`

### Samples

In this sample, according to the value of the `enableVerbose` symbol, an environment variable is set to true.

```cmd
rem #if enableVerbose
set environment_verbose = true
rem #endif
```

### Related  
[Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.cmd)

## Razor Views

#### File Extensions

`.cshtml`

The comment block starts with `@*` and ends with `*@`. Inside this block you can add your conditional expressions

### Samples

In this sample, according to the value of the `IndividualLocalAuth` symbol, the using is added to an cshtml file.

```razor
@*#if (IndividualLocalAuth)
@using Microsoft.AspNetCore.Identity
#endif*@
```

In this sample, according to the value of the `IndividualB2CAuth` symbol, the inject statement is added to an cshtml file.

```razor
@*#if (IndividualB2CAuth)
@inject IOptions<AzureAdB2COptions> AzureAdB2COptions
#endif *@
```

### Related

[Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.cshtml)

## Haml Files

#### File Extensions
`.haml`

The comment block starts with `-#` to the end of the line. After this marker you can add the conditional expressions. 

### Samples

In this sample, according to the value of the `addParagraph` symbol, a paragraph is added.

```haml
-##if addParagraph
  %p A new paragraph is added.
-##endif
```

### Related
[Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.haml)

## Jsx Files

#### File Extensions

`.jsx `,`.tsx`

The comment block starts with `{/*` and ends with `*/}`. Inside this block you can add your conditional expressions. 

### Samples

In this sample, according to the value of the `addParagraph` symbol, a paragraph is added.

```jsx
const myElement = (
  <div>
    {/*#if addParagraph
    <p>A new paragraph is added</p>
    #endif*/}
    <p>I am a paragraph.</p>
  </div>
  );
```

### Related
[Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.jsx)

## Other File Types

The file types that do not have special configuration predefined in template engine or `template.json` configuration will follow default settings.
The comment block starts with `//` to the end of the line. After this marker you can add the conditional expressions using `#if`, `#elseif`, `#endif`, `#else` directives.

### Samples

In this sample, according to the value of the boolean `param1` symbol, `option1` is added to the file.
```jsx
//#if (param1)
option1
//#endif
option2
```

### Related
[Sample](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateConditionalProcessing/Test.othertype)

---

### Documentation TemplateEngine Conditions (`documentation/TemplateEngine/Conditions.md`)

# Conditions

## Table of contents

* [Overview](#overview)
  * [Generated Conditions](#generated-conditions)
  * [Example](#example)
* [Choice symbols](#choice-symbols)
  * [Quoteless literals](#quoteless-literals)
  * [Multichoice symbols](#multi-choice-symbols)
  * [Using Computed Conditions to work with Multichoice Symbols](#using-computed-conditions-to-work-with-multi-choice-symbols)
* [Conditional parameters](#conditional-parameters)
  * [Evaluation](#evaluation)
  * [Performing evaluation externally](#performing-evaluation-externally)

## Overview

Conditions are used to drive [dynamic content generating or replacing](Conditional-processing-and-comment-syntax.md).

Conditions use C++ style of [conditional preprocessor expressions](https://docs.microsoft.com/en-us/cpp/preprocessor/hash-if-hash-elif-hash-else-and-hash-endif-directives-c-cpp?view=msvc-170). Expressions are composed from constant literals (strings, numbers, `true`, `false`), [operators](../../src/TemplateEngine/Microsoft.TemplateEngine.Core/Expressions/Cpp/Operator.cs), [symbols](Available-Symbols-Generators.md), brackets and whitespaces. Only single line expressions are supported. Boolean and numerical expressions are supported (nonzero value is interpreted as `true`)

[Sample conditions in source code](../../test/TemplateEngine/Microsoft.TemplateEngine.Core.UnitTests/ConditionalTests.CStyleEvaluator.cs)

### Generated Conditions
Unlike C++ preprocessor conditions, template engine allows ability for using conditional expressions that are based on results of other expressions. Specifically [Evaluate](Available-Symbols-Generators.md#evaluate) and [Computed](Reference-for-template.json.md#computed-symbol) symbols can be leveraged for this purpose.

### Example 
(other related sample in [GeneratorTest.json](https://github.com/dotnet/sdk/blob/6423cf7db53/test/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/SchemaTests/GeneratorTest.json#L82-L84)):

`template.json`:
```json
"symbols":{
    "langVersion": {
      "type": "parameter",
      "datatype": "text",
      "description": "Sets the LangVersion property in the created project file",
      "defaultValue": "",
      "replaces": "$(ProjectLanguageVersion)",
      "displayName": "Language version"
    },
    "csharp10orLater": {
      "type": "generated",
      "generator": "regexMatch",
      "datatype": "bool",
      "parameters": {
        "pattern": "^(|10\\.0|10|preview|latest|default|latestMajor)$",
        "source": "langVersion"
      }
    },
    "csharpFeature_ImplicitUsings": {
      "type": "computed",
      "value": "csharp10orLater == \"true\""
    },
}
```

`Program.cs`:
```C#
#if (!csharpFeature_ImplicitUsings)
using System;
#endif
```

## Choice symbols

### Quoteless literals

[Choice Symbol](Reference-for-template.json.md#examples) can have one of N predefined values. Those predefined values can be referenced in the conditions as quoted literals. Unquoted literals are as well supported as opt-in feature via [`enableQuotelessLiterals`](Reference-for-template.json.md#enableQuotelessLiterals). Following 2 expressions are equivalent when opted in:

`#if (PLATFORM == "Windows")`

`#if (PLATFORM == Windows)`

This allows for easier authoring of nested generated conditions.

### Multi-choice symbols

Information about multi-choice symbols can be found in [Reference for `template.json`](Reference-for-template.json.md#multichoice-symbols-specifics)

Comparison to multi-choice symbol results in operation checking of a presence of any value of a multi-choice parameter - meaning `==` operator behaves as `contains()` operation. Example (sourced from [integration test](../../test/TestAssets/TestPackages/TemplateEngine/test_templates/TemplateWithMultiValueChoice)):

`template.json`:
```json
  "symbols": {
    "Platform": {
      "type": "parameter",
      "description": "The target platform for the project.",
      "datatype": "choice",
      "allowMultipleValues": true,
      "enableQuotelessLiterals": true,
      "choices": [
        {
          "choice": "Windows",
          "description": "Windows Desktop"
        },
        {
          "choice": "WindowsPhone",
          "description": "Windows Phone"
        },
        {
          "choice": "MacOS",
          "description": "Macintosh computers"
        },
        {
          "choice": "iOS",
          "description": "iOS mobile"
        },
        {
          "choice": "android",
          "description": "android mobile"
        },
        {
          "choice": "nix",
          "description": "Linux distributions"
        }
      ],
      "defaultValue": "MacOS|iOS"
    }
}
```

`Program.cs`:
```C#
#if (Platform == MacOS)
// MacOS choice flag specified here
#endif
```

In above example if `Platform` has it's default value (`MacOS` and `iOS`) or if those 2 values are passed to the engine (e.g. via command line: `dotnet new MyTemplate --Platform MacOS --Platform iOS`), the condition in `Program.cs` file will be evaluated as true.

Order of operands doesn't matter - `PLATFORM == Windows` evaluates identical as `Windows == PLATFORM`. Comparing 2 multi-choice symbols leads to standard equality check

### Using Computed Conditions to work with multi-choice symbols

Cases that needs evaluation of different type of condition over multi-choice symbols than 'contains' (e.g. exclusive equality or membership in subset of possible values) can be achieved with slightly more involved condition - so we recommend definition of aliases via computed conditions.

#### Example:

Lets consider following multi-choice symbol:

`template.json`:
```json
  "symbols": {
    "PLATFORM": {
      "type": "parameter",
      "description": "The target platform for the project.",
      "datatype": "choice",
      "allowMultipleValues": true,
      "enableQuotelessLiterals": true,
      "choices": [
        {
          "choice": "Windows",
          "description": "Windows Desktop"
        },
        {
          "choice": "WindowsPhone",
          "description": "Windows Phone"
        },
        {
          "choice": "MacOS",
          "description": "Macintosh computers"
        },
        {
          "choice": "iOS",
          "description": "iOS mobile"
        },
        {
          "choice": "android",
          "description": "android mobile"
        },
        {
          "choice": "nix",
          "description": "Linux distributions"
        }
      ],
      "defaultValue": "WindowsPhone|iOS|android"
    }
}
```

Then Checking whether platform is a mobile platform can be performed with following condition: `(PLATFORM == android || PLATFORM == iOS || PLATFORM == WindowsPhone)  && PLATFORM != Windows && PLATFORM != MacOS && PLATFORM != nix`

Checking for one and only one platform needs similarly involved condition: `PLATFORM == android && PLATFORM != iOS && PLATFORM != WindowsPhone && PLATFORM != Windows && PLATFORM != MacOS`

This is given by the fact that we do not support exclusive equality operator (in the future, if needed, we can introduce dedicated operator for that - e.g. `===`).

To simplify templates and make them more readable - following computed conditions can be defined:

`template.json`:
```json
  "symbols": {
    "IsMobile": {
      "type": "computed",
      "value": "(PLATFORM == android || PLATFORM == iOS || PLATFORM == WindowsPhone)  && PLATFORM != Windows && PLATFORM != MacOS && PLATFORM != nix"
    },
    "IsAndroidOnly": {
      "type": "computed",
      "value": "PLATFORM == android && PLATFORM != iOS && PLATFORM != WindowsPhone && PLATFORM != Windows && PLATFORM != MacOS && PLATFORM != nix"
    },
}
```

Usage can then look as following:

`Program.cs`
```C#
#if IsAndroidOnly
// This renders for android only
#elseif IsMobile
// This renders for rest of mobile platforms
#else
// This renders for desktop platforms
#endif
```

## Conditional Parameters

[Parameter symbols in template](Reference-for-template.json.md#parameter-symbol) can be specified together with optional conditions:
* [`IsEnabled Condition`](Reference-for-template.json.md#isEnabled) - Used to determine when (or if) this symbol should be used. If this condition is specified and evaluates to `false` (or a `false` constant is passed), then this parameter is treated as if it does not exist. This applies to the use of [conditional processing of sources](Conditional-processing-and-comment-syntax.md) and [replacements](Reference-for-template.json.md#replaces). [Verification of mandatory parameters](Reference-for-template.json.md#isRequired) does not consider disabled parameters (even if marked as required).
* [`IsRequired Condition`](Reference-for-template.json.md#isRequired) - defines if parameter is required or optional.

### Evaluation

**Input** - currently only other parameter symbols from the template configuration are supported within the parameter conditions. Any other variables are not bound and replaced (they are considered part of literal string).

**Evaluation order** - Dependencies between parameters are detected and evaluation is performed in order that guarantees that all dependencies are evaluated prior their dependant (see [Topological Sorting](https://en.wikipedia.org/wiki/Topological_sorting) for details).

 In case of cyclic dependency the evaluation proceeds only if current input values of parameters do not lead to nondeterministic result (and the cycle is indicated in warning log message). That means order of evaluation or number of reevaluations should not have impact on the result of evaluation. Otherwise an error is reported, indicating the cycle.

 Example `template.json` with cyclic dependency:
```json
  "symbols": {
    "A": {
      "type": "parameter",
      "datatype": "bool",
      "isEnabled": "B != false",
      "defaultValue": false
    },
    "B": {
      "type": "parameter",
      "datatype": "bool",
      "isEnabled": "A != true",
      "defaultValue": true
    }
}
```

The following input parameter values can (and will) be evaluated deterministically: `--A false --B true`

The following input parameter values cannot be evaluated deterministically (and will lead to error): `--A true --B false`

**Applying user, host and default values** - All user-provided, host-provided and default values are applied before the conditions are evaluated. After the evaluation default values are reapplied to parameters that were evaluated as optional and that do not have user-/host-provided values. After this an evaluation of presence of required values takes place.

### Performing evaluation externally

Users of Edge API can supply evaluation results of parameters conditions when instantiating template via `TemplateCreator`. More details are in [Inside the Template Engine](api/Inside-the-Template-Engine.md#supplying-parameters-conditions-results) document.

---

### Documentation TemplateEngine Constraints (`documentation/TemplateEngine/Constraints.md`)

#  Constraints

| Constraint | `type` |
|:-----|----------|
| [Operating system](#operating-system) | `os` |
| [Running template engine host](#template-engine-host) | `host` |
| [Installed workloads](#installed-workloads) | `workload` |
| [Current SDK version](#current-sdk-version) | `sdk-version` |
| [Project capabilities](#project-capabilities) | `project-capability` |

The feature is available since .NET SDK 7.0.100.
The template may define constraints, all of which must be met in order for the template to be usable.  In case constraints are not met, the template will be installed, however will not be visible nor used by default. 


# Base configuration
The constraints are defined under `constraints` top-level property in `template.json`. `constraints` contains objects (constraint definition). Each constraint should have a unique name, and the following properties:
- `type`: (string) - constraint type (mandatory)
- `args`: (string, array, object) - constraint arguments - depend on actual constraint implementation. May be optional.

Example `template.json`:
```json
}
  // other template elements

  "constraints": {
    "windows-only": {    // Custom name - not validated
      "type": "os",      // Type of the constraint - used to match to proper Constraint component to evaluate the constraint
      "args": "Windows"  // Arguments passed to the evaluating constraint component
    }
  }
}
```

## Operating system

Restrict the template instantiation to certain operating system.

**Configuration:**

 - `type`: `os`
 - `args`: (string, array) - list of supported operating systems. Possible values are: `Windows`, `Linux`, `OSX`.

**Supported in:**
   - all hosts (by default). 3rd party host may explicitly disable the constraint.


### Examples

```json
"constraints": {
   "linux-only": {
      "type": "os",
      "args": "Linux"
   },
}
```  
```json
"constraints": {
  "linux-and-osx": {
    "type": "os",
    "args": [ "Linux", "OSX" ]
  },
}
```  

## Template engine host
Restrict template to be run only in certain application and its version.
The following host identifiers are available:
- `dotnetcli` - .NET SDK
- `vs` - Visual Studio
- `vs-mac` - Visual Studio for Mac
- `ide` - may refer to both Visual Studio and Visual Studio for Mac
- `dotnetcli-preview` - `dotnet new3` command (used for debugging testing)

3rd party applications may define other host identifiers.

**Configuration:**

- `type`: `host`
- `args` (array). Mandatory. Array elements can have following properties:
  - `hostname`: (string) - the host identifier (see above)
  - `version`: (string, optional) - supported version, or version range. If not specified, all the versions are supported.
 
**Supported in**:
   - all hosts (by default). 3rd party host may explicitly disable the constraint.

The version and version range syntax is explained [here](https://docs.microsoft.com/en-us/nuget/concepts/package-versioning).

The parsing is done in following order:
- exact version syntax (`1.0.0`)
- floating version syntax (`1.*`)
- version range syntax (`(1.0,)`)

### Examples

Supported on .NET SDK 6.
```json
"constraints": {
   "sdk-only": {
      "type": "host",
      "args": [
        {
            "hostname": "dotnetcli",
            "version": "6.0.*"
        }
      ]
   },
}
```  

Supported from .NET SDK 6.
```json
"constraints": {
   "sdk-only": {
      "type": "host",
      "args": [
        {
            "hostname": "dotnetcli",
            "version": "[6.0,)"
        }
      ]
   },
}
```

Supported in .NET SDK and Visual Studio
```json
"constraints": {
   "sdk-only": {
      "type": "host",
      "args": [
        {
            "hostname": "dotnetcli"
        },
        {
            "hostname": "vs"
        },
      ]
   },
}
```

## Installed Workloads
Defines applicability of a template in the dotnet runtime with specific [workloads](https://github.com/dotnet/designs/blob/main/accepted/2020/workloads/workloads.md) installed.
All the installed (queryable via `dotnet workload list`) as well as [extended](https://github.com/dotnet/designs/blob/main/accepted/2020/workloads/workload-manifest.md#workload-composition) workloads are inspected during evaluating of this constraint.

**Configuration:**

- `type`: `workload`
- `args` (string, array). Mandatory. List of names of supported workloads (running host need to have at least one of the requested workloads installed).

  To see the list of installed workloads run [`dotnet workload list`](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-workload-list). To see the list of available workloads run [`dotnet workload search`](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-workload-search)

**Supported in**:
   - .NET SDK CLI (`dotnet new`)
   - Visual Studio 17.4

### Examples

```json
"constraints": {
   "android-runtime": {
      "type": "workload",
      "args": [ "microsoft-net-runtime-android", "microsoft-net-runtime-android-aot" ]
   },
}
```  
```json
"constraints": {
   "web-assembly": {
      "type": "workload",
      "args": "wasm-tools"
   },
}
```

## Current SDK Version
Defines .NET SDK version(s) the template can be used on.

Only the currently active SDK (queryable via `dotnet --version`, changeable by the [`global.json`](https://docs.microsoft.com/en-us/dotnet/core/tools/global-json)) is being considered. Other available SDKs (queryable via `dotnet --list-sdks`) are checked for possible match and result is reported in the evaluation output with possible remedy steps - the form of reporting is dependent on the templating host.

**Configuration:**

- `type`: `sdk-version`
- `args` (string, array). List of versions supported by the template. Syntax and match evaluation of versions are identical as in the [Template engine host](#template-engine-host) constraint.

**Supported in**:
   - .NET SDK CLI (`dotnet new`)
   - Visual Studio 17.4

### Examples

```json
"constraints": {
   "LTS ": {
      "type": "sdk-version",
      "args": [ "6.0.*", "3.1.*" ]
   },
}
```  
```json
"current-with-previews": {
   "web-assembly": {
      "type": "sdk-version",
      "args": "7.*.*-*"
   },
}
```
## Project capabilities
Defines [project capabilities](https://github.com/microsoft/VSProjectSystem/blob/master/doc/overview/about_project_capabilities.md) that the template requires.
Commonly used with item templates to define the certain projects it is applicable to. 
`dotnet new` attempts to find the closest project file using following rules:
- The project in current directory or `--output` directory (matching `*.*proj` extension).
- If not found, the parent of above and so on.
- The path to the project can be explicitly specified using `--project` instantiation option. This path takes precedence - so it can be used in case of ambiguity.

Once project is located, its project capabilities are evaluated. The project should be restored, otherwise evaluation fails.
Only .NET [SDK-style projects](https://docs.microsoft.com/en-us/dotnet/core/project-sdk/overview) are supported.

**Configuration:**

- `type`: `project-capability`
- `args`: (string) project capability [expression](https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.interop.vsprojectcapabilityexpressionmatcher) that should be satisfied by the project.

**Supported in**:
   - .NET SDK CLI (`dotnet new`)
   - Visual Studio 17.4 Preview 3

### Examples

```json
"constraints": {
   "CSharp": {
      "type": "project-capability",
      "args": "CSharp",
   },
}
```  
```json
"constraints": {
   "CSharpTest": {
      "type": "project-capability",
      "args": "CSharp & TestContainer",
   },
}
```

---

### Documentation TemplateEngine Exit Codes (`documentation/TemplateEngine/Exit-Codes.md`)

# `dotnet new` exit codes and their meaning

Exit codes are chosen to conform to existing standards or standardization attempts and well known exit code. See [Related resources](#related) for more details 

| Exit&nbsp;Code | Reason |
|:-----|----------|
| 0 | Success |
| [70](#70) | Unexpected internal software issue. |
| [73](#73) | Can't create output file. |
| [100](#100) | Instantiation Failed - Processing issues. |
| [101](#101) | Invalid template or template package. |
| [102](#102) | Missing required option(s) and/or argument(s) for the command. |
| [103](#103) | The template or the template package was not found. |
| [104](#104) | PostAction operation was cancelled. |
| [105](#105) | Instantiation Failed - Post action failed. |
| [106](#106) | Template/Package management operation Failed. |
| [107 - 113](#107) | Reserved. |
| [127](#127) | Unrecognized option(s) and/or argument(s) for a command. |
| [130](#130) | Command terminated by user. |


To enable verbose logging in order to troubleshoot issue(s), set the `DOTNET_CLI_CONTEXT_VERBOSE` environment variable to `true`

_PowerShell:_
```PowerShell
$env:DOTNET_CLI_CONTEXT_VERBOSE = 'true'
```

_Cmd:_
```cmd
set DOTNET_CLI_CONTEXT_VERBOSE=true
```

## <a name="70"></a>70 - Unexpected internal software issue

Unexpected result or issue. [File a bug](https://github.com/dotnet/sdk/issues/new?title=Unexpected%20Internal%20Software%20Issue%20(EX_SOFTWARE)) if you encounter this exit code.

This is a semi-standardized exit code (see [EX_SOFTWARE in /usr/include/sysexits.h](https://github.com/openbsd/src/blob/master/include/sysexits.h#L107))


## <a name="73"></a>73 - Can't create output file.

The operation was cancelled due to detection of an attempt to perform destructive changes to existing files. This can happen if you are attempting to instantiate template into the same folder where it was previously instantiated under same target name (specified via `--name` option or defaults to the target directory name)

_Example:_
```console
> dotnet new console

The template "Console App" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on C:\tmp\tmp.csproj...
  Determining projects to restore...
  Restored C:\tmp\tmp.csproj (in 47 ms).
Restore succeeded.

> dotnet new console

Creating this template will make changes to existing files:
  Overwrite   ./tmp.csproj
  Overwrite   ./Program.cs

Rerun the command and pass --force to accept and create.

For details on current exit code please visit https://aka.ms/templating-exit-codes#73
```

Destructive changes can be forced by passing `--force` option.

This is a semi-standardized exit code (see [EX_CANTCREAT in /usr/include/sysexits.h](https://github.com/openbsd/src/blob/master/include/sysexits.h#L110))


## <a name="100"></a>100 - Instantiation Failed - Processing issues

The template instantiation failed due to error(s). Caused by environment (failure to read/write template(s) or cache). 

## <a name="101"></a>101 - Invalid template or template package

_Reserved for future usage - described behavior is yet not implemented. [Feature is tracked](https://github.com/dotnet/templating/issues/4801)_

Caused by erroneous template(s) (incomplete conditions, symbols or macros etc.). Exact error reason will be output to stderr.

_Examples:_

Missing mandatory properties in template.json
```json
{
    "author": "John Doe",
    "name": "name",
}
```


## <a name="102"></a>102 - Missing required option(s) and/or argument(s) for the command

_Reserved for future usage - described behavior is only partially implemented. Some cases that should fall under this exit code are now leading to code [127](#127) [Issue is tracked](https://github.com/dotnet/templating/issues/4806)_

The exit code is used when one or more required options or/and arguments used for the command were not passed. Applicable to `search` command with not enough information as well.

Applicable as well if template option [marked as required](Reference-for-template.json.md#isrequired) was not passed during the template instantiation.

_Examples:_
```console
> dotnet new my-template
Mandatory option '--MyMandatoryParam' is missing for the template 'My Template'.

For details on current exit code please visit https://aka.ms/templating-exit-codes#102
```

```console
> dotnet new search
Search failed: not enough information specified for search.
To search for templates, specify partial template name or use one of the supported filters: '--author', '--baseline', '--language', '--type', '--tag', '--package'.
Examples:
   dotnet new search web
   dotnet new search --author Microsoft
   dotnet new search web --language C#

For details on current exit code please visit https://aka.ms/templating-exit-codes#102
```


## <a name="103"></a>103 - The template or the template package was not found

Applicable to instantiation, listing, remote sources searching and installation.

_Examples:_
```console
> dotnet new xyz
No templates found matching: 'xyz'.

To list installed templates, run:
   dotnet new list
To search for the templates on NuGet.org, run:
   dotnet new search xyz

For details on current exit code please visit https://aka.ms/templating-exit-codes#103
```

```console
> dotnet new list xyz
No templates found matching: 'xyz'.

To search for the templates on NuGet.org, run:
   dotnet new search xyz

For details on current exit code please visit https://aka.ms/templating-exit-codes#103
```

```console
> dotnet new search xyz
Searching for the templates...
Matches from template source: NuGet.org
No templates found matching: 'xyz'.

For details on current exit code please visit https://aka.ms/templating-exit-codes#103
```

```console
> dotnet new install foobarbaz
The following template packages will be installed:
   foobarbaz

foobarbaz could not be installed, no NuGet feeds are configured or they are invalid.

For details on current exit code please visit https://aka.ms/templating-exit-codes#103
```

## <a name="104"></a>104 - Post action operation was cancelled

Applicable to a case when user aborts run-script post action.


## <a name="105"></a>105 - Instantiation Failed - Post action failed

Applicable to a case when post action fails - unless it is configured to [continue on errors](Post-Action-Registry.md#continueOnError).

## <a name="106"></a>106 - Template/Package management operation failed

The exit code is used for errors during templates installation, uninstallation or updates.
Failure to download packages, read/write templates or cache, erroneous or corrupted template, or an attempt to install same package multiple times.

_Example:_
```console
>dotnet nuget disable source nuget.org
Package source with Name: nuget.org disabled successfully.

> dotnet new install webapi2
The following template packages will be installed:
   webapi2

Error: No NuGet sources are defined or enabled.
webapi2 could not be installed, the package does not exist.

For details on current exit code please visit https://aka.ms/templating-exit-codes#106
```

## <a name="107"></a><a name="108"></a><a name="109"></a><a name="110"></a><a name="111"></a><a name="112"></a><a name="113"></a>107 - 113

Reserved for future use.

[File a bug](https://github.com/dotnet/sdk/issues/new?title=Unexpected%20Exit%20Code) if you encounter any of these exit codes.


## <a name="127"></a>127 - Unrecognized option(s) and/or argument(s) for a command

The exit code is used when one or more options or/and arguments used in the command not recognized or invalid. 

Usually a mismatch in type of the specified template option or unrecognized choice value. 

_Examples:_

```console
> dotnet new console --framework xyz
Error: Invalid option(s):
--framework xyz
   'xyz' is not a valid value for --framework. The possible values are:
      net6.0   - Target net6.0
      net7.0   - Target net7.0

For details on current exit code please visit https://aka.ms/templating-exit-codes#127
```

```console
dotnet new update --smth
Unrecognized command or argument '--smth'



Description:
Checks the currently installed template packages for update, and install the updates.



Usage:
dotnet new update [options]



Options:
--interactive Allows the command to stop and wait for user input or action (for
example to complete authentication).
--add-source, --nuget-source <nuget-source> Specifies a NuGet source to use during install.
--check-only, --dry-run Only check for updates and display the template packages to be updated
without applying update.
-?, -h, --help Show command line help.

For details on current exit code please visit https://aka.ms/templating-exit-codes#127
```

This is a semi-standardized exit code (see [127 - "command not found" in 'The Linux Documentation Project'](https://tldp.org/LDP/abs/html/exitcodes.html))


## <a name="130"></a>130 - Command terminated by user.

_Reserved for future usage - described behavior is yet not implemented. [Feature is tracked](https://github.com/dotnet/templating/issues/4799)_

The exit code is used if command is terminated after user non-forceful termination request (e.g. `Ctrl-C`, `Ctrl-Break`).

This is a semi-standardized exit code (see [130 - Script terminated by Control-C in 'The Linux Documentation Project'](https://tldp.org/LDP/abs/html/exitcodes.html))

<BR/>
<BR/>
<BR/>

### Related Resources
* [`BSD sysexit.h`](https://github.com/openbsd/src/blob/master/include/sysexits.h)
* [`Special exit codes - The Linux Documentation Project`](https://tldp.org/LDP/abs/html/exitcodes.html)

---

### Documentation TemplateEngine Home (`documentation/TemplateEngine/Home.md`)

# Environments using Template Engine
- `dotnet new`
- Visual Studio
- Visual Studio for Mac

# Community templates
- See [available templates for dotnet new](Available-templates-for-dotnet-new.md)

# Template authoring
- [How to create templates](https://docs.microsoft.com/dotnet/core/tools/custom-templates)
- [Samples repository](https://github.com/dotnet/dotnet-template-samples)
- [Reference for `template.json`](Reference-for-template.json.md)
- [Post actions](Post-Action-Registry.md)
- [Symbols Generators](Available-Symbols-Generators.md)
- [Value Forms](Value-Forms.md)
- [Conditional content generation](Conditional-processing-and-comment-syntax.md)
- [Template constraints](Constraints.md)
- [Binding and project context evaluation](Binding-and-project-context-evaluation.md)
- [Authoring tools: localization](authoring-tools/Localization.md)
- [Authoring tools: testing the templates](authoring-tools/Templates-Testing-Tooling.md)

---

### Documentation TemplateEngine Naming And Default Value Forms (`documentation/TemplateEngine/Naming-and-default-value-forms.md`)

# `sourceName` default value forms

`sourceName` defines the name in the source tree to replace with the name the user specifies. The value to be replaced with can be given using the `-n` `--name` options while running a template or Name field in IDE. The template engine will look for any occurrence of the name present in the config file and replace it in file names and file contents. If no name is specified by the host, the current directory is used. The value of the `sourceName` is available in built-in `name` symbol and can be used as the source for creating other symbols and condition expressions. Therefore, it is not allowed to define `name` symbol in `symbols` in template.json configuration.

When selecting a `sourceName` for a template you're authoring, keep in mind the default value forms applied to this symbol: 
- `identity` - the value as entered by user.
- `namespace` - the value transformed in a way to be a correct .NET namespace.  [Details](https://github.com/dotnet/sdk/blob/6423cf7db53/src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DefaultSafeNamespaceValueFormFactory.cs#L16-L58)
- `class name` - the value transformed in a way to be a correct .NET class name. [Details](https://github.com/dotnet/sdk/blob/6423cf7db53/src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/DefaultSafeNameValueFormFactory.cs#L15-L21)
- `lower case namespace` - same as `namespace`, but lower case.
- `lower case class name` - same as `class name`, but lower case.

`sourceName` is available in template configuration as `name` variable.

A good choice for `sourceName` is the value that produces distinct values under the below transformations, for example `Template.1`: 
Form | Source | Transformed value
-------|------|--------
`identity` | `Template.1` | `Template.1`
`namespace` | `Template.1` | `Template._1`
`class name`  | `Template.1` | `Template__1`
`lower case namespace` | `Template.1` | `template._1`
`lower case class name`| `Template.1` | `template__1`

In this case, you can use the transformed value to force using the form, for example:
```csharp
namespace Template._1; //uses `namespace` form

public class Template__1  //uses `class` form
{
   var str = "My template name is Template.1"; //uses `identity` form
}
```

In this case, if user use `My-App` as the name, the generated content will be as follows:
Form | Source | Transformed value
-------|------|--------
`identity` | ` My-App` | `My-App`
`namespace` | ` My-App` | `My_App`
`class name`  | `My-App` | `My_App`
`lower case namespace` | `My-App` | `my_app`
`lower case class name`| `My-App` | `my_app`

```csharp
namespace My_App; //uses `namespace` form

public class My_App  //uses `class` form
{
   var str = "My template name is My-App"; //uses `identity` form
}
```

An example of wrong `sourceName` is `template1`, in this case all form transformations result in `template1`.
Referring to previous example:
```csharp
namespace template1; //intent to use `namespace` form

public class template1  //intent to use `class` form
{
   var str = "My template name is template1"; //intent to use `identity` form
}
```

In this case, if the user use `My-App` as the name, the generated content may be as follows:
```csharp
namespace My-App; //intent to use `namespace` form, but `identity` was used instead. It is not guaranteed which of `My-App`, `My_App`, `my_app` will be used here.

public class My-App //intent to use `class` form, but `identity` was used instead
{
   var str = "My template name is My_App"; //intent to use `identity` form, but `namespace` was used instead
}
```
As the result, this code won't compile as namespace and class are not using correct names.

Besides using the forms in template content, it is possible to access certain form of `sourceName` via the following variables:
- `identity`: `name{-VALUE-FORMS-}identity`, equivalent to `name`.
- `namespace`: `name{-VALUE-FORMS-}safe_namespace`
- `class name`: `name{-VALUE-FORMS-}safe_name`
- `lower case namespace`: `name{-VALUE-FORMS-}lower_safe_namespace`
- `lower case class name`: `name{-VALUE-FORMS-}lower_safe_name`

You can use them in conditions or other expressions of template configuration. Example:
```xml
<RootNamespace Condition="'$(name)' != '$(name{-VALUE-FORMS-}safe_namespace)'">Company.ConsoleApplication1</RootNamespace>
```

For more details on value forms, refer to [the article](Value-Forms.md).

---

### Documentation TemplateEngine Post Action Registry (`documentation/TemplateEngine/Post-Action-Registry.md`)

# Existing Post Actions

| Description | ActionID |
|:-----|----------|
| [Restore NuGet packages](#restore-nuget-packages) | `210D431B-A78B-4D2F-B762-4ED3E3EA9025` |
| [Run script](#run-script) | `3A7C4B45-1F5D-4A30-959A-51B88E82B5D2` |
| [Open a file in the editor](#open-a-file-in-the-editor) | `84C0DA21-51C8-4541-9940-6CA19AF04EE6` |
| [Add a reference to a project file](#add-a-reference-to-a-project-file) | `B17581D1-C5C9-4489-8F0A-004BE667B814` |
| [Add projects to a solution file](#add-projects-to-a-solution-file) | `D396686C-DE0E-4DE6-906D-291CD29FC5DE` |
| [Change file permissions (Unix/OS X)](#change-file-permissions) | `CB9A6CF3-4F5C-4860-B9D2-03A574959774` |
| [Display manual instructions](#display-manual-instructions) | `AC1156F7-BB77-4DB8-B28F-24EEBCCA1E5C` |
| [Add a property to an existing JSON file](#add-a-property-to-an-existing-json-file) | `695A3659-EB40-4FF5-A6A6-C9C4E629FCB0` |

# Base configuration
Each post action has set of standard properties as well as custom properties defined by certain post action.
The standard properties are listed below.
 - **Configuration** :
   - `actionId` (string): Action ID.
   - `condition` (string) (optional): A C++ style boolean expression defining if post action should be run. This expression may use any symbols that have been defined.
   - `description` (string) (optional): A human-readable description of the action.
   - `configFile` (string) (optional): Additional configuration for the associated post action. The structure & content will vary based on the post action.
   - <a name="continueOnError"></a>`continueOnError` (bool) (optional): If this action fails, the value of continueOnError indicates whether to process the next action, or stop processing the post actions. Should be set to true when subsequent actions rely on the result of the current action. The default value is false.
   - `manualInstructions` (array) (optional): An ordered list of possible instructions to display if the action cannot be performed. Each element in the list must contain a key named "text", whose value contains the instructions. Each element may also optionally provide a key named "condition" - a boolean expression. The first instruction with blank condition is considered a default. If true conditions are present, the last one of them will be considered valid, all other ignored. It is recommended not to have more than one true condition at the time.
   - `applyFileRenamesToArgs` (array) (optional): A list of arguments names from 'args' to which the file renames configured in symbols should be applied. By default, the file renames are not applied. Available since .NET SDK 8.0.100.
   - `applyFileRenamesToManualInstructions` (boolean) (optional): If set to true, the file renames configured in symbols should be applied to manual instructions. By default, the file renames are not applied. Available since .NET SDK 8.0.100.

# Restore NuGet packages

Used to restore NuGet packages after project create.

 - **Action ID** : `210D431B-A78B-4D2F-B762-4ED3E3EA9025`
 - **Specific Configuration** :
    - `args`:
      - `files` (string|array) (optional):
        - `string`: A semicolon delimited list of files that should be restored. If specified, the primary outputs will be ignored for processing. If not specified, matching primary outputs are restored.
        - `array`: An array of files that should be restored. If specified, the primary outputs will be ignored for processing. If not specified, matching primary outputs are restored.

      Note: the file path specified in `files` is used as glob pattern matching relative source path that starts with `./`. If none of the patterns is matched, matching primary outputs are restored.

      Given that relative source paths are:
      - ./src/Client/Client.csproj
      - ./src/Client/Client.Library.csproj
      - ./src/Client/Client.Test.csproj
      
      The following patterns can be used.
      |Description|Glob Pattern|
      |-|-|
      |Exact path matching single project|`./src/Client/Client.Test.csproj`|
      |Wildcard `*` matching multiple projects|`./src/Client/Client.*.csproj`|
      |Globstar `**` recursively matching multiple layers of directories|`**/Client.Library.csproj;**/Client.csproj`|
      |File name without parent path matching the project with the same name|`Client.Library.csproj`|

 - **Supported in**:
   - `dotnet new3`
   - `dotnet new` (2.0.0 or higher)
 - **Ignored in**:
   - `Visual Studio` - Visual Studio restores all projects automatically, so post action will be ignored.

Note: when using `files` argument it should contain the path to the file in source template definition, and ignore all the path and filename changes that can happen when instantiating template. For more details, see [the article](Using-Primary-Outputs-for-Post-Actions.md).

### Example

Restores the project mentioned in primary outputs:

```
"primaryOutputs": [
  {
    "path": "MyTestProject.csproj"        
  }
],
"postActions": [{
  "condition": "(!skipRestore)",
  "description": "Restore NuGet packages required by this project.",
  "manualInstructions": [{
    "text": "Run 'dotnet restore'"
  }],
  "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025",
  "continueOnError": true
}]
```

Restores the files mentioned in `files` argument. The primary outputs will be ignored.

```
"primaryOutputs": [
  {
    "path": "Primary/Output/PrimaryOutput.csproj"        // will not be restored
  }
],
"postActions": [{
  "condition": "(!skipRestore)",
  "description": "Restore NuGet packages required by this project.",
  "manualInstructions": [{
    "text": "Run 'dotnet restore'"
  }],
  "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025",
  "continueOnError": true,
  "args": {
    "files": ["./Client/Client.csproj", "./Server/Server.csproj"]
  }
}]
```

If none of files mentioned in `files` argument is matched, the primary outputs will be restored.

```
"primaryOutputs": [
  {
    "path": "Primary/Output/PrimaryOutput.csproj"        // will be restored
  }
],
"postActions": [{
  "condition": "(!skipRestore)",
  "description": "Restore NuGet packages required by this project.",
  "manualInstructions": [{
    "text": "Run 'dotnet restore'"
  }],
  "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025",
  "continueOnError": true,
  "args": {
    "files": ["Client/Client.csproj"]        // This will not match any project because relative source path starts with "./"
  }
}]
```

# Run script

Used to run a script after create.

 - **Action ID** : `3A7C4B45-1F5D-4A30-959A-51B88E82B5D2`
 - **Specific Configuration** : There are three required properties that must be specified.
   - `args`
     - `executable` (string): The executable to launch.
     - `args` (string): The arguments to pass to the executable.
     - `redirectStandardOutput` (bool) (optional): Whether or not to redirect stdout for the process (prevents output from being displayed if true). The default value is true.
     - `redirectStandardError` (bool) (optional): Defines whether or not the stderr should be redirected. If the output is redirected, it prevents it from being displayed. The default value is true. Available since .NET SDK 6.0.100.
   - `manualInstructions` (required)
 - **Supported in**:
   - `dotnet new3`
   - `dotnet new` (2.0.0 or higher)

The working directory for the launched executable is set to the root of the output template content.

### Example

```
"postActions": [{
  "actionId": "3A7C4B45-1F5D-4A30-959A-51B88E82B5D2",
  "args": {
    "executable": "setup.cmd",
    "args": "",
    "redirectStandardOutput": false,
    "redirectStandardError": false
  },
  "manualInstructions": [{
     "text": "Run 'setup.cmd'"
  }],
  "continueOnError": false,
  "description ": "setups the project by calling setup.cmd"
}]
```

# Open a file in the editor

Opens a file in the editor. For command line cases this post action will be ignored.

 - **Action ID** : `84C0DA21-51C8-4541-9940-6CA19AF04EE6`
 - **Specific Configuration** :
   - `files` (string): A semicolon delimited list of indexes to the primary outputs.
     Note: If primary outputs are conditional, multiple post actions with the same
     conditions as the primary outputs might be necessary.
 - **Supported in**:
   - since `Visual Studio 2017.3 Preview 1`

### Example

```
"primaryOutputs": [
  { "path": "Company.ClassLibrary1.csproj" },
  {
    "condition": "(HostIdentifier != \"dotnetcli\")",
    "path": "Class1.cs"
  }
],
"postActions": [
  {
    "condition": "(HostIdentifier != \"dotnetcli\")",
    "description": "Opens Class1.cs in the editor",
    "manualInstructions": [ ],
    "actionId": "84C0DA21-51C8-4541-9940-6CA19AF04EE6",
    "args": {
      "files": "1"
    },
    "continueOnError": true
  }
]
```

# Add a reference to a project file
 - **Action ID** : `B17581D1-C5C9-4489-8F0A-004BE667B814`
 - **Specific Configuration** :
   - `args`
     - `targetFiles` (string|array) (optional):
        - `string`: A semicolon delimited list of files that should be processed.  If not specified, the project file in output directory or its closest parent directory will be used.
        - `array`: An array of files that should be processed. If not specified, the project file in output directory or its closest parent directory will be used.
     - `referenceType` (string): Either "package" or "project".
     - `reference` (string): The package ID or relative path of the project to add the reference to.
     - `projectFileExtensions` (string) (optional): A semicolon delimited list of literal file extensions to use when searching for the project to add the reference to. If not specified, `*.*proj` mask is used when searching.
     - `version` (string) (optional) (package referenceType only): The version of the package to install.
 - **Supported in**:
   - `dotnet new3`
   - `dotnet new` (2.0.0 or higher)

Note: when using `targetFiles` argument it should contain the path to the file in source template definition, and ignore all the path and filename changes that can happen when instantiating template. For more details, see [the article](Using-Primary-Outputs-for-Post-Actions.md).

### Example

Adds a reference `Microsoft.NET.Sdk.Functions` to the project file.

```
"postActions": [{
  "Description": "Adding Reference to Microsoft.NET.Sdk.Functions NuGet package",
  "ActionId": "B17581D1-C5C9-4489-8F0A-004BE667B814",
  "ContinueOnError": "false",
  "ManualInstructions": [{
    "Text": "Manually add the reference to Microsoft.NET.Sdk.Functions to your project file"
  }],
  "args": {
    "referenceType": "package",
    "reference": "Microsoft.NET.Sdk.Functions",
    "version": "1.0.0",
    "projectFileExtensions": ".csproj"
  }
}]
```

Includes a reference to `SomeDependency` into `MyProjectFile`. The referenced project file is in the `SomeDependency` folder.

```
"postActions": [{
  "Description": "Adding a reference to another project",
  "ActionId": "B17581D1-C5C9-4489-8F0A-004BE667B814",
  "ContinueOnError": "false",
  "ManualInstructions": [{
    "Text": "Manually add the reference to SomeDependency to MyProjectFile"
  }],
  "args": {
    "targetFiles": ["MyProjectFile.csproj"]
    "referenceType": "project",
    "reference": "SomeDependency/SomeDependency.csproj"
  }
}]
```

## Adding references to existing projects

It is possible to add references to existing projects in your working directory. Since the name of the existing project is likely not a constant value for all template instantiations, a symbol can be used to pass the name of the existing project.

The example below demonstrates how to add the existing project ```src/AlreadyExisting/AlreadyExisting.csproj``` as a reference to the template source project ```Project1/Project1.csproj```.

```
{
  "symbols": {
    "existingProject": {
      ...
      "type": "parameter",
      "datatype": "string",
      "defaultValue": "ExistingProject/ExistingProject.csproj",
      "fileRename": "ExistingProjectPath" // Must be same as targetFile
    }
  },
  "postActions": [
    {
      "Description": "Add ProjectReference to ExistingProject/ExistingProject.csproj",
      "applyFileRenamesToArgs": [
        "targetFiles" // Must be specified
      ],
      "args": {
        "targetFiles": [
          "ExistingProjectPath" // Must be same as fileRename
        ],
        "referenceType": "project",
        "reference": "Project1/Project1.csproj"
      }
    }]
}
```

The template above:
- Configures the ```existingProject``` parameter *symbol* with a ```fileRename``` configuration. 
- Instructs the *'add reference to a project file'* post action to apply ```fileRename``` to the ```targetFiles``` argument.
- Uses the value passed to the ```existingProject``` *symbol* to replace the value of the matching  ```targetFiles```.

This template can be instantiated using:

```dotnet new [templateName] --existingProject src/AlreadyExisting/AlreadyExisting.csproj```


# Add project(s) to a solution file

 - **Action ID** : `D396686C-DE0E-4DE6-906D-291CD29FC5DE`
 - **Specific Configuration** :
   - `args`:
     - `projectFiles` (string|array) (optional): 
        - `string`: A semicolon delimited list of files that should be added to solution. If not specified, primary outputs will be used instead.
        - `array`: An array of files that should be added to solution. If not specified, primary outputs will be used instead.
     - `primaryOutputIndexes` (string) (optional): A semicolon delimited list of indexes to the primary outputs. If not specified, all primary outputs will be added. Note: If primary outputs are conditional, multiple post actions with the same conditions as the primary outputs might be necessary.
     - `solutionFolder` (string) (optional) (supported in 5.0.200 or higher): the destination solution folder path to add the projects to.
     - `inRoot` (boolean) (optional) (supported in 7.0.200 or higher): whether to place the projects in the root of the solution, rather than create a solution folder. Cannot be used with `solutionFolder`.
 - **Supported in**:
   - `dotnet new3`
   - `dotnet new` (2.0.0 or higher)
 - **Ignored in**:
   - `Visual Studio` - the user indicates where to add project explicitly, so post action defined in the template will be ignored.

Note: when using `projectFiles` argument it should contain the path to the file in source template definition, and ignore all the path and filename changes that can happen when instantiating template. For more details, see [the article](Using-Primary-Outputs-for-Post-Actions.md).


### Example

Adds `MyTestProject.csproj` to solution in output directory or its closest parent directory.

```
"primaryOutputs": [
    {
      "path": "MyTestProject.csproj"        
    }
],
"postActions": [{
  "description": "Add projects to solution",
  "manualInstructions": [ { "text": "Add generated project to solution manually." } ],
  "args": {
    "solutionFolder": "src"
  },
  "actionId": "D396686C-DE0E-4DE6-906D-291CD29FC5DE",
  "continueOnError": true
}]
```

Adds `MyTestProject.csproj` to solution in output directory or its closest parent directory (using `projectFiles` argument).

```
"postActions": [{
  "description": "Add projects to solution",
  "manualInstructions": [ { "text": "Add generated project to solution manually." } ],
  "args": {
    "solutionFolder": "src",
    "projectFiles": ["MyTestProject.csproj"]
  },
  "actionId": "D396686C-DE0E-4DE6-906D-291CD29FC5DE",
  "continueOnError": true
}]
```

Adds `MyTestProject.csproj` in the root of the solution.

```json
"primaryOutputs": [{
    "path": "MyTestProject.csproj"
  }
],
"postActions": [{
    "description": "Add projects to solution",
    "manualInstructions": [{
        "text": "Add generated project to solution manually."
      }
    ],
    "args": {
      "inRoot": true
    },
    "actionId": "D396686C-DE0E-4DE6-906D-291CD29FC5DE",
    "continueOnError": true
  }
]
```

# Change file permissions

Unix / OS X only (runs the Unix `chmod` command).

 - **Action ID** : `CB9A6CF3-4F5C-4860-B9D2-03A574959774`
 - **Specific Configuration** :
    - `args`: The permissions to set (see examples). Usually this will contain a glob like `{ "+x": "*.sh" }` or a list of filenames like `{ "+x": ["script1", "script2"] }`.
 - **Supported in**:
   - `dotnet new3`
   - `dotnet new` (2.0.0 or higher)

### Example

```
"postActions": [{
  "condition": "(OS != \"Windows_NT\")",
  "description": "Make scripts executable",
  "manualInstructions": [{
    "text": "Run 'chmod +x *.sh'"
  }],
  "actionId": "cb9a6cf3-4f5c-4860-b9d2-03a574959774",
  "args": {
    "+x": "*.sh"
  },
  "continueOnError": true
}]
```

or

```
"postActions": [{
  "condition": "(OS != \"Windows_NT\")",
  "description": "Make scripts executable",
  "manualInstructions": [ { "text": "Run 'chmod +x *.sh somethingelse'" }  ],
  "actionId": "cb9a6cf3-4f5c-4860-b9d2-03a574959774",
  "args": {
    "+x": [
      "*.sh",
      "somethingelse"
    ]
  },
  "continueOnError": true
}]
```

# Display manual instructions

Prints out the manual instructions after instantiating template in format:
```
Description: <description defined in post action>
Manual instructions: <manual instructions defined in post action>
Actual command: <executable> <args>
```

Command is printed only if defined in post action arguments.

 - **Action ID** : `AC1156F7-BB77-4DB8-B28F-24EEBCCA1E5C`
 - **Specific Configuration** :
    - `args`: 
     - `executable` (string) (optional): command to run
     - `args` (string) (optional): arguments to use
 - **Supported in**:
   - `dotnet new3`
   - `dotnet new` (2.0.0 or higher)

### Example

```
"postActions": [{
  "description": "Manual actions required",
  "manualInstructions": [{
    "text": "Run the following command"
  }],
  "actionId": "AC1156F7-BB77-4DB8-B28F-24EEBCCA1E5C",
  "args": {
    "executable": "setup.cmd",
    "args": "<your project name>"
  },
  "continueOnError": true
}]
```

# Add a property to an existing JSON file

Adds a new JSON property in an existing JSON file.

- **Action ID** : 695A3659-EB40-4FF5-A6A6-C9C4E629FCB0
- **Specific Configuration** :
   - `args`:
      - `jsonFileName (string)`: The path to the JSON file that must be modified.
      - `parentPropertyPath (string)` (optional): Specifies an existing property in the JSON file for which the new property must be a child property. The complete path must be specified, using a colon (:) as a separator character, for instance, `Person:Address`. If parentPropertyPath is not defined, the new property will be added to the root of the JSON document.
   - `newJsonPropertyName (string)`: The name that must be given to the new property.
   - `newJsonPropertyValue (string)`: The value that must be assigned to the new property. This must be a valid JSON.
   - `allowPropertyOverwrite (bool)` (optional, .NET 12 SDK or later): Whether an existing property may be replaced with a different value. The default is `true` for compatibility. When `false`, an existing equal value is accepted, but a conflicting value causes the post action to fail with a diagnostic and leaves the file unchanged. Missing properties can still be added.
   - `ignorePropertyValueCase (bool)` (optional, .NET 12 SDK or later): When `allowPropertyOverwrite` is `false`, compare scalar string values using `OrdinalIgnoreCase` and retain an existing matching value. The default is `false`. This does not change object property names or strings nested inside objects or arrays.
   - Starting in .NET 10 SDK, the following are also supported:
       - `detectRepositoryRoot (bool)`: Whether or not a detection logic to find repo root is enabled. When the JSON file is not found, it will be created in the detected repo root if this option is true. Also when searching for an existing JSON file, the search will stop at the repo root and won't consider any parent directories. The default is `false`.
       - `includeAllDirectoriesInSearch (bool)`: Whether or not sub-directories are searched for a matching json file (i.e, use `SearchOption.AllDirectories`). The default is `true`.
       - `includeAllParentDirectories (bool)`: Whether or not all parent directories (up to repo root, if `detectRepositoryRoot` is true) are searched for a matching JSON file. When `false`, only one level up is searched. The default is `false`.
- **Supported in** :
   - dotnet new3
   - dotnet new (2.0.0 or higher)

The built-in MSTest, Playwright MSTest, NUnit, and xUnit v3 templates set
the [JSON post-action's](../../src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/AddJsonPropertyPostActionProcessor.cs)
`allowPropertyOverwrite` to `false` and `ignorePropertyValueCase` to `true` when selecting Microsoft.Testing.Platform in
`global.json`. An explicit conflicting runner is preserved rather than silently
migrating every project in that file's scope. Runner comparison matches the
[CLI's case-insensitive resolution](../../src/Cli/Microsoft.DotNet.Cli.Definitions/Commands/Test/TestCommandDefinition.cs),
without changing the JSON post-action's default case-sensitive comparison.
Project creation still succeeds because
these post actions use [`continueOnError`](../../src/Cli/Microsoft.TemplateEngine.Cli/PostActionDispatcher.cs), but the diagnostic and manual instructions
require the user to resolve the runner choice. If no runner is configured, the templates
still add Microsoft.Testing.Platform; existing projects in that scope must be compatible.
Older SDK hosts do not implement this guard, so servicing requires updating both the
post-action processor and the template configuration.

## Example
```
"postActions": [{  `
  `"description": "Adds a new JSON property in an existing JSON file.",`
  `"manualInstructions": [ { "text": "Add a new property 'LogLevel' with value 'Information' to '.\deployment.json' under existing property 'moduleConfiguration:edgeAgent:properties.desired'" }  ],`
  `"actionId": "695A3659-EB40-4FF5-A6A6-C9C4E629FCB0",`
  `"args": {`
    `"jsonFileName": ".\deployment.json",`
    `"parentPropertyPath": "moduleConfiguration:edgeAgent:properties.desired",`
    `"newJsonPropertyName": "LogLevel",`
    `"newJsonPropertyValue": "Information"`
  `},`
  `"continueOnError": true`
`}]
```

---

### Documentation TemplateEngine Reference For Template.Json (`documentation/TemplateEngine/Reference-for-template.json.md`)

## Overview

This page describes the available properties of `template.json` configuration file.

The templates defined using `template.json`are still the "runnable projects" A "runnable project" is a project that can be
executed as a normal project can. Instead of updating your source files to be tokenized you define replacements, and other processing, mostly in an external file,
the `template.json` file. This requires that a few changes have to be done on the fly during the preparation of the package, and in the `template.json` we define all the operations needed to create a well working package.

**Benefits of "runnable project" templates**
* Code format is not modified, therefore existing editors work great for template content
* You can still build, run, debug and test your template just like any other project
* No injection of special templating tokens into the project is required (though possible)

**Typical layout on disk**
```
  .template.config/
      template.json
  MyTemplate/
      MyTemplate.csproj
      Program.cs
```

The templates can be packaged to a NuGet package for further distribution.
A tutorial on how to create the template package can be found [here](https://learn.microsoft.com/en-us/dotnet/core/tutorials/cli-templates-create-template-package).


|Category|Description|  
|------|------|     
|[Template Definition](#template-definition)|Metadata of the template|     
|[Content Manipulation](#content-manipulation)|Configuration of content changes in source files|
|[Output Management](#output-management)|Configuration of the final output|

### Template Definition
|Name|Description|Mandatory|
|---|---|---|
|`identity`|A unique name for this template|yes|
|`author`|The author of the template|no|
|<a name="classifications"></a>`classifications`| Zero or more characteristics of the template which are shown in the tabular output of `dotnet new list` and `dotnet new search` as "Tags". It is possible to filter the templates based on them using `--tag` option. In Visual Studio those items are shown in New Project Dialog in the available list of templates together with template name, description and language. Common classifications are: `Library`, `Test`, `Web` etc. |no|
|`name`|The name for the template. This is displayed as the template name when using `dotnet new` and Visual Studio.|yes|
|`groupIdentity`|The ID of the group this template belongs to. This allows multiple templates to be displayed as one, with the decision for which one to use based on the template options. See more information on templates grouping in [this article](./Using-Group-Identity.md). |no|
|`tags`|You can use tags to improve the metadata of your project. Well-known tags are: `language` and `type`. To specify the template language, use the tag `language`. To specify the template type, use the tag `type`. Supported types are: `project`, `item`, `solution`.|no|
|`shortName`|A name for selecting the template in CLI environment. This is the name shown as `Short Name` in `dotnet new` list of templates, and is the name to use to run this template. It is possible to specify multiple short names for the single template, and then any of them can be used to instantiate the template. The first element of the array is considered as the primary and first choice in scenarios where only single value is allowed (for example in tab completion of `dotnet new`). Be mindful when selecting the short name and using synonyms to avoid conflicts with other templates - the template short name should be unique. In case multiple template with the same short name are installed at the same time, the user won't be able to use any of them until one of the packages is uninstalled making the short name unique again. This doesn't apply for the templates that are part of the same group (have same `groupIdentity`). |yes|
|`postActions`|Enables actions to be performed after the project is created. See [the article](Post-Action-Registry.md) on post actions for more details.|no|
|`constraints`|[Template constraints](#template-constraints)||no|

#### Template constraints

Available since .NET SDK 7.0.100.
The template may define the constraints all of which must be met in order for the template to be used. 
In case constraints are not met, the template will be installed, however will not be visible by default. 
For the details on available constraints, refer to [the article](Constraints.md).
The constraints are defined under `constraints` property (top level in template.json). `constraints` contains objects (constraint definition). Each constraint should have a unique name, `type` and optional arguments (`args`). Argument syntax depends on the constraint implementation.

```json
"constraints": {
  "linux-only": {
    "type": "os",
    "args": "Linux"
  },
  "sdk-only": {
    "type": "host",
    "args": [
      {
        "hostname": "dotnetcli",
        "version": "[6.0.100, )"
      }
    ]
  }
}
```

### Content Manipulation
|Name|Description|Default|Mandatory|
|---|---|---|---|
|`sources`|The set of mappings in the template content to user directories. It's defined as any array of [Source](#source-definition) |If not specified, an implicit source is created with `"source": "./"` and `"target": "./"`, all other properties in the source are set to their defaults|no|
|`guids`|[Guids](#guids)||no|
|`symbols`|[Symbols](#symbols)||no|
|`forms`|[Value forms](Value-Forms.md)||no|

#### Source Definition
|Name|Description|Default|Mandatory|
|---|---|---|---|
|`source`|The path in the template content (relative to the directory containing the .template.config folder) that should be processed|`./`|no|
|`target`|The path (relative to the directory the user has specified) that content should be written to|`./`|no|
|`include`|The set of globing patterns indicating the content to process in the path referred to by `source`|[ "**/*" ]|no|
|`exclude` |The set of globing patterns indicating the content that was included by sources.include that should not be processed|`[ "**/[Bb]in/**", "**/[Oo]bj/**", ".template.config/**/*", "**/*.filelist", "**/*.user", "**/*.lock.json" ]`|no|
|`copyOnly` |The set of globing patterns indicating the content that was included by `include`, that hasn't been excluded by sources.exclude that should be placed in the user's directory without modification|`[ "**/node_modules/**/*" ]`|no|
|`rename`|The set of explicit renames to perform. Each key is a path to a file in the source, each value is a path to the target location - only the values will be evaluated with the information the user supplies||no|
|`condition`|A boolean condition to indicate if the sources configuration should be included or ignored. If the condition evaluates to `true` or is not provided, the sources config will be used for creating the template. If it evaluates to `false`, the sources config will be ignored||no|
|`modifiers`|A list of additional source information which gets added to the top-level source information, based on evaluation the corresponding `source.modifiers.condition`. Is defined as an array of [Modifier](#modifier-definition)||no|

#### Modifier Definition
|Name|Description|Mandatory|
|---|---|---|
|`condition`|A boolean condition to indicate if the `sources.modifiers` instance should be included or ignored. If the condition evaluates to `true` or is not provided, the `sources.modifiers` instance will be used for creating the template. If it evaluates to false, the `sources.modifiers` config will be ignored.|yes|
|`include`|Include configuration specific to this `sources.modifiers` instance, contingent on the corresponding `sources.modifiers.condition`. See `sources.include` for more info.|no|
|`exclude`|Exclude configuration specific to this `sources.modifiers` instance, contingent on the corresponding `sources.modifiers.condition`. See `sources.exclude` for more info|no|
|`copyOnly`|CopyOnly configuration specific to this `sources.modifiers` instance, contingent on the corresponding `sources.modifiers.condition`. See `sources.copyOnly` for more info|no|

### Guids
An optional list of guids which appear in the template source and should be replaced in the template output. For each guid listed, a replacement guid is generated, and replaces all occurrences of the source guid in the output. Matching of the guids in the source template works independently on the format and casing of the guids in the `template.json` file and source files. Format and casing from template source is preserved in the output (casing and format of the guid in `Guids` section of `template.json` doesn't influence matching or output generation).

##### Example
Sample template.json snippet:
```json
  "guids": [
    "98048C9C-BF28-46BA-A98E-63767EE5E3A8",
    "c7ab42cf938548c08b8784349ab5e04b"
  ],
```

Sample template file content:
```console
[n]: 98048c9cbf2846baa98e63767ee5e3a8
[d]: 98048c9c-bf28-46ba-a98e-63767ee5e3a8
[b]: {98048c9c-bf28-46ba-a98e-63767ee5e3a8}
[p]: (98048c9c-bf28-46ba-a98e-63767ee5e3a8)
[x]: {0x98048c9c,0xbf28,0x46ba,{0xa9,0x8e,0x63,0x76,0x7e,0xe5,0xe3,0xa8}}
[N]: 98048C9CBF2846BAA98E63767EE5E3A8
[D]: 98048C9C-BF28-46BA-A98E-63767EE5E3A8
[B]: {98048C9C-BF28-46BA-A98E-63767EE5E3A8}
[P]: (98048C9C-BF28-46BA-A98E-63767EE5E3A8)
[X]: {0X98048C9C,0XBF28,0X46BA,{0XA9,0X8E,0X63,0X76,0X7E,0XE5,0XE3,0XA8}}

[n]: c7ab42cf938548c08b8784349ab5e04b
[d]: c7ab42cf-9385-48c0-8b87-84349ab5e04b
[b]: {c7ab42cf-9385-48c0-8b87-84349ab5e04b}
[p]: (c7ab42cf-9385-48c0-8b87-84349ab5e04b)
[x]: {0xc7ab42cf,0x9385,0x48c0,{0x8b,0x87,0x84,0x34,0x9a,0xb5,0xe0,0x4b}}
[N]: C7AB42CF938548C08B8784349AB5E04B
[D]: C7AB42CF-9385-48C0-8B87-84349AB5E04B
[B]: {C7AB42CF-9385-48C0-8B87-84349AB5E04B}
[P]: (C7AB42CF-9385-48C0-8B87-84349AB5E04B)
[X]: {0XC7AB42CF,0X9385,0X48C0,{0X8B,0X87,0X84,0X34,0X9A,0XB5,0XE0,0X4B}}
```

Output content after template instantiation:
```console
[n]: a6d920ff125841318f5e07df108f5a4a
[d]: a6d920ff-1258-4131-8f5e-07df108f5a4a
[b]: {a6d920ff-1258-4131-8f5e-07df108f5a4a}
[p]: (a6d920ff-1258-4131-8f5e-07df108f5a4a)
[x]: {0xa6d920ff,0x1258,0x4131,{0x8f,0x5e,0x07,0xdf,0x10,0x8f,0x5a,0x4a}}
[N]: A6D920FF125841318F5E07DF108F5A4A
[D]: A6D920FF-1258-4131-8F5E-07DF108F5A4A
[B]: {A6D920FF-1258-4131-8F5E-07DF108F5A4A}
[P]: (A6D920FF-1258-4131-8F5E-07DF108F5A4A)
[X]: {0XA6D920FF,0X1258,0X4131,{0X8F,0X5E,0X07,0XDF,0X10,0X8F,0X5A,0X4A}}

[n]: 2879773c9a5241f78fa5ac318214f54d
[d]: 2879773c-9a52-41f7-8fa5-ac318214f54d
[b]: {2879773c-9a52-41f7-8fa5-ac318214f54d}
[p]: (2879773c-9a52-41f7-8fa5-ac318214f54d)
[x]: {0x2879773c,0x9a52,0x41f7,{0x8f,0xa5,0xac,0x31,0x82,0x14,0xf5,0x4d}}
[N]: 2879773C9A5241F78FA5AC318214F54D
[D]: 2879773C-9A52-41F7-8FA5-AC318214F54D
[B]: {2879773C-9A52-41F7-8FA5-AC318214F54D}
[P]: (2879773C-9A52-41F7-8FA5-AC318214F54D)
[X]: {0X2879773C,0X9A52,0X41F7,{0X8F,0XA5,0XAC,0X31,0X82,0X14,0XF5,0X4D}}
```

### Symbols 
The symbols section defines variables and their values, the values may be the defined in terms of other symbols. When a defined symbol name is encountered anywhere in the template definition, it is replaced by the value defined in this configuration. The symbols configuration is a collection of key-value pairs. The keys are the symbol names, and the value contains key-value-pair configuration information on how to assign the symbol a value.
The supported symbol types are:
- Parameter
- Derived
- Computed
- Generated
- Bind

There are 3 places from which a symbol can acquire its value:
- Template configuration (this).
- Host provided values, which override template configuration values. For example, the host may provide the operating system kind as "Linux", overriding a template default value of "Windows".
- User provided values, which override host & template values. The way these are provided to the template generation broker is specific to the broker. This may be via additional configuration files, command line parameters, inputs to a UI, etc.

#### Parameter symbol

A symbol for which the config provides literal and/or default values.

|Name|Description|Mandatory|
|---|---|---|
|`type`|`parameter`| yes |
|`dataType`|	Supported values: <br />- `bool`: boolean type, possible values: `true`/`false`. <br />- `choice`: enumeration, possible values are defined in `choices` property.<br />- `float`: double-precision floating format number. Accepts any value that can be parsed by `double.TryParse()`.<br />- `int`/`integer`: 64-bit signed integer. Accepts any value that can be parsed by `long.TryParse()`.<br />- `hex`: hex number. Accepts any value that can be parsed by `long.TryParse(value.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long convertedHex)`.<br />- `text`/`string`: string type.<br />- `<any other>`: treated as string.| no, default - `string` |
|<a name="defaultValue"></a>`defaultValue`|The value assigned to the symbol if no parameter is provided by the user or host. The default is *not applied* if [`isRequired`](#isRequired) configuration is set to `true` for a parameter (or is set to condition that evaluates to `true`), as that is an indication that user specified value is required.  | no |
|`defaultIfOptionWithoutValue`|The value assigned to the symbol if explicit `null` parameter value is provided by the user or host.|no |
|<a name="replaces"></a>`replaces`|The text to be replaced by the symbol value in the template files content|	no | 
|`fileRename`|The portion of template filenames to be replaced by the symbol value.| 	no | 
|`description`|Human readable text describing the meaning of the symbol. This has no effect on template generation.|	no | 
|<a name="isRequired"></a>`isRequired`|Optional. Indicates if the user supplied value is required or not. Might be a fixed boolean value or a condition string that evaluates based on passed parameters - more details in [Conditions documentation](Conditions.md#conditional-parameters).<br/>If set to `true` (or condition that evaluates to `true`) and user has not specified the value on input, validation error occurs - even if [`defaultValue`](#defaultValue) is present.|	no | 
|<a name="isEnabled"></a>`isEnabled`| Optional condition indicating whether parameter should be processed. Might be a fixed boolean value or a condition string that evaluates based on passed parameters - more details in [Conditions documentation](Conditions.md#conditional-parameters).|	no | 
|`choices`|Applicable only when `datatype=choice.`<br />List of available choices. Contains array of the elements: <br />- `choice`: possible value of the symbol.<br />- `description`: human readable text describing the meaning of the choice. This has no effect on template generation. <br /> If not provided, there are no valid choices for the symbol, so it can never be assigned a value.| yes, for `dataType` = `choice` | 
|`allowMultipleValues`|Applicable only when `datatype=choice`.<br /> Enables ability to specify multiple values for single symbol.| no | 
|<a id="enableQuotelessLiterals"></a>`enableQuotelessLiterals`|Applicable only when `datatype=choice`. <br /> Enables ability to specify choice literals in conditions without quotation.|no |
|`onlyIf`| Defines the conditions that should be fulfilled in order that replacement happens. |no |
|`forms`|Defines the set of transforms that can be referenced by symbol definitions. Forms allow the specification of a "replaces"/"replacement" pair to also apply to other ways the "replaces" value may have been specified in the source by specifying a transform from the original value of "replaces" in configuration to the one that may be found in the source. [Details](Value-Forms.md)|no |

##### Examples
Boolean optional parameter with default value `false`:
```json
  "symbols": {
    "TestProject": {
      "type": "parameter",
      "dataType": "bool",
      "defaultValue": "false"
    }
  },
```
 
<a id="choice-sample"></a>Choice optional parameter with 3 possible values:
```json
  "symbols": {
    "Framework": {
      "type": "parameter",
      "description": "The target framework for the project.",
      "datatype": "choice",
      "enableQuotelessLiterals": true,
      "choices": [
        {
          "choice": "netcoreapp3.1",
          "description": "Target netcoreapp3.1"
        },
        {
          "choice": "netstandard2.1",
          "description": "Target netstandard2.1"
        },
        {
          "choice": "netstandard2.0",
          "description": "Target netstandard2.0"
        }
      ],
      "replaces": "netstandard2.0",
      "defaultValue": "netstandard2.0"
    }
}
```
 
String optional parameter, replaces TargetFrameworkOverride:
```json
 "symbols": {
    "TargetFrameworkOverride": {
      "type": "parameter",
      "description": "Overrides the target framework",
      "replaces": "TargetFrameworkOverride",
      "datatype": "string",
      "defaultValue": ""
    }
}
```

#### Multi-choice symbols specifics
Multi-choice symbols have similar behavior and usage scenarios as [C# Flag enums](https://docs.microsoft.com/en-us/dotnet/api/system.flagsattribute) - they express a range of possible values (not a single value - unlike the plain [choice symbol](#choice-sample))

##### Example definition of multi-choice symbol:

```json
"symbols": 
{
  "Platform": {
    "type": "parameter",
    "description": "The target platform for the project.",
    "datatype": "choice",
    "allowMultipleValues": true,  // multi-choice indicator
    "choices": [
      {
        "choice": "Windows",
        "description": "Windows Desktop"
      },
      {
        "choice": "MacOS",
        "description": "Macintosh computers"
      },
      {
        "choice": "iOS",
        "description": "iOS mobile"
      },
      {
        "choice": "android",
        "description": "android mobile"
      },
      {
        "choice": "nix",
        "description": "Linux distributions"
      }
    ],
    "defaultValue": "MacOS|iOS"
  }
}
```

There are some specifics in behavior of multi-choice symbols that are worth noting:

* Condition evaluation - closer described in [Conditions document](Conditions.md#multichoice-literals).
* [`Switch` symbol](Available-Symbols-Generators.md#switch) evaluation - conditions are evaluated by identical evaluator as preprocessing conditions (previous bullet point). 
* Argument passing and tab completion on CLI - User can specify multiple options via repeating the argument switch for each option:  
  `dotnet new MyTemplate --MyParameter value1 --MyParameter value2`

  or by passing multiple tokens to single option switch:

  `dotnet new MyTemplate --MyParameter value1 value2`  

  Tab completion works identically as for standard choice symbol

* Default values specification and API usage - Currently multiple values can be specified within single string separated by `|` or `,` characters. Escaping of those characters within values is currently not supported.
* Using multi-choice value as a string in template content - this can be achieved via leveraging the [`join` symbol](Available-Symbols-Generators.md#multichoice-join-sample). For simplicity it is as well possible to specify replacement for choice symbol with multiple values - in such case the values will be rendered into single string separated by `|` sign.



#### Derived symbol

A symbol that defines transformation of another symbol.  The value of this symbol is derived from the value of another symbol by the application of form defined in `valueTransform`.

|Name|Description|Mandatory|
|---|---|---|
|`type`|`derived`| yes |
|`valueSource`|The name of the other symbol which value will be used to derive this value.| yes |
|`valueTransform`|The name of the value form to apply to the source value.| yes |
|`replaces`|The text to be replaced by the symbol value in the template files content| no |	 
|`fileRename`|The portion of template filenames to be replaced by the symbol value.| no | 
|`description`|Human readable text describing the meaning of the symbol. This has no effect on template generation.| no | 

##### Examples
Renames `Application1` file to value of `name` symbol after last dot
```json
{
...
  "symbols": {
    "app1Rename": {
      "type": "derived",  
      "valueSource": "name",  
      "valueTransform": "ValueAfterLastDot",  
      "fileRename": "Application1",  
      "description": "A value derived from the 'name' param, used to rename Application1.cs"
    }
  }
...
  "forms": {
    "ValueAfterLastDot": {
      "identifier": "replace",
      "pattern": "^.*\\.(?=[^\\.]+$)",        // regex to match everything up to and including the final "."
      "replacement": ""  // replace it with empty string
    }
  }
...
}
```

#### Generated symbol

A symbol which value gets computed by a built-in symbol value generator. [Details](Available-Symbols-Generators.md)

|Name|Description|Mandatory|
|---|---|---|
|`type`|`generated`| yes |
|`generator`|Generator to use: See [this article](Available-Symbols-Generators.md) for more details.| yes |
|`parameters`|The parameters for generator. See [description](Available-Symbols-Generators.md) for each generator for details.| depends on generator |
|`replaces`|The text to be replaced by the symbol value in the template files content| no |	 
|`fileRename`|(supported in 5.0.200 or higher) The portion of template filenames to be replaced by the symbol value.| no | 
|`dataType`|	Supported values: <br />- `bool`: boolean type, possible values: `true`/`false`. <br />- `float`: double-precision floating format number. Accepts any value that can be parsed by `double.TryParse()`.<br />- `int`/`integer`: 64-bit signed integer. Accepts any value that can be parsed by `long.TryParse()`.<br />- `hex`: hex number. Accepts any value that can be parsed by `long.TryParse(value.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long convertedHex)`.<br />- `text`/`string`: string type.<br />- `<any other>`: treated as string.| no, default: `string` |

##### Example
 
- `myconstant`: replaces `1234` with `5001`
- `ownername`: replaces `John Smith (a)` with the value of the `ownername` parameter
- `nameUpper`: 
    - replaces `John Smith (U)` with the value of the `ownername` parameter in upper case in template files content
    - replaces `author_uc` with the value of the `ownername` parameter in upper case in filenames
- `nameLower`: 
    - replaces `John Smith (l)` with the value of the `ownername` parameter in lower case in template files content
    - replaces `author_lc` with the value of the `ownername` parameter in lower case in filenames
 
```json
"symbols":{
  "myconstant": {
    "type": "generated",
    "generator": "constant",
    "parameters": {
      "value":"5001"
    },
    "replaces":"1234"
  },
  "ownername":{
    "type": "parameter",
    "datatype":"text",
    "replaces": "John Smith (a)",
    "defaultValue": "John Doe"
  },
  "nameUpper":{
    "type": "generated",
    "generator": "casing",
    "parameters": {
      "source":"ownername",
      "toLower": false
    },
    "replaces":"John Smith (U)",
    "fileRename": "author_uc"
  },
  "nameLower":{
    "type": "generated",
    "generator": "casing",
    "parameters": {
      "source":"ownername",
      "toLower": true
    },
    "replaces":"John Smith (l)",
    "fileRename": "author_lc"
  }
}
```

#### Computed symbol

A symbol for which the config provides a Boolean predicate whose evaluation result is the computed symbol result.

|Name|Description|Mandatory|
|---|---|---|
|`type`|`computed`| yes |
|`value`| Boolean expression to be computed.| yes |
|`evaluator`|Language to be used for evaluation of expression: <br />- `C++2` <br />- `C++`<br />- `MSBUILD`<br />- `VB`| no, default: `C++2` |

Please note that math operations are not supported in expressions at this point.

##### Example

Values of `OrganizationalAuth`, `WindowsAuth`, `MultiOrgAuth`, `SingleOrgAuth`, `IndividualAuth`, `NoAuth`, `RequiresHttps` symbols are computed based on `auth` symbol.

```
/* Detailed source-code truncated for AI context efficiency. */
```

#### Bind symbol
See [the article](Binding-and-project-context-evaluation.md#bind-symbols).


### Output Management
|Name|Description|Default|Mandatory|
|---|---|---|---|
|`sourceName`| The text in the source content to replace with the name the user specifies. The value to be replaced with can be given using the `-n` `--name` options while running a template. The template engine will look for any occurrence of the `sourceName` present in the config file and replace it in file names and file contents. If no name is specified by the host, the current directory is used. The value of the `sourceName` is available in built-in `name` symbol and can be used as the source for creating other symbols and condition expressions. Due to implicit forms applied to `sourceName` it is important to select the replacement that doesn't cause the conflicts. See more details about `sourceName` in [the article](Naming-and-default-value-forms.md)||no|
|`preferDefaultName`| Boolean value that decides which name will be used if no `--name` is specified during creation. If `false` it will use the fallback name (output folder name), if `true` it will use the template's `defaultName`. If no `defaultName` and no fallback name is specified and `preferDefaultName` is set to `true`, the template creation will not succeed with a `TemplateIssueDetected` exception. | If not specified, `false` is used. | no
|`preferNameDirectory`| Boolean value, indicates whether to create a directory for the template if name is specified but an output directory is not set (instead of creating the content directly in the current directory).|If not specified, `false` is used.|no|
|`placeholderFilename`|A filename that will be completely ignored, used to indicate that its containing directory should be copied. This allows creation of empty directory in the created template, by having a corresponding source directory containing just the placeholder file. By default, empty directories are ignored.|If not specified, a default value of `"-.-"` is used.|no|
|`primaryOutputs`|A list of template files for further processing by the host (including post-actions). The path should contain the relative path to the file prior to the symbol based renaming that may happen during template generation. It is defined as an array of [Primary Outputs](#primary-output-definition)||no|

#### Primary Output Definition
Primary outputs define the list of template files for further processing, usually post actions. 
|Name|Description|Mandatory|
|---|---|---|
|`path`|should contain the relative path to the file after the template is instantiated.|yes|
|`condition`|if the condition evaluates to `true`, the corresponding path will be added to primary outputs, if `false`, the path is ignored. If no condition is provided for a path, the condition defaults to `true`.|no|

For more information on primary outputs, refer to [the article](Using-Primary-Outputs-for-Post-Actions.md).

### Global custom operations and special custom operations
This advanced configuration allows the template author to define custom actions for the template creation process. Global custom operations are scoped globally unless overridden by a more restrictive custom configuration.
Special custom operations are scoped to the files matched by their glob pattern.

Customizations allowed include:
* Flag definitions
* Modification operations

There can only be one instance of the (global) `customOperations` section, as follows:
```JSON
  "customOperations": {
    // configuration details
  }
```

But since there can be many instances of the SpecialCustomOperations, each applicable to their glob patterns, the `specialCustomOperations` configuration section is defined as follows:

```JSON
  "specialCustomOperations": {
    "<fileglob1>": {
      // configuration details
    },
    "<fileglob2>": {
      // configuration details
    },
  }
```

The configuration details options are identical in both situations, they only differ in the scopes they're applied in. The below sections are labelled `customOperations.<item>`, but are equally applicable to `specialCustomOperations.<fileglob>.<Item>`

|Name|Description|Mandatory|
|---|---|---|
|`flagPrefix`|Overrides the default prefix to indicate a flag option in a file being processed.|no|
|`operations`|An array that defines custom operations for processing data in the files within the scope of the configuration. These operations are applied in addition to other operations setup by default, except in the case of the conditional operation. If a custom conditional operation is defined, the default conditional operation(s) are ignored (in this scope).|no|
|`operations.type`|Indicates the type of operation being configured. The operations currently available to configure are: <br /> - `balancedNesting`<br /> - `conditional` <br /> - `flag` <br /> - `include`<br /> - `region` <br /> - `replacement`|yes|
|`operations.condition`|A boolean expression whose result determines whether or not to use this custom operation. If this is not provided, the operation is used.|no|
|`operations.configuration`|The details of the operation configuration. Each type of operation has its own configuration options, as detailed below.|yes|

SpecialCustomOperations can be used for adding conditions for handling files with extensions not listed in [Conditional processing and comment syntax](Conditional-processing-and-comment-syntax.md#introduction).

```JSON
{
  "SpecialCustomOperations": {
    "**.axml": {
      "operations": [
        {
          "type": "conditional",
          "configuration": {
            "endif": [ "#endif", "<!--#endif" ],
            "actionableIf": [ "<!--#if" ],
            "actionableElse": [ "#else", "<!--#else" ],
            "actionableElseif": [ "#elseif", "<!--#elseif", "#elif", "<!--#elif" ],
            "trim": true,
            "wholeLine": true,
            "evaluator": "C++"
          }
        }
      ]
    }
  }
}
```

#### Balanced nesting
This operation type is designed to be used in conjunction with a conditional operation, to help maintain the proper commenting on conditional, and the text they may optionally emit. See the section on configuring a custom conditional operation for more details.

#### Conditional
Conditional operations allow sections of template files to be optionally included during template creation.

The customization of this operation facilitates preprocessing on many file formats for which there is no standard preprocessor syntax defined, by defining comment-based symbols to represent the preprocessor directives. 
By using comments recognized by the file formats, the unprocessed file content is valid even when it contains the customized preprocessor directives (since they're commented out as needed).

Conditional processing is based on the 4 conditional keywords:
* `if`
* `elseif`
* `else`
* `endif`

Other than the `endif` keyword, each keyword type can be defined in up to 2 flavors, `basic` and `actionable`. The basic flavor indicates that if the condition is `true`, the contents should be emitted verbatim. The `actionable` flavor indicates that other actions should be taken on the content of the conditional - usually the other action is uncommenting.

Here is an example of defining a custom conditional operation (this is the actual predefined C-style line comments conditional configuration, which is the default for .json files)
``` JSON
{
  "type": "conditional",
  "configuration": {
    "if": [ "//#if" ],
    "else": [ "//#else" ],
    "elseif": [ "//#elseif" ],
    "endif": [ "//#endif" ],
    "actionableIf": [ "////#if" ],
    "actionableElse": [ "////#else" ],
    "actionableElseif": [ "////#elseif" ],
    "actions": [ "cStyleUncomment", "cStyleReduceComment" ],
    "trim": true,
    "wholeLine": true,
    "evaluator": "C++"
  },
}
```

Because there are actionable keywords, there is an "actions" field provided, which refers to other action(s) to activate when an actionable token is encountered. The other actions remain active until any other token in the conditional config is encountered. In this case, the other actions jobs are to remove comments, and to reduce consecutive double comments to a single comment. 

These other actions are defined as:
``` JSON
{
  "type": "replacement",
  "configuration": {
    "original": "//",
    "replacement": "",
    "id": "cStyleUncomment",
  },
},
{
  "type": "replacement",
  "configuration": {
    "original": "////",
    "replacement": "//",
    "id": "cStyleReduceComment",
  },
}
```

Note that the `id` in the replacement configurations correspond to the actions in the conditional configuration. This is what ties them together - it causes the replacements to be activated / deactivated when the actionable tokens are in / out of scope.

Let's look at a specific example of a template file being processed by this configuration, and see what happens:

```
...
//#if (A)
  // comment related to the 'if' content
  default content // also appropriate if A is true
////#elseif (B)
  //// comment related to the 'elseif' content
  //content for when B is true and A is false
////#else
  // comment related to the 'else' content
  // content for when both A & B are false
//#endif
...
```

There are 4 possible scenarios for when this appears in a template file.

1) No appropriate conditional processing. In this case, the entire block above will be copied to the created template as-is. This includes all the commenting, i.e.:
```
//#if (A)
  // comment related to the 'if' content
  default content // also appropriate if A is true
////#elseif (B)
  //// comment related to the 'elseif' content
  //content for when B is true and A is false
////#else
  //// comment related to the 'else' content
  // content for when both A & B are false
//#endif
```
which means only the default content under the 'if' will be interpreted in the created template.

2) A is `true`

Because the conditional token `//#if` was specified in the conditional configuration as an `if` token (as opposed to an `actionableIf` token), the `actions` operations are not activated, so no commenting will change. Thus, the lines between the `//#if` and the `/#elseif` is the only part emitted to the created template, i.e.:
```
  // comment related to the 'if' content
  default content // also appropriate if A is true
```

3) B is true (A is false)

The `elseif` predicate is `true`, so only content under the elseif will be emitted to the created template. But `////#elseif` is an actionable token, so the `actions` operations get activated, resulting in this text to be output:
```
  // comment related to the 'elseif' content
  content for when B is true and A is false
```
Note the comment changes from the original text - they're a results of the other 'actions'.

4) Both A & B are false
 
 The else should happen. Note that `////#else` is an actionable token, resulting in this text to be output:
```
  // comment related to the 'else' content
    content for when both A & B are false
```

For more details, refer to [Conditional processing](Conditional-processing-and-comment-syntax.md) article.

---

### Documentation TemplateEngine Reserved Aliases (`documentation/TemplateEngine/Reserved-Aliases.md`)

### Reference for dotnetcli.host.json
In `dotnet new` the parameter symbols are exposed as additional template options that can be passed to the command. Generally, `dotnet new` uses the name of parameter symbol to generate the long and the short alias for the option:
- The long alias is a parameter symbol name with `--` prefix.
- The short alias is a parameter symbol name first character with `-` prefix.

Note that the aliases are case sensitive.

With `dotnetcli.host.json` file we can change long alias and short alias of the template option and its visibility. `dotnetcli.host.json` is located at the same directory as template.json file. It has the following configuration:
- `symbolsInfo`  
It has a collection of the name of specified parameter symbol in template.json with corresponding long or short aliases to override original ones and the visibility of the template option.  
   - `longName` - overrides the long alias for the parameter symbol.
   - `shortName` - overrides the short alias for the parameter symbol. Empty means short alias should not be used.
   - `isHidden` - `true` if the parameter should be hidden in `dotnet new`.
- `usageExamples` - not used; see [#3262](https://github.com/dotnet/templating/issues/3262) for more details.

In case when option assignment results in duplicate options, `--param:` prefix is used for the long alias and short alias is generated from the beginning of the symbol's name till the one which can form a unique short name with `-` prefix or `-p:` prefix is used.

##### Examples
##### Example 1
Overrides original long alias `--TargetFrameworkOverride` with `--targetframework` and overrides short alias `-T` with `-tf`.
```
{
  "$schema": "http://json.schemastore.org/dotnetcli.host",
  "symbolInfo": {
    "TargetFrameworkOverride": {
      "longName": "targetframework",
      "shortName": "tf"
    }
  }
}
```
Part of the output of `dotnet new <template shortName> --help` looks like:
```
Template options:
  -tf, --targetframework <net7.0|net6.0|...>  Overrides the target framework.
```

##### Example 2
Parameter `TargetFrameworkOverride` is hidden from `dotnet new` help information.
```
{
  "$schema": "http://json.schemastore.org/dotnetcli.host",
  "symbolInfo": {
    "TargetFrameworkOverride": {
      "isHidden": "true"
    }
  }
}
```

##### Example 3
If short name is not specified, short name is the first character of overridden long name. Long alias is `--targetframework` and short alias is `-t`.
```
{
  "$schema": "http://json.schemastore.org/dotnetcli.host",
  "symbolInfo": {
    "TargetFrameworkOverride": {
      "longName": "targetframework"
    }
  }
}
```

##### Example 4
If short name is empty, there is no short alias for the template option. Long alias is `--targetframework`.
```
{
  "$schema": "http://json.schemastore.org/dotnetcli.host",
  "symbolInfo": {
    "TargetFrameworkOverride": {
      "longName": "targetframework",
      "shortName": ""
    }
  }
}
```
Part of the output of `dotnet new <template shortName> --help` looks like:
```
Template options:
  --targetframework <net7.0|net6.0|...>  Overrides the target framework.
```

##### Example 5
If long/short alias from overridden long/short name is reserved alias, long name will be prefixed with `--param:` and short name will be prefixed with `-p:` instead. Here long alias is `--param:package` and short alias is `-p:i`. See [Reserved Aliases](#reserved-aliases).
```
{
  "$schema": "http://json.schemastore.org/dotnetcli.host",
  "symbolInfo": {
    "pack": {
      "longName": "package",
      "shortName": "i"
    }
  }
}
```

##### Example 6
Assuming `template.json` has the symbols below.
```
  "symbols": {
    "TargetFrameworkOverride": {
      "type": "parameter",
      "description": "Overrides the target framework.",
      "dataType": "string",
      "defaultValue": "net7.0"
    },
    "targetframework": {
      "type": "parameter",
      "description": "The target framework for the project.",
      "dataType": "string",
      "defaultValue": "net6.0"
    }
  }
```
With the following `dotnetcli.host.json`, long alias and short alias of symbol `TargetFrameworkOverride` is `--targetframework` and `-t`. For symbol `targetframework`, since aliases `--targetframework` `-t` are already taken its long alias is prefixed with `--param:` to be `--param:targetframework` and short alias is `-ta`.
```
{
  "$schema": "http://json.schemastore.org/dotnetcli.host",
  "symbolInfo": {
    "TargetFrameworkOverride": {
      "longName": "targetframework"
    }
  }
}
```
Part of the output of `dotnet new <template shortName> --help` looks like:
```
Template options:
  -t, --targetframework <net7.0>  Overrides the target framework.
  -ta, --param:targetframework <net6.0>  The target framework for the project.
```

### Reserved Aliases
The following are [reserved aliases](#list-of-reserved-aliases) in `dotnet new`. They are applied to .NET SDK 7+.

If long alias is reserved alias, long name will be prefixed with `--param:` instead.  
If short alias is reserved alias, short name will be prefixed with `-p:` instead.  
##### Example
    "symbols": {
        "package": {
           "description": "A sample symbol for --package is reserved.",
           "type": "parameter",
           "defaultValue": "This is the default value for package."
        },
         "u": {
            "description": "A sample symbol for -u is reserved.",
            "type": "parameter",
            "defaultValue": "This is the default value for u."
         }
    }
When instantiating the template, for symbol `package` the template option is **`--param:package`** , and `-p` for short.
For symbol `u` the template option is `--u`, and **`-p:u`** for short.

#### List of reserved aliases
|Alias|Description|
|-|-|
|create|Instantiates a template with given short name.|
|install<br/>--install<br/>-i|Installs a template package.|
|uninstall<br/>--uninstall<br/>-u|Uninstalls a template package.|
|update<br/>--update-check|Checks the currently installed template packages for update, and install the updates.|
|search<br/>--search|Searches for the templates on NuGet.org.|
|list<br/>--list<br/>-l|Lists templates containing the specified template name. If no name is specified, lists all templates.|
|alias|Creates or displays defined aliases.|
|-o<br/>--output|Location to place the generated output.|
|-n<br/>--name|The name for the output being created. If no name is specified, the name of the output directory is used.|
|--dry-run|Displays a summary of what would happen if the given command line were run if it would result in a template creation.|
|--force|Forces content to be generated even if it would change existing files.|
|--no-update-check|Disables checking for the template package updates when instantiating a template.|
|--type|Specifies the template type to instantiate.|
|--author|Filters the templates based on the template author.|
|--baseline|Filters the templates based on baseline defined in the template.|
|--language<br/>-lang|Filters templates based on language.|
|--tag|Filters the templates based on the tag.|
|--package|Filters the templates based on NuGet package ID.|
|--interactive|Allows the command to stop and wait for user input or action (for example to complete authentication).|
|--add-source<br/>--nuget-source|Specifies a NuGet source to use during install.|
|--columns-all|Display all columns in the output.|
|--columns|Specifies the columns to display in the output. |
|--debug:custom-hive|Sets custom settings location.|
|--debug:ephemeral-hive<br/>--debug:virtual-hive|If specified, the settings will be not preserved on file system.|
|--debug:attach|Allows to pause execution in order to attach to the process for debug purposes.|
|--debug:reinit|If specified, resets the settings prior to command execution.|
|--debug:rebuild-cache<br/>--debug:rebuildcache|If specified, removes the template cache prior to command execution.|
|--debug:show-config<br/>--debug:showconfig|If specified, shows the template engine config prior to command execution.|
|--project|The project that should be used for context evaluation.|
|--debug:disable-sdk-templates|If present, prevents templates bundled in the SDK from being presented.|
|--debug:disable-project-context|Disables evaluating project context using MSBuild.|
|--update-apply|Checks the currently installed template packages for updates.|
|--alias<br/>-a|Creates an alias for instantiate command with a certain set of arguments.|
|--show-alias|Displays defined aliases.|
|-h<br/>/h<br/>--help<br/>-?<br/>/?|Show command line help.|

---

### Documentation TemplateEngine Using Group Identity (`documentation/TemplateEngine/Using-Group-Identity.md`)

# Using group identity

## What is group identity

Template configuration features optional `groupIdentity` property.  From `template.json` documentation, `groupIdentity` is the ID of the group this template belongs to. This allows multiple templates to be displayed as one, with the decision for which one to use based on the template options.

It depends on template engine host implementation how `groupIdentity` is implemented. In this article, the implementation for dotnet CLI (`dotnet new`) will be explained. 

When developing the template, **it is important to create unique group identity to avoid clashes with other templates**.

The are 2 typical use cases for using `groupIdentity`:

- grouping the templates for different languages under the same short name 

Example: the console template for different languages
```
> dotnet new list console
These templates matched your input: 'console'

Template Name             Short Name    Language    Tags
------------------------  ------------  ----------  -----------------
Console App               console       [C#],F#,VB  Common/Console

```

- grouping the several templates under the same group identity that adds up different choice parameters to base template. The most known example for this use case is having `Framework` choice symbol listing supported frameworks for the template and implementing each supported framework in separate template. This also allows distributing different templates in different template packages if needed. 

When using groups, it is important to mention two other important properties from template configuration to pay attention too:
- `identity` - the template identity. **All the templates, including the individual templates in the template group, should have unique `identity`.**
- `precedence` - an integer value used to determine the precedence of this template among the other templates within the same group identity. The highest value is the preferred one. It is recommended to have different precedence values in all the templates in a group to avoid clashes during template resolution.

## Use case #1: how to use group identity to group templates for different languages

This is the most typical scenario for template groups. The example is a well-known console template. 
The template can be defined for only one language, however in dotnet CLI we often see the templates for multiple languages as:
```
> dotnet new list console
These templates matched your input: 'console'

Template Name             Short Name    Language    Tags
------------------------  ------------  ----------  -----------------
Console App               console       [C#],F#,VB  Common/Console

```
Typically, these are 3 individual templates put in the same template group.
You can see definition for this particular template here: [C# template](https://github.com/dotnet/sdk/tree/main/template_feed/Microsoft.DotNet.Common.ProjectTemplates.8.0/content/ConsoleApplication-CSharp), [F# template](https://github.com/dotnet/sdk/tree/main/template_feed/Microsoft.DotNet.Common.ProjectTemplates.8.0/content/ConsoleApplication-FSharp), [VB template](https://github.com/dotnet/sdk/tree/main/template_feed/Microsoft.DotNet.Common.ProjectTemplates.8.0/content/ConsoleApplication-VisualBasic).

To define a similar scenario, you need the following configuration for your templates defined in template.json:

C# template:
```json
  "author": "Me",
  "classifications": [
    "Common",
    "Library"
  ],
  "name": "My Awesome Template",
  "groupIdentity": "My.Awesome.Template.GroupID",
  "precedence": "100",
  "identity": "My.Awesome.Template.CSharp.1.0",
  "shortName": "awesome",
  "tags": {
    "language": "C#",
  },

```
F# template:
```json
  "author": "Me",
  "classifications": [
    "Common",
    "Library"
  ],
  "name": "My Awesome Template",
  "groupIdentity": "My.Awesome.Template.GroupID",
  "precedence": "100",
  "identity": "My.Awesome.Template.FSharp.1.0",
  "shortName": "awesome",
  "tags": {
    "language": "F#",
  },

```
VB template:
```json
  "author": "Me",
  "classifications": [
    "Common",
    "Library"
  ],
  "name": "My Awesome Template",
  "groupIdentity": "My.Awesome.Template.GroupID",
  "precedence": "100",
  "identity": "My.Awesome.Template.VB.1.0",
  "shortName": "awesome",
  "tags": {
    "language": "VB",
  },

```

With this configuration, after installed those templates will be shown in as
```
> dotnet new list awesome
These templates matched your input: 'awesome'

Template Name             Short Name    Language    Tags
------------------------  ------------  ----------  -----------------
My Awesome Template       awesome       [C#],F#,VB  Common/Library

```

The usage for those templates will be:
- `dotnet new awesome` - C# template will be run (as C# is default language)
- `dotnet new awesome --language F#` - F# template will be run
- `dotnet new awesome --language VB` - VB template will be run
- `dotnet new awesome --help` - the help for C# template will be shown (as C# is default language)
- `dotnet new awesome --help --language F#` - the help for F# template will be shown
- `dotnet new awesome --help --language VB` - the help for VB template will be shown

The templates in a group may be distributed via multiple template packages. This means that the author is usually able to define the new template for another language and group them with existing or default ones (if the author knows the group identity).

This means for previous example another author may define a different template for different language:
```json
  "author": "You",
  "classifications": [
    "Common"
  ],
  "name": "My Awesome Template",
  "groupIdentity": "My.Awesome.Template.GroupID",
  "precedence": "100",
  "identity": "My.Awesome.Template.Cust.1.0",
  "shortName": "awesome",
  "tags": {
    "language": "Cust",
  },

```
After new template is installed, it will be grouped together with templates:
```
Template Name             Short Name    Language    Author      Tags
------------------------  ------------  ----------  ----------  -----------------
My Awesome Template       awesome       [C#],F#,VB  Me          Common/Library
                                        Cust        You         Common
```


## Use case #2: how to use group identity to group templates with different choices in choice symbol

This is more advanced scenario for the grouping, and it is not visible in dotnet CLI for final user. Microsoft templates are using this scenario to split the templates for different target frameworks for the following reasons:
- so they can be distributed separately
- the templates for different target frameworks may differ a lot. Defining them in a separate template makes the template definition easier.

Console template is also one of such templates. You can see definition here: [8.0 C# template](https://github.com/dotnet/sdk/tree/main/template_feed/Microsoft.DotNet.Common.ProjectTemplates.8.0/content/ConsoleApplication-CSharp), [7.0 C# template](https://github.com/dotnet/sdk/tree/release/7.0.1xx/template_feed/Microsoft.DotNet.Common.ProjectTemplates.7.0/content/ConsoleApplication-CSharp).

To define a similar scenario, you need the following configuration for your templates defined in template.json:
.NET 8.0 C# template:
```json
  "author": "Me",
  "classifications": [
    "Common",
    "Library"
  ],
  "name": "My Awesome Template",
  "groupIdentity": "My.Awesome.Template.GroupID",
  "precedence": "800",
  "identity": "My.Awesome.Template.CSharp.8.0",
  "shortName": "awesome",
  "tags": {
    "language": "C#",
  },
  "symbols": {
    "Framework": {
        "type": "parameter",
        "description": "The target framework for the project.",
        "datatype": "choice",
        "choices": [
        {
            "choice": "net8.0",
            "description": "Target net8.0",
            "displayName": ".NET 8.0"
        }
        ],
        "replaces": "net8.0",
        "defaultValue": "net8.0",
        "displayName": "Framework"
    },
  }
```
.NET 7.0 C# template:
```json
  "author": "Me",
  "classifications": [
    "Common",
    "Library"
  ],
  "name": "My Awesome Template",
  "groupIdentity": "My.Awesome.Template.GroupID",
  "precedence": "700",
  "identity": "My.Awesome.Template.CSharp.7.0",
  "shortName": "awesome",
  "tags": {
    "language": "C#",
  },
  "symbols": {
    "Framework": {
        "type": "parameter",
        "description": "The target framework for the project.",
        "datatype": "choice",
        "choices": [
        {
            "choice": "net7.0",
            "description": "Target net7.0",
            "displayName": ".NET 7.0"
        }
        ],
        "replaces": "net7.0",
        "defaultValue": "net7.0",
        "displayName": "Framework"
    },
  }
```

Note:
- these configurations have different precedence values, so in case `Framework` parameter is not specified, the .NET 8.0 template is run
- these configurations have same choice symbol `Framework` defined, and they have different choice values.

With this configuration, after installed those templates will be shown in as
```
> dotnet new list awesome
These templates matched your input: 'awesome'

Template Name             Short Name    Language    Tags
------------------------  ------------  ----------  -----------------
My Awesome Template       awesome       [C#]        Common/Library

```
Note, there is no indication that group contains 2 templates.


The usage for those templates will be:
- `dotnet new awesome` - .NET 8 template is run, as its precedence is higher.
- `dotnet new awesome --Framework net8.0` - .NET 8 template is run (same as above)
- `dotnet new awesome --Framework net7.0` - .NET 7 template is run.
- `dotnet new awesome --Framework net6.0` - this is error, as net6.0 choice is not defined.

Note difference in showing help:
- `dotnet new awesome --help` - the combined help for both templates will be shown
```
...
Template options:
  -Framework <net8.0|net7.0>     The target framework for the project.
                                 Type: choice
                                    net8.0  Target net8.0
                                    net7.0  Target net7.0
                                 Default: net8.0
...
```

Note down:
- in case the templates have different parameter symbols defined, all of them are shown in help
- the choice parameters contain combined choices from all the templates in the group (here, net8.0 from 1st template. net7.0 from 2nd template)
- the help is shown always for a particular template language. If you are combining this use case with use case #1 (grouping for different language), only the templates for selected language are combined when the help is shown.

**When using this use case, it is very important to configure different precedence values in the template definition for all the templates in single template group. If any combination of template options results in more than one template resolved and their precedence values are not specified, or are the same, this combination is unusable and results in runtime error.**

## Links
- [Reference for `template.json`](Reference-for-template.json.md)
- [`template.json` JSON schema](https://json.schemastore.org/template.json)
- [Template resolution for `dotnet new`](./template-resolution-for-dotnet-cli.md)
- Open issues:
  - [#5358 Allow share template name for different languages](https://github.com/dotnet/templating/issues/5358)
  - [#5844 Item templates should pick correct language from project](https://github.com/dotnet/templating/issues/5844)
  - [#4135 Allow to pick up certain template group or certain template to be run in case of ambiguity](https://github.com/dotnet/templating/issues/4135)

---

### Documentation TemplateEngine Using Primary Outputs For Post Actions (`documentation/TemplateEngine/Using-Primary-Outputs-for-Post-Actions.md`)

## Primary outputs
Primary outputs define the list of template files for further processing. 
The primary outputs are returned by template engine API after template instantiation (`Microsoft.TemplateEngine.IDE.Bootstrapper.CreateAsync`, `Microsoft.TemplateEngine.Edge.Template.TemplateCreator.InstantiateAsync`) or dry run (`Microsoft.TemplateEngine.IDE.Bootstrapper.GetCreationEffectsAsync`).
The main use for primary outputs is to provide the list of files to perform post actions implemented by the host. dotnet CLI host and Visual Studio host implement the default set of post actions based on primary outputs returned by API, described in [post-action registry](Post-Action-Registry.md). In case the template files have to be used in post actions, they should be added as the primary outputs in `template.json` definition.

The template can define any number of primary outputs. Each primary output contains the following information:
- `path` - the path should contain the relative path to the file after template instantiation is done and prior to symbol based renaming is applied.
- `condition` - if the condition evaluates to `true`, the corresponding path will be added to primary outputs, if `false`, the path is ignored. If no condition is provided for a path, the condition defaults to `true`.

Basic example:

template files:
- `MyTestProject.csproj`
- `Class.cs`

`template.json` definition
```
{
  "author": "Test Asset",
  "classifications": [ "Test Asset" ],
  "name": "BasicTemplate",
  "generatorVersions": "[1.0.0.0-*)",
  "groupIdentity": "TestAssets.BasicTemplate",
  "precedence": "100",
  "identity": "TestAssets.BasicTemplate",
  "shortName": "TestAssets.BasicTemplate",
  "tags": {
    "language": "C#",
    "type": "project"
  },
  "sourceName": "MyTestProject",
  "primaryOutputs": [
    {
      "path": "MyTestProject.csproj"        
    }
  ],
  "postActions": [
    {
      "description": "Restore NuGet packages required by this project.",
      "manualInstructions": [
        { "text": "Run 'dotnet restore'" }
      ],
      "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025",
      "continueOnError": true,
      "args": {
        "files": [ "MyTestProject.csproj" ]
      }
    }
  ]
}
```
Note that the example above contains primary output with original name. The actual primary output returned by API, will contain the final file name after renames are applied.
Example:
```
dotnet new TestAssets.BasicTemplate --name Awesome 
```
The primary output returned by API is `Awesome.csproj` and actual file produced is `Awesome.csproj`.

## Using primary outputs with source modifiers
Source modifiers defined in `template.json` can override source or target location during template instantiation, or rename files during instantiation. It is important that primary outputs are specified correctly in combination with source modifiers.

### Changing source
When changing the source, make sure that primary output path contains final location of the file after instantiation relative to default target path (`./`)
Example:
template files:
- `./Custom/Path/MyTestProject.csproj`
- `./Custom/Path/Class.cs`

`template.json` definition
```
{
  "author": "Test Asset",
  "classifications": [ "Test Asset" ],
  "name": "TemplateWithSourceNameAndCustomSourcePath",
  "generatorVersions": "[1.0.0.0-*)",
  "groupIdentity": "TestAssets.TemplateWithSourceNameAndCustomSourcePath",
  "precedence": "100",
  "identity": "TestAssets.TemplateWithSourceNameAndCustomSourcePath",
  "shortName": "TestAssets.TemplateWithSourceNameAndCustomSourcePath",
  "sourceName": "MyTestProject",
  "sources": [
    {
      "source": "./Custom/Path/"
    }
  ],
  "primaryOutputs": [
    {
      "path": "MyTestProject.csproj"        
    }
  ],
  "postActions": [
    {
      "description": "Restore NuGet packages required by this project.",
      "manualInstructions": [
        { "text": "Run 'dotnet restore'" }
      ],
      "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025",
      "continueOnError": true,
      "args": {
        "files": [ "./Custom/Path/MyTestProject.csproj" ]
      }
    }
  ]
}
```
Note that the example above contains primary output with original name in the final location. The actual primary output returned by API, will contain the final file name after renames are applied.
Post action `files` should contain the original location in template definition.
Example:
```
dotnet new TestAssets.TemplateWithSourceNameAndCustomSourcePath --name Awesome 
```
The primary output returned by API is: `Awesome.csproj`.
The final location of the files is: 
- `./Awesome.csproj`
- `./Class.cs`

### Changing target
When changing the target for template instantiation, make sure that primary output path contains final location of the file after instantiation including target path.
Example:
template files:
- `MyTestProject.csproj`
- `Class.cs`

`template.json` definition
```
{
  "author": "Test Asset",
  "classifications": [ "Test Asset" ],
  "name": "TemplateWithSourceNameAndCustomTargetPath",
  "generatorVersions": "[1.0.0.0-*)",
  "groupIdentity": "TestAssets.TemplateWithSourceNameAndCustomTargetPath",
  "precedence": "100",
  "identity": "TestAssets.TemplateWithSourceNameAndCustomTargetPath",
  "shortName": "TestAssets.TemplateWithSourceNameAndCustomTargetPath",
  "sourceName": "MyTestProject",
  "sources": [
    {
      "target": "./Custom/Path/"
    }
  ],
  "primaryOutputs": [
    {
      "path": "./Custom/Path/MyTestProject.csproj"        
    }
  ],
  "postActions": [
    {
      "description": "Restore NuGet packages required by this project.",
      "manualInstructions": [
        { "text": "Run 'dotnet restore'" }
      ],
      "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025",
      "continueOnError": true,
      "args": {
        "files": [ "MyTestProject.csproj" ]
      }
    }
  ]
}
```
Note that the example above contains primary output with original name in the final location. The actual primary output returned by API, will contain the final file name after renames are applied.
`files` argument should contain the original location in template definition.
Example:
```
dotnet new TestAssets.TemplateWithSourceNameAndCustomTargetPath --name Awesome 
```
The primary output returned by API is: `/Custom/Path/Awesome.csproj`.
The final location of the files is: 
- `./Custom/Path/Awesome.csproj`
- `./Custom/Path/Class.cs`

### Changing source and target
When changing both source and target for template instantiation, make sure that primary output path contains final location of the file after instantiation including target path.
Example:
template files:
- `./Src/Custom/Path/MyTestProject.csproj`
- `./Src/Custom/Path/Class.cs`

`template.json` definition
```
{
  "author": "Test Asset",
  "classifications": [ "Test Asset" ],
  "name": "TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "generatorVersions": "[1.0.0.0-*)",
  "groupIdentity": "TestAssets.TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "precedence": "100",
  "identity": "TestAssets.TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "shortName": "TestAssets.TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "sourceName": "MyTestProject",
  "sources": [
    {
      "source": "./Src/Custom/Path/",
      "target": "./Target/Output/"
    }
  ],
  "primaryOutputs": [
    {
      "path": "./Target/Output/MyTestProject.csproj"        
    }
  ],
  "postActions": [
    {
      "description": "Restore NuGet packages required by this project.",
      "manualInstructions": [
        { "text": "Run 'dotnet restore'" }
      ],
      "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025",
      "continueOnError": true,
      "args": {
        "files": [ "./Src/Custom/Path/MyTestProject.csproj" ]
      }
    }
  ]
}
```
Note that the example above contains primary output with original name in the final location. The actual primary output returned by API, will contain the final file name after renames are applied.
Post action `files` should contain the original location in template definition.
Example:
```
dotnet new TestAssets.TemplateWithSourceNameAndCustomSourceAndTargetPaths --name Awesome 
```
The primary output returned by API is: `Target/Output/Awesome.csproj`.
The final location of the files is: 
- `./Target/Output/Awesome.csproj,`
- `./Target/Output/Class.cs`

### Renaming
When using renames in source modifiers, make sure that primary output path contains the filename after source based file rename is applied, however before symbol based renames are applied.
Example:
template files:
- `MyTestProject.csproj`

`template.json` definition
```
{
  "author": "Test Asset",
  "classifications": [ "Test Asset" ],
  "name": "TemplateWithSourceBasedRenames",
  "generatorVersions": "[1.0.0.0-*)",
  "groupIdentity": "TestAssets.TemplateWithSourceBasedRenames",
  "precedence": "100",
  "identity": "TestAssets.TemplateWithSourceBasedRenames",
  "shortName": "TestAssets.TemplateWithSourceBasedRenames",
  "sourceName": "foo",
  "sources": [
    {
      "rename": {
        "MyTestProject.csproj": "MyFirstTestProject.csproj"
      }
    }
  ],
  "symbols": {
    "firstRename": {
      "type": "parameter",
      "dataType": "string",
      "fileRename": "First"
    }
  },
  "primaryOutputs": [
    {
      "path": "MyFirstTestProject.csproj"
    }
  ],
  "postActions": [
    {
      "description": "Restore NuGet packages required by this project.",
      "manualInstructions": [
        { "text": "Run 'dotnet restore'" }
      ],
      "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025",
      "continueOnError": true,
      "args": {
        "files": [ "MyTestProject.csproj" ]
      }
    }
  ]
}
```
Note that the example above contains primary output with name <b>after source based rename is applied</b>. The actual primary output returned by API, contains the final file name after symbol based renames are applied. Post action `files` should contain the original location in template definition.
Example:
```
dotnet new TestAssets.TemplateWithSourceBasedRenames --firstRename Awesome 
```
The primary output returned by API is: `MyAwesomeTestProject.csproj`.
The final location of the files is: `./MyAwesomeTestProject.csproj`.


# Different ways of using primary outputs in post actions

Post actions support different ways of choosing the files to process, for more details see the documentation for specific post action.

## Example 1 - apply post action to all primary outputs
The following example restores the projects mentioned in primary outputs:
template files:
- `./Custom/MyTestProject/MyTestProject.csproj`
- `./Custom/MyTestProject/Class.cs`
- `./Custom/MyTestProject.Tests/MyTestProject.Tests.csproj`
- `./Custom/MyTestProject.Tests/Class.cs`

`template.json` definition
```
{
  "author": "Test Asset",
  "classifications": [ "Test Asset" ],
  "name": "TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "generatorVersions": "[1.0.0.0-*)",
  "groupIdentity": "TestAssets.TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "precedence": "100",
  "identity": "TestAssets.TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "shortName": "TestAssets.TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "sourceName": "MyTestProject",
  "sources": [
    {
      "source": "./Custom/MyTestProject/",
      "target": "./src/MyTestProject/"
    },
    {
      "source": "./Custom/MyTestProject.Tests/",
      "target": "./test/MyTestProject.Tests/"
    },
  ],
  "primaryOutputs": [
    {
      "path": "./src/MyTestProject/MyTestProject.csproj"        
    }
  ],
  "postActions": [
    {
      "description": "Restore NuGet packages required by this project.",
      "manualInstructions": [
        { "text": "Run 'dotnet restore'" }
      ],
      "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025",
      "continueOnError": true,
    }
  ]
}
```

## Example 2 - reference source files in post action arguments
The following example restores individual project specified in `files` property. Defining them in primary outputs is optional.
template files:
- `./Custom/MyTestProject/MyTestProject.csproj`
- `./Custom/MyTestProject/Class.cs`
- `./Custom/MyTestProject.Tests/MyTestProject.Tests.csproj`
- `./Custom/MyTestProject.Tests/Class.cs`

`template.json` definition
```
{
  "author": "Test Asset",
  "classifications": [ "Test Asset" ],
  "name": "TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "generatorVersions": "[1.0.0.0-*)",
  "groupIdentity": "TestAssets.TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "precedence": "100",
  "identity": "TestAssets.TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "shortName": "TestAssets.TemplateWithSourceNameAndCustomSourceAndTargetPaths",
  "sourceName": "MyTestProject",
  "sources": [
    {
      "source": "./Custom/MyTestProject/",
      "target": "./src/MyTestProject/"
    },
    {
      "source": "./Custom/MyTestProject.Tests/",
      "target": "./test/MyTestProject.Tests/"
    },
  ],

  "postActions": [
    {
      "description": "Restore NuGet packages required by this project.",
      "manualInstructions": [
        { "text": "Run 'dotnet restore'" }
      ],
      "actionId": "210D431B-A78B-4D2F-B762-4ED3E3EA9025",
      "continueOnError": true,
      "args": {
        "files": [ "./Custom/MyTestProject/MyTestProject.csproj" ]  //here the source location should be used as the post action supports this notation
      }
    }
  ]
}
```
Specifying files in post action arguments is supported by:
- restore NuGet packages (dotnet CLI) - `files` argument
- add reference to a project file (dotnet CLI) - `targetFiles` argument 
- add project(s) to a solution file (dotnet CLI) - `projectFiles` argument 

## Example 3 - using primary output indexes in post action arguments

Opens the file from primary outputs defined by index.

`template.json` definition:
```
"primaryOutputs": [
  { "path": "Company.ClassLibrary1.csproj" },
  { "path": "Class1.cs" }
],
"postActions": [
  {
    "description": "Opens Class1.cs in the editor",
    "manualInstructions": [ ],
    "actionId": "84C0DA21-51C8-4541-9940-6CA19AF04EE6",
    "args": {
      "files": "1"
    },
    "continueOnError": true
  }
]
```

Using indexes in post action arguments is supported by:
- open a file in the editor (Visual Studio)

---

### Documentation TemplateEngine Value Forms (`documentation/TemplateEngine/Value-Forms.md`)

# Value forms

## Overview

At a high level, value forms allow the specification of a "replaces"/"replacement" pair to also apply to other ways the "replaces" value may have been specified in the source by specifying a transform from the original value of "replaces" in configuration to the one that may be found in the source.


*Example*

In my source, the value `"Hi there"` should be replaced by a user supplied value, but, `&quot;Hi there&quot;` should be as well. The user value should be XML encoded for the latter and not for the former. The below snippet from template.json shows how to accomplish this.

```json
{
  ...
  "symbols": {
    "example": {
      "type": "parameter",
      "dataType": "string",
      "replaces": "\"Hi there\"",
      "forms": {
        "global": [ "encode" ]
      }
    }
  },
  "forms": {
    "encode": {
      "identifier": "xmlEncode"
    }
  }
}
```

The `forms` section (peer to `symbols`) defines the set of transforms that can be referenced by symbol definitions. In the symbol called `example`, the entry from the `forms` section is referenced for all file patterns (the property `global` indicates that the transform should be included everywhere).

When the value say, `Test ©` is supplied as the value for the parameter `example`, two replacements get set up:
1) `"Hi There"` -> `Test ©`
2) `&quot;Hi There&quot;` -> `Test &copy;`

## Available transforms:

**`replace`**   - Performs a replacement with regular expressions
```json
"forms": {
    "dotToUnderscore": {
      "identifier": "replace",
      "pattern": "\\.",        // A regular expression matching the characters to replace
      "replacement": "_"       // The replacement for the matched characters
    }
}
```

**`chain`**     - Performs multiple transformations
```json
"forms": {
    "chained": {
      "identifier": "chain",
      "steps": [ "dotToUnderscore", "digitToBang" ]  // An array of names of other transformations (applied in the order they appear in the array)
    },
}
```

**`xmlEncode`** - XML encodes a value
```json
"forms": {
    "encode": {
      "identifier": "xmlEncode"
    }
}
```

**`lowerCase`** - Converts the letters of the value to lowercase using the casing rules of the current culture.
```json
"forms": {
    "lc": {
      "identifier": "lowerCase"
    }
}
```

**`lowerCaseInvariant`** - Converts the letters of the value to lowercase using the casing rules of the invariant culture.
```json
"forms": {
    "lc": {
      "identifier": "lowerCaseInvariant"
    }
}
```

**`upperCase`** - Converts the letters of the value to uppercase using the casing rules of the current culture.
```json
"forms": {
    "uc": {
      "identifier": "upperCase"
    }
}
```

**`upperCaseInvariant`** - Converts the letters of the value to uppercase using the casing rules of the invariant culture.
```json
"forms": {
    "uc": {
      "identifier": "upperCaseInvariant"
    }
}
```

**`firstLowerCase`** - Converts the first letter of the value to lowercase using the casing rules of the current culture. Available since .NET 5.0.300.
```json
"forms": {
    "first_lc": {
      "identifier": "firstLowerCase"
    }
}
```

**`firstLowerCaseInvariant`** - Converts the first letter of the value to lowercase using the casing rules of the invariant culture. Available since .NET 5.0.300.
```json
"forms": {
    "first_lc": {
      "identifier": "firstLowerCaseInvariant"
    }
}
```

**`firstUpperCase`** - Converts the first letter of the value to uppercase using the casing rules of the current culture. Available since .NET 5.0.300.
```json
"forms": {
    "first_uc": {
      "identifier": "firstUpperCase"
    }
}
```

**`firstUpperCaseInvariant`** - Converts the first letter of the value to uppercase using the casing rules of the invariant culture. Available since .NET 5.0.300.
```json
    "forms": {
        "first_uc": {
          "identifier": "firstUpperCaseInvariant"
        }
    }
```

**`titleCase`** - Converts the value to title case using the casing rules of the current culture. See [TextInfo.ToTitleCase(String) documentation](https://docs.microsoft.com/dotnet/api/system.globalization.textinfo.totitlecase) for more details. Available since .NET 5.0.300.
```json
"forms": {
    "title": {
      "identifier": "titleCase"
    }
}
```

**`kebabCase`** - Converts the value to kebab case using the casing rules of the invariant culture. Available since .NET 5.0.300.
```json
"forms": {
    "kebab": {
      "identifier": "kebabCase"
    }
}
```

---

### Documentation TemplateEngine Template Resolution For Dotnet Cli (`documentation/TemplateEngine/template-resolution-for-dotnet-cli.md`)

# Template resolution for dotnet CLI

## Template resolution details

In dotnet new CLI, we use template groups in listings instead of individual
templates.

Template group is set of templates with same `groupIdentity` defined in
template.json. In case group identity is not set, the template is treated as
a template group on its own.

`dotnet new list` and `dotnet new search` show the list of template groups, not
all the templates.

Templates in a template group:
-   can have different languages (all the languages are shown in ‘Language’
    column in table listing)
-   can have different short names: in this case the short names can be equally used
    as synonyms in command input and will be shown in comma separated list in
    table listing.
-   are assumed to have the same type, name, author, and tags (classification). When
    showing the group, the information from the template with highest
    ‘precedence’ value will be shown; however, the template group will be
    considered as match if at least one template from the group is a match. For
    help and instantiating only the templates which match the given type and
    baseline will be considered.

When resolving the template to be shown/used:
-   first the template group is evaluated based on short name or name match.
    Name match/partial matches is only applicable for `list` and `search`.
-   when evaluating the template group, the supported languages are considered:
    if the template group has multiple languages defined and the user didn’t
    specify a language to use the default language (C\#) will be used. Otherwise
    the input results in error.
-   then the other matches of the group are evaluated based on the other
    template info filters (type, author, tag, baseline) and template specific
    parameters.
-   Starting with .NET SDK 7.0.100, the `list` command might not show all the templates installed on the machine. It takes the result of template constraints into account, and the templates that can't be used won't be shown. To force show all the templates, use the `--ignore-constraints` option.

In order to instantiate (create) the template, the command input should resolve
single template from single template group:
-   in case multiple template groups are resolved, it results in error.
-   in case of multiple templates within single template group are resolved, the
    precedence value from template.json will be used to determine the template
    to run. If the precedence value is not given or is the same for multiple
    templates, it results in error.

In order to show help for a template, the command input should resolve to a
single template group (based on short name). If the resolved group
contains multiple matching templates, they should have same language. In case of multiple templates,
the template parameters will be combined when displaying the help; the template
information will be taken from highest precedence template.

The command input for search and list may resolve multiple templates/template
groups: output is done in tabular format, where row corresponds to template
group.

## Instantiate template (dotnet new \<short name\>)

Argument (name) matching: exact short name
*Example:* `dotnet new console`

### Template info filters
-   Language
    -   If the user specified the language via `--language` option, the value should 
    exactly match the template language.
    -   If the template group has multiple languages defined, the default language
        is preferred
    -   If the template group has single language defined, this language is used

    -   *Example:* `dotnet new console --language F#`

-   Type
    -   Exact match on `--type` option
    -   *Example:* `dotnet new console --type project`

-   Baseline (hidden)
    -   Exact match on `--baseline` option
    -   *Example:* `dotnet new classlib --baseline standard`

### Template parameter filters

-   Exact match on parameter name
-   Exact match on parameter value
-   All required parameters should be specified.

-   *Example:* `dotnet new console --framework net7.0 --langVersion 9.0`

#### Error cases

**Invalid template parameter value (choice)**

```
> dotnet new console --framework invalid
Error: Invalid option(s):
--framework invalid
   'invalid' is not a valid value for --framework. The possible values are:
      net6.0          - Target net6.0
      net7.0          - Target net7.0
      netcoreapp3.1   - Target netcoreapp3.1

For more information, run:
   dotnet new console -h

For details on the exit code, refer to https://aka.ms/templating-exit-codes#127
```

**Invalid template parameter**

```
> dotnet new console --invalid
Error: Invalid option(s):
--invalid
   '--invalid' is not a valid option

For more information, run:
   dotnet new console -h

For details on the exit code, refer to https://aka.ms/templating-exit-codes#127
```

**Invalid language**

```
> dotnet new console --language invalid
No templates found matching: 'console', --language='invalid'.
Allowed values for '--language' option are: 'C#', 'F#', 'VB'.


For details on the exit code, refer to https://aka.ms/templating-exit-codes#103
```

**Combination of invalid parameters:**
```
> dotnet new console --language invalid --invalidParam
No templates found matching: 'console', --language='invalid'.
Allowed values for '--language' option are: 'C#', 'F#', 'VB'.


For details on the exit code, refer to https://aka.ms/templating-exit-codes#103
```

## List the templates (dotnet new list)

Argument (name) matching: exact or partial short name or name, optional.

*Example:* `dotnet new list`  
*Example:* `dotnet new list con`

### Template info filters

-   Language
    -   If user specified the language via `--language` option, only the template
        groups that match the language will be shown (exact match)
    -   The default language is not considered

    -   *Example:* `dotnet new list --language F#`
    -   *Example:* `dotnet new list con --language F#`

-   Type
    -   If user specified the type via `--type` option, only the template groups
        that match the type will be shown (exact match)

    -   *Example:* `dotnet new list --type project`
    -   *Example:* `dotnet new list con --type project`

-   Baseline (hidden)
    -   If user specified the baseline via `--baseline` option, only the template
        groups that match the baseline will be shown (exact match)

    -   *Example:* `dotnet new list --baseline standard`
    -   *Example:* `dotnet new list con --baseline standard`

-   Author
    -   If user specified the author via `--author` option, only the template
        groups that match the author will be shown (exact or partial match)

    -   *Example:* `dotnet new list --author Microsoft`
    -   *Example:* `dotnet new list con --author soft`

-   Tags
    -   If user specified the tag via `--tag` option, only the template groups
        that match the tag will be shown (exact match on single tag)

    -   *Example:* `dotnet new list --tag Common`
    -   *Example:* `dotnet new list con --tag Common`

### Template parameter filters

This feature is currently unsupported (support was removed with moving to a new command line parser) - but it's being [tracked](https://github.com/dotnet/templating/issues/4061)

### Error cases

#### No argument

**No match on language:**

```
dotnet new list --language invalid
No templates found matching: --language='invalid'.
73 template(s) partially matched, but failed on --language='invalid'.

To search for the templates on NuGet.org, run:
   dotnet new search [<template-name>]


For details on the exit code, refer to https://aka.ms/templating-exit-codes#103
```

### With argument

**No match on language:**

```
dotnet new list con --language invalid
No templates found matching: 'con', --language='invalid'.
17 template(s) partially matched, but failed on --language='invalid'.

To search for the templates on NuGet.org, run:
   dotnet new search con


For details on the exit code, refer to https://aka.ms/templating-exit-codes#103
```

## Search for the templates (dotnet new search)

Argument (name) matching: exact or partial (substring) short name or name. Optional if
filters applied.

*Example:* `dotnet new search con`

### Template info filters:

-   Language
    -   If user specified the language via `--language` option, only the template
        groups that match the language will be shown (exact match)
    -   The default language is not considered

    -   *Example:* `dotnet new search --language F#`
    -   *Example:* `dotnet new search con --language F#`

-   Type
    -   If user specified the type via `--type` option, only the template groups
        that match the type will be shown (exact match)

    -   *Example:* `dotnet new search --type project`
    -   *Example:* `dotnet new search con --type project`

-   Baseline (hidden)
    -   If user specified the baseline via `--baseline` option, only the template
        groups that match the baseline will be shown (exact match)

    -   *Example:* `dotnet new search --baseline standard`
    -   *Example:* `dotnet new search con --baseline standard`

-   Author
    -   If user specified the author via `--author` option, only the template
        groups that match the author will be shown (exact or partial match)

    -   *Example:* `dotnet new search --author Microsoft`
    -   *Example:* `dotnet new search con --author soft`

-   Tags
    -   If user specified the tag via `--tag` option, only the template groups
        that match the tag will be shown (exact match on single tag)

    -   *Example:* `dotnet new search --tag Common`
    -   *Example:* `dotnet new search con --tag Common`

-   Package name
    -   If user specified the package name via `--package` option, only the
        template groups that match the package name will be shown (exact or
        partial)

    -   *Example:* `dotnet new search --package Micro`
    -   *Example:* `dotnet new search con --package Micro`

### Template parameter filters

This feature is currently unsupported (support was removed with moving to a new command line parser) - but it's being [tracked](https://github.com/dotnet/templating/issues/4061)

### Error cases

#### No argument

**No match**
```
> dotnet new search --language invalid
Searching for the templates...
Matches from template source: NuGet.org
No templates found matching: --language='invalid'.


For details on the exit code, refer to https://aka.ms/templating-exit-codes#103
```


#### With argument
```
> dotnet new search con --language invalid
Searching for the templates...
Matches from template source: NuGet.org
No templates found matching: 'con', --language='invalid'.


For details on the exit code, refer to https://aka.ms/templating-exit-codes#103
```

## Template help (dotnet new \<short name\> [--help|-h])

Argument (name) matching: exact short name

*Example:* `dotnet new console -h`  
*Example:* `dotnet new console --help`

When instantiating a template, `--no-update-check` skips both NuGet update checks
and notices about newer or equal-version packages available from built-in providers,
including optional workloads. Installation-time guidance about a manually installed
package overriding a built-in package is unaffected.

### Template info filters

-   Language

    -   If user specified the language via `--language` option, should be exact
        match
    -   If the template group has multiple languages defined, default language
        is preferred
    -   If the template group has single language defined, this language is used
    -   *Example:* `dotnet new console -h --language F#`

-   Type

    -   Exact match on `--type` option
    -   *Example:* `dotnet new console -h --type project`

-   Baseline (hidden)

    -   Exact match on `--baseline` option
    -   *Example:* `dotnet new classlib -h --baseline standard`*`
    -   Applying baseline will also show parameters applied by baseline

```
/* Detailed source-code truncated for AI context efficiency. */
```

---

### Documentation General ExecutingCustomerCode (`documentation/general/ExecutingCustomerCode.md`)

# Executing Customer Code

## Summary

When customers discover issues with the .NET SDK, we often need more information to see how exactly their scenarios differ from the (presumably working) mainline scenarios. This additional information often takes the form of a 'repro' or set of steps by which we can see the error ourselves and walk through what is happening as their scenario plays out and how it ultimately diverged from our expectations.

Blindly executing, or even just opening in an IDE like Visual Studio without intending to build, unvetted customer code can be a security hazard, however, not just for the machine executing the code but for any machine on the same network and any service accessible using credentials they can access through those machines. In this way, a malicious actor can exfiltrate sensitive Microsoft data, including information about other Microsoft employees, proprietary code, or private customer data. They may even be able to take down a service or introduce further security bugs in shipping products. Indeed, the most common vector hackers use to gain access is through compromising one or more individual users with employee credentials. At Microsoft where security is paramount, we want to prevent such hacks.

This document contains recommended best practices on how to securely test users' code. They are arranged in order of security with the most secure at the top. This should also be the priority you should use to stay secure when executing code.

## Strategies for Staying Secure

### Binary Logs

MSBuild binary logs (binlogs) are structured data covering what happened during a build. Many operations that aren't obviously 'builds' such as publish (`dotnet publish`) or pack (`dotnet pack`) include building as part or all of the process, which makes them very useful for learning more about and potentially diagnosing a variety of potential problems. Furthermore, they are safe in the sense that analyzing a binlog does not expose your system to risks.

To provide information to customers about collecting binlogs, direct them to:
https://aka.ms/msbuild/binlog

It is important to note, however, that binlogs often collect secrets as part of the information relevant to the build. A binlog of a simplified repro can work as well, but it may be difficult to create a simple repro. Customers are sometimes concerned (with good reason) about sharing binlogs of their real (or simplified) builds. If so, they can attempt to redact secrets from their binlog, either via the [MSBuild Structured Log Viewer](https://msbuildlog.com/#redaction) or with [binlogtool](https://www.nuget.org/packages/binlogtool). If that isn't sufficient, or if the reported issue does not involve MSBuild, another option may be more relevant.

### Windows Sandbox

Windows Sandbox permits safely running any operation in a controlled, isolated environment where it will not affect your machine or Microsoft in any detrimental way. More information can be found [here](https://learn.microsoft.com/windows/security/application-security/application-isolation/windows-sandbox/windows-sandbox-overview). If the steps a customer provides for reproducing their scenario can be executed in Windows Sandbox, it is the safest place to do so. Unfortunately, Sandbox does come with a few notable downsides:
1. Windows Sandbox only exists for Windows. If a customer's scenario only reproduces on macOS or linux, it will not be able to be reproduced on Windows, and Sandbox is not helpful.
2. When Sandbox exits for any reason, all data is lost. This means, for instance, that if the computer hosting Sandbox restarts while Sandbox is open, any progress you might have made in putting together the customer's repro scenario is lost.
3. Sandbox is essentially empty when you first create it. It has internet access as long as your host computer has internet access, but it will be missing various programs and tools you may need to reproduce the customer's problem. Such programs and tools need to be downloaded anew every time you want to use Sandbox.

Conveniently, however, it is relatively easy to copy files from your host computer into Sandbox, and as noted earlier, it is a secure, isolated environment, so it is an excellent choice if it is viable.

Before executing customer code in Windows Sandbox, make sure to [disable networking](https://learn.microsoft.com/windows/security/application-security/application-isolation/windows-sandbox/windows-sandbox-configure-using-wsb-file#networking).

### Create Your Own Solution

Depending on how well you understand the customer's scenario, you may or may not understand ahead of time the most likely problem, but if it's possible to create your own solution that reproduces the issue the customer alluded to in their report, and you understand all the steps it took to create that solution, that is a safe method for obtaining a project to test and debug. Note that this is only a secure method if you understand all steps involved in creating the test project. "Copy project file provided by customer to disk and build it" does not count as a well-understood pair of steps.

### Create a Virtual Machine Without Your Credentials

Creating and using a virtual machine (VM) without your credentials is another secure way to test a customer's code, as it's disconnected from either your credentials or your computer. It is important if using this method to ensure that you do not give your VM your credentials at any point such as, for example, signing into your Microsoft account so you can use Visual Studio Enterprise.

The other disadvantage of this approach is that it can take a lot of time to select appropriate parameters for your VM, start it, connect to it, set it up properly for your scenario, and execute the scenario. Unlike Sandbox, it can retain certain information across restarts, but it may lose active work just as your computer loses active work when you restart it. It's important to keep in mind that many VMs restart automatically at a fixed time every day when not in use to save resources.

That said, this is a secure means for executing a customer's scenario, and it works for any operating system and can even be configured to work for other architectures. Note that using a VM in the cloud costs real money, though a local VM (such as using [Hyper-V](https://learn.microsoft.com/windows-server/virtualization/hyper-v/get-started/create-a-virtual-machine-in-hyper-v)) typically does not.

For Microsoft employees, [DevTestLab](https://ms.portal.azure.com/#browse/Microsoft.Compute%2FVirtualMachines) can help you create VMs.

### Read Code

If none of the above methods work, it may be viable to read all customer code carefully to ensure that no part of it is risky or malicious. Many IDEs such as Visual Studio automatically run design-time builds when code is open. As a result, even just opening a malicious code base in Visual Studio can lead to exploits. Prefer an IDE that does not run design-time builds. Some examples include:
1. Visual Studio Code (if no addons are installed)
2. Notepad
3. Emacs/Vim

Some examples of specific patterns to watch out for that can cause issues include:
1. PackageReferences. These download code from the internet and permit its execution locally. If you are unfamiliar with any package in a PackageReference, this is insecure.
2. MSBuild SDKs. At the top of many .NET projects is a line that includes `Sdk="<SDK>"`. This automatically imports build logic associated with the specified SDK. If you are unfamiliar with the specified SDK, ensure it is secure before building any code including it.
3. MSBuild tasks. Within a `Target` block are MSBuild Tasks. Many of these, including `Exec` and `DownloadFile` execute logic that pulls code or build logic from the internet and may execute it. If you are unfamiliar with any MSBuild Task in a customer-provided project, ensure you fully understand its semantics before executing it (by building).
4. Typos. NuGet packages starting with Microsoft. and System. can only be pushed to nuget.org by Microsoft accounts, but Mircosoft and Sysstem are unregulated.
5. Malicious NuGet.Config files. Even if a PackageReference points to a package you're familiar with, perhaps even a Microsoft. or System. package, a NuGet.Config file can dictate searching in a different package source first that may not be secure and may include a malicious version of the package.

More examples of patterns that can easily be exploited by malicious users can be found [here](https://aka.ms/msbuild-security-documentation)

In addition to those more specific examples, it is important to follow the principle of least privilege. This means, for instance, that when on linux, you should only run a command as root if that's truly necessary to reproduce the customer's scenario. On Windows, you should only use an admin terminal if it's necessary.

## Response to Malicious Repros

If you discover that a customer provided a malicious project or solution, there are several steps. You should do all of these if possible.

1. Most importantly, do not keep any vestige of the repro on your machine. Do not follow their steps.
2. Add a note to the issue that it was malicious. Include this information in the title if possible.
3. Delete the contents of the repro steps. (On GitHub, it can still be found by looking at your edit.)
4. Report the infraction using https://aka.ms/reportitnow (This step is only available to Microsoft employees.)
5. Report your finding to your manager and your security team.
6. Depending on the severity of the issue, consider banning the user from GitHub.

If you are external, you may not be able to follow all of these steps. Reach out to someone from our team to help facilitate doing all these.

Last but not least, thank you for helping keep Microsoft secure!

---

### Documentation General SelfContainedBreakingChangeNotification (`documentation/general/SelfContainedBreakingChangeNotification.md`)

# [Breaking change]: Handling of command-line RuntimeIdentifier and SelfContained properties across project references

## Description

The `RuntimeIdentifier` and `SelfContained` properties can be specified on the command line to commands such as `dotnet build` and `dotnet publish`.
They can be specified either via parameters such as `-r` or `--self-contained`, or via the generic `-p:Key=Value` parameter, such as `-p:SelfContained=true`.

If these properties are specified on the command line, we've updated how they are applied (or not applied) to projects referenced by the initial project that is being built.

## Version

???

## Previous behavior

If `SelfContained` was specified on the command line, it would always flow to referenced projects.

`RuntimeIdentifier` would flow to referenced projects where either the `RuntimeIdentifier` or `RuntimeIdentifiers` properties were non-empty.

## New Behavior

Both `SelfContained` and `RuntimeIdentifier` will flow to a referenced project if any of the following are true for the referenced project:

- The `IsRidAgnostic` property is set to `false`
- The `OutputType` is `Exe` or `WinExe`
- Either the `RuntimeIdentifier` or `RuntimeIdentifiers` property is non-empty

## Type of breaking change

Source incompatible

## Reason for change

As of .NET SDK 6.0.100, we recommend specifying the value for self-contained on the command line if you specify the RuntimeIdentifier.
(This is because in the future we are considering [changing the logic](https://github.com/dotnet/designs/blob/main/accepted/2021/architecture-targeting.md)
so that specifying the RuntimeIdentifier on the command line doesn't automatically set the app to self-contained.)  We also added a warning message
to guide you to do so.

However, if you followed the warning and switched to a command specifying both the RuntimeIdentifier and the value for self-contained (for example
`dotnet build -r win-x64 --self-contained`), the command could fail if you referenced an Exe project, because the `RuntimeIdentifier` you specified
would not apply to the referenced project, but the `SelfContained` value would, and it's an error for an Exe project to have `SelfContained` set to
true without having a `RuntimeIdentifier` set.

## Recommended action

If you were relying on the `SelfContained` property to apply to all projects when it was specified on the command line, then you can get similar behavior
by setting `IsRidAgnostic` to false either in a file ([such as Directory.Build.props](https://docs.microsoft.com/visualstudio/msbuild/customize-your-build#directorybuildprops-and-directorybuildtargets)),
or as a command-line parameter such as `-p:IsRidAgnostic=false`.

## Open Questions

TODO: How does this apply to solutions?  Could a solution build set IsRidAgnostic to false for all projects, and would that fix other issues we have when specifying the RuntimeIdentifier for a solution build?
TODO: What happens if there's an Exe1 -> Library -> Exe2 reference, especially if there's also a direct reference from Exe1 -> Exe2

---

### Documentation General UpdateToNewTargetFramework (`documentation/general/UpdateToNewTargetFramework.md`)

# Updating the SDK to a new target framework

This guide describes the annual rollover where the `main` branch moves from target
framework `net(N-1).0` to `netN.0`. Use a tracking issue for release-specific state,
owners, exact preview versions, and temporary workarounds. Keep this document focused on
the repeatable process and invariants.

Current example: [net12 transition tracking](https://github.com/dotnet/sdk/issues/55851).

## Recommended sequence

The work spans several repositories and should be coordinated in roughly this order.
Some steps can overlap, but the dependency and bootstrap steps must be ordered so the SDK
can build itself throughout the transition.

### 1. Prepare branches and branding

- Update the download/build table for the new `main` and the release candidate branches.
- Update branding so the release branches retain the intended `N-1` branding and `main`
  becomes `N.0.1xx-alpha`.
- Create the next `N-1` feature-band branch and configure the required inter-branch
  flows.
- Move localization after the appropriate release candidate snap.

Branding is best changed in the VMR so product repositories receive a consistent update.
Expect to fix or temporarily disable tests when the branding change flows back.

### 2. Add known framework references

Add the `netN.0` targeting contract in
[`GenerateBundledVersions.targets`](../../src/Layout/redist/targets/GenerateBundledVersions.targets)
before netN runtime packs are available. The live `netN.0` entries can initially resolve
to the current `N-1` product packs; they will move to netN packs when those dependencies
flow.

This change has two equally important parts:

1. Add complete live metadata for `netN.0`.
2. Freeze `net(N-1).0` so later netN package and RID changes cannot alter it.

#### Snapshot the previous TFM's package versions

Capture the exact flowed `N-1` runtime and targeting pack versions for:

- `Microsoft.NETCore.App`
- `Microsoft.WindowsDesktop.App`
- `Microsoft.AspNetCore.App`

Define version-specific properties for those values. While `N-1` is prerelease, use the
exact available package versions. After `N-1` releases, replace temporary pins with
`(N-1).0.$(VersionFeature...)` and remove the temporary follow-up comment.

While `N-1` is still the current TFM, keep its generated metadata aligned with the live
packs bundled in the SDK. Activate the frozen values only after the netN targeting packs
become current; otherwise the SDK advertises pack versions that are not installed and
isolated-source restores fail.

Do not leave the previous TFM bound to live `Microsoft*PackageVersion` properties. Those
properties will advance to netN when new dependencies flow.

#### Establish per-TFM RID boundaries

Create explicit `NetN*` item layers for every version-sensitive pack family, even when a
new layer initially inherits `Net(N-1)*` without adding RIDs:

- apphost packs
- CoreCLR runtime packs
- Mono runtime packs
- Crossgen2 packs, including portable RIDs
- ILCompiler packs, including portable RIDs
- NativeAOT runtime packs
- ASP.NET Core runtime packs

Point aggregate "current" aliases at the new `NetN*` layers. Point the previous TFM's
metadata directly at `Net(N-1)*` layers.

Add new RIDs only when the producing runtime/assets support them. New netN-only RIDs
belong in the `NetN*` layer so older TFMs do not gain unsupported packs. Shared,
non-versioned lists such as WindowsDesktop should remain shared unless the producing
repository introduces a TFM-specific difference.

#### Add the complete live TFM block

Copy the previous live TFM block and audit every copied major number, property, item
name, default version, and RID list. A complete block currently includes:

- `KnownFrameworkReference`
- `KnownAppHostPack`
- `KnownCrossgen2Pack`
- `KnownILCompilerPack`
- NativeAOT and Mono `KnownRuntimePack` entries
- `KnownILLinkPack`
- `KnownWebAssemblySdkPack`
- `KnownAspNetCorePack`
- WindowsDesktop, WPF, Windows Forms, and ASP.NET Core framework references

The new TFM uses live product package properties and aggregate current RID lists. The
previous TFM uses frozen package properties and version-specific RID lists.

Preserve intentional cross-TFM conventions only after checking the surrounding entries.
For example, older `KnownWebAssemblySdkPack` entries currently use the current runtime
package version rather than a per-TFM frozen property.

#### Validate the generated contract

Generate `Microsoft.NETCoreSdk.BundledVersions.props` through the normal layout target
and inspect the expanded output, not only the source target.

Verify that:

- one complete entry set exists for `netN.0`;
- netN uses current package properties and current RID aliases;
- `net(N-1).0` uses only frozen `N-1` versions and RID snapshots;
- changing a netN-only RID list does not change generated `net(N-1).0` metadata;
- generated `net(N-2).0` metadata is unchanged; and
- the dynamically generated bundled/current TFM still comes from the current targeting
  pack's `FrameworkList.xml`.

Run the focused framework-reference, default-runtime-version, and self-contained
runtime-pack tests that consume the built bundled versions props.

### 3. Retarget sources independently of the bootstrap SDK

Arcade can build sources targeting `netN.0` with a stage-0 SDK that supports only
`net(N-1).0`. Its `TargetingPacks.BeforeCommonTargets.targets` copies known pack metadata
from a supported baseline and changes the `TargetFramework` metadata. Configure this
after the Arcade props import in [`Directory.Build.props`](../../Directory.Build.props):

- Set `NetCurrent` to `netN.0` and keep `SdkTargetFramework` derived from it.
- Explicitly set `TargetingPackBaselineTargetFramework` to the supported `net(N-1).0`;
  do not assume Arcade's default baseline is the previous major version.
- Set `TargetingPackCurrentTargetFramework` to `$(SdkTargetFramework)`. These explicit
  properties also allow targeting independently of Arcade's `NetCurrent` default.
- Raise the repository build's `NETCoreAppMaximumVersion` for the new source TFM.

Keep both `sdk.version` and `tools.dotnet` in `global.json` unchanged for this step.
This changes the source TFM, not the reference-pack API surface or the runtime used to
execute the resulting tools. Inspect the copied versions and generated runtimeconfig
files, then build with the exact pinned stage-0 SDK.

Check the pinned Arcade implementation's coverage. It creates Core framework, apphost,
Crossgen2, ILCompiler, ILLink, Mono, and NativeAOT entries, but not ASP.NET Core entries.
SDK sources that reference ASP.NET Core need a conditional baseline copy while stage 0
lacks the new entry; see [`Directory.Build.targets`](../../Directory.Build.targets).
An older bootstrap can also lack pruning data for the new TFM. Scope
`LoadPrunePackageDataFromNearestFramework` to the new source framework (including
platform-qualified variants) and the older bootstrap, and remove it after the bootstrap
update. Use the baseline data instead of allowing missing data and leaving normally
pruned packages in the dependency graph.

Preserve the live reference-pack overrides for the baseline framework, not just packages
whose major version matches the new source TFM. Otherwise compilation uses the older
bootstrap reference pack while the layout ships newer runtime packages. This can leave
framework assemblies copied beside SDK tools. For example, an SDK-local dependency
injection abstractions assembly can load into MSBuild's logger context while options
loads from the shared runtime, causing incompatible `IServiceCollection` type identities.
Check package conflict resolution and the final layout as well as restore.

Update task/tool lookup paths and TFM-specific API baselines with the source outputs.
Keep paths into externally produced packages, such as F# and WindowsDesktop, on their
actual packaged TFM until those producers retarget. Distinguish the compiled SDK TFM
from generated test-app defaults in
[`ToolsetInfo.cs`](../../test/Microsoft.NET.TestFramework/ToolsetInfo.cs).

Also preserve compatibility for SDK packages consumed by other repositories during
stage-2 source-build. For example,
[`WorkloadManifestReader`](../../src/Resolvers/Microsoft.NET.Sdk.WorkloadManifestReader/Microsoft.NET.Sdk.WorkloadManifestReader.csproj)
temporarily includes a previous-TFM target in source-only builds so Arcade's workload
tasks can consume the newly source-built package before Arcade retargets. Validate both
the online build and the offline rebuild using its outputs; the online build alone can
hide this mismatch by consuming older, previously-source-built packages.

### 4. Flow product dependencies and update the bootstrap SDK

- Flow netN runtime, WindowsDesktop, and ASP.NET Core dependencies.
- Update `global.json` separately to a bootstrap SDK build that supports targeting netN.
- Update restore-toolset inputs for the `N-1` runtime where required.

Do not hand-edit generated dependency-flow properties. Follow the repository's
dependency-flow process so versions, manifests, and feeds remain consistent.

### 5. Advance product defaults, tests, and templates

- Confirm SDK sources and all task/tool lookup paths target `netN.0`.
- Update the shared test framework constants in
  [`ToolsetInfo.cs`](../../test/Microsoft.NET.TestFramework/ToolsetInfo.cs).
- Retarget default templates to `netN.0`.
- Update build-time analyzer and package-generation commands that explicitly select the
  current TFM.
- Author workload manifests for the new TFM:
  - Move the Mono toolchain and Emscripten `.Current` workload manifests to `netN`.
  - Create `net(N-1)` Mono toolchain and Emscripten manifest snapshots from the
    `.Current` manifests, not from the older versioned manifests, so net(N-1) keeps any
    changes made while it was current.
  - Register the new versioned manifests in
    [`BundledManifests.targets`](../../src/Layout/redist/targets/BundledManifests.targets).
  - Centralize the previous TFM's workload pack versions through its
    `VersionFeature...ForWorkloads` property in [`eng/Versions.props`](../../eng/Versions.props).
    Use that property in both versioned manifest projects and the `.Current` manifest's
    previous-TFM runtime version entry. If net(N-1) is still prerelease, temporarily pin
    the property to the suffix of the exact flowed version (for example,
    `0-rc.1.26453.118` for `11.0.0-rc.1.26453.118`). After GA, reference the corresponding
    `VersionFeature...` servicing property instead. Keep the previous TFM independent of
    live netN dependency versions.

Use `PreviousTargetFramework` for tests that must temporarily remain on `N-1`. Mark
temporary transition changes with `NetTFMUpdate` so they can be found and removed later.

Templates from other repositories, such as WindowsDesktop templates, may need to remain
pinned to `N-1` until their netN packages are available.
If the bundled SDK still supports only `N-1`, also keep the bundled web/MCP templates
and test-app ASP.NET package references on `N-1`: netN templates generate projects
that the bundled SDK cannot build, and netN ASP.NET packages may no longer support
net(N-1) test apps. Keep the temporary versions in `eng/ManualVersions.props` rather
than changing Maestro-generated dependency versions, and advance them together once
the SDK supports targeting netN. The Windows SDK bundle must also select the template
MSI for `TemplateFrameworkVersion`, which can differ from the SDK's product version
during this transition. Keep the shared MSI filename aligned for the SDK bundle and
Visual Studio redist package ([`GenerateMSIs.targets`](../../src/Layout/redist/targets/GenerateMSIs.targets),
[`VS.Redist.Common.NetCore.Templates.proj`](../../src/Layout/VS.Redist.Common.NetCore.Templates/VS.Redist.Common.NetCore.Templates.proj)).

Default-template tests should compare against `ToolsetInfo.CurrentTargetFramework`,
not the newest installed runtime, which can already be netN during this transition
(see [`ProjectBuildTests`](../../test/EndToEnd.Tests/ProjectBuildTests.cs)).

### 6. Unwind temporary transition changes

- Re-enable or unpin tests and templates disabled during branding and runtime flow.
- Search for and remove all temporary `NetTFMUpdate` changes.
- Remove temporary `PreviousTargetFramework` usage that is no longer necessary.
- Replace exact `N-1` framework-pack pins after GA.
- Confirm the SDK, tests, templates, and documentation all describe netN as current.

## Common failure modes

- **Backward version leakage:** the previous TFM still references live current-product
  package properties and starts resolving netN packs after dependency flow.
- **Backward RID leakage:** the previous TFM references aggregate current RID lists and
  silently gains netN-only platforms.
- **Partial pack coverage:** only framework references are copied, omitting apphost,
  Crossgen2, NativeAOT, Mono, ILLink, WebAssembly, or internal ASP.NET Core metadata.
- **Copy/paste major mismatch:** comments, property names, or item names still identify
  the wrong TFM.
- **Premature hardcoding:** the current or maximum TFM is hardcoded instead of being read
  from the current targeting pack.
- **Untracked temporary changes:** disabled tests and pinned templates are not marked for
  cleanup.

## Historical examples

### net11

- [Transition tracker](https://github.com/dotnet/sdk/issues/50295)
- [Branding](https://github.com/dotnet/sdk/pull/50468)
- [Initial known framework references](https://github.com/dotnet/sdk/pull/50329)
- [CoreCLR Apple mobile RID separation](https://github.com/dotnet/sdk/pull/51429)
- [Additional next-TFM RID metadata](https://github.com/dotnet/sdk/pull/51855)
- [Update frozen net10 versions after release](https://github.com/dotnet/sdk/pull/51925)
- [Backflow from the VMR](https://github.com/dotnet/sdk/pull/52242)
- [Unwind temporary test changes](https://github.com/dotnet/sdk/pull/52512)

### net7

These older changes predate the current VMR and repository layout, but remain useful for
identifying less common transition surfaces:

- [SDK branding](https://github.com/dotnet/sdk/pull/20212)
- [Runtime flow and Blazor baselines](https://github.com/dotnet/sdk/pull/20859)
- [Feeds and runtime flow](https://github.com/dotnet/sdk/pull/19824)
- [Template package updates](https://github.com/dotnet/sdk/pull/27486)
- [Installer known framework references and bootstrap updates](https://github.com/dotnet/installer/pull/11750)
- [Post-release installer template update](https://github.com/dotnet/installer/pull/14961)

---

### Documentation General Analyzer Redirecting (`documentation/general/analyzer-redirecting.md`)

# Redirecting analyzers in SDK to VS

We will redirect analyzers from the SDK to ones deployed in VS to avoid the [torn SDK][torn-sdk] issue at design time.
Only matching major+minor versions will be redirected because different versions of the same analyzer cannot be assumed to be compatible.
So this applies to a situation like:
- Having an analyzer in SDK 9.0.1 referencing Roslyn 4.12. That gets deployed to VS 17.12.
- Having an analyzer in SDK 9.0.7 referencing Roslyn 4.13.
- User loads project with SDK 9.0.7 in VS 17.12.
  Previously the analyzers would fail to load as they reference a newer Roslyn version (4.13) than what is part of VS (4.12).
  Now we will redirect the analyzers to those from SDK 9.0.1 that are deployed as part of VS and reference the matching Roslyn (4.12).

Loading older analyzer versions should not be a problem because they must reference an older version of Roslyn.

Targeting an SDK (and hence also loading analyzers) with newer major version in an old VS already results in an error like:

> error NETSDK1045: The current .NET SDK does not support targeting .NET 10.0.
> Either target .NET 9.0 or lower, or use a version of the .NET SDK that supports .NET 10.0.
> Download the .NET SDK from https://aka.ms/dotnet/download

## Overview

- The SDK will deploy analyzer DLLs and Roslyn will deploy an implementation of `IAnalyzerAssemblyRedirector`
  (could be deployed by SDK but we are saving on analyzer loads and Roslyn already has a VSIX with a DLL).
  Implementations of this interface are imported by Roslyn and can redirect analyzer DLL loading.

- That implementation of `IAnalyzerAssemblyRedirector` will redirect any analyzer DLL matching some pattern
  to the corresponding DLL deployed with VS.
  Details of this process are described below.

- Note that when `IAnalyzerAssemblyRedirector` is involved, Roslyn is free to not use shadow copy loading and instead load the DLLs directly.

- It is possible to opt out of analyzer redirecting by setting environment variable `DOTNET_ANALYZER_REDIRECTING=0`.
  That is an unsupported scenario though and compiler version mismatch errors will likely occur.

## Details

The VS deployment contains some analyzers, for example:

```
AspNetCoreAnalyzers\analyzers\dotnet\cs\Microsoft.AspNetCore.App.Analyzers.dll
NetCoreAnalyzers\analyzers\dotnet\cs\System.Text.RegularExpressions.Generator.dll
WindowsDesktopAnalyzers\analyzers\dotnet\System.Windows.Forms.Analyzers.dll
SDKAnalyzers\Sdks\Microsoft.NET.Sdk\analyzers\Microsoft.CodeAnalysis.NetAnalyzers.dll
WebSDKAnalyzers\Sdks\Microsoft.NET.Sdk.Web\analyzers\cs\Microsoft.AspNetCore.Analyzers.dll
```

And metadata at `metadata.json`:

```json
{
  "AspNetCoreAnalyzers":
  {
    "Version": "9.0.0-preview.5.24306.11",
    "Files": ["analyzers\\dotnet\\cs\\Microsoft.AspNetCore.App.Analyzers.dll"]
  },
  "NetCoreAnalyzers":
  {
    "Version": "9.0.0-preview.5.24306.7",
    "Files": ["analyzers\\dotnet\\cs\\System.Text.RegularExpressions.Generator.dll"]
  },
  "WindowsDesktopAnalyzers":
  {
    "Version": "9.0.0-preview.5.24306.8",
    "Files": ["analyzers\\dotnet\\System.Windows.Forms.Analyzers.dll"]
  },
  "SDKAnalyzers":
  {
    "Version": "9.0.100-dev",
    "Files": ["Sdks\\Microsoft.NET.Sdk\\analyzers\\Microsoft.CodeAnalysis.NetAnalyzers.dll"]
  },
  "WebSDKAnalyzers":
  {
    "Version": "9.0.100-dev",
    "Files": ["Sdks\\Microsoft.NET.Sdk.Web\\analyzers\\cs\\Microsoft.AspNetCore.Analyzers.dll"]
  },
}
```

Given an analyzer assembly load going through our `IAnalyzerAssemblyRedirector`,
we will redirect it if the original path of the assembly being loaded matches the path of a VSIX-deployed analyzer -
only relevant segments (see example below) of these paths are compared,
plus the major and minor component of the versions must match.

For example, the analyzer

```
C:\Program Files\dotnet\sdk\9.0.100-preview.5.24307.3\Sdks\Microsoft.NET.Sdk\analyzers\Microsoft.CodeAnalysis.NetAnalyzers.dll
```

will be redirected to

```
{InstallDir}\SDKAnalyzers\Sdks\Microsoft.NET.Sdk\analyzers\Microsoft.CodeAnalysis.NetAnalyzers.dll
```

where `metadata.json` has `"SDKAnalyzers": { "Version": "9.0.100-dev" }`, because
1. the suffix `Sdks\Microsoft.NET.Sdk\analyzers\Microsoft.CodeAnalysis.NetAnalyzers.dll` matches, and
2. the version `9.0.100-preview.5.24307.3` has the same major and minor component (`9.0`) as the version `9.0.100-dev`
   (both versions are read from the paths, not DLL metadata).

Analyzers that cannot be matched will continue to be loaded from the SDK
(and will fail to load if they reference Roslyn that is newer than is in VS).

### Implementation

Analyzer DLLs are contained in transport package `VS.Redist.Common.Net.Core.SDK.RuntimeAnalyzers`.

[torn-sdk]: https://github.com/dotnet/sdk/issues/42087

---

### Documentation General Aspnetcore Tools (`documentation/general/aspnetcore-tools.md`)

ASP.NET Core Command Line Tools
===============================

The .NET Core CLI includes some commands that are specific to ASP.NET Core projects.

 - dotnet dev-certs
 - dotnet user-secrets
 - dotnet user-jwts
 - dotnet sql-cache

For more information on these tools, see <https://github.com/dotnet/aspnetcore/tree/main/src/Tools>.

---

### Documentation General Build Deb Rpm Locally (`documentation/general/build-deb-rpm-locally.md`)

# Build Deb or Rpm locally

We do not need to build Debian or RPM locally too often. However, if we need, it is not productive to check in and wait for a build since the feedback loop could be 2 hours for a typo. The following guide is a quick solution if you don't have an existing environment setup.

## Use a VM

It is good to have an editor on the machine. So you can edit and run in the same environment. Setting up git credentials might be an hassle you could edit on the host machine, push to github and the pull from the VM. Prefer VM if you know it would take a while to build and test the feature. 

### For Deb

The build script has not been updated since Ubuntu 16.04. Due to dependencies like Python 2 on the path, you cannot easily build on later versions. 

- Download and install ubuntu 16.04 ios file on a hypervisor
- install all apt-get dependency following https://github.com/dotnet/installer/blob/main/eng/docker/ubuntu.16.04/Dockerfile. debhelper and build-essential are must have, since the build script would not build deb if the depending softwares are not present on the machine.
- Once all installed, run `./build.sh --pack` to create deb.

### For Rpm

Unfortunately, old Fedoras are out of support, and you cannot easily download RHEL images. You could try Fedora 24. https://github.com/dotnet/cli/blob/release/2.2.4xx/scripts/docker/fedora.24/Dockerfile

## User docker

If you are on Windows, try to run docker in a Linux VM. Do not mount drive because you cannot build sdk successfully if you build on an mounted Windows drive due to a file permission issue.

- cd to docker folder locally for example https://github.com/dotnet/installer/tree/main/eng/docker
- Use and editor remove everything under `ARG USER_ID=0 ` locally in the DockerFile. For example `~/Documents/installer/eng/docker/rhel/DockerFile`. The lines to be deleted are for special tests (Install sudo and create a user account, so that it can test package installation). Without deleting the lines, you cannot build the docker file locally.
- Say you want to test Rpm, `docker build rhel/ -t image`
- `docker run -v /home/HOSTMOUNTFOLDER:/home/installer -it --name image2 image /bin/bash`
- After `git pull` the new build, run `./build.sh --pack -bl`. You should be able to inspect files on the host mounted drive easily. More importantly, it is easy for you to copy binlog out to a Windows machine to read.

---

### Documentation General Cli Ux Guidelines (`documentation/general/cli-ux-guidelines.md`)

.NET Core Command-Line Tools UX Guidelines
-------------------------------------------

This document outlines the User Experience (UX) of the .NET Core command line tools (CLI). These guidelines are intended for anyone that wants to add a new command to the CLI. 

The guidelines presented in this document have been adopted to provide a clear and concise 
command line syntax that is easy to learn, remember and work with, and that has an added benefit 
of being familiar to people who have used other command-line interfaces as well as existing 
Visual Studio users. 

## Naming the commands

In the .NET Core CLI, commands should be **verbs**. This rule was adopted
because most of the commands do *something*.

Sub-commands are supported in the CLI, and they are usually nouns. A good
example of this is the “dotnet add reference” command. If there is a need to add
a subcommand, that subcommand should usually specialize what the parent command
does.

## Create/Read/Update/Delete (CRUD) commands
New CRUD commands should be named according to the following logic:

-   Does the command work on data in the project (either properties or
    items)? If yes, then it should be added as a noun to the “dotnet
    add/list/remove/update”, e.g. “dotnet add foo”.

-   Does the command work on the solution (SLN) file? If yes, then it should be
    added as a verb to the “dotnet sln” command.

-   Does the command work on a completely new artifact (e.g. a new metadata file
    that is added in the future)? If yes, it should be created as a top level
    noun with all of the underlying operations defined as sub-commands.

-   If the command adds a new artifact to the project, it should become an item
    template that is dropped with “dotnet new” command.


If none of the above applies, the proposal should clearly outline why none of
the above applies and suggest an alternative naming that will be decided on
during the process described above.

If the command works on the project or solution, it must also accept an optional
argument that specifies which project or solution to work on. The current
convention is for that argument to follow the verb in the CRUD command. For
example:

>   dotnet add \<PROJECT\> reference \<REFERENCE\>

All the existing CRUD commands have this argument defined and it will be passed
to the sub-command as part of the overall options. The sub-command is expected
to consider this optional argument.

## Options 
CLI follows the [GNU convention](https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html) for options’ format, which is based on the POSIX
standard. The summary is:

-   Command can have both short and long options.

-   The short format starts with a single dash (“-“), and has **exactly** one
    letter. The letter is usually the start letter of the longer form of the
    option, e.g. “-o” for “--output” or any of its words. This provides a good
    mnemonic.

    -   **Example:** “dotnet build -o path/to/where/to/put/output”

-   The long format starts with double dashes (“--“) and can have one or more
    words. Multiple words are separated by a single dash (“-“).

    -   **Example:** “dotnet test --test-case-filter”

-   The double dashes (“--“) on their own mark the **argument separator**.
    Anything after this option is passed verbatim to whatever the command starts
    as a sub-process.

    -   **Example:** “dotnet run -- --app-arg-1”

-   Windows-style forward slash options (e.g. “/p”) are supported **only for
    MSBuild parameters.**

-   PowerShell-style single dashes with a word (e.g. “-Filter”) are **not
    supported**.

-   Help options are predefined as “-h \| --help” and those should be used.

There are common options in the CLI that are reserved for certain concepts. The
table below outlines those common options. If a command needs to accept the same
options, it should use these and it must not replace their semantics (e.g. use
“--output” to mean something different or redefine what “-f” means for just that
command).

| Long option      | Short option | Description                                                  |
|------------------|--------------|--------------------------------------------------------------|
| \--framework     | \-f          | Specifies which framework (target) to use in the invocation. |
| \--output        | \-o          | Specifies where the output of the command should be placed.  |
| \--runtime       | \-r          | Specifies the runtime ID (RID) to use in the invocation.     |
| \--configuration | \-c          | Specifies the configuration to use in the invocation.        |
| \--verbosity     | \-v          | Specifies the verbosity level of the command.                |
| \--help          | \-h          | Shows the help for the command.                              |

One special area is interacting with MSBuild. If a command has the need to do
that, there are two additional requirements with regards to options:

1.  The commands need to be able to take “/p” parameters in addition to whatever
    other properties they require.

2.  If the command invokes a predefined MSBuild target, it needs to block
    “/t:\<target\>” and “/target:\<target\>” options and throw an error that is
    pre-defined in the CLI.

It is important to note that commands that invoke user-specified targets
should not be submitted to the CLI, since the CLI comes with “dotnet msbuild”
command that does precisely that.

## Arguments
Arguments can have any name that authors of the commands being added need. We do have predefined
argument names for the SLN file and project file. They are defined in the CLI
source code and should be used if the command has the need to use those two
arguments.

## Help messages
Help messages are automatically generated based on the arguments, options and
command name. No other work should be required here apart from setting up the
above mentioned and their descriptions.

## Output 
For commands that are invoking MSBuild, the output will be controlled by MSBuild
itself.

In case of a long running operation, the command needs to provide a feedback
mechanism to the user to help the user reason about whether the command has
crashed or is just waiting for I/O. The feedback mechanism guidelines are below:

1. Feedback should not require fonts with special glyphs for display. 
2. Pure text is acceptable (e.g. `Running background process...`) as a feedback mechanism. 
3. Spinners that conform to rule \#1 above are also acceptable.


### Verbosity
If the command interacts with MSBuild, it is required that it can accept a
“--verbosity \| -v” argument and pass it to MSBuild verbatim.

If the command’s verbosity levels cannot fit naturally in [MSBuild’s verbosity levels](https://docs.microsoft.com/en-us/visualstudio/msbuild/msbuild-command-line-reference) or the command does not interact with MSBuild but still has an option to set the verbosity, it
is the job of the command to map them in the most appropriate way. This way, the
verbosity levels will be uniform across all commands which brings consistency to
the toolset.

#### Example
As an example, let us consider a “dotnet configure” command. It doesn’t interact
with MSBuild. I wish to have verbosity on it, but it really has only two levels:
quiet (just successes or errors) and verbose (every operation) that I've defined for the command. To satisfy the
above-mentioned requirement, in my command I would define the “--verbosity \|
-v” option and would map the arguments in the following way:

-   “Quiet” gets mapped naturally to “quiet”

-   “Minimal”, “Normal” and “Diagnostic” get mapped into “verbose”

---

### Documentation General Decouple Vs And Net Sdk (`documentation/general/decouple-vs-and-net-sdk.md`)

# Decoupling the .NET SDK and Visual Studio

## Goals

Visual Studio and the .NET SDK are separate products, but their experiences are tightly coupled. Changes to the .NET SDK version can influence Visual Studio's design-time behavior, while updating Visual Studio can impact command-line builds for .NET SDK projects. When the products are in sync these interactions are benign, but when they are not, they lead to compatibility and reliability issues. This document proposes a design to decouple these products, allowing each to provide a more defined and independent experience.

Design Goals:

1. **Consistent Build Experiences**: The `msbuild` and `dotnet build` command line build experience for a solution should be functionally equivalent.
2. **Independent Design Time Behavior**: Visual Studio's design-time experience should be largely independent of the .NET SDK used by the solution.
3. **Clear Handling of Divergence**: To make explicit that it is okay, and even expected, that the design time and command line build experiences can differ when the two products are not in sync.

## Terminology

- **msbuild**: refers to the .NET Framework-based msbuild included with Visual Studio.
- **dotnet build**: refers to the .NET Core based msbuild included with the .NET SDK.
- **analyzers**: this document will use analyzers to refer to both analyzers and generators.
- **torn state**: when the .NET SDK and Visual Studio are not in sync.
- **.NET SDK project**: a project that uses the .NET SDK project format.

## Summary

Visual Studio and the .NET SDK are separate products but they are intertwined in command line and design time build scenarios as different components are loaded from each product. This table represents how intertwined Roslyn specifically is currently:

| Scenario | Loads Roslyn | Loads Analyzers / Generators |
| --- | --- | --- |
| msbuild | From Visual Studio | From .NET SDK |
| dotnet build | From .NET SDK | From .NET SDK |
| Visual Studio Design Time | From Visual Studio | From Both |

There are other products that have similar intertwined behavior such as NuGet, MSBuild, Razor, etc ... Roslyn is generally the most impactful and the one we are focusing on in this document as its path forward can be generalized to the other products.

Generally this mixing of components is fine because Visual Studio will install a .NET SDK that is functionally paired with it. For example 17.10 installs .NET SDK 8.0.3xx, 17.9 installs .NET SDK 8.0.2xx, etc ... In that scenario the components are the same version and the mixing is largely benign. However when the customer is in a torn state, that is the .NET SDK used is not paired with the Visual Studio version, then compatibility issues can, and **will**, arise. Particularly when the .NET SDK is _newer_ than Visual Studio customers will end up with the following style of error[^1]:

> CSC : warning CS9057: The analyzer assembly '..\dotnet\sdk\8.0.200\Sdks\Microsoft.NET.Sdk.Razor\source-
> generators\Microsoft.CodeAnalysis.Razor.Compiler.SourceGenerators.dll' references version '4.9.0.0' of the compiler, which is newer
> than the currently running version '4.8.0.0'.

These bugs slip by because even though a given .NET SDK is supported in many Visual Studio versions, we do not fully validate its correctness. Specifically, consider that when releasing the .NET 8.0.400 SDK. It is supported in 17.8-17.11 but only fully validated in 17.11. Likewise, when Visual Studio releases servicing fixes it does not attempt to fully validate all supported .NET SDKs. This work on both sides would be prohibitively expensive. Instead, we seek to decouple these experiences so that such testing is not necessary.

Customers existing in a torn state is a common scenario:

|Visual Studio Version | Match% | Float % | Torn % |
| --- | --- | --- | --- |
| 16.11 | 81.4% | 10.8% | 7.8% |
| 17.2 | 91% | 8% | 1% |
| 17.4 | 91.5% | 5.7% | 2.7% |
| 17.6 | 91.6% | 5% | 3.5% |
| 17.7 | 94.9% | 2.2% | 3% |
| 17.8 | 96% | 0% | 4% |

To address this issue we are going to separate Visual Studio and the .NET SDK in build scenarios. That will change our matrix to be the following:

| Scenario | Loads Roslyn | Loads Analyzers / Generators |
| --- | --- | --- |
| msbuild | From .NET SDK | From .NET SDK |
| dotnet build | From .NET SDK | From .NET SDK |
| Visual Studio Design Time | From Visual Studio | From Visual Studio |

Specifically we will be:

1. Changing `msbuild` to use tools and tasks from the .NET SDK when building .NET SDK projects.
2. Changing Visual Studio to use analyzers installed with Visual Studio.

In addition to making our builds more reliable this will also massively simplify our [analyzer development strategy][sdk-lifecycle]. Analyzers in the SDK following this model can always target the latest Roslyn version without the need for complicated multi-targeting. Further it will allow Visual Studio the ability to NGEN or R2R analyzers which is a long standing request from the Visual Studio perf team.

## Torn State Scenarios

There are a number of scenarios where customers end up in a torn state. The most common is when customers have a CI setup with the following items:

1. They use a task like [actions/setup-dotnet][setup-dotnet] to install the .NET SDK and use a flexible version format like `8.x`.
2. They use `msbuild` to actually drive their build. This `msbuild` comes from the Visual Studio installed on the machine image.

This means that CI systems are updated to the latest .NET SDK virtually as soon as we release them. However the version of Visual Studio is updated much later as CI images usually take several weeks to upgrade to a new Visual Studio version. This is a very common CI setup and means a significant number of our customers end up in a torn state for several weeks.

Teams also get into this state when the Visual Studio used for development is older than the .NET SDK they are using:

1. Teams can get locked into older Visual Studio via org policy but freely update to newer .NET SDKs.
2. Using a preview version of the .NET SDK. These inherently represent a torn SDK state because they almost never match the compiler in Visual Studio. This results in blockers for big teams like Bing from testing out our previews.
3. Using a global.json that specifies a different version of the .NET SDK than the Visual Studio version.

## Solution

### MSBuild will use the .NET SDK tools for SDK projects

When building .NET SDK projects, `msbuild` will load tasks from the .NET SDK instead of Visual Studio. Specifically it will load the Roslyn compiler task from the .NET SDK. That task will then function the same as it does when launched from `dotnet build`.

To facilitate tasks from the .NET SDK launching .NET Core based processes, the `msbuild` host will [set the property][dotnet-host-path] `DOTNET_HOST_PATH`. This will point to the same .NET Core host that the .NET SDK uses. This will allow tasks to launch .NET Core based processes with the same behavior as the .NET SDK would.

This change will allow for `msbuild` to have a more consistent build experience with `dotnet build` for .NET SDK projects. It will have no impact on non-SDK projects as they will continue to use the compiler tasks that come from Visual Studio.

### .NET SDK analyzers will load from Visual Studio

Analyzers and generators which ship in the .NET SDK box will change to having a copy checked into Visual Studio. This will occur as part of the .NET SDK insertion process. When .NET SDK based projects are loaded at design time, the Visual Studio copy of the analyzer [will be loaded](analyzer-redirecting.md).

This means that the behavior of analyzers in Visual Studio design time will be independent of the .NET SDK used by the project. This increases the predictability of our product as we know at ship time what analyzer and generator experience our customers will be getting. It will no longer change as the underlying SDK does.

Having a consistent version also enables us to take actions like NGEN or R2R analyzers inside of Visual Studio. This is a long standing request from the Visual Studio perf team but impossible to satisfy when the versions change based on global.json resolution.

This approach is already taken by [the Razor generator][code-razor-vs-load] to great success. It allowed us to provide a consistent, and testable, experience for Razor editing. Recently it was also adopted by [C# code style analyzers](https://github.com/dotnet/roslyn/pull/75250) to similar success. There is every reason to expect similar success as we expand this to all analyzers and generators in the .NET SDK.

This also benefits the developement model for analyzers and generators that ship in the .NET SDK as they can now target the latest version of Roslyn. There is no more need to multi-target because the version of the compiler the analyzer will be used with is known at ship time for all core build scenarios.

This does mean that our design time experience can differ from our command line experience when customers are in a torn state. Specifically it's possible, even likely in some cases, that the diagnostics produced by design time builds will differ from command line builds. That is a trade off that we are willing to make for reliability. Customers who wish to have a consistent experience between design time should not operate in a torn state.

### NuGet based analyzers

Analyzers which ship via NuGet will continue to follow the existing [support policies][matrix-of-paine]. This means that they will either need to target a sufficiently old version of Roslyn or implement multi-targeting support to function in Visual Studio.

In the case of [multi-targeting][issue-analyzer-mt] this proposal is effectively a no-op. Analyzer multi-targeting is already based off of Roslyn versions, not .NET SDK versions, hence the proper version of the analyzer will still load in a torn state. The version of the Roslyn compiler in a torn state for `msbuild` is the same used for `dotnet build` hence it's already a scenario the analyzer needs to support.

There is nothing preventing NuGet based analyzers from following the same model as .NET SDK based analyzers. The mechanism for redirection is extensible. This is not a requirement for this proposal and is left as a future work item.

## Issues

### Multiple compiler servers

Solutions that mix .NET SDK and Visual Studio projects will end up with multiple compiler servers running. This is a result of the .NET SDK projects using the compiler from the .NET SDK and non-SDK projects using the compiler from Visual Studio. There is nothing functionally wrong with this but it's possible customers will notice this and ask questions about it.

The compiler will offer a property that allows SDK projects to use the MSBuild version of the compiler when being built with `msbuild`: `<RoslynCompilerType>Framework</RoslynCompilerType>`. This can be added to a `Directory.Build.props` file to impact the entire solution. This is not expected to be a common scenario but is available for customers who need it. This property will be ignored when using `dotnet build` as there is no way to fall back to the Visual Studio compiler in that scenario.

### .NET Framework based analyzers

There are a few analyzers which are built against .NET Framework TFMs. That means when loaded in a .NET Core compiler it could lead to compatibility issues. This is not expected to be a significant issue as our processes have been pushing customers to target `netstandard` in analyzers for 5+ years. However it is possible that some customers will run into issues here.

For those customers we will recommend that they set `<RoslynCompilerType>Framework</RoslynCompilerType>` in their build to ensure a .NET Framework based compiler is used.  However, it is not our intent to support loading .NET Framework based analyzers in perpetuity. Starting in .NET 12 the compiler will begin issueing warnings is this setup when it detects framework analyzers, and this will become an error in .NET 13. Non-SDK projects will support loading framework based analyzers for the foreseeable future.

### Build server shutdown

Today there is not a 100% reliable way to shutdown the VBCSCompiler process. The `dotnet build-server shutdown` command works in common cases but fails in a number of corner cases. This has lead to customers who require the server to be shutdown to add lines like `kill VBCSCompiler` into their infrastructure scripts. This proposal will break those scripts as it will change the process name of the compiler server from `VBCSCompiler` to `dotnet`.

To mitigate this we will be fixing the `build-server shutdown` command to be reliable across all the scenarios we care about. The details of this are captured in [issue 45956](https://github.com/dotnet/sdk/issues/45956).

## RoslynCompilerType

Based on the value of the `RoslynCompilerType` property, the SDK (or compiler toolset packages) set the following properties:
- `RoslynTasksAssembly` to a full path to a [Roslyn build task DLL][roslyn-build-task],
  and the SDK targets use `$(RoslynTasksAssembly)` to load the build task
- `RoslynTargetsPath` to the directory path of the roslyn tasks assembly. This property is used by some targets
  but it should be avoided if possible because the tasks assembly name can change as well, not just the directory path.
  This property is a misnomer for historical reasons, it really points to _tasks_, there is no guarantee there will be any _targets_ in the directory.
- `RoslynAssembliesPath` to the directory path of other roslyn assemblies (like `Microsoft.CodeAnalysis.dll`).
  In builds using .NET Framework MSBuild, the path is set to the Roslyn directory that ships with MSBuild (no .NET Framework Roslyn assemblies ship with the .NET SDK).
- `RoslynCoreAssembliesPath` to the directory path of other roslyn assemblies which target .NET Core regardless of the host being .NET Framework or Core MSBuild.

These values are recognized for property `RoslynCompilerType`:
- `Core`: use the compiler that comes with the .NET SDK
- `Framework`: use the compiler that comes with .NET Framework MSBuild (this option is [deprecated and will be removed in .NET 11](https://aka.ms/roslyn-compiler-type-framework))
- `FrameworkPackage`: download the Microsoft.Net.Sdk.Compilers.Toolset package which contains the .NET Framework compiler corresponding to the .NET SDK version
- `Custom`: the SDK will not override `RoslynTasksAssembly` and the other properties listed above - used for example by Microsoft.Net.Compilers.Toolset package which injects its own version of the build task

## Alternative

### Make the compiler in Visual Studio pluggable

An alternative approach is to allow the compiler inside Visual Studio, both the design time and MSBuild copy, to be pluggable. Essentially for a given .NET SDK, grab the equivalent .NET Framework bits and have Visual Studio load them at startup.

This proposal is deemed very unlikely to be successful. Visual Studio is **highly** sensitive to the version of Roslyn it uses. Keeping Visual Studio perf neutral on every Roslyn insertion requires active work by both the Roslyn and Visual Studio teams. It is very unlikely that we could load arbitrary versions of Roslyn into Visual Studio and expect to get equivalent performance.  Consider that concretely this would mean that switching between solutions that used different .NET SDK versions would require a Visual Studio restart as well as rebuilding the MEF cache.

Further Visual Studio supports loading many different versions of the .NET SDK. For this to work Visual Studio would need to be tolerant of loading much older Roslyns into current shipping versions. That is a significant engineering effort that is unlikely to be successful.

### .NET SDK in box analyzers multi-target

Technically in box analyzers can have a multi-targeting strategy just as NuGet based analyzers do. This is actively discouraged because it leads to unnecessary increases in .NET SDK sizes. The time spent implementing multi-targeting is likely better spent moving to a dual insertion to keep .NET SDK sizes down and provide a consistent experience with other analyzers.

### .NET SDK in box analyzers use light up

In box could also employ a light up strategy. Essentially reference older versions of the compiler and use reflection to opportunistically discover + use newer APIs. This is successfully employed in analyzers like StyleCop.

### Avoid the torn state

Customers can avoid these problems by not pinning the .NET SDK and simply using the version that is naturally paired with Visual Studio.

## Misc

### Visual Studio Code

This is how Visual Studio Code fits into our matrix after this work is complete:

| Scenario | Loads Roslyn | Loads Analyzers / Generators |
| --- | --- | --- |
| msbuild | From .NET SDK | From .NET SDK |
| dotnet build | From .NET SDK | From .NET SDK |
| Visual Studio Design Time | From Visual Studio | From Visual Studio |
| DevKit | From DevKit | From .NET SDK |

On the surface it seems like VS Code has the same issues as Visual Studio does today. However this is not the case. Visual Studio is problematic because at any given time there can be ~5 different versions in active support each with a different version of the compiler. Every Visual Studio but the latest is an older compiler that run into issues with analyzers.

There is only one version of the DevKit extension. It is released using the latest compilers from roslyn at a very high frequency. That frequency is so high that the chance it has an older compiler than the newest .NET SDK is virtually zero. That means at the moment there is no need to solve the problem here. If DevKit changes its release cadence in the future this may need to be revisited.

### Related Issues

- [Roslyn tracking issue for torn state](https://github.com/dotnet/roslyn/issues/72672)
- [MSBuild property for torn state detection](https://github.com/dotnet/installer/pull/19144)
- [Long term build-server shutdown issue](https://github.com/dotnet/msbuild/issues/10035)
- [MSBuild decouple issue](https://github.com/dotnet/msbuild/issues/11142)

[^1]: This specific problem is now largely mitigated in `msbuild` scenarios by the .NET SDK implicitly adding the Microsoft.Net.Sdk.Compilers.Toolset package to builds in a torn state. This will install and use a newer C# compiler when MSBuild is older than the .NET SDK. That fixes a large amount of the problems but has a number of downsides: increases restore time, compiler must go through full JIT, corner case scenarios like `$(NuGetPackageRoot)` not being set lead to errors, only fixes one type of torn state, etc ... 


[matrix-of-paine]: https://aka.ms/dotnet/matrixofpaine
[sdk-lifecycle]: https://learn.microsoft.com/en-us/dotnet/core/porting/versioning-sdk-msbuild-vs#lifecycle
[code-razor-vs-load]: https://github.com/dotnet/roslyn/blob/9aea80927e3d4e5a2846efaa710438c0d8d2bfa2/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.cs#L1009
[roslyn-build-task]: https://github.com/dotnet/roslyn/blob/ccb05769e5298ac23c01b33a180a0b3715f53a18/src/Compilers/Core/MSBuildTask/README.md
[setup-dotnet]: https://github.com/actions/setup-dotnet
[pr-detect-torn-state]: https://github.com/dotnet/installer/pull/19144
[issue-analyzer-mt]: https://github.com/dotnet/sdk/issues/20355
[issue-legacy-wpf]: https://github.com/dotnet/wpf/issues/9112
[dotnet-host-path]: https://github.com/dotnet/msbuild/issues/11086

---

### Documentation General Dotnet Run File (`documentation/general/dotnet-run-file.md`)

# `dotnet run file.cs`

This is a proposal for extending the dotnet CLI to allow running C# source files with no need for an explicit backing project.
We call these *file-based programs* (as opposed to *project-based programs*).

```ps1
dotnet run file.cs
```

See also [IDE spec](https://github.com/dotnet/roslyn/blob/main/docs/features/file-based-programs-vscode.md).

## Motivation

File-based programs
- should be a viable alternative to using PowerShell/bash scripts in .NET repos, and
- lower the entry barrier for new customers.

## Guiding principle

The overarching guiding principle is that file-based programs have a simple and reliable [grow up](#grow-up) story to project-based programs.
Previous file-based approaches like scripting are a variant of C# and as such have no simple and reliable grow up story.

## Implicit project file

The [guiding principle](#guiding-principle) implies that we can think of file-based programs as having an implicit project file
(also known as a virtual project file because it exists only in memory unless the file-based program is converted to a project-based program).

The implicit project file is the default project that would be created by running `dotnet new console`.
This means that the behavior of `dotnet run file.cs` can change between SDK versions if the `dotnet new console` template changes.

Additionally, the implicit project file has the following customizations:

- `PublishAot` is set to `true`, see [`dotnet publish file.cs`](#other-commands) for more details.

- `PackAsTool` is set to `true`, see [`dotnet pack file.cs`](#other-commands) for more details.

- `UserSecretsId` is set to a hash of the entry point file path.

- [File-level directives](#directives-for-project-metadata) are applied.

- The following are virtual only, i.e., not preserved after [converting to a project](#grow-up):

  - `ArtifactsPath` is set to a [temp directory](#build-outputs),
    unless [artifacts output layout][artifacts-output] is enabled.

  - `PublishDir` and `PackageOutputPath` are set to `./artifacts/` so the outputs of `dotnet publish` and `dotnet pack` are next to the file-based app,
    unless [artifacts output layout][artifacts-output] is enabled.

  - `RuntimeHostConfigurationOption`s are set for `EntryPointFilePath` and `EntryPointFileDirectoryPath` (except for `Publish` and `Pack` targets)
    which can be accessed in the app via `AppContext`:

    ```cs
    string? filePath = AppContext.GetData("EntryPointFilePath") as string;
    string? directoryPath = AppContext.GetData("EntryPointFileDirectoryPath") as string;
    ```

  - `EntryPointFilePath` property is set to the entry-point file path and is made visible to analyzers via `CompilerVisibleProperty`.

  - `FileBasedProgram` property is set to `true` and can be used by SDK targets to detect file-based apps.

  - `DisableDefaultItemsInProjectFolder` property is set to `true` which results in `EnableDefaultItems=false` by default
    in case there is a project or solution in the same directory as the file-based app.
    This ensures that items from nested projects and artifacts are not included by the app.

  - `EnableDefaultCompileItems` property is set to `false` and there is a special `Compile` item for the entry-point file instead.
    See [multiple files](#multiple-files) for more details.

  - `EnableDefaultEmbeddedResourceItems` and `EnableDefaultNoneItems` properties are set to `false` if the default SDK (`Microsoft.NET.Sdk`) is being used.
    This avoids including files like `./**/*.resx` in simple file-based apps where users usually don't expect that.
    See [multiple files](#multiple-files) for more details.

  - `AssemblyName` and `RootNamespace` are set to the entry-point file name without extension (e.g., `Program` for `Program.cs`)
    to ensure the binary name and generated code namespaces are not affected by the virtual project file name (which includes the `.cs` extension).

## Grow up

When file-based programs reach an inflection point where build customizations in a project file are needed,
a single CLI command can be executed to generate a project file.
In fact, this command simply materializes the [implicit project file](#implicit-project-file) on disk.
This action should not change the behavior of the target program.

```ps1
dotnet project convert file.cs
```

The command takes a path to the entry-point file.

## Target path

The path passed to `dotnet run ./some/path.cs` is called *the target path*.
The target path must point to *the entry-point file* which
either has the `.cs` file extension, or whose contents start with `#!`.
*The target directory* is the directory of the target file.

## Integration into the existing `dotnet run` command

`dotnet run file.cs` already has a meaning if there is a project file inside the current directory,
specifically `file.cs` is passed as the first command-line argument to the target program.
We preserve this behavior to avoid a breaking change.
The file-based build and run kicks in only when:
- a project file cannot be found (in the current directory or via the `--project` option), and
- if the target file exists, and has the `.cs` file extension or contents that start with `#!`.

Otherwise, project-based `dotnet run` fallback is used and you might get an error like "Couldn't find a project to run."
You can explicitly use the `--file` option to avoid the fallback behavior.
However, it is discouraged to put file-based apps in the same directory as a `.csproj` file (such file-based apps might not be properly recognized by tooling).

File-based programs are processed by `dotnet run` equivalently to project-based programs unless specified otherwise in this document.
For example, the remaining command-line arguments after the first argument (the target path) are passed through to the target app
(except for the arguments recognized by `dotnet run` unless they are after the `--` separator)
and working directory is not changed (e.g., `cd /x/ && dotnet run /y/file.cs` runs the program in directory `/x/`).

If a dash (`-`) is given instead of the target path (i.e., `dotnet run -`), the C# file to be executed is read from the standard input.
In this case, the current working directory is not used to search for other files (launch profiles, other sources in case of multi-file apps);
the compilation consists solely of the single file read from the standard input.
However, the current working directory is still used as the working directory for building and executing the program.
To reference projects or files relative to the current working directory (instead of relative to the temporary directory the file is isolated in),
you can use something like `#:project $(MSBuildStartupDirectory)/relative/path` or `#:ref $(MSBuildStartupDirectory)/relative/lib.cs`.

`dotnet path.cs` is a shortcut for `dotnet run --file path.cs` provided that `path.cs` is a valid [target path](#target-path) (`dotnet -` is currently not supported)
and it is not a DLL path, built-in command, or a NuGet tool (e.g., `dotnet watch` invokes the `dotnet-watch` tool
even if a valid `watch` file-based app exists in the current directory;
one can use `dotnet ./watch` to run the file-based app).

### Other commands

Commands `dotnet restore file.cs` and `dotnet build file.cs` are needed for IDE support and hence work for file-based programs.

Commands `dotnet publish file.cs` and `dotnet pack file.cs` are also supported for file-based programs.
Note that file-based apps have implicitly set `PublishAot=true`, so publishing uses Native AOT (and building reports AOT warnings).
To opt out, use `#:property PublishAot=false` directive in your `.cs` file.
Additionally, file-based apps have implicitly set `PackAsTool=true` because file-based apps are usually tools;
again, you can opt out via `#:property PackAsTool=false`.

Command `dotnet clean file.cs` can be used to clean build artifacts of the file-based program.

Sub-commands of `dotnet package add` and `dotnet reference` can be used to manipulate `#:package`/`#:project`/`#:ref` directives in the C# files,
similarly to what the commands do for project-based apps. For example, `dotnet package add PackageName --file app.cs`.

## Multiple files

By default, the app only includes the entry-point file (plus any implicit build files like `Directory.Build.props` are considered).
This is achieved by having property `EnableDefaultCompileItems=false` and entry-point file `Compile` item in the virtual project.
(The `Compile` item has `Exclude="@(Compile)"` to avoid duplicate `Compile` items when using e.g., `#:include *.cs` directive).

Thanks to this, it is possible to have multiple file-based apps in a single directory.

Default items like `.resx` are included in the build only if an `#:sdk` other than `Microsoft.NET.Sdk` is used (to improve performance for simple file-based apps).
Again, this is achieved by setting `EnableDefaultNoneItems=false` and `EnableDefaultEmbeddedResourceItems=false` in the virtual project.

To customize this default behavior, you can use the `#:include`/`#:exclude` [directives](#directives-for-project-metadata)
or use some custom MSBuild code like `#:property EnableDefaultCompileItems=true`.

During [conversion](#grow-up), any `Content`, `None`, `Compile`, and `EmbeddedResource` items that do not have metadata `ExcludeFromFileBasedAppConversion=true` are copied into the output directory.
The implicit `EnableDefault*Items` properties and `Compile` item are not preserved in the converted project,
because the constructed project will have the same behavior even if all default items are included thanks to the output directory being isolated
and the conversion process only copying the items that were included in the original virtual project.

## Build outputs

If [artifacts output layout][artifacts-output] is enabled, build outputs of the file-based app are placed there
(except caching markers which are placed in the global temp directory described next).
Otherwise, build outputs are placed under a subdirectory whose name is hashed file path of the entry point
inside a temp or app data directory which should be owned by and unique to the current user per [runtime guidelines][temp-guidelines].
The subdirectory is created by the SDK CLI with permissions restricting access to it to the current user (`0700`) and the run fails if that is not possible.
Note that it is possible for multiple users to run the same file-based program, however each user's run uses different build artifacts since the base directory is unique per user.
Apart from keeping the source directory clean, such artifact isolation also avoids clashes of build outputs that are not project-scoped, like `project.assets.json`, in the case of multiple entry-point files.

Artifacts are cleaned periodically (every 2 days) by a background task that is started by `dotnet run` and
removes current user's `dotnet run` build outputs that haven't been used in 30 days.
They are not cleaned immediately because they can be re-used on subsequent runs for better performance.
The automatic cleanup can be disabled by environment variable `DOTNET_CLI_DISABLE_FILE_BASED_APP_ARTIFACTS_AUTOMATIC_CLEANUP=true`,
but other parameters of the automatic cleanup are currently not configurable.
The same cleanup can be performed manually via command `dotnet clean file-based-apps`.

## Directives for project metadata

It is possible to specify some project metadata via *file-level directives*
which are [ignored][ignored-directives] by the C# language but recognized by the SDK CLI.

```cs
#:sdk Microsoft.NET.Sdk.Web
#:property TargetFramework=net11.0
#:property LangVersion=preview
#:package System.CommandLine@2.0.0-*
#:package Microsoft.Build@17.0.0 ExcludeAssets=runtime PrivateAssets=all
#:project ../MyLibrary
#:ref ../lib/lib.cs
#:include ./**/*.cs
#:include appsettings.json CopyToOutputDirectory=PreserveNewest
```

Each directive has a kind (e.g., `package`), a name (e.g., `System.CommandLine`), a separator (e.g., `@`), and a value (e.g., the package version).
The value is required for `#:property`, optional for `#:package`/`#:sdk`, and disallowed for `#:project`/`#:ref`/`#:include`.  

The name must be separated from the kind of the directive by whitespace
and any leading and trailing white space is not considered part of the name and value.

The remainder of a directive (after the kind) is split into whitespace-separated tokens.
Whitespace inside a value is not allowed unless the value is enclosed in double quotes (`"`).
A value is written either bare or wrapped entirely in double quotes.
A quoted value is lexed as a regular C# string literal,
so its escape sequences are decoded, e.g., `#:property Description="Hello World"` sets the value to `Hello World`,
`#:property Path="a\\b"` sets it to `a\b`, and `#:property Text="a\"b"` sets it to `a"b`.
Verbatim (`@"..."`) and raw (`"""..."""`) string literals are not supported.
Quotes can only enclose a whole value, so `#:property A=B` and `#:property A="B"` are allowed, but `#:property A=B"C"` is an error.
It is an error if a quote is left unterminated or if a quoted value contains an invalid escape sequence (e.g., `"a\q"`).

`#:package`, `#:project`, `#:ref`, and `#:include` directives can specify additional MSBuild item metadata as trailing `Name=Value` tokens,
e.g., `#:package Microsoft.Build@17.0.0 ExcludeAssets=runtime PrivateAssets=all`.
Each metadata name must be a unique valid XML element name; each metadata value can be quoted to contain whitespace.
When a `#:package` directive specifies its version after `@`, it cannot also specify `Version` metadata.
The other directive kinds do not support trailing metadata and it is an error to specify extra tokens for them.

Whitespace may surround the separator (`@` or `=`) of any directive,
so `#:property Xyz="abc "`, `#:property Xyz ="abc "`, and `#:property Xyz = "abc "` are equivalent,
as are `#:package Package@1.0.0 Note="see the docs"` and `#:package Package @ 1.0.0 Note = "see the docs"`.
Either side of the separator can be quoted, e.g., `#:package "Humanizer"@2.0`.

Because a bare value keeps a backslash literal while a quoted value follows C# escape rules,
a Windows path is simplest written bare (`#:project C:\src\lib`)
or with forward slashes if quoting is needed (`#:project "C:/src/my lib"`);
quoting a backslash path requires escaping it (`"C:\\src\\my lib"`).

For backward compatibility, a directive whose value contains no double quotes is still accepted in a *legacy mode*
when its trailing whitespace-separated tokens cannot be parsed as the new metadata form:
the entire remainder after the name and separator is taken verbatim as a single value (including any internal whitespace),
matching how these directives behaved before quoting and metadata were supported.
For `#:package`, `#:project`, `#:ref`, and `#:include`, if every trailing token is valid `Name=Value` metadata,
those tokens are treated as metadata instead; for example, `#:project path A=B` has the value `path` and the metadata `A=B`.
Analyzer [CA2267](https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2267)
flags legacy directives and offers a code fix to rewrite them into the quoted form.

The directives are processed as follows:

- The name and value of the first `#:sdk` is injected into `<Project Sdk="{0}/{1}">` (or just `<Project Sdk="{0}">` if it has no value),
  and the subsequent `#:sdk` directive names and values are injected as `<Sdk Name="{0}" Version="{1}" />` elements (or without the `Version` attribute if it has no value).
  It is an error if the name is empty (the version is allowed to be empty, but that results in empty `Version=""`).

- Each `#:property` is injected as `<{0}>{1}</{0}>` in a `<PropertyGroup>`.
  It is an error if property does not have a value or if its name is empty (the value is allowed to be empty) or contains invalid characters.

- Each `#:package` is injected as `<PackageReference Include="{0}" Version="{1}">` (or without the `Version` attribute if it has no value) in an `<ItemGroup>`.
  It is an error if its name is empty (the value, i.e., package version, is allowed to be empty, but that results in empty `Version=""`).
  Any trailing `Name=Value` metadata is injected as child elements, e.g.,
  `<PackageReference Include="{0}" Version="{1}"><ExcludeAssets>runtime</ExcludeAssets></PackageReference>`.

  It is valid to have a `#:package` directive without a version.
  That's useful when central package management (CPM) is used.
  NuGet will report an appropriate error if the version is missing and CPM is not enabled.

- Each `#:project` is injected as `<ProjectReference Include="{0}" />` in an `<ItemGroup>`.
  It is an error if the value is empty.
  Any trailing `Name=Value` metadata is injected as child elements of the `<ProjectReference>`.
  If the path points to an existing directory, a project file is found inside that directory and its path is used instead
  (because `ProjectReference` items don't support directory paths).
  An error is reported if zero or more than one projects are found in the directory, just like `dotnet reference add` would do.

- Each `#:ref` references another `.cs` file as a separate project reference.
  A virtual project is created for the referenced file (e.g., `lib.cs` produces a virtual `lib.cs.csproj`),
  and a `<ProjectReference Include="lib.cs.csproj" />` is injected in an `<ItemGroup>`.
  It is an error if the name is empty or if the referenced file does not exist.
  Any trailing `Name=Value` metadata is injected as child elements of the `<ProjectReference>`.
  Unlike `#:project`, `#:ref` points to a `.cs` file (not a `.csproj` file or directory).

  The referenced file is itself a file-based program with its own virtual project (defaulting to `OutputType=Exe`).
  Library files without an entry point should use `#:property OutputType=Library` to avoid compilation errors.
  Because the referenced file is compiled as a separate assembly, internal members of the referenced file are not accessible from the referencing file.
  The `#:ref` directive is transitive: a referenced file can itself contain `#:ref` directives (or any other directives).

  Relative paths are resolved relative to the file containing the directive.
  MSBuild variables (like `$(MSBuildProjectDirectory)`) can be used in the path.

  During [conversion](#grow-up), each `#:ref` directive creates a separate library project in a sibling directory
  and a corresponding `<ProjectReference>` entry is added to the converted project.
  The conversion is recursive: any `#:ref` directives in the referenced files are also converted in the same way.

- Each `#:include` is injected as `<{1} Include="{0}" />` in an `<ItemGroup>`
  where `{0}` is the directive's value and `{1}` is determined by its extension.
  The mapping can be customized by setting the MSBuild property `FileBasedProgramsItemMapping`
  which is by default set to `.cs=Compile;.resx=EmbeddedResource;.json=None;.razor=Content;.dll=Reference`.

  It is an error if the value is empty.

  Any trailing `Name=Value` metadata is injected as child elements of the inferred item, e.g.,
  `#:include appsettings.json CopyToOutputDirectory=PreserveNewest` produces
  `<None Include="appsettings.json"><CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory></None>`.

  Relative paths are resolved relative to the file containing the directive.

- Each `#:exclude` is injected similarly to `#:include` but with `Remove="{0}"` instead of `Include="{0}"`.
  It does not support trailing metadata because MSBuild does not allow metadata on `Remove` items.

- Other directive kinds result in an error, reserving them for future use.

Directive values support MSBuild variables (like `$(..)`) normally as they are translated literally and left to MSBuild engine to process.
However, in `#:project` and `#:ref` directives, variables might not be preserved during [grow up](#grow-up),
because there is additional processing of those directives that makes it technically challenging to preserve variables in all cases
(project and ref directive values need to be resolved to be relative to the target directory
and also to point to a project file rather than a directory).
Note that it is not expected that variables inside the path change their meaning during the conversion,
so for example `#:project ../$(LibName)` is translated to `<ProjectReference Include="../../$(LibName)/Lib.csproj" />` (i.e., the variable is preserved).
However, variables at the start can change, so for example `#:project $(ProjectDir)../Lib` is translated to `<ProjectReference Include="../../Lib/Lib.csproj" />` (i.e., the variable is expanded).
In other directives, all variables are preserved during conversion.

Because these directives are limited by the C# language to only appear before the first "C# token" and any `#if`,
dotnet CLI can look for them via a regex or Roslyn lexer without any knowledge of defined conditional symbols
and can do that efficiently by stopping the search when it sees the first "C# token" or `#if`.

For a given `dotnet run file.cs`, we include directives from the current entry point file (`file.cs`) and all other non-entry-point C# files,
specifically from all `Compile` items included in the project, no matter whether the `Compile` items are specified in some MSBuild code or inferred from `#:include`.
The order in which other files are processed is currently unspecified (can change across SDK versions) but deterministic (stable in a given SDK version).
We do not limit these directives to appear only in entry point files because it allows:
- a non-entry-point file like `Util.cs` to be self-contained and have all the `#:package`s it needs specified in it,
- which also makes it possible to share it independently or symlink it to multiple script folders,
- and it's similar to `global using`s which users usually put into a single file but don't have to.

Duplicate directives are handled according to the MSBuild construct they represent.
For `#:sdk`, `#:property`, and `#:package`, directives are considered duplicate if their kind and name are equal case-insensitively.
If the duplicate has the same unevaluated value (before any MSBuild variable expansion), it is ignored.
If the duplicate has a different unevaluated value, it is an error (which might be relaxed in the future with smarter deduplication,
for example, properties could be concatenated via `;`, more specific package versions could override less specific ones.)
For `#:project`, `#:ref`, `#:include`, and `#:exclude`, duplicates are allowed and translated to the corresponding MSBuild items.
Any resulting item behavior, including warnings for duplicate `Compile` items, is left to MSBuild and the compiler.
Directive deduplication allows separate "self-contained" utilities to e.g. reference overlapping sets of packages even if they end up in the same compilation.

During [grow up](#grow-up), `#:` directives are removed from the `.cs` files and turned into elements in the converted `.csproj` file when needed.
Files included with `#:include` are copied into the converted project directory; if an included file is not picked up by the converted project's defaults, the corresponding project item is also written explicitly into an `<ItemGroup>` in the converted project.
For project-based programs, `#:` directives are an error (reported by Roslyn when it's told it is in "project-based" mode).
`#!` directives are also removed during grow up, although we could consider to have an option to preserve them
(since they might still be valid after grow up, depending on which program they are actually specifying to "interpret" the file, i.e., it might not be `dotnet run` at all).

## Shebang

Along with `#:`, the language also ignores `#!` which could be then used for [shebang][shebang] support.

```cs
#!/usr/bin/env dotnet
Console.WriteLine("Hello");
```

When a file-based program uses [`#:include`](#multiple-files) directives to include additional files,
the entry point file should start with `#!` to clearly distinguish it from included files.
This helps IDEs to properly handle multi-file scenarios and discover entry points.
The analyzer **CA2266** reports a warning if the entry point file is missing the shebang line in this scenario.

## Implementation

The build is performed using MSBuild APIs on in-memory project files.

### Optimizations

If an up-to-date check detects that inputs didn't change in subsequent `dotnet run file.cs` invocations,
building is skipped (as if `--no-build` option has been passed).
The up-to-date check is not 100% precise (e.g., files imported through an implicit build file are not considered).
It is possible to enforce a full build using `--no-cache` flag or `dotnet build file.cs`
(for a more permanent opt-out, there is MSBuild property `FileBasedProgramCanSkipMSBuild=false`).
Environment variable [`DOTNET_CLI_CONTEXT_VERBOSE=true`][verbose-env] can be used to get more details about caching decisions made by `dotnet run file.cs`.

There are multiple optimization levels - skipping build altogether, running just the C# compiler, or running full MSBuild.
We always need to re-run MSBuild if implicit build files like `Directory.Build.props` change but
from `.cs` files, the only relevant MSBuild inputs are the `#:` directives,
hence we can first check the `.cs` file timestamps and for those that have changed, compare the sets of `#:` directives.
If only `.cs` files change, it is enough to invoke `csc.exe` (directly or via a build server)
re-using command-line arguments that the last MSBuild invocation passed to the compiler.
If no inputs change, it is enough to start the target executable without invoking the build at all.

## Alternatives and future work

This section outlines potential future enhancements and alternatives considered.

### Target path extensions

We could allow folders as the target path in the future (e.g., `dotnet run ./my-app/`).

Similarly, it could be possible to specify the whole C# source text in a command-line argument
like `dotnet run --cs-code 'Console.WriteLine("Hi")'`.

### Enhancing integration into the existing `dotnet run` command

`dotnet run path` stops working when a file-based program [grows up](#grow-up) into a project-based program.
Users could avoid that by using `cd path; dotnet run` instead.
For that to work always (before and after grow up),
`dotnet run` without a `--project` argument and without a project file in the current directory
would need to search for a file-based program in the current directory instead of failing.

We could add a universal option that works with both project-based and file-based programs,
like `dotnet run --directory ./dir/`. For inspiration, `dotnet test` also has a `--directory` option.
We already have a `--file` option. Both could be unified as `--path`.
Since there can be multiple entry points in a single directory, it would be useful to have
an option like `dotnet run --entry ./dir/name` which would work for both `./dir/name.cs` and `./dir/name/name.csproj`.

### Nested files errors

We could report an error if there are many nested directories and files,
so for example, if someone puts a C# file with `#:include **.cs` into `C:/sources`
and executes `dotnet run C:/sources/file.cs` or opens that in the IDE,
we do not walk all user's sources. Note that this problem exists with project-based programs as well.
Also, having a project-based or file-based program in the drive root would result in
[error MSB5029](https://learn.microsoft.com/visualstudio/msbuild/errors/msb5029).

### Shebang support

Some shells do not support multiple command-line arguments in the shebang
which is needed if one wants to use `/usr/bin/env` to find the `dotnet` executable
(although `-S` argument can be sometimes used to enable multiple argument support),
so `dotnet file.cs` instead of `dotnet run file.cs` should be used in shebangs:

```cs
#!/usr/bin/env dotnet
// ^ Should work in all shells.
```

```cs
#!/usr/bin/env dotnet run
// ^ Might not work in all shells. "dotnet run" might be passed as a single argument to "env".
```

```cs
#!/usr/bin/env -S dotnet run
// ^ Works in some shells.
```

### Other possible commands

We can consider supporting other commands like `dotnet watch`,
however the primary scenario is `dotnet run` and we might never support additional commands.

All commands supporting file-based programs should have a way to receive the target path similarly to `dotnet run`,
e.g., via options like `--directory`/`--entry` as described [above](#integration-into-the-existing-dotnet-run-command),
or as the first argument if it makes sense for them.

We could also add `dotnet compile` command that would be the equivalent of `dotnet build` but for file-based programs
(because "compiling" might make more sense for file-based programs than "building").

`dotnet clean` could be extended to support cleaning all file-based app outputs,
e.g., `dotnet clean --all-file-based-apps`.

### Explicit importing

Instead of implicitly including files from the target directory, the importing could be explicit, like via a directive:

```cs
#import ./another-file.cs
```



[artifacts-output]: https://learn.microsoft.com/dotnet/core/sdk/artifacts-output
[verbose-env]: https://learn.microsoft.com/dotnet/core/tools/dotnet-environment-variables#dotnet_cli_context_
[ignored-directives]: https://github.com/dotnet/csharplang/blob/c85bbf501958fa86ee2db94b14c82ee8fd2066b9/proposals/csharp-14.0/ignored-directives.md
[shebang]: https://en.wikipedia.org/wiki/Shebang_%28Unix%29
[temp-guidelines]: https://github.com/dotnet/runtime/blob/d0e6ce8332a514d70b635ca4829bf863157256fe/docs/design/security/unix-tmp.md

---

### Documentation General Dotnet Test Artifact Post Processing (`documentation/general/dotnet-test-artifact-post-processing.md`)

# `dotnet test` artifact post-processing (Microsoft.Testing.Platform)

## Overview

When `dotnet test` runs a solution (or several projects) on
[Microsoft.Testing.Platform](https://learn.microsoft.com/dotnet/core/testing/microsoft-testing-platform-intro)
(MTP), every test application produces its own artifacts — one TRX report per module, one
code-coverage file per module, and so on. Left as-is, the run summary lists each of those
files individually, and downstream consumers (Azure DevOps `PublishTestResults`,
`ReportGenerator`, CI dashboards) have to glob dozens of paths or merge them out of band.

**Artifact post-processing** consolidates compatible artifacts produced by different test
applications into a single merged artifact, so a multi-project run surfaces one report per
format instead of one per module. It is on by default and runs automatically; nothing in the
project or the command line is required to opt in.

This document describes what the .NET SDK actually does. The upstream concept is defined by
microsoft/testfx
[RFC 018](https://github.com/microsoft/testfx/blob/main/docs/RFCs/018-Artifact-Post-Processing.md);
where the two differ, this document reflects the SDK's behavior.

> This feature applies only to the Microsoft.Testing.Platform runner for `dotnet test`. It is
> unrelated to the VSTest artifact post-processing described under [Caveats](#caveats).

## Code coverage summary

Coverage producers that implement the negotiated MTP coverage-summary contract also supply
measurements to the SDK's terminal reporter. For a single test application, its overall
measurements appear in the run summary. For several applications, the SDK uses measurements
read by the coverage post-processor from the **actual merged artifact**:

```text
  Code Coverage Summary:
    Total - Line: 98.9%
```

The SDK never adds or averages per-application percentages or counts: different applications
can cover the same assembly. `Total` is reserved for a complete, unambiguous merge whose
explicit input provenance represents every test application. Without such a merge, available
measurements remain application- or artifact-scoped, not a purported run total. This includes
`--no-artifact-post-processing`, partial or unsuccessful merges, and cancelled runs.

Completeness includes balanced session lifecycle and the association between each execution,
test-host instance, and session, not just matching their separate counts. Missing sibling
coverage, ambiguous controller/legacy identity, or a path overwritten by another source
keeps coverage scoped. Fallback labels retain instance/session identity. Replacing an output
path also invalidates its previous coverage metadata, including when its new metadata is
absent or invalid.

Percentages use a decimal point and one decimal place, independently of the current numeric
culture. Labels are localized. Set `DOTNET_CLI_UI_LANGUAGE=en` when a CI parser needs the
English labels; for example, the following regular expression captures the line percentage:

```regex
^\s*Total - Line: ([0-9]+(?:\.[0-9]+)?)%$
```

An explicit measurement with no coverable data is rendered as `no coverable data`, not as
zero or full coverage. Missing or unsupported summary metadata does not invent a measurement.
Older MTP or coverage-extension versions continue to run and report artifacts as before,
without the new summary. Summary reporting does not change threshold evaluation or exit codes.

## When it runs

Post-processing happens after every test application has exited and before the run summary is
rendered. To keep the merged report trustworthy, the SDK
[skips it entirely](../../src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs)
when any of the following is true:

- `--help` was requested (`dotnet test --help`).
- `--list-tests` was requested (test discovery, not execution).
- `--collect-test-map` was requested (mapping collection, not test execution).
- `--no-artifact-post-processing` was passed.
- The run was cancelled with <kbd>Ctrl</kbd>+<kbd>C</kbd>.

Runs cut short by `--maximum-failed-tests` or `--timeout` are handled differently. The SDK
plans only artifact groups whose processor explicitly advertised support for policy-truncated
runs. Other groups remain untouched, preventing an authoritative merger such as TRX or coverage
from making an incomplete run look complete while still allowing summary-style processors to
describe the truncation accurately.

Post-processing can never change the run's exit code; it only affects which artifacts are
listed. See [Failure behavior](#failure-behavior).

## How the SDK decides what to merge

The SDK never inspects artifact contents to decide what is mergeable. It works entirely from
data it already has: the capabilities each test application advertised during the MTP
handshake, and the artifacts that streamed live over the `dotnet-test` pipe during the run.
The grouping and election logic lives in
[`ArtifactPostProcessingPlanner`](../../src/Cli/dotnet/Commands/Test/MTP/ArtifactPostProcessingPlanner.cs).

### Capability comes from the handshake

During its handshake, each MTP test application reports the post-processors registered inside
it through two properties: `SupportedPostProcessorKinds` (reverse-DNS artifact *kinds*, e.g.
`microsoft.testing.trx`) and `SupportedPostProcessorExtensionsLegacy` (lowercase file
extensions, for producers that do not tag a kind). Both are semicolon-separated.
`SupportedTruncatedRunPostProcessorKinds` and
`SupportedTruncatedRunPostProcessorExtensionsLegacy` advertise the subsets whose processors
can consume the incomplete set of complete artifacts observed before
`--maximum-failed-tests` or `--timeout` stopped the run. An application that advertises no
capability applicable to the current run does not participate. The handshake property ids are
defined in [`CliConstants`](../../src/Cli/dotnet/Commands/Test/CliConstants.cs).

`RequiredPostProcessorKinds` (field 18) identifies the subset of supported kinds that
must be processed even for a single input. The SDK replies with
`RequiredPostProcessingSupported=true` (field 19) only for accepted handshakes in
eligible runs. That promise includes both singleton processing and the authoritative
manifest summary described below. It is not a protocol-version bump or a coverage
capability. Unsupported HTTP/WebAssembly workers, help, discovery, collection, and
explicit opt-out do not receive that promise.

### Grouping

Artifacts are de-duplicated by path and then grouped:

1. **Kind first.** Artifacts that carry a reverse-DNS `Kind` are grouped by that kind.
2. **Extension fallback.** Artifacts with no kind are grouped by lowercase file extension.

A group is a merge candidate only if a compatible application advertised the matching kind or
extension for the current run's completeness. Optional complete-run groups require
**at least two inputs**. Required kinds and explicitly supported policy-truncated groups
can run with **one input**. Required groups elect an application that advertises the
required kind, not an older optional-only processor. Zero-input jobs are not run.
(A kind group and a matching extension group that
individually have one input each can still be merged together when a shared application supports
both and the combined count reaches two.)

For binary code-coverage artifacts (kind `microsoft.codecoverage` / extension `.coverage`),
an application is a candidate only when its architecture matches the inputs. Coverage blobs
are architecture-specific, so an `x64` application is not asked to merge `arm64` coverage.
This constraint applies only to coverage; TRX and other text formats are
architecture-agnostic.

### Election

Multiple applications may be able to merge the same group. The planner runs a greedy minimal
[set-cover](https://en.wikipedia.org/wiki/Set_cover_problem): it repeatedly elects the
application that covers the most still-uncovered groups, so the **fewest** test applications
are relaunched. Ties are broken deterministically — preferring an application that produced
more of the inputs, then the higher target-framework version, then path order — so a given
input set always produces the same plan.

Applications whose worker transport is unsupported are removed **before** election. An
unsupported application must not win more groups and then be discarded, losing a required
job that a desktop application could have processed.

## How the merge is performed

Each elected application is relaunched **once** — not to run tests, but as an MTP tool. The tool
name is passed as the first argument, followed by the manifest
(`<test application> internal-merge-artifacts --manifest <manifest.json>`), and the process is
connected to a fresh `dotnet-test` pipe. The launch, timeout, and argument construction live in
[`TestApplication`](../../src/Cli/dotnet/Commands/Test/MTP/TestApplication.cs); the tool name
and manifest option are defined in
[`CliConstants`](../../src/Cli/dotnet/Commands/Test/CliConstants.cs).

The SDK writes a JSON manifest listing the input artifacts (path, kind, producing module,
target framework, architecture, execution id) and the output directory, then hands it to the
relaunched tool. On a policy-truncated run, the manifest also contains `truncationReason` with
the value `maximumFailedTests` or `timeout`; Microsoft.Testing.Platform exposes that through
`ArtifactPostProcessingContext`.

The producing module is the identity from the accepted handshake, which may be a managed
assembly behind the selected apphost. The executable launch path is retained separately.
An unavailable target framework is left null: the runtime reported by a handshake is not
proof of the assembly's compilation target, particularly with roll-forward or platform
suffixes.

Every manifest includes a `runSummary` object with integer `totalTests`, `passedTests`,
`failedTests`, `skippedTests`, `durationTicks`, `exitCode`, and `testModuleCount`. The SDK
captures it once after test-process and data-channel completion and after applying
cancellation, handshake, minimum-test, aggregate zero-test, and ignored-exit policies.
Counts come from the parent reporter's logical live results, not summed retry fragments
or recovered files. Duration is parent wall-clock test execution before artifact processing,
not the sum of module durations. The module count includes selected modules without
fragments. Every elected worker receives the same snapshot.

The processed artifacts flow **back over the same pipe** as ordinary
file-artifact messages, together with the exact manifest input paths represented by each output,
so they re-enter the normal reporter path. In the summary, the SDK
[removes only those consumed inputs and adds the processed output](../../src/Cli/dotnet/Commands/Test/MTP/ArtifactPostProcessingManager.cs)
in their place. This provenance keeps an unrelated artifact listed even when it happens to share
the processed output's file extension. Older hosts that do not report provenance retain the
previous kind-and-extension inference for compatibility.

Coverage summary support is negotiated independently of the base protocol: handshake property
`CoverageSummaryVersion` (id 20) must be `"1"` on both sides. Session measurements use
`CoverageSummaryMessages` (serializer id 15), while a successfully processed artifact can carry
its own counts in the optional `FileArtifactMessage.CoverageSummary` field (id 9).
The SDK stages this metadata with the artifact and only accepts it after successful
post-processing; legacy kind/extension inference alone is insufficient to establish a
coverage total. No coverage report parser or new collector dependency is included in the SDK.

The original per-module artifacts are **never deleted from disk** — only the run summary
changes. If you need the individual files (for example a per-module TRX), they are still where
each module wrote them.

## Where the merged artifact lands

The output directory is chosen by
[`ArtifactPostProcessingManager`](../../src/Cli/dotnet/Commands/Test/MTP/ArtifactPostProcessingManager.cs):

- **With `--results-directory <dir>`**, the merged artifact is written under that directory.
- **Without `--results-directory`**, each application writes beside its own binaries and no
  single directory belongs to the run, so the SDK picks the directory of an input produced by
  the elected application (falling back to the first input directory in path order). The
  merged artifact then lands next to the reports it summarizes instead of inside an unrelated
  project's output.

The merging extension — not the SDK — decides the final file name and may nest its output. The
version of `Microsoft.Testing.Extensions.TrxReport` currently referenced by the SDK names its output
`merged-<runId>.trx`, where `runId` is derived from the inputs, and writes it into a `merged/`
subdirectory of the supplied output directory. Because the merged report is nested, a non-recursive
`*.trx` glob over the results directory picks up the per-module inputs but not the merged report, so
it does not double-count tests. CI that wants the merged report must target the `merged/` subdirectory
explicitly, for example with `merged/merged-*.trx`; a broad recursive glob would also pick up the
per-module inputs and double-count tests.

## What currently merges

Microsoft.Testing.Platform extensions provide post-processors for **TRX, Microsoft code
coverage, JUnit, CTRF, and HTML reports**. The formats available to a run still depend on which
extensions its test applications reference and enable; the SDK does not install a processor or
infer mergeability from a file name.

Compatible GitHub Actions and Azure DevOps extensions use the **required** handoff to
produce a run-level summary. They defer standalone publication only after the SDK confirms
the capability. A single summary fragment is processed just like a multi-module group.
Older SDKs, undeclared capabilities, and explicit opt-out retain the extensions' per-module
fallback. Successful TRX/CTRF/JUnit merging alone does not demonstrate this summary handoff.

### Required-summary contract decision

The SDK consumes TestFx's existing additive contract rather than inventing a report-specific
merger or parsing CI fragments itself. The
[required interface and run-summary invariants](https://github.com/microsoft/testfx/blob/f4d8d35bf45ce0ece75a66e1b197c96684767e48/src/Platform/Microsoft.Testing.Platform/Extensions/ArtifactPostProcessing/IArtifactPostProcessor.cs),
[handshake capability definitions](https://github.com/microsoft/testfx/blob/f4d8d35bf45ce0ece75a66e1b197c96684767e48/src/Platform/Microsoft.Testing.Platform/ServerMode/DotnetTest/IPC/Constants.cs),
and [manifest consumer](https://github.com/microsoft/testfx/blob/f4d8d35bf45ce0ece75a66e1b197c96684767e48/src/Platform/Microsoft.Testing.Platform/Extensions/ArtifactPostProcessing/ArtifactPostProcessingManifest.cs)
define the producer/consumer boundary. TestFx owns fragment validation, provider rendering,
and compatible standalone fallback; the SDK owns election, invocation lifetime, and the
final test-policy verdict. The managed and Native AOT CLI share this implementation.

An incomplete set of complete files is different from a malformed file. Policy-truncated
processing requires the explicit truncation capability and reason. Missing or partially
written files can fail the worker and degrade reporting; they never justify fabricated
results or an altered test verdict. Module details come only from supplied fragments,
while the authoritative totals and selected-module denominator cover the whole invocation.
No new dependency pins, coverage-summary protocol, or general cancellation mechanism are
part of this contract.

Other formats continue to be listed individually until their producing extension ships a
post-processor. The contract for adding one is public; see
[Extending it to another artifact format](#extending-it-to-another-artifact-format).

## Extending it to another artifact format

The post-processing contract is **public API on `Microsoft.Testing.Platform`**, so a third-party
extension can consolidate its own format without any change to the SDK. It is gated behind the
`TPEXP` experimental diagnostic, so it can still change; suppressing that diagnostic is how you
opt in.

The relevant public types live in `Microsoft.Testing.Platform.Extensions.ArtifactPostProcessing`:

| Type | Role |
|---|---|
| `IArtifactPostProcessor` | The contract: `SupportedModes`, `SupportsTruncatedRuns`, `SupportedKinds`, `SupportedFileExtensionsFallback`, and `ProcessAsync(inputs, outputDirectory, context, cancellationToken)`. |
| `IArtifactPostProcessorRequiresPostProcessing` | Marks internal coordination formats that require processing even for one input. |
| `IArtifactPostProcessingManager` | Registration, via `AddArtifactPostProcessor(Func<IServiceProvider, IArtifactPostProcessor>)`. |
| `ArtifactPostProcessingContext` | Truncation reason, processing mode, and the authoritative `RunSummary`. |
| `ArtifactPostProcessingRunSummary` | Parent live totals, wall-clock test duration, final policy exit code, and selected-module count. |
| `InputArtifact` | One input: path, kind, producing test module, target framework, architecture, execution id. |
| `ProcessedArtifact` | The merged result: path, kind, display name, description. |

The dispatcher that runs post-processors, the manifest, and the handshake plumbing are all
internal — an extension never interacts with them.

A minimal processor:

```csharp
#pragma warning disable TPEXP // Artifact post-processing is experimental.
internal sealed class MyArtifactPostProcessor : IArtifactPostProcessor
{
    public string Uid => "Contoso.MyReport.PostProcessor";
    public string Version => "1.0.0";
    public string DisplayName => "Contoso report merger";
    public string Description => "Merges Contoso reports.";

    public IReadOnlyList<ArtifactPostProcessingMode> SupportedModes { get; } = [ArtifactPostProcessingMode.TestModules];
    public bool SupportsTruncatedRuns => false;
    public IReadOnlyList<string> SupportedKinds { get; } = ["contoso.myreport"];
    public IReadOnlyList<string> SupportedFileExtensionsFallback { get; } = [".myreport"];

    public Task<bool> IsEnabledAsync() => Task.FromResult(true);

    public async Task<ProcessedArtifact?> ProcessAsync(
        IReadOnlyList<InputArtifact> inputs,
        string outputDirectory,
        ArtifactPostProcessingContext context,
        CancellationToken cancellationToken)
    {
        if (inputs.Count < 2)
        {
            return null; // Nothing worth merging; the originals stay listed.
        }

        string output = Path.Combine(outputDirectory, "merged.myreport");
        await MergeAsync(inputs.Select(i => i.Path), output, cancellationToken);
        return new ProcessedArtifact(output, "contoso.myreport", "Contoso report (merged)", null);
    }
}
#pragma warning restore TPEXP
```

What `dotnet test` expects of a processor:

- **Tag the artifacts you produce with the same `Kind` you advertise.** Grouping is by kind first;
  the file-extension list is only a fallback for producers that have not adopted kinds.
- **Do not claim an overly generic fallback extension.** Claiming something like `.xml`, which
  several unrelated formats use, opts your extension into groups of artifacts that are not yours.
  Prefer kind-only routing for formats whose file extension is not distinctive.
- **Return `null` rather than throwing** when there is nothing to do. This remains a legal
  successful no-op for a required processor: required means it must be invoked, not that it
  must produce an output or affect the test verdict. The originals remain listed.
- **Treat inputs as read-only** and write under the supplied `outputDirectory`. Never return one of
  the inputs as your output, and never delete a source file.
- **Set `Kind` on the artifact you return.** The MTP dispatcher pairs the result with the exact
  inputs supplied to that processor, and the SDK uses that provenance to replace only those
  originals in the run summary.
- **Set `SupportsTruncatedRuns` only when the output can accurately describe an incomplete run.**
  When enabled, inspect `context.TruncationReason` and make the truncation visible in the result.
  The capability covers an incomplete set of complete artifacts, not malformed or partially
  written files.
- **Be deterministic**: the same set of inputs should produce the same output path.

Two SDK behaviors are worth knowing about. The SDK relaunches the *fewest* test applications that
cover all mergeable groups, so a processor may be asked to merge artifacts produced by a different
test application than the one hosting it. And architecture compatibility is enforced only for code
coverage (kind `microsoft.codecoverage` / extension `.coverage`), because that format is a binary
blob; every other kind may be elected regardless of architecture.

The design behind all of this, including the election algorithm and the reasoning for kinds over
file extensions, is
[microsoft/testfx RFC 018](https://github.com/microsoft/testfx/blob/main/docs/RFCs/018-Artifact-Post-Processing.md).

## Failure behavior

Post-processing is a best-effort convenience layered on top of an already-completed run, so it
**cannot change the run's exit code**. A merge failure, a non-zero exit from the merge host, or
a timeout is degraded to a warning, and the original per-module artifacts stay listed. A run
whose tests all passed still reports success even if merging failed.

The final summary also prints `Reporting: degraded (...)` separately from the test verdict.
This includes failures while planning or starting post-processing, not just a failed merge
process. Cancellation does not create an additional reporting-failure warning.

A successful worker exit still requires a valid worker handshake and completed reporting
connection before its outputs are applied. Ctrl+C during a worker stops that process tree
without waiting for the normal artifact timeout. The parent reevaluates cancellation after
processing; a user-requested abort is distinct from a best-effort reporting failure.

When a test host exits without completing its test session, the SDK labels its **live
results as incomplete**. A TRX or another report recovered by an extension can contain more
results than the SDK received over IPC. The SDK neither adds those recovered counts to the
live counts nor changes a crash into a passing run.

## CI progress and summaries

[Captured stdout and stderr](../../src/Cli/dotnet/Commands/Test/MTP/Terminal/TerminalTestReporter.cs)
associated with individual test results are shown only for
failed tests by default, including error, timeout, and cancellation outcomes. This applies
in every environment, even with `--output detailed`. Use `--show-stdout all --show-stderr all`
to restore output for all visible results, or select `none` independently for either stream.
Test-result visibility still controls whether the entire result block is shown.

The SDK resolves these stream options separately for each module from its
[effective arguments and configuration](../../src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs).
Capture, raw test-host process output, test counts, and exit
policies are unchanged.

On terminals that cannot update a progress area in place, the
[parent SDK renderer](../../src/Cli/dotnet/Commands/Test/MTP/Terminal/SilenceDrivenHeartbeatRenderer.cs) prints a bounded
progress line after 60 seconds without visible reporter output. Hidden passing results do
not reset that interval. The line includes cumulative completed/failed counts across both
finished and active modules, active-module count, and the age of the last completion (or an
explicit indication that no test has completed). Slow tests use exponential reporting
backoff. `--no-progress` or forwarded `--progress off` disables progress;
`MTP_PROGRESS_SILENCE_SECONDS=0` disables the silence heartbeat, while
`MTP_PROGRESS_SLOW_TEST_SECONDS=0` disables slow-test messages. Nonnegative integer values
override the corresponding 60-second default.

Parent progress uses each selected module's
[effective run and launch-profile arguments](../../src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs),
resolving response files against that module's working directory. Because the progress
display is shared, an effective opt-out in any selected module disables parent heartbeats
and slow-test messages for the invocation. `--no-launch-profile-arguments` also excludes
profile arguments from that decision.

Non-cursor final summaries normally put the verdict, counts, and module/handshake failure
context before artifact paths. In Azure Pipelines, parallel multi-module runs instead group
module details, coverage, and artifacts before the final verdict. The SDK omits module
pass/fail totals when a handshake failure or a module execution/disposal failure makes those
totals ambiguous; unselected module counts remain visible. Compatible test hosts
disable their own live Azure DevOps groups for these runs; older hosts may still emit
overlapping groups. Outside that mode, successful module summaries are not repeated if they
were already printed at completion, and interactive cursor-based summary ordering is unchanged.

[`--collect-test-map` has a separate parent lifecycle](../../src/Cli/dotnet/Commands/Test/MTP/Terminal/TerminalTestReporter.Collection.cs) because collection intentionally
suppresses child test-result reporting. Its progress counts **finished modules**, not
passed tests or successful maps. Its final `Test map collection: Completed/Failed/Aborted`
status follows the existing exit-code and cancellation policy, without a zero-test run
summary. Discovery/planning counts and mapped source paths are not test outcomes.
When discovery is requested, the final summary keeps the discovery format instead of
switching to collection status; test applications still validate their option combinations.

## Configuration

| Knob | Effect |
|---|---|
| `--no-artifact-post-processing` | Skip post-processing entirely. Each test application's artifacts are listed individually, one per module. |
| `DOTNET_CLI_TEST_ARTIFACT_POST_PROCESSING_TIMEOUT_SECONDS` | Override the default 15-minute bound on a single merge host. `0` removes the timer (useful for attaching a debugger), as does any value too large for the runtime to wait on (above roughly 49.7 days). User cancellation still stops the worker. An absent, non-numeric, or negative value keeps the default. |
| `--results-directory` | Determines the output directory recorded in the manifest (see [Where the merged artifact lands](#where-the-merged-artifact-lands)). It is not passed to the merge host on the command line — the merged output location travels in the manifest so the SDK keeps control of it even when it has to be derived. |
| `--config-file` | Forwarded to the merge host, so it resolves and enables the same extensions as the test run. |
| `--diagnostic` and `--diagnostic-output-directory` | Forwarded together when requested, preserving MTP's diagnostic validation and placing worker logs beside the run's. |
| `--diagnostic-verbosity`, `--diagnostic-file-prefix`, `--diagnostic-synchronous-write` | Preserved for the worker, including when provided through response files or launch-profile arguments. Test filters, retries, collection switches, and test timeouts are not forwarded to the worker. |

## Caveats

- **`--no-build` uses whatever binary is on disk.** If that binary no longer advertises the
  kind (for example it was rebuilt without the TRX extension), post-processing silently does
  nothing — there is no candidate to elect.
- **Merging is scoped to a single `dotnet test` invocation.** There is deliberately no
  cross-invocation correlation. Artifacts produced by separate `dotnet test` runs are never
  merged together.
- **This is not VSTest artifact post-processing.** The VSTest runner has its own, unrelated
  two-phase flow (`--artifactsProcessingMode-collect` / `--artifactsProcessingMode-postprocess`
  with a `--testSessionCorrelationId`) and its own opt-out environment variable,
  `VSTEST_DISABLE_ARTIFACTS_POSTPROCESSING`. That variable has **no effect on MTP runs**, and
  `--no-artifact-post-processing` has **no effect on VSTest runs**. The two mechanisms are
  independent.
- **Retried tests.** `Microsoft.Testing.Extensions.Retry` re-runs only previously failed
  tests, so each attempt's report holds a different subset of results. De-duplicating across
  attempts is the responsibility of the merging extension, not the SDK.

## Troubleshooting

- **Did post-processing run?** When it starts, the SDK prints
  `Merging compatible artifacts produced by different test applications...`. If merging
  succeeded, the artifacts list shows a single merged path in place of the per-module inputs.
  If the line never appears, no group met the [criteria for merging](#how-the-sdk-decides-what-to-merge)
  (for example, only one artifact of a kind, or no installed extension advertised a
  post-processor for it).
- **Merge host command line and failures.** Setting `DOTNET_CLI_TEST_TRACEFILE` to a file path
  enables SDK trace logging, which records the merge host command line and any failure details.
  This is the fastest way to see exactly which application was relaunched and why a merge did
  not happen.

---

### Documentation General Eliminate Duplicate Files (`documentation/general/eliminate-duplicate-files.md`)

# Eliminate Duplicate SDK Files

## Overview

This proposal focuses on eliminating duplicated files within the .NET SDK to reduce installation size and improve disk footprint.
By removing duplicate assemblies, we can reduce the SDK size by 35% (53 MB compressed, 140 MB on disk) on Linux x64.

**Tracking issue:** [dotnet/sdk#41128](https://github.com/dotnet/sdk/issues/41128)

## Customer Impact: Why SDK Size Matters

While we often envision the .NET SDK as something installed once on a developer's machine, the reality is that most SDK installations occur in ephemeral, high-volume scenarios where the SDK is repeatedly downloaded and extracted.
SDK size directly affects both network costs (download/wire transfer) and time costs (extraction overhead).

Containers represent one of the largest and most measurable areas of impact.
Official .NET SDK container images are pulled approximately [750,000 times per week](https://msit.powerbi.com/groups/6b5ffb99-5fd3-492b-bd02-724f09fe9eff/reports/7e5d7fef-a86c-4f94-8aa3-d356c3125ee0?ctid=72f988bf-86f1-41af-91ab-2d7cd011db47&pbi_source=linkShare&bookmarkGuid=f44da1fd-c619-4158-aa51-f050b379a2b3).
When developers build within containers, whether for local development or CI/CD pipelines, they're pulling that full SDK image.
A 50 MB reduction in compressed size translates to 37.5 TB per week in bandwidth saved from official .NET container pulls alone.
Beyond containers, SDK installations also happen at high volume in CI/CD pipelines, cloud development environments, and through various tooling extensions.

The [Native AOT SDK epic](https://github.com/dotnet/sdk/issues/40931) represents a significant investment in improving performance, but it comes at the cost of increased SDK size.
Without addressing duplication, Native AOT will exacerbate the size problem and likely make customers in CI and container scenarios unhappy.
This deduplication work gives us the headroom needed to absorb the Native AOT expansion while still delivering a better overall experience.

## By the Numbers

A duplicate file analysis was performed on the SDK layout of .NET 10.0.100, where file uniqueness is defined by *name*, *TFM* (Target Framework Moniker), and *culture*.
The following data is the result of this analysis using the [SdkLayoutAnalyzer](https://github.com/MichaelSimons/SdkLayoutAnalyzer) tool.

The goal is for the vast majority if not all of the components within the SDK to depend on and use the same version of their dependencies.

**Notes:**

1. The baseline measurements in the following tables compare the complete .NET installation (including runtimes, packs, shared frameworks, host, etc.) versus just the SDK directory contents.
1. Standard archive formats (zip and tar) do not automatically deduplicate identical files, each file is compressed independently, even when multiple files have identical content.
This means that duplicate files consume space both on disk after extraction and within the compressed archive itself.

### Linux x64

| Metric       | Baseline 10.0 (dotnet / SDK only) | Detected SDK Duplicates | % Duplicates (dotnet / SDK only) |
|--------------|-----------------------------------|-------------------------|----------------------------------|
| Archive Size | 229 MB / 150 MB                   | 53 MB                   | 23.1% / 35.3%                    |
| Disk Size    | 623 MB / 402 MB                   | 140 MB                  | 22.5% / 34.8%                    |
| File Count   | 4,915 / 3,667                     | 816 files               | 16.6% / 22.2%                    |

### Windows x64

| Metric       | Baseline 10.0 (dotnet / SDK only) | Detected SDK Duplicates | % Duplicates (dotnet / SDK only) |
|--------------|-----------------------------------|-------------------------|----------------------------------|
| Disk Size    | 789 MB / 411 MB                   | 148 MB                  | 18.8% / 36.0%                    |
| File Count   | 5,610 / 3,791                     | 908 files               | 16.2% / 24.0%                    |

**Note:** The WindowsDesktop runtime and target pack, along with .NET Framework support are the major reasons for the differences between Windows and Linux.

### Download impact of removing duplicates

The following table shows download times for the .NET Linux x64 archive at various network speeds, comparing the baseline 229 MB archive against the optimized 176 MB archive (53 MB reduction).
These times represent pure wire transfer costs and do not include connection overhead such as DNS resolution, TLS handshake, or other protocol negotiations.

| Network Speed        | Before (229 MB) | After (176 MB) | Time Saved |
| -------------------- | --------------: | -------------: | ---------: |
| 100 Mbps             | 18.32s          | 14.08s         | 4.24s      |
| 500 Mbps             | 3.66s           | 2.82s          | 0.85s      |
| 1 Gbps (1000 Mbps)   | 1.83s           | 1.41s          | 0.42s      |
| 10 Gbps (10,000 Mbps)| 0.18s           | 0.14s          | 0.04s      |

The deduplicated archive downloads 23% faster on average across all network speeds.

### Extraction impact of removing duplicates

The following table shows .NET archive extraction times measured on a Linux x64 development environment with SSD storage.

| Metric  | Before (228.05 MB) | After (175.73 MB) | Time Saved |
| ------- | -----------------: | ----------------: | ---------: |
| Mean    | 3.81s              | 2.91s             | 0.90s      |
| Median  | 3.78s              | 2.92s             | 0.86s      |
| Min     | 3.77s              | 2.88s             | 0.89s      |
| Max     | 3.92s              | 2.96s             | 0.96s      |

The deduplicated archive extracts 23.5% faster on average, saving approximately 0.90 seconds per extraction.

### Duplicate categorization (relative to lowest version file to keep)

- Duplicates with same hash as file to keep: 663 (100.3 MB)
- Duplicates with different version: 40 (5.9 MB)
- Duplicates with same version but different hash: 113 (33.8 MB)
  - Of which, same version but different arch: 89 (31.4 MB)

### Top 10 Largest Duplicates

| Filename                                  | Culture | TFM            | Duplicate Count | Duplicate Size (MB) |
|-------------------------------------------|---------|--------------- |-----------------|---------------------|
| Microsoft.CodeAnalysis.CSharp.dll         | neutral | net9.0         | 3               | 24.7                |
| Microsoft.CodeAnalysis.dll                | neutral | net9.0         | 3               | 10.8                |
| Microsoft.CodeAnalysis.Features.dll       | neutral | net9.0         | 2               | 5.3                 |
| Newtonsoft.Json.dll                       | neutral | net6.0         | 7               | 5.2                 |
| Microsoft.CodeAnalysis.VisualBasic.dll    | neutral | net9.0         | 2               | 4.6                 |
| Microsoft.CodeAnalysis.Workspaces.dll     | neutral | net9.0         | 2               | 4.0                 |
| Microsoft.CodeAnalysis.Razor.Compiler.dll | neutral | netstandard2.0 | 2               | 3.6                 |
| Microsoft.Build.Tasks.Core.dll            | neutral | net10.0        | 2               | 2.6                 |
| Microsoft.Build.dll                       | neutral | net10.0        | 2               | 2.5                 |
| System.Diagnostics.EventLog.Messages.dll  | neutral | netstandard2.0 | 4               | 2.3                 |
| **Total**                                 |         |                | **29**          | **65.6**            |

### Trends

An analysis of the current in-support versions of .NET (Linux x64) illustrates that this problem is not trending towards a desirable end state.
Notice the 33% increase in duplicate file size in 10.0 compared to 9.0.

| .NET Version | SDK Only File Count | SDK Only Disk Size | # Duplicate Files | Duplicate Size |
|--------------|---------------------|--------------------|-------------------|----------------|
| 8.0          | 3499                | 394 MB             | 772               | 114 MB         |
| 9.0          | 3619                | 380 MB             | 811               | 107 MB         |
| 10.0         | 3667                | 402 MB             | 816               | 140 MB         |

#### Top 4 Duplicate File Size Increases in 10.0

| File Name                             | Source                       | Change   | Size Increase (MB) |
|---------------------------------------|------------------------------|----------|--------------------|
| Microsoft.CodeAnalysis.CSharp.dll     | sdk/                         | New Copy | 18.2               |
| Microsoft.CodeAnalysis.dll            | sdk/                         | New Copy | 7.9                |
| Microsoft.CodeAnalysis.Features.dll   | sdk/DotnetTools/dotnet-watch | New Copy | 5.3                |
| Microsoft.CodeAnalysis.Workspaces.dll | sdk/DotnetTools/dotnet-watch | New Copy | 4.0                |
| **Total**                             |                              |          | **35.4**           |

## Proposed Approach

The proposed approach leverages file links to eliminate duplicate files within the SDK layout, reducing both disk footprint and archive size without requiring changes to component assembly loading logic or directory structures.

### Platform-Specific Link Strategy

Due to platform-specific constraints, the implementation will at least initially use different link types on different operating systems:

**Windows: Hard Links**

On Windows, hard links must be used because symbolic links require the `SeCreateSymbolicLinkPrivilege` privilege, which by default only Administrators have.
Regular users cannot create symbolic links without either having this privilege explicitly granted or [enabling Developer Mode](https://blogs.windows.com/windowsdeveloper/2016/12/02/symlinks-windows-10/).
Hard links do not require elevated privileges and work for all users.

**Linux and macOS: Symbolic Links (Current Strategy)**

Our desired direction is to use hard links across all platforms for their performance advantages.
However, there are currently unknowns with using hard links in RPM packages that prevent us from implementing this approach on Linux at this time.

While the RPM protocol itself supports hard links, there are known issues in both the tooling used to create RPM packages and in some package managers' extraction implementations ([RHEL investigation](https://github.com/dotnet/source-build/discussions/3535#discussioncomment-6939375)).
Additionally, our current build infrastructure (Arcade) does not support creating RPM packages with hard links ([dotnet/arcade#16453](https://github.com/dotnet/arcade/issues/16453)).

Before we can confidently support hard links on Linux, we need to:

1. Fix the Arcade infrastructure to support creating RPM packages with hard links
2. Test comprehensively on the Linux distributions we target, particularly Azure Linux
3. Work with distribution maintainers to ensure compatibility

Until this work is completed and validated, we will use symbolic links on non-Windows platforms including macOS for implementation simplicity.

If we find that hard links cannot be used in RPM packages long term, one alternative to consider would be using hard links everywhere except RPM packages, which would continue using symbolic links.
However, this approach has trade-offs that would need to be carefully evaluated:

- **Con:** Different link types across acquisition channels adds complexity
- **Con:** Distribution maintainers who create RPM packages from our source tarballs would need to translate hard links to symbolic links

A decision on this alternative approach will be made once the RPM packaging investigation is complete and we have a clearer understanding of the constraints.

**Why Hard Links are Preferred**

Hard links are generally preferred because they [offer performance advantages since no extra steps are needed to resolve the file path](https://www.linuxbash.sh/post/symbolic-links-ln-s-vs-hard-links), providing slightly better access time compared to symbolic links which require path resolution.

**Key Benefits of File Links:**

- **No runtime changes required** — Components continue to reference files using their existing paths. Both hard links and symbolic links are transparent to applications.
- **Immediate disk savings** — Links reduce disk usage by the size of duplicate files.
- **Tarball compatibility** — Tar format natively supports both hard links and symbolic links, preserving space savings in compressed archives.
- **Simple implementation** — Identification and replacement can be implemented entirely during the layout generation phase.

### Implementation Strategy

Files will be identified as duplicates by comparing hashes of their content.
When multiple files within the SDK layout share identical hashes, all copies except one will be replaced with links (hard links on Windows, symbolic links on Linux and macOS) pointing to a single retained instance.

Creating links is straightforward now that the .NET runtime has added native support for creating both hard links and symbolic links across all supported platforms in .NET 11.
The SDK build infrastructure can leverage `File.CreateHardLink` and `File.CreateSymbolicLink` APIs during layout generation to replace duplicate files with the appropriate link type for each platform.

Archive formats like tar.gz natively support both hard links and symbolic links, preserving the space savings when the SDK is distributed in compressed form.

### Windows Archive Format Considerations

Zip archives do not support hard links.
To solve this problem, we will add tarball support for Windows distributions.

Windows 11 and recent versions of Windows 10 include native support for extracting tar.gz archives through Windows Explorer and the `tar` command-line utility.
This native support makes tarballs a viable distribution format for Windows users without requiring third-party tools.

### Windows Tarball Adoption Plan

The transition to tarball-based distributions for Windows will be implemented in phases:

**Phase 1: Enable Hard Links in SDK Layout**

In the initial preview release, hard links will be added to the SDK layout during the build process.
This change enables space savings in tarball distributions immediately.
Tarballs created from this layout will preserve hard links and deliver the full size reduction benefits.
The existing zip archives will continue to be published with duplicates during this phase.

**Phase 2: Migrate Acquisition Channels**

In subsequent preview releases, we will migrate the acquisition channels under our control to use Windows tarballs:

- **dotnet-install scripts** ([dotnet/install-scripts](https://github.com/dotnet/install-scripts)) — Update to prefer tarballs on Windows
- **Azure DevOps .NET install task** ([microsoft/azure-pipelines-tasks](https://github.com/microsoft/azure-pipelines-tasks)) — Add tarball support for Windows agents
- **GitHub Actions setup-dotnet** ([actions/setup-dotnet](https://github.com/actions/setup-dotnet)) — Add tarball extraction support for Windows
- **Official .NET Docker images** ([dotnet/dotnet-docker](https://github.com/dotnet/dotnet-docker)) — Migrate Windows containers to use tarballs

This phased migration allows us to validate the tarball experience with our own tooling before encouraging broader adoption, and enables us to gather telemetry data on zip usage to inform the decisions about retaining zip archive support.

### Runtime Tarball Support

To provide a coherent installation experience, all .NET runtimes should be updated to include Windows tarballs alongside existing archive formats.
This consistency allows consumers and tooling to handle the SDK and runtimes uniformly, simplifying installation scripts and automation workflows.

### Retaining Zip Archive Support

Two key factors impact the decision of whether to retain zip archive support:

**1. Support Matrix Considerations:**

The .NET 11 support matrix has not yet been finalized.
The [.NET 10 support matrix](https://github.com/dotnet/core/blob/main/release-notes/10.0/supported-os.md) includes three Windows versions that lack native tarball support: Windows Server 2016, Windows Server 2012 R2, and Windows Server 2012.
These versions appear to reach EOL before .NET 11, meaning they are candidates to remove from the support matrix pending what their Windows extended support policies.
If these versions remain in the .NET 11 support matrix, we may need to retain zip support to provide a first-class installation experience for those platforms.

**2. Existing Zip Usage:**

After migrating various acquisition changnels to use the Windows tarball like, dotnet-install scripts, Azure DevOps install tasks, GitHub Actions setup-dotnet, and official .NET Docker images, we can measure the remaining zip usage through .NET telemetry.
This data will inform whether there is a significant long tail of users who depend on zip archives.
This data will allow us to make an informed decision if the zip archives should be retained for .NET 11.

### Installer Considerations

Although installers are not the primary audience for this deduplication work, they should ideally benefit from link support to preserve disk space savings.

**Linux Packages (deb, rpm):**

Linux package formats support symbolic links natively.
Package managers like `dpkg` and `rpm` preserve symbolic links during installation, maintaining the disk space benefits when installing from packages.
As noted in the [Platform-Specific Link Strategy](#platform-specific-link-strategy) section, symbolic links avoid the problems that hard links cause with RPM packages, making them the appropriate choice for Linux distributions.

**macOS Installer (pkg):**

The macOS pkg installer format supports symbolic links and will preserve them during installation, maintaining disk space savings on macOS systems.

**Windows Installer (MSI):**

MSI installers do not natively support hard links.
Supporting hard links in MSI would require custom logic that Windows installer subject matter experts have identified as problematic and do not recommend pursuing.
Further investigation is need to confirm this.
As a result, Windows MSI installations will likely not benefit from hard link deduplication and will consume additional disk space compared to tarball installations on Windows.
The Windows installers at least have historically had a more 'maximal' approach to what is included in them, so there's precedence for the methods to have deltas.

### Testing Strategy

Tests will be created to ensure:

- **Layout validation:** Verify that duplicate files outside of links do not exist, with correct link types per platform (hard links on Windows, symbolic links on Linux/macOS)
- **Archive Extraction testing:** Verify that tarball extraction preserves links on all supported platforms
- **Installer testing:** Verify that non-Windows installers preserve symbolic links

## Proof of Concept Results

A proof of concept for link-based deduplication was implemented, demonstrating the viability and effectiveness of the approach:

**Implementation Details:**

- A new MSBuild task `DeduplicateFilesWithHardLinks` was created to identify and replace duplicate files with links during SDK layout generation
- Files are hashed to identify duplicates
- The POC initially used hard links; the production implementation will use platform-specific link types (hard links on Windows, symbolic links on Linux/macOS)

**Space Savings:**

In a Linux x64 development build of .NET 11.0 SDK, the link-based approach achieved:

- 131 MB reduction in disk size
- 61 MB reduction in archive size

**Note:** Development build measurements differ from production builds due to signing, optimization, and release packaging differences.
Production measurements will be captured during full implementation.
Both hard links and symbolic links provide equivalent space savings, as both eliminate duplicate file content on disk and in archives.

## Other Concerns

### Architecture Differences

As noted in the [duplicate categorization](#linux-x64), a portion of duplicates with the same version but different hash are due to architecture differences (AnyCPU vs x64).
The plan is to eliminate these differences by standardizing on CPU-specific versions.

Initial analysis indicates these differences stem from AnyCPU builds coexisting with CPU-specific builds of the same assembly.
The general approach will be to prefer the CPU-specific version over the AnyCPU version when eliminating these duplicates.

### Non-Assembly Duplicates

The data above only covers assemblies.
There are also duplicated non-assembly files such as `msdia140.dll.manifest`, `Microsoft.TestPlatform.targets`, `Microsoft.TemplateEngine.Cli.xml`, and `dotnet.runtimeconfig.json`.

- Duplicate non-assembly files (same hash): 65
- Total size of duplicates: 0.45 MB
- Largest duplicated file: `Microsoft.TemplateEngine.Cli.xml` — 0.18 MB

Non-assembly files are not directly targeted in this work.
They will be removed when the cost is low; otherwise, they remain out of scope due to limited ROI.

### Different TFM Duplicates

Beyond files duplicated with the same TFM (the primary focus of this work), some files with the same name and culture target different TFMs.
Eliminating these duplicates is outside the scope of the planned work.
Once same-TFM duplicates are addressed, additional analysis can be performed to evaluate the ROI of consolidating files across different TFMs.

The analysis categorizes these groups as follows:

**Linux x64 (10.0.100):**

Group Categorization:

- Groups differing by Core vs FX: 228
- Groups with different FX versions: 3
- Groups with different Core versions: 1
- Groups with multiple NetStandard versions: 0
- Groups with NetStandard + NetFx: 5
- Groups with NetStandard + Core: 30

Potential Savings (if duplicates were eliminated):

- Different FX versions (keep lowest): 1.9 MB
- Different Core versions (keep lowest): 0.1 MB
- NetStandard + NetFx (keep NetStandard): 0.9 MB
- NetStandard + Core (keep NetStandard): 5.9 MB

Total potential savings: 8.7 MB

**Key Observations:**

- **Core vs FX differences** are generally expected and necessary to support both frameworks.
- **Different Core versions** (e.g., net8.0 and net10.0) represent potential consolidation opportunities where the SDK could standardize on newer TFMs.
- **Different FX versions** (e.g., net472 and net48) may be necessary for backward compatibility but should be reviewed.
- **NetStandard combinations** indicate multi-targeting strategies that may be optimizable in some cases.

These groups are not mutually exclusive—a single file group can appear in multiple categories.
For example, a file with `netstandard2.0`, `net472`, and `net8.0` would be counted in both "NetStandard + NetFx" and "NetStandard + Core" categories.

Addressing different TFM duplicates requires different strategies than same-TFM duplicates and may involve API surface area analysis and compatibility considerations.

### Mixed RID Content

The SDK currently ships with some content placement issues related to Runtime Identifier (RID) specificity that contribute to unnecessary bloat:

#### RID-Specific Content in Inappropriate RIDs

In some cases, we ship RID-specific content to runtime identifiers where it's not applicable.
This represents content that should be trimmed out entirely as it serves no purpose on the target platform.

**Example:** [dotnet/sdk#51743](https://github.com/dotnet/sdk/issues/51743) - Windows-specific assemblies shipped in Linux distributions.

#### Cross-Platform Support Content

In other cases, we ship content to support cross-platform development scenarios—for example, Windows-specific assemblies included in Linux SDKs to enable cross-compilation or multi-targeting scenarios.
While this content does serve a purpose, it should be analyzed case-by-case to determine whether it should:

- Ship in-box as part of the core SDK experience
- Be available as optional packages that can be dynamically acquired when needed

**Example:** [dotnet/sdk#51835](https://github.com/dotnet/sdk/issues/51835) - Cross-platform development tooling dependencies.

#### Scope and Next Steps

Both of these content placement issues are outside the scope of the duplicate elimination work.
However, they will likely be surfaced and made more visible as part of this effort.
When identified, independent issues will be logged to address these concerns separately.

### Windows Containers

Windows containers do not support hard links, which blocks adoption of this feature for Windows container images.
The impact of this limitation is modest: Windows containers have significantly fewer supported versions/SKUs than Linux, and Windows base image updates occur only once per month (Patch Tuesday), resulting in far fewer image rebuilds.
As a result, the potential savings for Windows container images would be an order of magnitude less than Linux.

## Related

- [Visual Studio de-duplication effort](https://microsoft.sharepoint.com/:w:/s/b3f10b15-fb59-4650-957a-2c632aa943ba/IQBR2aXv7jC8RatIyxJJNPCeAQxjDmLii-R65o0yUvOJatk?e=IcnsAG)
- [NuGet Vision 2027 - Better supporting apps running in hosted environments or with specific composition/deployment patterns](https://microsoft-my.sharepoint.com/:w:/r/personal/aortiz_microsoft_com/Documents/NuGet%20Vision%202027.docx?d=w9f413c3dc36a4e7d887fe007071e10c0&csf=1&web=1&e=MD76Wr&nav=eyJoIjoiMjE2NDM5NDIwIn0)

## Appendix: Alternative Approach - Shared Assembly Location

This appendix documents an alternative approach that was initially considered for eliminating duplicate assemblies.
While this approach was ultimately not selected in favor of hard link deduplication, it remains valuable as a reference for understanding different strategies and their trade-offs.

### Overview

The alternative approach focused on eliminating the vast majority of duplicate assemblies within the .NET SDK by having each shared dependency carried only once in a common location.
This required solving two distinct but related problems:
First, from a runtime and execution perspective, SDK components must be able to reliably load a single shared copy of each assembly from a common location.
Second, from a build and production perspective, SDK components would ideally be compiled against the same shared set of assemblies, and the SDK layout and packaging process must ensure that only one copy of each shared assembly is included in the final SDK distribution.

### Define a Common Assembly Location

A well-defined common assembly location is essential for shared assemblies to be loaded by SDK components, particularly out-of-process components like global tools.
All SDK components should depend on a single version of shared dependencies as much as possible.

The root SDK directory is a natural location for this common assembly cache.
However, the root SDK folder is already quite large, and consolidating shared assemblies there would add over 100 files to the root directory.
This level of clutter doesn't seem desirable and would negatively impact readability.

A dedicated subdirectory for shared assemblies is preferred.
This approach keeps the root directory clean and makes it clear which assemblies are part of the shared cache.
Since we're centralizing on a single version of each shared dependency, there's no need for version-specific subdirectories within the common location.

**Directory Structure Considerations:**

While version folders aren't needed, we must account for framework versus core components.
Some framework-specific assemblies are shared and would need to be placed in a subdirectory to distinguish them from core assemblies (e.g., `shared/net472/` for framework components, with core assemblies directly in `shared/`).

**Possible names for the common assembly location:**

- `shared` — simple, clear, and consistent with .NET conventions (like the existing `shared` directory for runtimes).
- `common` — widely recognized across ecosystems for shared dependencies and utilities.
- `dependencies` / `deps` — descriptive and clear.
- `libs` — short and familiar in many build systems.

#### Side Effects of a Common Assembly Location

Consolidating assemblies into a common location introduces potential side effects that must be carefully considered.
Discussions with compiler experts have noted that the compiler toolchain is particularly sensitive to assembly availability and resolution paths.
The presence of assemblies in a shared location can affect behavior.

Beyond the compiler, other SDK components may have similar sensitivities to assembly placement and availability.
These areas require careful analysis to identify potential behavioral changes when moving to a shared assembly model.
Further ivestigation in these areas will be required.

### Load from the Common Assembly Location

With the introduction of a formalized common assembly location, SDK components must be able to load assemblies from it.
The approach varies based on the type of component:

**Out-of-Process Components:** Components that run in their own process, such as global tools, will use **AssemblyLoadContext** to load shared assemblies from the common location.
This approach is already used today by [dotnet-watch](https://github.com/dotnet/sdk/blob/26bbbd92e5a3cc58037e696147fa25e03e68e3a8/src/BuiltInTools/dotnet-watch/Program.cs#L288).

**In-Process Framework Components:** These components are hosted within the SDK's framework context and define the assembly resolution paths.

**In-Process Core Components:** These components are hosted within the SDK's core context and define the assembly resolution paths.

**Performance:** Performance is a concern that must be validated.
We need to ensure that any changes to assembly loading do not regress performance in any way.

### SDK Layout Adjustments

The SDK layout needs to be updated to:

1. Populate the common assembly location.
1. Exclude common assemblies from individual components.

The strategy for achieving this varies based on the type of component:

**Global Tools:** Global tools have special layout targets today.
A good strategy would be for these targets to list out the assemblies to keep in the tool's directory, and the rest would be added to a shared assemblies list that gets copied to the shared assembly location.

**In-Process Components:** Other components that load in the same process would just need to ensure that the shared assemblies are defined and copied to the shared assembly location.
This can be done via various copying logic or using the `ExcludeAssets` mechanism.
The approach will vary based on the component type, but whenever possible we want to use a systematic approach.

**Version Control:** It's important to define which component controls what version is placed in the shared assembly cache.
This is critical for resolving version conflicts.
Higher version references may cause load failures, while lower version references could trigger security alerts.
Compile-time checks can be added to enforce the desired version rules.
The VMR has helped reduce version conflict occurrences.

The upcoming [NuGet Vision 2027 work](https://microsoft-my.sharepoint.com/:w:/r/personal/aortiz_microsoft_com/Documents/NuGet%20Vision%202027.docx?d=w9f413c3dc36a4e7d887fe007071e10c0&csf=1&web=1&e=MD76Wr&nav=eyJoIjoiMjE2NDM5NDIwIn0) for "better supporting apps running in hosted environments or with specific composition/deployment patterns" will help facilitate version conflict resolution in this area.
This work will introduce the capability to declare dependencies as "provided by the hosting environment," allowing components to use the host environment's version rather than carrying their own copy.
This approach will make it much easier to eliminate version differences and consolidate on shared dependency versions within the SDK.

Similar patterns will be used for architecture differences as discussed in the [Architecture Differences](#architecture-differences) section.

### Why This Approach Was Not Selected

While the shared assembly location approach offers theoretical benefits in terms of explicit dependency management, it was ultimately not selected due to several significant challenges:

1. **Complexity:** Requires extensive changes to component loading logic, assembly resolution paths, and SDK infrastructure across numerous components.
2. **Runtime Impact:** Potential for performance regressions and behavioral changes due to modified assembly loading patterns.
3. **Side Effects:** Compiler toolchain and other components are sensitive to assembly placement, requiring extensive testing and validation.
4. **Version Conflicts:** Managing version conflicts across components requires sophisticated coordination and tooling.
5. **Implementation Cost:** High development and maintenance burden compared to filesystem-level deduplication.

The hard link approach was selected because it achieves the same disk and archive size benefits without requiring changes to component loading logic or risking behavioral changes in sensitive toolchain components.

## Appendix: Docker Image Savings Analysis

This section quantifies the downstream impact of deduplication on .NET Docker images.
The estimates use .NET 10 as a representative single release to project per-release savings.
The "In-Support" columns show the projected combined impact once three in-support versions all include this feature.
The "All" columns show cumulative totals across all SDK images and pulls (in-support and EOL), illustrating savings that accrue over time.

### Linux SDK Archive Size Reduction

As of .NET 11.0 Preview 4, the Linux SDK archive is **56 MB smaller** as a result of this work.

### Linux SDK Image Pull Bandwidth Savings

| .NET 10 Pulls/Wk | In-Support Pulls/Wk | All Pulls/Wk | .NET 10 Saved (TB wk / yr) | In-Support Saved (TB wk / yr) | All Saved (TB wk / yr) |
|------------------|---------------------|--------------|----------------------------|-------------------------------|------------------------|
| 147,000          | 485,400             | 630,000      | 7.9 / 408.2                | 25.9 / 1348.0                 | 33.9 / 1749.6          |

### Linux SDK Image Storage Savings

| New .NET 10 Images/Mo | New In-Support Images/Mo | All Images | .NET 10 Saved (GB mo / yr) | In-Support Saved (GB mo / yr) | All Saved (GB) |
|-----------------------|--------------------------|------------|----------------------------|-------------------------------|----------------|
| 42.6                  | 130.5                    | 26,866     | 2.3 / 27.6                 | 7.1 / 85.6                    | 1,469.2        |

---

<sup>1</sup> "All" columns represent all SDK images ever published to MCR and all SDK image pulls per week, regardless of whether the .NET version is currently in support or end-of-life.

<sup>2</sup> New images per month are driven by multiple sources: .NET servicing releases (Patch Tuesday) and base image updates. .NET images are rebuilt whenever an underlying base image (e.g., Ubuntu, Alpine) is updated.

<sup>3</sup> Assuming saved storage is billed at the [ACR](https://azure.microsoft.com/en-us/pricing/details/container-registry/) additional storage rate of $0.00334/GB/day, the in-support storage savings of 7.1 GB/month translate to approximately **$0.71/month**. If every Linux SDK image ever shipped had included this feature, the total cumulative savings of ~1.5 TB would translate to roughly **$147/month**.

### Key Takeaways

- Over the .NET 10 LTS three-year support period, this saves approximately **1,224.6 TB** in bandwidth (408.2 TB/yr x 3) and **82.8 GB** in storage (27.6 GB/yr x 3).
Those savings don't count previews, usage increase when the previous LTS (8.0) reaches end-of-life or pulls after EOL.
- **Bandwidth savings are significant in absolute terms**, over 1,350 TB/year for in-support versions at 630,000 pulls per week.
This is modest relative to the scale at which Azure operates, as indicated by its pricing.
- **Storage savings are negligible.** Even if every Linux SDK image ever shipped had included this feature, the cumulative savings would be ~1.5 TB.
- The primary value is **customer-facing**: every Linux SDK image pull is 56 MB smaller, resulting in faster downloads and reduced storage/higher density for users.

---

### Documentation General Intro To Cli (`documentation/general/intro-to-cli.md`)

Introduction to .NET Core CLI
=============================

The .NET Core CLI is a simple, extensible and standalone set of tools for building, managing and otherwise operating on .NET projects. It will or already includes commands such as compilation, NuGet package management and launching a debugger session. It is intended to be fully featured, enabling extensive library and app development functionality appropriate at the command-line. It should provide everything you'd need to develop an app in an SSH session! It is also intended to be a fundamental building block for building finished experiences in tools such as Visual Studio.

Goals:

- Language agnostic - embrace "common language runtime".
- Target agnostic - multi-targets.
- Simple extensibility and layering - "you had one job!"
- Cross-platform - support and personality.
- Semantic user interface over [MSBuild](https://github.com/Microsoft/msbuild).

Experience 
==========

The [.NET Core command-line tools](https://github.com/dotnet/cli) present the "dotnet" tool as the entry-point tool. It provides higher-level commands, often using multiple tools together to complete a task. It's a convenience wrapper over the other tools, which can also be used directly. "dotnet" isn't magical at all, but a very simple aggregator of other tools.

You can get a sense of using the tools from the examples below.

**dotnet restore**

`dotnet restore` restores dependent package from a given NuGet feed (e.g. NuGet.org) for the project in scope.

**dotnet run**

`dotnet run` compiles and runs your app with one step.

**dotnet build**

`dotnet build` compiles your app or library as an IL binary.

Design
======

There are a couple of moving pieces that you make up the general design of the .NET Core CLI:

* The `dotnet` driver
* Specific commands that are part of the package

The `dotnet` driver is very simple and its primary role is to run commands and give users basic information about usage. 

The way the `dotnet` driver finds the command it is instructed to run using `dotnet {command}` is via a convention; any executable that is placed in the PATH and is named `dotnet-{command}` will be available to the driver. For example, when you install the CLI toolchain there will be an executable called `dotnet-build` in your PATH; when you run `dotnet build`, the driver will run the `dotnet-build` executable. All of the arguments following the command are passed to the command being invoked. So, in the invocation of `dotnet build --native`, the `--native` switch will be passed to `dotnet-build` executable that will do some action based on it (in this case, produce a single native binary).

Adding a new command to the .NET Core CLI 
=========================================

If you want to contribute to the actual .NET Core CLI by adding a new command that you think would be useful, refer to the [developer guide](../project-docs/developer-guide.md) in this directory. It contains all of the guidance on both the process as well as the infrastructure that you need to adhere to when adding a new command to the CLI toolchain. 

After you familiarize yourself with the process of working with the source code in the repo, consult the [CLI UX guidelines](cli-ux-guidelines.md) to get to know the user experience tenants the CLI has. 

Adding a new command locally
============================ 
If you wish to extend the CLI, you can read more about supported extensibility models in the [official extensibility document](https://docs.microsoft.com/en-us/dotnet/articles/core/tools/extensibility)/. 

Guidance on how to write a command 
==================================
How you write a given command depends largely on whether you are trying to add it to the CLI project or want to add the command locally, that is on your machine or server. 

For the former case, the [developer guide](../project-docs/developer-guide.md) has all of the details that you will need to get going. 

If you are adding a command on your own machine(s), then there is really no special model to keep in mind. However, since your users will be using the local commands through the `dotnet` driver, we strongly suggest to keep to the principles outlined in the [CLI UX guidelines](cli-ux-guidelines.md) to have an unified user experience for your users.

---

### Documentation General Publish Build Optimization (`documentation/general/publish-build-optimization.md`)

# Publish Build Optimization

## Overview

When `dotnet publish` runs, it implicitly runs a full `Build` before the publish step.
This is necessary because the SDK cannot assume the previous `dotnet build` used the same
configuration (e.g., the default build configuration is `Debug` while publish defaults to
`Release`), runtime identifier, or other settings.

However, for some publish modes, the full `Build` output (written to `bin\<config>\<tfm>\<rid>\`)
is never used by the publish pipeline. The publish steps read from intermediate outputs
(`obj\`) and resolution items, not from the `bin\` directory. This means the `Build` step
produces artifacts that are confusing to users and automation, as `bin\<config>\<tfm>\<rid>\`
contains a full self-contained managed deployment that is not the intended output.

## How Publish Modes Work Today

### Common Architecture

All publish modes share this flow:

1. **Build** (or equivalent) — produces the IL assembly at `@(IntermediateAssembly)` in `obj\`
2. **ComputeResolvedFilesToPublishList** — collects files to publish from `@(IntermediateAssembly)`,
   `@(RuntimeCopyLocalItems)`, `@(RuntimePackAsset)`, and content items
3. **Post-processing** — mode-specific transformations (ILC, ILLink, crossgen2, bundler)
4. **Copy to PublishDir** — final output written to `bin\<config>\<tfm>\<rid>\publish\`

Key insight: All post-processing steps read from `@(IntermediateAssembly)` (obj) and
`@(ResolvedFileToPublish)` (resolved from NuGet/project references), **never** from the
`Build` output directory.

### PublishAot (Native AOT)

**Status: Optimized by default in .NET 12**

- `IlcCompile` reads `@(IntermediateAssembly)` from `obj\` and produces a native binary
- The full `Build` was running a self-contained deployment to `bin\<config>\<tfm>\<rid>\`,
  including apphost, managed DLLs, deps.json, runtimeconfig.json, and runtime pack files
- **None of these files are used** by the AOT pipeline
- **Optimization**: Replace `Build` with `Compile` (plus resource/satellite targets)
- **Default**: The optimization is enabled by default in .NET 12. Set
  `UseOptimizedPublish=false` to restore full `Build` behavior.
- .NET 11 keeps the optimization opt-in to preserve compatibility.
- `UseOptimizedPublish` currently has no effect when `PublishAot` is not enabled
- `--no-build` continues to skip the build regardless of `UseOptimizedPublish`

Target chain for optimized AOT publish:
```
_CheckForInvalidConfigurationAndPlatform → BuildOnlySettings → PrepareForBuild → PreBuildEvent → ResolveReferences → PrepareResources → ResolveKeySource → Compile → CreateSatelliteAssemblies
```

`ResolveReferences` builds project references before resource preparation, and `Compile`
includes `CoreCompile`.
The optimized path retains the configuration/platform validation target and its SDK
hooks, including runtime identifier/platform compatibility and apphost/hosting checks.
`NoBuild=true` continues to use the separate no-build publish path.

After compilation and additional optimized-build targets, `IncrementalClean` records
the current intermediate outputs and removes tracked outputs that are no longer produced.
This also removes obsolete managed build-directory outputs from an earlier full build.
If the optimized build fails, `_CleanRecordFileWrites` preserves prior and newly generated
file tracking without deleting stale outputs. A subsequent `dotnet clean` can remove the
tracked compiler outputs, including intermediate DLL, PDB, and generated XML documentation.
This retains build cleanup bookkeeping; it does not add tracking for every native compiler
or publish artifact.

For tool projects (`PackAsTool=true`) with explicit `PackAsToolShimRuntimeIdentifiers`,
the PackTool SDK adds `GenerateShimsAssets` to the optimized-build extension point.
Shims are generated before incremental cleanup and publish file collection, so requested
`publish\shims\<rid>\` assets are preserved without copying the managed deployment to
the build directory. Projects without requested shims do not add this step, and no-build
publish continues to locate and reuse shims from a previous build rather than generate them.
Generation, incremental-build discovery, and no-build discovery share the staging directory
`$(PackagedShimOutputRootDirectory)\shims\$(TargetFramework)\`. It does not depend on
`SelfContained`, which can be inferred differently during build and publish. This allows
both Build and optimized publish outputs to be reused by a subsequent no-build publish.
Relative staging roots, including the default `$(OutDir)`, are resolved against the
project directory rather than the MSBuild process working directory.

### PublishTrimmed (IL Trimming)

**Status: Not yet optimized — candidate for future optimization**

- `ILLink` (the IL trimmer) processes `@(ResolvedFileToPublish)` items marked with
  `PostprocessAssembly=true`
- These items come from `ComputeResolvedFilesToPublishList` which reads from
  `@(IntermediateAssembly)` (obj) and resolved references
- The `Build` output in `bin\` is not consumed by the trimmer
- The same `Compile`-based optimization would apply here

### PublishReadyToRun (R2R / Crossgen2)

**Status: Not yet optimized — candidate for future optimization**

- `RunCrossgen2` processes `@(ResolvedFileToPublish)` items
- Input assemblies come from resolution, not from `Build` output
- Same optimization opportunity as trimming

### PublishSingleFile (Single-File Bundling)

**Status: Not yet optimized — candidate for future optimization**

- `GenerateSingleFileBundle` bundles `@(ResolvedFileToPublish)` items into one executable
- All inputs come from resolved items and `@(IntermediateAssembly)`
- Same optimization opportunity

### Combined Modes

These modes can be combined (e.g., `PublishAot` implies `PublishTrimmed`). The optimization
applies when the outermost mode is optimized:

| Combination | Optimized? | Notes |
|---|---|---|
| PublishAot (implies trimmed) | ✅ Yes | Set `UseOptimizedPublish=false` to opt out |
| PublishTrimmed + PublishSingleFile | ❌ Not yet | Future candidate |
| PublishReadyToRun + PublishSingleFile | ❌ Not yet | Future candidate |
| PublishTrimmed alone | ❌ Not yet | Future candidate |
| PublishReadyToRun alone | ❌ Not yet | Future candidate |

## Default Behavior: AOT Publish Build Optimization

### What Changed

Starting in .NET 12, `dotnet publish` with `PublishAot=true` no longer runs a full `Build`
before publish. Instead, it runs only `Compile` (and resource/satellite assembly targets).
.NET 11 preserves full `Build` behavior by default and requires
`UseOptimizedPublish=true` to enable the optimization.

### Impact

- **BeforeBuild / AfterBuild targets**: These will not execute during AOT publish. If you have
  custom targets attached to `BeforeBuild`, `AfterBuild`, or using
  `BeforeTargets="Build"` / `AfterTargets="Build"`, they will not run.
  - **Workaround**: Attach your targets to `BeforeTargets="Publish"` / `AfterTargets="Publish"`,
    or to `BeforeTargets="Compile"` / `AfterTargets="Compile"` instead.
- **PreBuildEvent / PostBuildEvent**: `PreBuildEvent` still executes when the optimization
  is enabled; `PostBuildEvent` is skipped. Both are skipped with `--no-build`.
- **Third-party NuGet Build hooks**: Targets from NuGet packages that hook into `Build` will be
  skipped (consistent with `--no-build` behavior).
- **Output directory**: `bin\<config>\<tfm>\<rid>\` will no longer contain managed apphost,
  DLLs, deps.json, runtimeconfig.json, or runtime pack files. Only `native\` and `publish\`
  subdirectories will be present, along with `shims\` for explicitly requested tool shims.

### Opt-Out

To restore the previous behavior of running a full `Build` before AOT publish, set:

```xml
<PropertyGroup>
  <UseOptimizedPublish>false</UseOptimizedPublish>
</PropertyGroup>
```

Or pass it on the command line:

```
dotnet publish /p:UseOptimizedPublish=false
```

## Future Work

The same optimization could be applied to `PublishTrimmed`, `PublishReadyToRun`, and
`PublishSingleFile` modes, as they all share the same architecture of reading from
`@(IntermediateAssembly)` and resolved references rather than `Build` output. Each mode
would need:

1. Compatibility analysis for Build hooks used by projects and NuGet packages
2. The same target chain: `BuildOnlySettings → PrepareForBuild → PrepareResources → Compile → CreateSatelliteAssemblies`
3. Tests verifying the expected build and publish outputs
4. Documentation of the breaking change for that mode

---

### Documentation General Signing Global Tool Packages (`documentation/general/signing-global-tool-packages.md`)

Signing .NET Core Global Tool Packages
===============================

To create a signed package for your Dotnet Tool, you will need to create a signed shim. If a shim is found in the nupkg during `dotnet tool install`, it is used instead of creating one on consumer's machine.

To create a signed shim, you need to add the following extra property in you project file:

```
   <PackAsToolShimRuntimeIdentifiers>[list of RIDs]</PackAsToolShimRuntimeIdentifiers>
```

When this property is set, `dotnet pack` will generate a shim in the package (nupkg). Assuming all other other content is signed, after you sign the shim you can sign the nupkg.

Example:
```xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <PackAsTool>true</PackAsTool>
    <PackAsToolShimRuntimeIdentifiers>win-x64;win-x86;osx-x64</PackAsToolShimRuntimeIdentifiers>
  </PropertyGroup>
</Project>
```

The result nupkg will have packaged shim included. Of course `dotnet pack` does not sign the shim or the package. The mechanism for that depends on your processes. The structure of the unzipped nupkg is:

```
│   shimexample.nuspec
│   [Content_Types].xml
│
├───package
│   └───services
│       └───metadata
│           └───core-properties
│                   9c20d06e1d8b4a4ba3e126f30013ef32.psmdcp
│
├───tools
│   └───netcoreapp2.1
│       └───any
│           │   DotnetToolSettings.xml
│           │   shimexample.deps.json
│           │   shimexample.dll
│           │   shimexample.pdb
│           │   shimexample.runtimeconfig.json
│           │
│           └───shims
│               ├───osx-x64
│               │       shimexample
│               │
│               ├───win-x64
│               │       shimexample.exe
│               │
│               └───win-x86
│                       shimexample.exe
│
└───_rels
        .rels
```

---

### Documentation General Solution Publish (`documentation/general/solution-publish.md`)

# Publishing a Solution

## Overview

`dotnet publish` accepts a solution (`.sln`) file as input, but doing so is generally **not recommended**.

## Why publishing a solution is problematic

### CLI arguments don't flow to dependent projects correctly

When you run `dotnet publish` with CLI arguments on a solution, those arguments are not correctly forwarded to the individual projects inside the solution. Common examples include:

- **`-r` / `--runtime` (RuntimeIdentifier)** – most library projects don't declare any RIDs, so when a RID flows down to them it changes their build behavior. Those projects will look for restore assets that were produced for that specific RID, but restore was most likely run without a RID, so the assets aren't there. Running `dotnet publish --no-restore` with a RID makes the situation worse: it disables the implicit restore that could otherwise recover from the missing assets.
- **`-f` / `--framework` (TargetFramework)** – when a solution passes a target framework to its projects it bypasses the normal project-to-project target framework negotiation. As a result, library projects that are referenced by multiple app projects may be scheduled for build multiple times, potentially running concurrently and writing to the same intermediate output directory at the same time.

As a result, the published output may be built with the wrong runtime or framework settings, leading to subtle or hard-to-diagnose issues at runtime.

### Output path conflicts with `-o` / `--output`

If you specify an output directory with `-o` (or `--output`), all projects in the solution write their outputs to the same directory. This causes two problems:

1. **Race conditions** – if multiple projects are publishing simultaneously, they may try to write to the same output directory at the same time and interfere with each other.
2. **File overwriting** – if multiple projects depend on different versions of a package that produces a file with the same name, the last project to publish wins and overwrites the file, potentially leaving you with an inconsistent mix of binaries.

Because of the `-o` concern, `dotnet publish` already emits a warning when `-o` is specified together with a solution file.

### Publishing a solution only works in limited scenarios

Publishing a solution without any CLI arguments can work when:

- All projects in the solution target the same framework and runtime.
- No two projects produce conflicting output files.
- You don't need to apply any publish-time customization (self-contained, single-file, trimming, etc.).

In practice these conditions are rarely all true for a non-trivial solution.

## Recommended workflow

Use the following approach to achieve a reliable, repeatable publish:

1. **Build the solution** to compile all projects and validate that all framework/runtime combinations work:

   ```shell
   dotnet build MySolution.sln
   ```

   This is safe because `dotnet build` does not produce a deployable output and the arguments flow more predictably across projects.

2. **Publish individual projects** to get a deployable output for a specific runtime and framework combination:

   ```shell
   dotnet publish src/MyApp/MyApp.csproj -r linux-x64 -f net9.0
   ```

   Publishing individual projects gives you precise control over the `RuntimeIdentifier`, `TargetFramework`, self-contained mode, single-file packaging, trimming, and any other publish-time properties.

3. **Repeat for each combination** you need to ship (e.g. `win-x64`, `linux-x64`, `osx-arm64`).

   Note that publishing each project separately for multiple RIDs will rebuild shared library projects once per RID. For advanced scenarios where you want to publish many projects for many RIDs in a single invocation you can author a [traversal project](https://github.com/microsoft/MSBuildSdks/blob/main/src/Traversal/README.md) that sets the appropriate properties per `ProjectReference`, though that approach requires more MSBuild expertise.

This approach avoids the argument-forwarding and output-path problems described above and gives you a clear mapping from source project to published artifact.

## Summary

| Scenario | Recommended command |
|---|---|
| Build all projects in a solution | `dotnet build MySolution.sln` |
| Publish a specific project for a specific runtime | `dotnet publish src/MyApp/MyApp.csproj -r <rid> -f <tfm>` |
| Publish with custom output directory | `dotnet publish src/MyApp/MyApp.csproj -o out/myapp` |

Avoid `dotnet publish MySolution.sln -r <rid>`, `dotnet publish MySolution.sln -f <tfm>`, and `dotnet publish MySolution.sln -o <dir>`.

---

### Documentation General Tab Completion (`documentation/general/tab-completion.md`)

# .NET CLI Tab Completion

In version 2.0 of the .NET Core CLI, we have added support for providing suggestions when you press `tab`. While it's not yet enabled by default, you can try it out in PowerShell, bash, or zsh by following the instructions below. 

Here are some examples of what it provides:

Input                                | becomes                                                                     | because
:------------------------------------|:----------------------------------------------------------------------------|:--------------------------------
`dotnet a⇥`                          | `dotnet add`                                                                 | `add` is the first subcommand, alphabetically.
`dotnet add p⇥`                      | `dotnet add --help`                                                          | it matches substrings and `--help` comes first alphabetically.
`dotnet add p⇥⇥`                    | `dotnet add package`                                                          | pressing tab a second time brings up the next suggestion.      
`dotnet add package Microsoft⇥`      | `dotnet add package Microsoft.AspNetCore.Http`                               | results are returned alphabetically.
`dotnet remove reference ⇥`          | `dotnet remove reference ..\..\src\OmniSharp.DotNet\OmniSharp.DotNet.csproj` | it is project file aware.

## How to enable it

Tab completion is currently supported in three shells: PowerShell, bash, and zsh. These scripts assume that `dotnet` v2.0 is on your path. You can verify that you have the correct version of `dotnet` on your path by trying out the new `complete` command directly:

```
[04/26/2017 11:38:20] C:\
> dotnet complete "dotnet add p"
```

If you just installed `dotnet` you may see the first-run output:

```
Welcome to .NET Core!
---------------------
Learn more about .NET Core: https://aka.ms/dotnet-docs
...
...
```

You should see the following output (perhaps coming at the end of the first-run output). This indicates that `dotnet` is resolving to a v2.0 installation that supports completion.

```
--help
package
```

### PowerShell

To enable tab completion in PowerShell, edit your PowerShell profile:

```
notepad $PROFILE
```

Add the contents of [register-completions.ps1](https://github.com/dotnet/cli/blob/master/scripts/register-completions.ps1) to this file and save. 

### bash

To enable tab completion in bash, edit your `.bashrc` file to add the contents of [register-completions.bash](https://github.com/dotnet/cli/blob/master/scripts/register-completions.bash).

### zsh 

To enable tab completion in zsh, edit your `.zshrc` file to add the contents of [register-completions.zsh](https://github.com/dotnet/cli/blob/master/scripts/register-completions.zsh).

## How it works

Each of these scripts provides a hook for completions for its respective shell. The logic that determines which suggestions to provide is in the CLI itself, configured using [our new parser](https://github.com/dotnet/CliCommandLineParser). You can see a code example [here](https://github.com/dotnet/cli/blob/master/src/dotnet/commands/dotnet-add/dotnet-add-package/AddPackageParser.cs).

---

### Documentation General Tool Nuget Package Format (`documentation/general/tool-nuget-package-format.md`)

Tool NuGet package format
-------------------------------------------

The most straightforward way to create a .NET tool package is to run `dotnet pack` with `PackAsTool` property set in the project file. However, if your build process is highly customized, `dotnet publish` may not create the right package for you. In this case, you can create a NuGet package for your tool using a *nuspec* file and explicitly placing assets into the NuGet package following these rules.

- The NuGet package has only _/tools_ folder under the root and does **not** contain any other folders; do not include folders like  _/lib_, _/content_, etc.
- Under _/tools_ folder, the subfolders must be structured with pattern _target framework short version/RID_. For example, tool assets targeting .NET core framework V2.1 that are portable across platforms should be in the folder _tools/netcoreapp2.1/any_.

Let's call assets under every _tools/target framework short version/RID_ combination "per TFM-RID assets" :
- There is a DotnetToolSettings.xml for every "per TFM-RID assets".
- The package type is DotnetTool.
- Each set of TFM-RID assets should have all the dependencies the tool requires to run. The TFM-RID assets should work correctly after being copied via `xcopy` to another machine, assuming that machine has the correct runtime version and RID environment.
- For portable app, there must be runtimeconfig.json for every "per TFM-RID assets".

# Remark:
- Currently, only portable apps are supported so the RID must be _any_.
- Only one tool per tool package.

DotnetToolSettings.xml:
Example:
```xml
<?xml version="1.0" encoding="utf-8" ?>
    <DotNetCliTool>
    <Commands>
        <Command Name="%sayhello%" EntryPoint="%console.dll%" Runner="dotnet" />
    </Commands>
</DotNetCliTool>
```
Currently only configurable part is command name: _sayhello_ and entry point: _console.dll_. Command Name is what the user will type in their shell to invoke the command. Entry point is the relative path to the entry dll with main.

---

### Documentation General Torn Sdk (`documentation/general/torn-sdk.md`)

# Torn .NET SDK

> [!CAUTION]
> This document has been superseded by [Decoupling the .NET SDK and Visual Studio](decouple-vs-and-net-sdk.md).

## Terminology

- **msbuild**: refers the .NET Framework based msbuild included with Visual Studio.
- **dotnet msbuild**: refers to the .NET Core based msbuild included with the .NET SDK.
- **analyzers**: this document will use analyzers to refer to both analyzers and generators.

## Summary

Visual Studio and .NET SDK are separate products but they are intertwined in command line and design time build scenarios as different components are loaded from each product. This table represents how the products currently function:

| Scenario | Loads Roslyn | Loads Analyzers / Generators |
| --- | --- | --- |
| msbuild | From Visual Studio | From .NET SDK |
| dotnet msbuild | From .NET SDK | From .NET SDK |
| Visual Studio Design Time | From Visual Studio | From Both |

Generally this mixing of components is fine because Visual Studio will install a .NET SDK that is functionally paired with it. That is the compiler and analyzers are the same hence mixing poses no real issue. For example 17.10 installs .NET SDK 8.0.3xx, 17.9 installs .NET SDK 8.0.2xx, etc ... However when the .NET SDK is not paired with the Visual Studio version,then compatibility issues can, and will, arise. Particularly when the .NET SDK is _newer_ than Visual Studio customers will end up with the following style of error:

> CSC : warning CS9057: The analyzer assembly '..\dotnet\sdk\8.0.200\Sdks\Microsoft.NET.Sdk.Razor\source-
> generators\Microsoft.CodeAnalysis.Razor.Compiler.SourceGenerators.dll' references version '4.9.0.0' of the compiler, which is newer
> than the currently running version '4.8.0.0'.

This torn state is a common customer setup:

|Visual Studio Version | Match% | Float % | Torn % |
| --- | --- | --- | --- |
| 16.11 | 81.4% | 10.8% | 7.8% |
| 17.2 | 91% | 8% | 1% |
| 17.4 | 91.5% | 5.7% | 2.7% |
| 17.6 | 91.6% | 5% | 3.5% |
| 17.7 | 94.9% | 2.2% | 3% |
| 17.8 | 96% | 0% | 4% |

To address this issue we are going to separate Visual Studio and the .NET SDK in build scenarios. That will change our matrix to _logically_ be the following:

| Scenario | Loads Roslyn | Loads Analyzers / Generators |
| --- | --- | --- |
| msbuild | From .NET SDK | From .NET SDK |
| dotnet msbuild | From .NET SDK | From .NET SDK |
| Visual Studio Design Time | From Visual Studio | From Visual Studio |

Specifically we will be

1. Changing msbuild to use a compiler at least as new as the .NET SDKs compiler
2. Changing Visual Studio to use analyzers from Visual Studio

In addition to making our builds more reliable this will also massively simplify our [analyzer Development strategy][sdk-lifecycle]. Analyzers in the SDK following this model can always target the latest Roslyn version without the need for complicated multi-targeting.

## Motivations

There are a number of scenarios where customers end up in a torn state. The most common is when customers have a CI setup with the following items:

1. They use a task like [actions/setup-dotnet][setup-dotnet] to install the .NET SDK and use a flexible version format like `8.x`.
2. They use `msbuild` to actually drive their build. This `msbuild` comes from the Visual Studio installed on the machine image.

This means that CI systems are updated to the latest .NET SDK virtually as soon as we release them. However the version of Visual Studio is updated much later as CI images usually take several weeks to upgrade to a new Visual Studio version. This is a very common CI setup and means a significant number of our customers end up in a torn state for several weeks.

Another reason is that teams use older Visual Studio versions due to internal constraints: like an organizational policy. At the same time they install the latest .NET SDK which puts them into a torn state.

This also hits any customer that uses a preview version of .NET SDK. These inherently represent a torn SDK state because they almost never match the compiler in Visual Studio. This results in blockers for big teams like Bing from testing out our previews.

## Goals

This design has a number of goals:

1. The `msbuild` and `dotnet msbuild` build experience should be equivalent.
1. The Visual Studio Design time experience is independent of the .NET SDK installed.
1. To make explicit that it is okay, and even expected, that the design time and command line build experiences can differ when the SDK is in a torn state.

## MSBuild using .NET SDK Compiler

The .NET SDK will start producing a package named Microsoft.Net.Sdk.Compilers.Toolset. This will contain a .NET Framework version of the Roslyn compiler that matches .NET Core version. This will be published as a part of the .NET SDK release process meaning it's available for all publicly available .NET SDKs.

The .NET SDK has the capability to [detect a torn state][pr-detect-torn-state]. When this is detected and msbuild's compiler is older, the matching Microsoft.Net.Sdk.Compilers.Toolset package for this version of the .NET SDK will be downloaded via `<PackageDownload>`. Then the `$(RoslynTargetsPath)` will be reset to point into the package contents. This will cause MSBuild to load the Roslyn compiler from that location vs. the Visual Studio location.

One downside to this approach is that it is possible to end up with two VBCSCompiler server processes. Consider a solution that has a mix of .NET SDK style projects and non-SDK .NET projects. In a torn state the .NET SDK projects will use the .NET SDK compiler and non-SDK .NET projects will use the Visual Studio compiler. While not a desirable outcome, it is a correct one. Customers who wish to only have one VBCSCompiler should correct the torn state in their build tools.

## Visual Studio using Visual Studio Analyzers

Analyzers are required to function in all of our currently supported Visual Studio versions. This design proposal does not change this requirement. Instead it seeks to simplify the set of scenarios that analyzers need to consider by making compiler versions more predictable. It also helps establish a simple path for inbox analyzers to simply use the latest Roslyn in their development.

### .NET SDK in box analyzers dual insert

Analyzers which ship in the .NET SDK box will change to having a copy checked into Visual Studio. When .NET SDK based projects are loaded at design time, the Visual Studio copy of the analyzer will be loaded. Roslyn already understands how to prefer Visual Studio copies of analyzers. That work will need to be extended a bit but that is pretty straight forward code.

This approach enables us to take actions like NGEN or R2R analyzers inside of Visual Studio. This is a long standing request from the Visual Studio perf team but very hard to satisfy in our current setup.

This approach is already taken by [the Razor generator][code-razor-vs-load]. This work was done for other reliability reasons but turned out working well for this scenario. There is initial upfront work to get the Visual Studio copy loading in design time builds but it has virtually zero maintenance cost.

This also means these analyzers can vastly simplify their development model by always targeting the latest version of Roslyn. There is no more need to multi-target because the version of the compiler the analyzer will be used with is known at ship time for all core build scenarios.

This does mean that our design time experience can differ from our command line experience when customers are in a torn state. Specifically it's possible, even likely in some cases, that the diagnostics produced by design time builds will differ from command line builds. That is a trade off that we are willing to make for reliability. Customers who wish to have a consistent experience between design time should not operate in a torn state.

## .NET SDK in box analyzers target oldest

Analyzers which have no need to target the latest Roslyn could instead choose to target the oldest supported version of Roslyn. That ensures they can safely load into any supported scenario without issue.

This strategy should be considered short term. The Roslyn API is under constant development to respond to the performance demands of Visual Studio. New APIs can quickly become virtually mandatory for analyzers and generators to use and will only be available on latest. At that point the analyzer will need to also update to use dual insertions.

### NuGet based analyzers

Analyzers which ship via NuGet will continue to following the existing [support policies][matrix-of-paine]. This means that they will either need to target a sufficiently old version of Roslyn or implement multi-targeting support.

In the case of [multi-targeting][issue-analyzer-mt] this proposal is effectively a no-op. Analyzer multi-targeting is already based off of Roslyn versions, not .NET SDK versions, hence the proper version of the analyzer will still load in a torn state. The version of the Roslyn compiler in a torn state for msbuild is the same used for dotnet build hence it's already a scenario the analyzer needs to support.

## Alternative

### .NET SDK in box analyzers multi-target

Technically in box analyzers can have a multi-targeting strategy just as NuGet based analyzers do. This is actively discouraged because it leads to unnecessary increases in .NET SDK sizes. The time spent implementing multi-targeting is likely better spent moving to a dual insertion to keep .NET SDK sizes down and provide a consistent experience with other analyzers.

### .NET SDK in box analyzers use light up

In box could also employ a light up strategy. Essentially reference older versions of the compiler and use reflection to opportunistically discover + use newer APIs. This is successfully employed in analyzers like StyleCop.

### PackageReference

Instead of `<PackageDownload>` the toolset package could be installed via `<PackageReference>`. This is how the existing Microsoft.Net.Compilers.Toolset package works today. This has a number of disadvantages:

1. `PackageReference` elements are not side effect free and have been shown to cause issues in complex builds. For example this package did not work by default in the Visual Studio or Bing builds. Deploying this at scale to all our customers will almost certainly cause issues.
1. This approach does not solve all scenarios. The mechanics of restore mean that the compiler is not swapped until part way through the build. Build operations that happen earlier, such as [legacy WPF][issue-legacy-wpf], will still use the Visual Studio compiler and hence experience analyzer compatibility issues.
1. Mixing builds that do and do not restore can lead to different build outcomes as they can end up choosing different compilers. Mixing the version of msbuild / dotnet msbuild can also lead to strange outcomes as they can end up choosing different compilers.
1. `PackageReference` elements, even when implicit, end up showing up in NuGet lock files. That makes it difficult for lock files to be kept in a consistent state as subtly changing the Visual Studio or .NET SDK version would end up impacting the lock file.

### Install the Framework compiler

An alternative is simply shipping both Roslyn compilers in the Windows .NET SDK. This means there is no need for a `<PackageDownload>` step as the compiler is always there. This is a simpler build but it means that all .NET SDK installs on Windows will increase by ~6-7%.

This approach does have downsides:

1. The Windows .NET SDK increased in size even when it's not needed. For example our main Windows containers do not install Visual Studio hence are never in a torn state yet they'll see increased size cost here. Changing the .NET SDK such that these extra compilers are only installed sometimes would add significant complexity to our installer setup.
2. This will make the Windows and Linux .NET SDK's visibly different in layout. Comparing them will show different contents which could be confusing to customers. At the same time the current proposal is functionally the same, it just changes where the framework compilers are placed on disk and that also could be confusing to customers.

### Use the .NET Core compiler

Instead of downloading a .NET Framework Roslyn in a torn state, the SDK could just use the .NET Core Roslyn it comes with. That would have virtually no real compatibility issues. This has a number of disadvantages:

1. Changes the process name from VBCSCompiler to `dotnet`. That seems insignificant but the process name is important as it's referenced in a lot of build scripts. This would be a subtle breaking change that we'd have to work with customers on.
2. This would make Visual Studio dependent on the servicing lifetime of the .NET Core runtime in the SDK. That has a very different lifetime and could lead to surprising outcomes down the road. For example if policy removed out of support runtimes from machines it would break the Visual Studio build.

## Misc

### Visual Studio Code

This is how Visual Studio Code fits into our matrix after this work is complete:

| Scenario | Loads Roslyn | Loads Analyzers / Generators |
| --- | --- | --- |
| msbuild | From .NET SDK | From .NET SDK |
| dotnet msbuild | From .NET SDK | From .NET SDK |
| Visual Studio Design Time | From Visual Studio | From Visual Studio |
| DevKit | From DevKit | From .NET SDK |

On the surface it seems like VS Code has the same issues as Visual Studio does today. However this is not the case. Visual Studio is problematic because at any given time there can be ~5 different versions in active support each with a different version of the compiler. Every Visual Studio but the latest is an older compiler that run into issues with analyzers.

There is only one version of the DevKit extension. It is released using the latest compilers from roslyn at a very high frequency. That frequency is so high that the chance it has an older compiler than the newest .NET SDK is virtually zero. That means at the moment there is no need to solve the problem here. If DevKit changes its release cadance in the future this may need to be revisited.

### Why not always use Micosoft.Net.Sdk.Compilers.Toolset?

This design puts us in a state where `msbuild` will sometimes use the compiler from the .NET and sometimes use it from the MSBuild install. One may ask it why not simplify this and always load from the .NET SDK? Essentially why have all this complexity around torn state detection instead of just always using Microsoft.Net.Sdk.Compilers.Toolset? Or always use it when the compiler versions are different, not just when the .NET SDK is newer than Visual Studio.

The main reason is performance. The compiler inside MSBuild is NGEN'd while the compiler inside Microosft.Net.Sdk.Compilers.Toolset is not. That means there is a small initial startup penalty when loading the compiler from the package. The VBCSCompiler server process largely amortizes that penalty though. Our expectation is that this difference will be largely unnoticeable to customers.

The second reason is that this introduces a new `PackageDownload` step into the build. Doing that always carries some amount of risk. By scoping to only when the `msbuild` compiler is older we reduce the scope of this potential problem.

We plan to revisit this decision in future releases of the .NET SDK as we get real world experience with this change and the customer feedback that comes from it.

### Related Issues

- [Roslyn tracking issue for torn state](https://github.com/dotnet/roslyn/issues/72672)
- [MSBuild property for torn state detection](https://github.com/dotnet/installer/pull/19144)
- [Long term build-server shutdown issue](https://github.com/dotnet/msbuild/issues/10035)

[matrix-of-paine]: https://aka.ms/dotnet/matrixofpaine
[sdk-lifecycle]: https://learn.microsoft.com/en-us/dotnet/core/porting/versioning-sdk-msbuild-vs#lifecycle
[code-razor-vs-load]: https://github.com/dotnet/roslyn/blob/9aea80927e3d4e5a2846efaa710438c0d8d2bfa2/src/Workspaces/Core/Portable/Workspace/ProjectSystem/ProjectSystemProject.cs#L1009
[setup-dotnet]: https://github.com/actions/setup-dotnet
[pr-detect-torn-state]: https://github.com/dotnet/installer/pull/19144
[issue-analyzer-mt]: https://github.com/dotnet/sdk/issues/20355
[issue-legacy-wpf]: https://github.com/dotnet/wpf/issues/9112

---

### Documentation General Trust Code (`documentation/general/trust-code.md`)

# Overview
The .NET SDK is intended to be a collection of tools for manipulating, building, and executing code. As a result, there is no way to ensure that it is 100% secure regardless of how it is used. This document attempts to make clear the line between what security threats are up to the user and what threats the SDK should protect against. It defines the trust boundary where the user can assume that as long as they are secure in the ways outlined in this document, they will not be compromised by an outside threat actor.

# Types of Threats

## Untrusted Source Code
You should never build or run code from an untrusted source without employing mitigating factors like those described [here](ExecutingCustomerCode.md). Additionally, some SDK commands will automatically find code or code-adjacent files in the current directory, project directory, executable directory, or any parent directory of any of those up to the file system root. Files that may affect a build or other command if found include but are not limited to a Directory.Build.props, global.json, NuGet.config, or dotnet-tools.json. You should also check your home folder as well as environment variables that may point to other locations the SDK will search to find code or configuration files.

## Untrusted Locations
Some folders often store untrusted files. (The Downloads folder is a fairly straightforward example of that.) Some commands look "next to" the project, solution, or other code file being worked with in the directory. Do not run dotnet CLI commands from within any directory that contains any files you do not trust.

## Untrusted Packages
Since many SDK commands utilize NuGet under the covers, we further assume that:
* NuGet packages in local caches are trustworthy.
* NuGet.Config, Packages.Config, .props, and similar files within our resolution scope (see previous comments on trusted and untrusted directories) point only to trusted package repositories and/or packages.

See: [Managing the global packages and cache folders](https://learn.microsoft.com/nuget/consume-packages/managing-the-global-packages-and-cache-folders), [Managing package trust boundaries](https://learn.microsoft.com/nuget/consume-packages/installing-signed-packages), and [Consuming packages from authenticated feeds](https://learn.microsoft.com/nuget/consume-packages/consuming-packages-authenticated-feeds) for more information.

Violating these assumptions may lead to unwanted code execution.

---

### Documentation Issue Mappings Cli.Mapping (`documentation/issue-mappings/cli.mapping.txt`)

https://github.com/dotnet/cli/issues/XXXX ---> https://github.com/dotnet/sdk/issues/YYYY
1 ---> 4283
2 ---> 4284
3 ---> 4285
4 ---> 4286
9 ---> 4287
10 ---> 4288
11 ---> 4289
12 ---> 4290
13 ---> 4291
14 ---> 4292
15 ---> 4293
16 ---> 4294
17 ---> 4295
18 ---> 4296
19 ---> 4297
20 ---> 4298
21 ---> 4299
22 ---> 4300
23 ---> 4301
24 ---> 4302
25 ---> 4303
26 ---> 4304
27 ---> 4305
28 ---> 4306
29 ---> 4307
30 ---> 4308
31 ---> 4309
32 ---> 4310
34 ---> 4311
35 ---> 4312
36 ---> 4313
39 ---> 4314
41 ---> 4315
44 ---> 4316
45 ---> 4317
47 ---> 4318
48 ---> 4319
51 ---> 4320
52 ---> 4321
53 ---> 4322
55 ---> 4323
57 ---> 4324
58 ---> 4325
59 ---> 4326
60 ---> 4327
62 ---> 4328
63 ---> 4329
64 ---> 4330
65 ---> 4331
66 ---> 4332
67 ---> 4333
68 ---> 4334
70 ---> 4335
71 ---> 4336
72 ---> 4337
76 ---> 4338
77 ---> 4339
79 ---> 4340
81 ---> 4341
82 ---> 4342
83 ---> 4343
84 ---> 4344
85 ---> 4345
90 ---> 4346
101 ---> 4347
106 ---> 4348
107 ---> 4349
112 ---> 4350
115 ---> 4351
116 ---> 4352
117 ---> 4353
118 ---> 4354
119 ---> 4355
125 ---> 4356
126 ---> 4357
127 ---> 4358
128 ---> 4359
129 ---> 4360
132 ---> 4361
134 ---> 4362
136 ---> 4363
137 ---> 4364
140 ---> 4365
144 ---> 4366
151 ---> 4367
156 ---> 4368
157 ---> 4369
159 ---> 4370
164 ---> 4371
165 ---> 4372
166 ---> 4373
167 ---> 4374
168 ---> 4375
171 ---> 4376
175 ---> 4377
181 ---> 4378
182 ---> 4379
184 ---> 4380
185 ---> 4381
186 ---> 4382
187 ---> 4383
191 ---> 4384
192 ---> 4385
194 ---> 4386
195 ---> 4387
198 ---> 4388
199 ---> 4389
200 ---> 4390
201 ---> 4391
202 ---> 4392
205 ---> 4393
212 ---> 4394
214 ---> 4395
215 ---> 4396
216 ---> 4397
218 ---> 4398
219 ---> 4399
221 ---> 4400
223 ---> 4401
226 ---> 4402
232 ---> 4403
233 ---> 4404
234 ---> 4405
236 ---> 4406
237 ---> 4407
238 ---> 4408
240 ---> 4409
242 ---> 4410
244 ---> 4411
246 ---> 4412
247 ---> 4413
249 ---> 4414
250 ---> 4415
251 ---> 4416
253 ---> 4417
254 ---> 4418
255 ---> 4419
257 ---> 4420
258 ---> 4421
259 ---> 4422
260 ---> 4423
261 ---> 4424
262 ---> 4425
263 ---> 4426
265 ---> 4427
266 ---> 4428
269 ---> 4429
270 ---> 4430
271 ---> 4431
274 ---> 4432
275 ---> 4433
278 ---> 4434
279 ---> 4435
280 ---> 4436
281 ---> 4437
282 ---> 4438
283 ---> 4439
287 ---> 4440
289 ---> 4441
290 ---> 4442
291 ---> 4443
293 ---> 4444
294 ---> 4445
295 ---> 4446
296 ---> 4447
298 ---> 4448
300 ---> 4449
301 ---> 4450
302 ---> 4451
304 ---> 4452
305 ---> 4453
306 ---> 4454
307 ---> 4455
308 ---> 4456
309 ---> 4457
311 ---> 4458
312 ---> 4459
313 ---> 4460
314 ---> 4461
316 ---> 4462
317 ---> 4463
319 ---> 4464
320 ---> 4465
325 ---> 4466
326 ---> 4467
328 ---> 4468
329 ---> 4469
332 ---> 4470
333 ---> 4471
335 ---> 4472
340 ---> 4473
342 ---> 4474
345 ---> 4475
350 ---> 4476
351 ---> 4477
353 ---> 4478
354 ---> 4479
356 ---> 4480
359 ---> 4481
360 ---> 4482
362 ---> 4483
365 ---> 4484
366 ---> 4485
369 ---> 4486
371 ---> 4487
374 ---> 4488
375 ---> 4489
376 ---> 4490
377 ---> 4491
381 ---> 4492
382 ---> 4493
383 ---> 4494
385 ---> 4495
390 ---> 4496
391 ---> 4497
392 ---> 4498
393 ---> 4499
394 ---> 4500
395 ---> 4501
397 ---> 4502
398 ---> 4503
399 ---> 4504
401 ---> 4505
402 ---> 4506
403 ---> 4507
404 ---> 4508
405 ---> 4509
406 ---> 4510
407 ---> 4511
408 ---> 4512
412 ---> 4513
414 ---> 4514
415 ---> 4515
416 ---> 4516
417 ---> 4517
418 ---> 4518
419 ---> 4519
420 ---> 4520
421 ---> 4521
422 ---> 4522
423 ---> 4523
426 ---> 4524
427 ---> 4525
428 ---> 4526
429 ---> 4527
431 ---> 4528
432 ---> 4529
433 ---> 4530
435 ---> 4531
437 ---> 4532
438 ---> 4533
439 ---> 4534
440 ---> 4535
441 ---> 4536
442 ---> 4537
443 ---> 4538
444 ---> 4539
446 ---> 4540
447 ---> 4541
450 ---> 4542
451 ---> 4543
452 ---> 4544
453 ---> 4545
454 ---> 4546
459 ---> 4547
460 ---> 4548
462 ---> 4549
463 ---> 4550
464 ---> 4551
465 ---> 4552
467 ---> 4553
468 ---> 4554
470 ---> 4555
471 ---> 4556
473 ---> 4557
476 ---> 4558
477 ---> 4559
478 ---> 4560
479 ---> 4561
481 ---> 4562
483 ---> 4563
484 ---> 4564
485 ---> 4565
486 ---> 4566
488 ---> 4567
489 ---> 4568
490 ---> 4569
491 ---> 4570
492 ---> 4571
494 ---> 4572
495 ---> 4573
496 ---> 4574
498 ---> 4575
500 ---> 4576
501 ---> 4577
502 ---> 4578
503 ---> 4579
504 ---> 4580
505 ---> 4581
506 ---> 4582
507 ---> 4583
510 ---> 4584
511 ---> 4585
513 ---> 4586
514 ---> 4587
515 ---> 4588
518 ---> 4589
519 ---> 4590
520 ---> 4591
523 ---> 4592
525 ---> 4593
526 ---> 4594
527 ---> 4595
528 ---> 4596
529 ---> 4597
531 ---> 4598
532 ---> 4599
533 ---> 4600
535 ---> 4601
539 ---> 4602
540 ---> 4603
541 ---> 4604
546 ---> 4605
547 ---> 4606
548 ---> 4607
549 ---> 4608
550 ---> 4609
551 ---> 4610
552 ---> 4611
553 ---> 4612
554 ---> 4613
555 ---> 4614
556 ---> 4615
557 ---> 4616
558 ---> 4617
559 ---> 4618
560 ---> 4619
561 ---> 4620
562 ---> 4621
563 ---> 4622
564 ---> 4623
565 ---> 4624
566 ---> 4625
567 ---> 4626
568 ---> 4627
569 ---> 4628
570 ---> 4629
571 ---> 4630
572 ---> 4631
573 ---> 4632
574 ---> 4633
575 ---> 4634
576 ---> 4635
577 ---> 4636
578 ---> 4637
579 ---> 4638
580 ---> 4639
581 ---> 4640
582 ---> 4641
583 ---> 4642
584 ---> 4643
585 ---> 4644
586 ---> 4645
587 ---> 4646
588 ---> 4647
589 ---> 4648
590 ---> 4649
591 ---> 4650
592 ---> 4651
593 ---> 4652
594 ---> 4653
595 ---> 4654
596 ---> 4655
597 ---> 4656
598 ---> 4657
599 ---> 4658
600 ---> 4659
601 ---> 4660
602 ---> 4661
603 ---> 4662
604 ---> 4663
605 ---> 4664
606 ---> 4665
607 ---> 4666
608 ---> 4667
609 ---> 4668
610 ---> 4669
615 ---> 4670
616 ---> 4671
618 ---> 4672
619 ---> 4673
620 ---> 4674
623 ---> 4675
624 ---> 4676
627 ---> 4677
628 ---> 4678
629 ---> 4679
631 ---> 4680
633 ---> 4681
635 ---> 4682
639 ---> 4683
640 ---> 4684
641 ---> 4685
643 ---> 4686
645 ---> 4687
646 ---> 4688
647 ---> 4689
648 ---> 4690
649 ---> 4691
651 ---> 4692
652 ---> 4693
654 ---> 4694
655 ---> 4695
656 ---> 4696
657 ---> 4697
659 ---> 4698
663 ---> 4699
668 ---> 4700
669 ---> 4701
670 ---> 4702
671 ---> 4703
673 ---> 4704
674 ---> 4705
678 ---> 4706
680 ---> 4707
682 ---> 4708
683 ---> 4709
685 ---> 4710
686 ---> 4711
687 ---> 4712
691 ---> 4713
692 ---> 4714
693 ---> 4715
694 ---> 4716
696 ---> 4717
697 ---> 4718
698 ---> 4719
702 ---> 4720
703 ---> 4721
704 ---> 4722
707 ---> 4723
710 ---> 4724
711 ---> 4725
712 ---> 4726
714 ---> 4727
715 ---> 4728
716 ---> 4729
718 ---> 4730
720 ---> 4731
721 ---> 4732
724 ---> 4733
726 ---> 4734
728 ---> 4735
729 ---> 4736
732 ---> 4737
733 ---> 4738
735 ---> 4739
737 ---> 4740
738 ---> 4741
742 ---> 4742
743 ---> 4743
745 ---> 4744
749 ---> 4745
750 ---> 4746
753 ---> 4747
754 ---> 4748
760 ---> 4749
762 ---> 4750
764 ---> 4751
765 ---> 4752
768 ---> 4753
771 ---> 4754
772 ---> 4755
773 ---> 4756
775 ---> 4757
777 ---> 4758
778 ---> 4759
781 ---> 4760
783 ---> 4761
784 ---> 4762
786 ---> 4763
790 ---> 4764
792 ---> 4765
794 ---> 4766
797 ---> 4767
799 ---> 4768
801 ---> 4769
802 ---> 4770
803 ---> 4771
804 ---> 4772
805 ---> 4773
806 ---> 4774
807 ---> 4775
809 ---> 4776
810 ---> 4777
811 ---> 4778
812 ---> 4779
813 ---> 4780
814 ---> 4781
819 ---> 4782
822 ---> 4783
823 ---> 4784
824 ---> 4785
825 ---> 4786
827 ---> 4787
832 ---> 4788
834 ---> 4789
835 ---> 4790
838 ---> 4791
839 ---> 4792
841 ---> 4793
844 ---> 4794
845 ---> 4795
846 ---> 4796
847 ---> 4797
848 ---> 4798
850 ---> 4799
854 ---> 4800
857 ---> 4801
858 ---> 4802
862 ---> 4803
864 ---> 4804
865 ---> 4805
866 ---> 4806
869 ---> 4807
870 ---> 4808
871 ---> 4809
876 ---> 4810
878 ---> 4811
881 ---> 4812
882 ---> 4813
884 ---> 4814
885 ---> 4815
886 ---> 4816
887 ---> 4817
888 ---> 4818
889 ---> 4819
892 ---> 4820
895 ---> 4821
897 ---> 4822
900 ---> 4823
901 ---> 4824
903 ---> 4825
904 ---> 4826
905 ---> 4827
907 ---> 4828
908 ---> 4829
910 ---> 4830
911 ---> 4831
912 ---> 4832
913 ---> 4833
914 ---> 4834
917 ---> 4835
918 ---> 4836
925 ---> 4837
928 ---> 4838
932 ---> 4839
933 ---> 4840
934 ---> 4841
937 ---> 4842
938 ---> 4843
941 ---> 4844
948 ---> 4845
949 ---> 4846
950 ---> 4847
951 ---> 4848
952 ---> 4849
953 ---> 4850
954 ---> 4851
955 ---> 4852
956 ---> 4853
959 ---> 4854
961 ---> 4855
962 ---> 4856
964 ---> 4857
965 ---> 4858
966 ---> 4859
967 ---> 4860
968 ---> 4861
969 ---> 4862
970 ---> 4863
974 ---> 4864
977 ---> 4865
980 ---> 4866
982 ---> 4867
986 ---> 4868
987 ---> 4869
988 ---> 4870
990 ---> 4871
991 ---> 4872
992 ---> 4873
994 ---> 4874
995 ---> 4875
997 ---> 4876
1000 ---> 4877
1001 ---> 4878
1002 ---> 4879
1003 ---> 4880
1005 ---> 4881
1006 ---> 4882
1007 ---> 4883
1008 ---> 4884
1009 ---> 4885
1010 ---> 4886
1011 ---> 4887
1014 ---> 4888
1016 ---> 4889
1017 ---> 4890
1019 ---> 4891
1020 ---> 4892
1022 ---> 4893
1024 ---> 4894
1026 ---> 4895
1031 ---> 4896
1032 ---> 4897
1033 ---> 4898
1034 ---> 4899
1035 ---> 4900
1036 ---> 4901
1038 ---> 4902
1039 ---> 4903
1040 ---> 4904
1041 ---> 4905
1042 ---> 4906
1043 ---> 4907
1044 ---> 4908
1046 ---> 4909
1047 ---> 4910
1049 ---> 4911
1050 ---> 4912
1053 ---> 4913
1054 ---> 4914
1057 ---> 4915
1059 ---> 4916
1064 ---> 4917
1065 ---> 4918
1066 ---> 4919
1068 ---> 4920
1069 ---> 4921
1070 ---> 4922
1071 ---> 4923
1072 ---> 4924
1073 ---> 4925
1075 ---> 4926
1076 ---> 4927
1079 ---> 4928
1080 ---> 4929
1081 ---> 4930
1084 ---> 4931
1087 ---> 4932
1090 ---> 4933
1091 ---> 4934
1092 ---> 4935
1093 ---> 4936
1094 ---> 4937
1096 ---> 4938
1098 ---> 4939
1099 ---> 4940
1101 ---> 4941
1102 ---> 4942
1103 ---> 4943
1106 ---> 4944
1109 ---> 4945
1110 ---> 4946
1111 ---> 4947
1112 ---> 4948
1115 ---> 4949
1118 ---> 4950
1119 ---> 4951
1122 ---> 4952
1125 ---> 4953
1126 ---> 4954
1129 ---> 4955
1131 ---> 4956
1132 ---> 4957
1135 ---> 4958
1136 ---> 4959
1137 ---> 4960
1139 ---> 4961
1140 ---> 4962
1141 ---> 4963
1142 ---> 4964
1143 ---> 4965
1144 ---> 4966
1145 ---> 4967
1146 ---> 4968
1147 ---> 4969
1148 ---> 4970
1149 ---> 4971
1150 ---> 4972
1152 ---> 4973
1153 ---> 4974
1154 ---> 4975
1156 ---> 4976
1161 ---> 4977
1162 ---> 4978
1163 ---> 4979
1165 ---> 4980
1166 ---> 4981
1171 ---> 4982
1174 ---> 4983
1177 ---> 4984
1179 ---> 4985
1181 ---> 4986
1183 ---> 4987
1184 ---> 4988
1188 ---> 4989
1189 ---> 4990
1190 ---> 4991
1196 ---> 4992
1199 ---> 4993
1201 ---> 4994
1202 ---> 4995
1204 ---> 4996
1205 ---> 4997
1210 ---> 4998
1213 ---> 4999
1215 ---> 5000
1216 ---> 5001
1218 ---> 5002
1219 ---> 5003
1222 ---> 5004
1223 ---> 5005
1224 ---> 5006
1227 ---> 5007
1229 ---> 5008
1230 ---> 5009
1233 ---> 5010
1236 ---> 5011
1237 ---> 5012
1239 ---> 5013
1245 ---> 5014
1246 ---> 5015
1247 ---> 5016
1250 ---> 5017
1251 ---> 5018
1255 ---> 5019
1266 ---> 5020
1267 ---> 5021
1268 ---> 5022
1273 ---> 5023
1274 ---> 5024
1275 ---> 5025
1276 ---> 5026
1277 ---> 5027
1278 ---> 5028
1279 ---> 5029
1280 ---> 5030
1282 ---> 5031
1283 ---> 5032
1286 ---> 5033
1287 ---> 5034
1288 ---> 5035
1289 ---> 5036
1290 ---> 5037
1291 ---> 5038
1292 ---> 5039
1294 ---> 5040
1296 ---> 5041
1297 ---> 5042
1298 ---> 5043
1299 ---> 5044
1301 ---> 5045
1302 ---> 5046
1303 ---> 5047
1304 ---> 5048
1305 ---> 5049
1306 ---> 5050
1307 ---> 5051
1308 ---> 5052
1309 ---> 5053
1310 ---> 5054
1311 ---> 5055
1315 ---> 5056
1316 ---> 5057
1319 ---> 5058
1320 ---> 5059
1322 ---> 5060
1323 ---> 5061
1326 ---> 5062
1327 ---> 5063
1329 ---> 5064
1331 ---> 5065
1334 ---> 5066
1335 ---> 5067
1336 ---> 5068
1337 ---> 5069
1339 ---> 5070
1341 ---> 5071
1342 ---> 5072
1343 ---> 5073
1344 ---> 5074
1349 ---> 5075
1351 ---> 5076
1352 ---> 5077
1353 ---> 5078
1355 ---> 5079
1356 ---> 5080
1359 ---> 5081
1360 ---> 5082
1361 ---> 5083
1365 ---> 5084
1366 ---> 5085
1368 ---> 5086
1369 ---> 5087
1370 ---> 5088
1371 ---> 5089
1372 ---> 5090
1374 ---> 5091
1376 ---> 5092
1380 ---> 5093
1381 ---> 5094
1383 ---> 5095
1384 ---> 5096
1385 ---> 5097
1388 ---> 5098
1389 ---> 5099
1390 ---> 5100
1391 ---> 5101
1394 ---> 5102
1396 ---> 5103
1399 ---> 5104
1401 ---> 5105
1403 ---> 5106
1404 ---> 5107
1405 ---> 5108
1407 ---> 5109
1409 ---> 5110
1410 ---> 5111
1412 ---> 5112
1413 ---> 5113
1414 ---> 5114
1415 ---> 5115
1420 ---> 5116
1422 ---> 5117
1425 ---> 5118
1427 ---> 5119
1429 ---> 5120
1430 ---> 5121
1431 ---> 5122
1433 ---> 5123
1437 ---> 5124
1440 ---> 5125
1445 ---> 5126
1446 ---> 5127
1447 ---> 5128
1448 ---> 5129
1450 ---> 5130
1453 ---> 5131
1456 ---> 5132
1459 ---> 5133
1472 ---> 5134
1473 ---> 5135
1474 ---> 5136
1475 ---> 5137
1476 ---> 5138
1480 ---> 5139
1481 ---> 5140
1485 ---> 5141
1486 ---> 5142
1488 ---> 5143
1489 ---> 5144
1492 ---> 5145
1493 ---> 5146
1494 ---> 5147
1495 ---> 5148
1496 ---> 5149
1497 ---> 5150
1498 ---> 5151
1503 ---> 5152
1505 ---> 5153
1506 ---> 5154
1507 ---> 5155
1508 ---> 5156
1509 ---> 5157
1510 ---> 5158
1512 ---> 5159
1514 ---> 5160
1515 ---> 5161
1517 ---> 5162
1518 ---> 5163
1519 ---> 5164
1520 ---> 5165
1521 ---> 5166
1525 ---> 5167
1527 ---> 5168
1528 ---> 5169
1531 ---> 5170
1532 ---> 5171
1534 ---> 5172
1537 ---> 5173
1540 ---> 5174
1541 ---> 5175
1542 ---> 5176
1543 ---> 5177
1544 ---> 5178
1545 ---> 5179
1547 ---> 5180
1548 ---> 5181
1549 ---> 5182
1550 ---> 5183
1555 ---> 5184
1556 ---> 5185
1557 ---> 5186
1558 ---> 5187
1559 ---> 5188
1560 ---> 5189
1561 ---> 5190
1562 ---> 5191
1566 ---> 5192
1567 ---> 5193
1569 ---> 5194
1570 ---> 5195
1571 ---> 5196
1572 ---> 5197
1573 ---> 5198
1574 ---> 5199
1575 ---> 5200
1576 ---> 5201
1578 ---> 5202
1579 ---> 5203
1580 ---> 5204
1581 ---> 5205
1582 ---> 5206
1584 ---> 5207
1585 ---> 5208
1586 ---> 5209
1587 ---> 5210
1588 ---> 5211
1589 ---> 5212
1591 ---> 5213
1592 ---> 5214
1593 ---> 5215
1596 ---> 5216
1599 ---> 5217
1600 ---> 5218
1601 ---> 5219
1602 ---> 5220
1603 ---> 5221
1604 ---> 5222
1605 ---> 5223
1606 ---> 5224
1607 ---> 5225
1612 ---> 5226
1613 ---> 5227
1614 ---> 5228
1616 ---> 5229
1617 ---> 5230
1618 ---> 5231
1619 ---> 5232
1620 ---> 5233
1623 ---> 5234
1624 ---> 5235
1625 ---> 5236
1626 ---> 5237
1627 ---> 5238
1628 ---> 5239
1629 ---> 5240
1631 ---> 5241
1632 ---> 5242
1635 ---> 5243
1637 ---> 5244
1639 ---> 5245
1641 ---> 5246
1642 ---> 5247
1643 ---> 5248
1644 ---> 5249
1646 ---> 5250
1647 ---> 5251
1649 ---> 5252
1650 ---> 5253
1651 ---> 5254
1654 ---> 5255
1655 ---> 5256
1656 ---> 5257
1657 ---> 5258
1658 ---> 5259
1659 ---> 5260
1661 ---> 5261
1662 ---> 5262
1663 ---> 5263
1664 ---> 5264
1665 ---> 5265
1666 ---> 5266
1668 ---> 5267
1669 ---> 5268
1670 ---> 5269
1672 ---> 5270
1675 ---> 5271
1677 ---> 5272
1679 ---> 5273
1680 ---> 5274
1681 ---> 5275
1682 ---> 5276
1683 ---> 5277
1685 ---> 5278
1686 ---> 5279
1688 ---> 5280
1689 ---> 5281
1690 ---> 5282
1693 ---> 5283
1694 ---> 5284
1695 ---> 5285
1698 ---> 5286
1700 ---> 5287
1702 ---> 5288
1705 ---> 5289
1706 ---> 5290
1707 ---> 5291
1709 ---> 5292
1711 ---> 5293
1713 ---> 5294
1714 ---> 5295
1715 ---> 5296
1716 ---> 5297
1717 ---> 5298
1718 ---> 5299
1719 ---> 5300
1720 ---> 5301
1721 ---> 5302
1722 ---> 5303
1723 ---> 5304
1725 ---> 5305
1726 ---> 5306
1727 ---> 5307
1728 ---> 5308
1729 ---> 5309
1730 ---> 5310
1732 ---> 5311
1733 ---> 5312
1735 ---> 5313
1736 ---> 5314
1742 ---> 5315
1743 ---> 5316
1744 ---> 5317
1745 ---> 5318
1746 ---> 5319
1748 ---> 5320
1749 ---> 5321
1751 ---> 5322
1752 ---> 5323
1753 ---> 5324
1754 ---> 5325
1755 ---> 5326
1758 ---> 5327
1759 ---> 5328
1760 ---> 5329
1762 ---> 5330
1764 ---> 5331
1765 ---> 5332
1767 ---> 5333
1770 ---> 5334
1771 ---> 5335
1774 ---> 5336
1775 ---> 5337
1776 ---> 5338
1777 ---> 5339
1778 ---> 5340
1779 ---> 5341
1780 ---> 5342
1781 ---> 5343
1783 ---> 5344
1785 ---> 5345
1787 ---> 5346
1788 ---> 5347
1790 ---> 5348
1791 ---> 5349
1793 ---> 5350
1794 ---> 5351
1797 ---> 5352
1799 ---> 5353
1800 ---> 5354
1803 ---> 5355
1804 ---> 5356
1805 ---> 5357
1811 ---> 5358
1812 ---> 5359
1813 ---> 5360
1815 ---> 5361
1816 ---> 5362
1818 ---> 5363
1821 ---> 5364
1822 ---> 5365
1826 ---> 5366
1827 ---> 5367
1828 ---> 5368
1829 ---> 5369
1830 ---> 5370
1832 ---> 5371
1833 ---> 5372
1834 ---> 5373
1835 ---> 5374
1837 ---> 5375
1839 ---> 5376
1846 ---> 5377
1848 ---> 5378
1854 ---> 5379
1855 ---> 5380
1858 ---> 5381
1859 ---> 5382
1860 ---> 5383
1863 ---> 5384
1864 ---> 5385
1876 ---> 5386
1881 ---> 5387
1882 ---> 5388
1886 ---> 5389
1888 ---> 5390
1896 ---> 5391
1897 ---> 5392
1904 ---> 5393
1905 ---> 5394
1907 ---> 5395
1908 ---> 5396
1910 ---> 5397
1914 ---> 5398
1916 ---> 5399
1917 ---> 5400
1919 ---> 5401
1924 ---> 5402
1925 ---> 5403
1926 ---> 5404
1928 ---> 5405
1933 ---> 5406
1935 ---> 5407
1936 ---> 5408
1940 ---> 5409
1944 ---> 5410
1948 ---> 5411
1949 ---> 5412
1950 ---> 5413
1955 ---> 5414
1956 ---> 5415
1957 ---> 5416
1958 ---> 5417
1959 ---> 5418
1961 ---> 5419
1962 ---> 5420
1963 ---> 5421
1964 ---> 5422
1965 ---> 5423
1966 ---> 5424
1967 ---> 5425
1968 ---> 5426
1970 ---> 5427
1973 ---> 5428
1974 ---> 5429
1975 ---> 5430
1976 ---> 5431
1977 ---> 5432
1979 ---> 5433
1981 ---> 5434
1985 ---> 5435
1988 ---> 5436
1992 ---> 5437
1993 ---> 5438
1994 ---> 5439
1995 ---> 5440
1997 ---> 5441
1998 ---> 5442
2000 ---> 5443
2001 ---> 5444
2002 ---> 5445
2004 ---> 5446
2005 ---> 5447
2006 ---> 5448
2007 ---> 5449
2008 ---> 5450
2009 ---> 5451
2010 ---> 5452
2012 ---> 5453
2013 ---> 5454
2018 ---> 5455
2020 ---> 5456
2024 ---> 5457
2025 ---> 5458
2026 ---> 5459
2027 ---> 5460
2028 ---> 5461
2037 ---> 5462
2038 ---> 5463
2039 ---> 5464
2042 ---> 5465
2044 ---> 5466
2045 ---> 5467
2047 ---> 5468
2050 ---> 5469
2052 ---> 5470
2054 ---> 5471
2055 ---> 5472
2057 ---> 5473
2058 ---> 5474
2059 ---> 5475
2061 ---> 5476
2063 ---> 5477
2070 ---> 5478
2071 ---> 5479
2072 ---> 5480
2073 ---> 5481
2081 ---> 5482
2082 ---> 5483
2085 ---> 5484
2089 ---> 5485
2090 ---> 5486
2091 ---> 5487
2093 ---> 5488
2098 ---> 5489
2099 ---> 5490
2100 ---> 5491
2103 ---> 5492
2104 ---> 5493
2110 ---> 5494
2112 ---> 5495
2113 ---> 5496
2115 ---> 5497
2116 ---> 5498
2119 ---> 5499
2120 ---> 5500
2121 ---> 5501
2122 ---> 5502
2123 ---> 5503
2125 ---> 5504
2126 ---> 5505
2127 ---> 5506
2129 ---> 5507
2132 ---> 5508
2134 ---> 5509
2135 ---> 5510
2140 ---> 5511
2141 ---> 5512
2142 ---> 5513
2143 ---> 5514
2146 ---> 5515
2152 ---> 5516
2154 ---> 5517
2155 ---> 5518
2157 ---> 5519
2159 ---> 5520
2161 ---> 5521
2164 ---> 5522
2165 ---> 5523
2166 ---> 5524
2170 ---> 5525
2172 ---> 5526
2173 ---> 5527
2174 ---> 5528
2175 ---> 5529
2176 ---> 5530
2178 ---> 5531
2179 ---> 5532
2180 ---> 5533
2182 ---> 5534
2183 ---> 5535
2184 ---> 5536
2189 ---> 5537
2190 ---> 5538
2192 ---> 5539
2193 ---> 5540
2194 ---> 5541
2195 ---> 5542
2196 ---> 5543
2199 ---> 5544
2200 ---> 5545
2201 ---> 5546
2202 ---> 5547
2203 ---> 5548
2204 ---> 5549
2205 ---> 5550
2206 ---> 5551
2207 ---> 5552
2210 ---> 5553
2211 ---> 5554
2212 ---> 5555
2213 ---> 5556
2216 ---> 5557
2217 ---> 5558
2218 ---> 5559
2221 ---> 5560
2222 ---> 5561
2225 ---> 5562
2228 ---> 5563
2229 ---> 5564
2230 ---> 5565
2231 ---> 5566
2233 ---> 5567
2234 ---> 5568
2236 ---> 5569
2237 ---> 5570
2241 ---> 5571
2242 ---> 5572
2243 ---> 5573
2245 ---> 5574
2246 ---> 5575
2250 ---> 5576
2251 ---> 5577
2252 ---> 5578
2254 ---> 5579
2255 ---> 5580
2256 ---> 5581
2257 ---> 5582
2258 ---> 5583
2260 ---> 5584
2261 ---> 5585
2262 ---> 5586
2263 ---> 5587
2265 ---> 5588
2266 ---> 5589
2267 ---> 5590
2270 ---> 5591
2273 ---> 5592
2276 ---> 5593
2277 ---> 5594
2278 ---> 5595
2279 ---> 5596
2281 ---> 5597
2285 ---> 5598
2286 ---> 5599
2287 ---> 5600
2288 ---> 5601
2289 ---> 5602
2291 ---> 5603
2292 ---> 5604
2293 ---> 5605
2295 ---> 5606
2299 ---> 5607
2302 ---> 5608
2303 ---> 5609
2305 ---> 5610
2307 ---> 5611
2308 ---> 5612
2309 ---> 5613
2311 ---> 5614
2314 ---> 5615
2315 ---> 5616
2317 ---> 5617
2318 ---> 5618
2322 ---> 5619
2324 ---> 5620
2326 ---> 5621
2327 ---> 5622
2330 ---> 5623
2332 ---> 5624
2333 ---> 5625
2334 ---> 5626
2335 ---> 5627
2336 ---> 5628
2339 ---> 5629
2341 ---> 5630
2343 ---> 5631
2344 ---> 5632
2346 ---> 5633
2347 ---> 5634
2348 ---> 5635
2349 ---> 5636
2351 ---> 5637
2352 ---> 5638
2355 ---> 5639
2357 ---> 5640
2359 ---> 5641
2361 ---> 5642
2362 ---> 5643
2364 ---> 5644
2366 ---> 5645
2367 ---> 5646
2369 ---> 5647
2370 ---> 5648
2372 ---> 5649
2373 ---> 5650
2374 ---> 5651
2375 ---> 5652
2380 ---> 5653
2381 ---> 5654
2382 ---> 5655
2383 ---> 5656
2384 ---> 5657
2385 ---> 5658
2386 ---> 5659
2388 ---> 5660
2389 ---> 5661
2390 ---> 5662
2391 ---> 5663
2393 ---> 5664
2394 ---> 5665
2395 ---> 5666
2396 ---> 5667
2397 ---> 5668
2398 ---> 5669
2400 ---> 5670
2402 ---> 5671
2404 ---> 5672
2405 ---> 5673
2406 ---> 5674
2407 ---> 5675
2408 ---> 5676
2413 ---> 5677
2417 ---> 5678
2418 ---> 5679
2419 ---> 5680
2420 ---> 5681
2421 ---> 5682
2423 ---> 5683
2424 ---> 5684
2425 ---> 5685
2426 ---> 5686
2427 ---> 5687
2428 ---> 5688
2429 ---> 5689
2430 ---> 5690
2431 ---> 5691
2432 ---> 5692
2433 ---> 5693
2434 ---> 5694
2435 ---> 5695
2436 ---> 5696
2438 ---> 5697
2440 ---> 5698
2442 ---> 5699
2444 ---> 5700
2446 ---> 5701
2448 ---> 5702
2451 ---> 5703
2452 ---> 5704
2453 ---> 5705
2454 ---> 5706
2455 ---> 5707
2456 ---> 5708
2457 ---> 5709
2458 ---> 5710
2459 ---> 5711
2460 ---> 5712
2461 ---> 5713
2462 ---> 5714
2463 ---> 5715
2464 ---> 5716
2465 ---> 5717
2466 ---> 5718
2467 ---> 5719
2468 ---> 5720
2469 ---> 5721
2474 ---> 5722
2475 ---> 5723
2476 ---> 5724
2477 ---> 5725
2479 ---> 5726
2480 ---> 5727
2482 ---> 5728
2483 ---> 5729
2484 ---> 5730
2485 ---> 5731
2486 ---> 5732
2487 ---> 5733
2488 ---> 5734
2489 ---> 5735
2490 ---> 5736
2492 ---> 5737
2494 ---> 5738
2495 ---> 5739
2496 ---> 5740
2497 ---> 5741
2498 ---> 5742
2499 ---> 5743
2500 ---> 5744
2501 ---> 5745
2502 ---> 5746
2503 ---> 5747
2504 ---> 5748
2505 ---> 5749
2506 ---> 5750
2507 ---> 5751
2509 ---> 5752
2510 ---> 5753
2512 ---> 5754
2513 ---> 5755
2514 ---> 5756
2515 ---> 5757
2520 ---> 5758
2521 ---> 5759
2522 ---> 5760
2523 ---> 5761
2524 ---> 5762
2525 ---> 5763
2526 ---> 5764
2528 ---> 5765
2529 ---> 5766
2531 ---> 5767
2532 ---> 5768
2533 ---> 5769
2535 ---> 5770
2536 ---> 5771
2537 ---> 5772
2540 ---> 5773
2541 ---> 5774
2542 ---> 5775
2543 ---> 5776
2544 ---> 5777
2545 ---> 5778
2547 ---> 5779
2549 ---> 5780
2551 ---> 5781
2552 ---> 5782
2555 ---> 5783
2556 ---> 5784
2558 ---> 5785
2561 ---> 5786
2562 ---> 5787
2563 ---> 5788
2564 ---> 5789
2565 ---> 5790
2566 ---> 5791
2567 ---> 5792
2568 ---> 5793
2569 ---> 5794
2570 ---> 5795
2571 ---> 5796
2572 ---> 5797
2573 ---> 5798
2576 ---> 5799
2577 ---> 5800
2578 ---> 5801
2581 ---> 5802
2582 ---> 5803
2583 ---> 5804
2584 ---> 5805
2585 ---> 5806
2587 ---> 5807
2588 ---> 5808
2589 ---> 5809
2590 ---> 5810
2592 ---> 5811
2593 ---> 5812
2595 ---> 5813
2596 ---> 5814
2598 ---> 5815
2599 ---> 5816
2600 ---> 5817
2602 ---> 5818
2604 ---> 5819
2605 ---> 5820
2607 ---> 5821
2608 ---> 5822
2609 ---> 5823
2611 ---> 5824
2612 ---> 5825
2613 ---> 5826
2615 ---> 5827
2616 ---> 5828
2618 ---> 5829
2621 ---> 5830
2622 ---> 5831
2623 ---> 5832
2624 ---> 5833
2625 ---> 5834
2627 ---> 5835
2628 ---> 5836
2629 ---> 5837
2632 ---> 5838
2633 ---> 5839
2634 ---> 5840
2635 ---> 5841
2637 ---> 5842
2639 ---> 5843
2640 ---> 5844
2641 ---> 5845
2643 ---> 5846
2644 ---> 5847
2645 ---> 5848
2646 ---> 5849
2647 ---> 5850
2649 ---> 5851
2650 ---> 5852
2652 ---> 5853
2655 ---> 5854
2656 ---> 5855
2657 ---> 5856
2660 ---> 5857
2664 ---> 5858
2665 ---> 5859
2666 ---> 5860
2668 ---> 5861
2669 ---> 5862
2671 ---> 5863
2672 ---> 5864
2674 ---> 5865
2675 ---> 5866
2676 ---> 5867
2677 ---> 5868
2678 ---> 5869
2682 ---> 5870
2683 ---> 5871
2686 ---> 5872
2687 ---> 5873
2688 ---> 5874
2689 ---> 5875
2690 ---> 5876
2691 ---> 5877
2692 ---> 5878
2693 ---> 5879
2695 ---> 5880
2697 ---> 5881
2698 ---> 5882
2701 ---> 5883
2702 ---> 5884
2706 ---> 5885
2708 ---> 5886
2710 ---> 5887
2712 ---> 5888
2713 ---> 5889
2714 ---> 5890
2715 ---> 5891
2716 ---> 5892
2718 ---> 5893
2719 ---> 5894
2720 ---> 5895
2727 ---> 5896
2728 ---> 5897
2729 ---> 5898
2730 ---> 5899
2731 ---> 5900
2734 ---> 5901
2737 ---> 5902
2739 ---> 5903
2740 ---> 5904
2741 ---> 5905
2743 ---> 5906
2748 ---> 5907
2751 ---> 5908
2752 ---> 5909
2753 ---> 5910
2754 ---> 5911
2755 ---> 5912
2756 ---> 5913
2758 ---> 5914
2759 ---> 5915
2760 ---> 5916
2761 ---> 5917
2762 ---> 5918
2763 ---> 5919
2765 ---> 5920
2766 ---> 5921
2768 ---> 5922
2771 ---> 5923
2772 ---> 5924
2773 ---> 5925
2775 ---> 5926
2776 ---> 5927
2777 ---> 5928
2780 ---> 5929
2782 ---> 5930
2783 ---> 5931
2784 ---> 5932
2785 ---> 5933
2786 ---> 5934
2788 ---> 5935
2791 ---> 5936
2793 ---> 5937
2794 ---> 5938
2796 ---> 5939
2799 ---> 5940
2800 ---> 5941
2801 ---> 5942
2802 ---> 5943
2803 ---> 5944
2806 ---> 5945
2807 ---> 5946
2810 ---> 5947
2811 ---> 5948
2815 ---> 5949
2817 ---> 5950
2819 ---> 5951
2821 ---> 5952
2823 ---> 5953
2824 ---> 5954
2825 ---> 5955
2826 ---> 5956
2827 ---> 5957
2829 ---> 5958
2830 ---> 5959
2831 ---> 5960
2833 ---> 10584
2835 ---> 5961
2836 ---> 5962
2840 ---> 5963
2841 ---> 5964
2843 ---> 5965
2844 ---> 5966
2845 ---> 5967
2847 ---> 5968
2852 ---> 5969
2853 ---> 5970
2854 ---> 5971
2855 ---> 5972
2859 ---> 5973
2861 ---> 5974
2862 ---> 5975
2865 ---> 5976
2866 ---> 5977
2867 ---> 5978
2869 ---> 5979
2871 ---> 5980
2872 ---> 5981
2873 ---> 5982
2874 ---> 5983
2879 ---> 5984
2881 ---> 5985
2882 ---> 5986
2883 ---> 5987
2884 ---> 5988
2885 ---> 5989
2886 ---> 5990
2887 ---> 5991
2888 ---> 5992
2889 ---> 5993
2890 ---> 5994
2892 ---> 5995
2893 ---> 5996
2894 ---> 5997
2895 ---> 5998
2896 ---> 5999
2897 ---> 6000
2902 ---> 6001
2904 ---> 6002
2905 ---> 6003
2906 ---> 6004
2907 ---> 6005
2908 ---> 6006
2909 ---> 6007
2910 ---> 6008
2911 ---> 6009
2912 ---> 6010
2913 ---> 6011
2914 ---> 6012
2915 ---> 6013
2916 ---> 6014
2917 ---> 6015
2918 ---> 6016
2919 ---> 6017
2920 ---> 6018
2921 ---> 6019
2922 ---> 6020
2923 ---> 6021
2924 ---> 6022
2925 ---> 6023
2926 ---> 6024
2927 ---> 6025
2928 ---> 6026
2929 ---> 6027
2931 ---> 6028
2934 ---> 6029
2935 ---> 6030
2937 ---> 6031
2938 ---> 6032
2939 ---> 6033
2940 ---> 6034
2942 ---> 6035
2944 ---> 6036
2947 ---> 6037
2948 ---> 6038
2949 ---> 6039
2950 ---> 6040
2951 ---> 6041
2952 ---> 6042
2953 ---> 6043
2955 ---> 6044
2956 ---> 6045
2957 ---> 6046
2958 ---> 6047
2959 ---> 6048
2960 ---> 6049
2961 ---> 6050
2962 ---> 6051
2963 ---> 6052
2964 ---> 6053
2965 ---> 6054
2966 ---> 6055
2967 ---> 6056
2968 ---> 6057
2970 ---> 6058
2971 ---> 6059
2972 ---> 6060
2973 ---> 6061
2974 ---> 6062
2975 ---> 6063
2976 ---> 6064
2977 ---> 6065
2978 ---> 6066
2979 ---> 6067
2982 ---> 6068
2983 ---> 6069
2984 ---> 6070
2985 ---> 6071
2986 ---> 6072
2987 ---> 6073
2988 ---> 6074
2989 ---> 6075
2992 ---> 6076
2994 ---> 6077
2995 ---> 6078
2996 ---> 6079
2997 ---> 6080
2999 ---> 6081
3000 ---> 6082
3006 ---> 6083
3008 ---> 6084
3009 ---> 6085
3010 ---> 6086
3012 ---> 6087
3014 ---> 6088
3015 ---> 6089
3016 ---> 6090
3017 ---> 6091
3019 ---> 6092
3021 ---> 6093
3023 ---> 6094
3024 ---> 6095
3026 ---> 6096
3029 ---> 6097
3030 ---> 6098
3031 ---> 6099
3034 ---> 6100
3035 ---> 6101
3036 ---> 6102
3037 ---> 6103
3038 ---> 6104
3040 ---> 6105
3041 ---> 6106
3043 ---> 6107
3044 ---> 6108
3048 ---> 6109
3049 ---> 6110
3050 ---> 6111
3051 ---> 6112
3053 ---> 6113
3054 ---> 6114
3055 ---> 6115
3057 ---> 6116
3059 ---> 6117
3062 ---> 6118
3063 ---> 6119
3064 ---> 6120
3065 ---> 6121
3066 ---> 6122
3067 ---> 6123
3069 ---> 6124
3070 ---> 6125
3071 ---> 6126
3072 ---> 6127
3073 ---> 6128
3075 ---> 6129
3076 ---> 6130
3077 ---> 6131
3078 ---> 6132
3079 ---> 6133
3081 ---> 6134
3082 ---> 6135
3083 ---> 6136
3084 ---> 6137
3085 ---> 6138
3086 ---> 6139
3087 ---> 6140
3088 ---> 6141
3089 ---> 6142
3090 ---> 6143
3091 ---> 6144
3093 ---> 6145
3094 ---> 6146
3095 ---> 6147
3096 ---> 6148
3097 ---> 6149
3098 ---> 6150
3099 ---> 6151
3101 ---> 6152
3102 ---> 6153
3103 ---> 6154
3105 ---> 6155
3108 ---> 6156
3109 ---> 6157
3110 ---> 6158
3112 ---> 6159
3113 ---> 6160
3114 ---> 6161
3115 ---> 6162
3117 ---> 6163
3118 ---> 6164
3119 ---> 6165
3120 ---> 6166
3121 ---> 6167
3123 ---> 6168
3124 ---> 6169
3125 ---> 6170
3126 ---> 6171
3127 ---> 6172
3128 ---> 6173
3130 ---> 6174
3131 ---> 6175
3133 ---> 6176
3135 ---> 6177
3136 ---> 6178
3137 ---> 6179
3141 ---> 6180
3143 ---> 6181
3144 ---> 6182
3145 ---> 6183
3146 ---> 6184
3147 ---> 6185
3151 ---> 6186
3152 ---> 6187
3153 ---> 6188
3154 ---> 6189
3155 ---> 6190
3156 ---> 6191
3157 ---> 6192
3158 ---> 6193
3159 ---> 6194
3162 ---> 6195
3164 ---> 6196
3166 ---> 6197
3168 ---> 6198
3169 ---> 6199
3170 ---> 6200
3171 ---> 6201
3172 ---> 6202
3173 ---> 6203
3174 ---> 6204
3175 ---> 6205
3176 ---> 6206
3177 ---> 6207
3178 ---> 6208
3179 ---> 6209
3181 ---> 6210
3183 ---> 6211
3184 ---> 6212
3185 ---> 6213
3186 ---> 6214
3187 ---> 6215
3189 ---> 6216
3190 ---> 6217
3192 ---> 6218
3193 ---> 6219
3194 ---> 6220
3196 ---> 6221
3197 ---> 6222
3198 ---> 6223
3199 ---> 6224
3200 ---> 6225
3201 ---> 6226
3202 ---> 6227
3203 ---> 6228
3205 ---> 6229
3206 ---> 6230
3209 ---> 6231
3210 ---> 6232
3211 ---> 6233
3212 ---> 6234
3213 ---> 6235
3214 ---> 6236
3216 ---> 6237
3218 ---> 6238
3219 ---> 6239
3220 ---> 6240
3221 ---> 6241
3222 ---> 6242
3224 ---> 6243
3226 ---> 6244
3232 ---> 6245
3233 ---> 6246
3234 ---> 6247
3235 ---> 6248
3237 ---> 6249
3238 ---> 6250
3239 ---> 6251
3243 ---> 6252
3244 ---> 6253
3247 ---> 6254
3249 ---> 6255
3250 ---> 6256
3251 ---> 6257
3252 ---> 6258
3253 ---> 6259
3255 ---> 6260
3259 ---> 6261
3263 ---> 6262
3265 ---> 6263
3266 ---> 6264
3267 ---> 6265
3269 ---> 6266
3274 ---> 6267
3279 ---> 6268
3280 ---> 6269
3282 ---> 6270
3283 ---> 6271
3285 ---> 6272
3286 ---> 6273
3288 ---> 6274
3289 ---> 6275
3290 ---> 6276
3292 ---> 6277
3293 ---> 6278
3294 ---> 6279
3296 ---> 6280
3297 ---> 6281
3298 ---> 6282
3301 ---> 6283
3306 ---> 6284
3307 ---> 6285
3310 ---> 6286
3311 ---> 6287
3314 ---> 6288
3315 ---> 6289
3316 ---> 6290
3317 ---> 6291
3318 ---> 6292
3320 ---> 6293
3322 ---> 6294
3330 ---> 6295
3335 ---> 6296
3338 ---> 6297
3339 ---> 6298
3340 ---> 6299
3342 ---> 6300
3343 ---> 6301
3344 ---> 6302
3345 ---> 6303
3347 ---> 6304
3348 ---> 6305
3349 ---> 6306
3350 ---> 6307
3356 ---> 6308
3360 ---> 6309
3362 ---> 6310
3363 ---> 6311
3365 ---> 6312
3366 ---> 6313
3367 ---> 6314
3368 ---> 6315
3371 ---> 6316
3372 ---> 6317
3377 ---> 6318
3379 ---> 6319
3381 ---> 6320
3382 ---> 6321
3383 ---> 6322
3385 ---> 6323
3387 ---> 6324
3390 ---> 6325
3391 ---> 6326
3392 ---> 6327
3396 ---> 6328
3400 ---> 6329
3401 ---> 6330
3404 ---> 6331
3406 ---> 6332
3408 ---> 6333
3409 ---> 6334
3410 ---> 6335
3415 ---> 6336
3416 ---> 6337
3418 ---> 6338
3419 ---> 6339
3420 ---> 6340
3421 ---> 6341
3422 ---> 6342
3424 ---> 6343
3427 ---> 6344
3428 ---> 6345
3430 ---> 6346
3431 ---> 6347
3432 ---> 6348
3434 ---> 6349
3436 ---> 6350
3438 ---> 6351
3439 ---> 6352
3440 ---> 6353
3444 ---> 6354
3445 ---> 6355
3447 ---> 6356
3450 ---> 6357
3453 ---> 6358
3457 ---> 6359
3459 ---> 6360
3460 ---> 6361
3462 ---> 6362
3465 ---> 6363
3466 ---> 6364
3467 ---> 6365
3469 ---> 6366
3473 ---> 6367
3474 ---> 6368
3475 ---> 6369
3476 ---> 6370
3478 ---> 6371
3481 ---> 6372
3488 ---> 6373
3495 ---> 6374
3496 ---> 6375
3497 ---> 6376
3498 ---> 6377
3499 ---> 6378
3500 ---> 6379
3501 ---> 6380
3502 ---> 6381
3503 ---> 6382
3504 ---> 6383
3505 ---> 6384
3506 ---> 6385
3508 ---> 6386
3509 ---> 6387
3510 ---> 6388
3511 ---> 6389
3512 ---> 6390
3513 ---> 6391
3515 ---> 6392
3517 ---> 6393
3519 ---> 6394
3520 ---> 6395
3521 ---> 6396
3522 ---> 6397
3527 ---> 6398
3528 ---> 6399
3530 ---> 6400
3531 ---> 6401
3532 ---> 6402
3533 ---> 6403
3534 ---> 6404
3536 ---> 6405
3539 ---> 6406
3540 ---> 6407
3542 ---> 6408
3544 ---> 6409
3546 ---> 6410
3548 ---> 6411
3550 ---> 6412
3552 ---> 6413
3553 ---> 6414
3557 ---> 6415
3558 ---> 6416
3560 ---> 6417
3561 ---> 6418
3565 ---> 6419
3568 ---> 6420
3569 ---> 6421
3570 ---> 6422
3571 ---> 6423
3573 ---> 6424
3576 ---> 6425
3577 ---> 6426
3580 ---> 6427
3581 ---> 6428
3582 ---> 6429
3583 ---> 6430
3584 ---> 6431
3585 ---> 6432
3586 ---> 6433
3587 ---> 6434
3589 ---> 6435
3590 ---> 6436
3592 ---> 6437
3594 ---> 6438
3595 ---> 6439
3596 ---> 6440
3597 ---> 6441
3598 ---> 6442
3599 ---> 6443
3600 ---> 6444
3601 ---> 6445
3602 ---> 6446
3603 ---> 6447
3605 ---> 6448
3606 ---> 6449
3607 ---> 6450
3608 ---> 6451
3609 ---> 6452
3610 ---> 6453
3611 ---> 6454
3612 ---> 6455
3614 ---> 6456
3615 ---> 6457
3616 ---> 6458
3617 ---> 6459
3618 ---> 6460
3619 ---> 6461
3620 ---> 6462
3621 ---> 6463
3623 ---> 6464
3624 ---> 6465
3625 ---> 6466
3626 ---> 6467
3629 ---> 6468
3630 ---> 6469
3631 ---> 6470
3633 ---> 6471
3634 ---> 6472
3636 ---> 6473
3637 ---> 6474
3638 ---> 6475
3641 ---> 6476
3646 ---> 6477
3647 ---> 6478
3648 ---> 6479
3649 ---> 6480
3651 ---> 6481
3652 ---> 6482
3655 ---> 6483
3656 ---> 6484
3657 ---> 6485
3658 ---> 6486
3659 ---> 6487
3661 ---> 6488
3662 ---> 6489
3663 ---> 6490
3664 ---> 6491
3665 ---> 6492
3666 ---> 6493
3668 ---> 6494
3670 ---> 6495
3671 ---> 6496
3672 ---> 6497
3674 ---> 6498
3675 ---> 6499
3676 ---> 6500
3679 ---> 6501
3681 ---> 6502
3683 ---> 6503
3684 ---> 6504
3689 ---> 6505
3691 ---> 6506
3692 ---> 6507
3693 ---> 6508
3695 ---> 6509
3697 ---> 6510
3698 ---> 6511
3699 ---> 6512
3700 ---> 6513
3701 ---> 6514
3702 ---> 6515
3703 ---> 6516
3704 ---> 6517
3705 ---> 6518
3707 ---> 6519
3711 ---> 6520
3712 ---> 6521
3713 ---> 6522
3714 ---> 6523
3715 ---> 6524
3716 ---> 6525
3717 ---> 6526
3718 ---> 6527
3720 ---> 6528
3722 ---> 6529
3723 ---> 6530
3724 ---> 6531
3725 ---> 6532
3727 ---> 6533
3728 ---> 6534
3729 ---> 6535
3730 ---> 6536
3732 ---> 6537
3733 ---> 6538
3734 ---> 6539
3735 ---> 6540
3736 ---> 6541
3739 ---> 6542
3740 ---> 6543
3741 ---> 6544
3742 ---> 6545
3743 ---> 6546
3745 ---> 6547
3746 ---> 6548
3747 ---> 6549
3749 ---> 6550
3751 ---> 6551
3753 ---> 6552
3754 ---> 6553
3755 ---> 6554
3756 ---> 6555
3757 ---> 6556
3758 ---> 6557
3759 ---> 6558
3761 ---> 6559
3762 ---> 6560
3763 ---> 6561
3764 ---> 6562
3765 ---> 6563
3768 ---> 6564
3769 ---> 6565
3770 ---> 6566
3771 ---> 6567
3772 ---> 6568
3773 ---> 6569
3774 ---> 6570
3776 ---> 6571
3778 ---> 6572
3780 ---> 6573
3781 ---> 6574
3782 ---> 6575
3783 ---> 6576
3784 ---> 6577
3785 ---> 6578
3786 ---> 6579
3788 ---> 6580
3790 ---> 6581
3791 ---> 6582
3792 ---> 6583
3793 ---> 6584
3795 ---> 6585
3796 ---> 6586
3797 ---> 6587
3798 ---> 6588
3799 ---> 6589
3800 ---> 6590
3801 ---> 6591
3802 ---> 6592
3803 ---> 6593
3804 ---> 6594
3805 ---> 6595
3807 ---> 6596
3810 ---> 6597
3814 ---> 6598
3815 ---> 6599
3816 ---> 6600
3817 ---> 6601
3819 ---> 6602
3820 ---> 6603
3823 ---> 6604
3824 ---> 6605
3825 ---> 6606
3826 ---> 6607
3827 ---> 6608
3828 ---> 6609
3829 ---> 6610
3830 ---> 6611
3831 ---> 6612
3832 ---> 6613
3833 ---> 6614
3834 ---> 6615
3835 ---> 6616
3837 ---> 6617
3838 ---> 6618
3839 ---> 6619
3840 ---> 6620
3841 ---> 6621
3843 ---> 6622
3844 ---> 6623
3847 ---> 6624
3850 ---> 6625
3851 ---> 6626
3852 ---> 6627
3853 ---> 6628
3855 ---> 6629
3856 ---> 6630
3858 ---> 6631
3860 ---> 6632
3861 ---> 6633
3862 ---> 6634
3864 ---> 6635
3865 ---> 6636
3866 ---> 6637
3867 ---> 6638
3868 ---> 6639
3870 ---> 6640
3874 ---> 6641
3875 ---> 6642
3877 ---> 6643
3880 ---> 6644
3881 ---> 6645
3882 ---> 6646
3883 ---> 6647
3889 ---> 6648
3891 ---> 6649
3892 ---> 6650
3893 ---> 6651
3894 ---> 6652
3896 ---> 6653
3897 ---> 6654
3898 ---> 6655
3899 ---> 6656
3900 ---> 6657
3901 ---> 6658
3902 ---> 6659
3903 ---> 6660
3906 ---> 6661
3907 ---> 6662
3908 ---> 6663
3909 ---> 6664
3910 ---> 6665
3912 ---> 6666
3913 ---> 6667
3915 ---> 6668
3919 ---> 6669
3921 ---> 6670
3926 ---> 6671
3928 ---> 6672
3929 ---> 6673
3930 ---> 6674
3931 ---> 6675
3932 ---> 6676
3933 ---> 6677
3934 ---> 6678
3935 ---> 6679
3936 ---> 6680
3938 ---> 6681
3939 ---> 6682
3940 ---> 6683
3946 ---> 6684
3947 ---> 6685
3949 ---> 6686
3951 ---> 6687
3959 ---> 6688
3961 ---> 6689
3964 ---> 6690
3965 ---> 6691
3966 ---> 6692
3967 ---> 6693
3968 ---> 6694
3969 ---> 6695
3973 ---> 6696
3974 ---> 6697
3977 ---> 6698
3982 ---> 6699
3985 ---> 6700
3986 ---> 6701
3987 ---> 6702
3988 ---> 6703
3990 ---> 6704
3991 ---> 6705
3992 ---> 6706
3993 ---> 6707
3994 ---> 6708
3995 ---> 6709
3996 ---> 6710
3997 ---> 6711
3998 ---> 6712
3999 ---> 6713
4001 ---> 6714
4002 ---> 6715
4003 ---> 6716
4004 ---> 6717
4005 ---> 6718
4010 ---> 6719
4011 ---> 6720
4012 ---> 6721
4014 ---> 6722
4015 ---> 6723
4016 ---> 6724
4021 ---> 6725
4022 ---> 6726
4026 ---> 6727
4028 ---> 6728
4029 ---> 6729
4030 ---> 6730
4033 ---> 6731
4034 ---> 6732
4036 ---> 6733
4037 ---> 6734
4039 ---> 6735
4042 ---> 6736
4043 ---> 6737
4044 ---> 6738
4045 ---> 6739
4046 ---> 6740
4047 ---> 6741
4048 ---> 6742
4049 ---> 6743
4050 ---> 6744
4051 ---> 6745
4052 ---> 6746
4054 ---> 6747
4055 ---> 6748
4056 ---> 6749
4057 ---> 6750
4060 ---> 6751
4062 ---> 6752
4063 ---> 6753
4065 ---> 6754
4066 ---> 6755
4067 ---> 6756
4068 ---> 6757
4069 ---> 6758
4070 ---> 6759
4072 ---> 6760
4073 ---> 6761
4075 ---> 6762
4076 ---> 6763
4077 ---> 6764
4078 ---> 6765
4080 ---> 6766
4081 ---> 6767
4082 ---> 6768
4084 ---> 6769
4085 ---> 6770
4086 ---> 6771
4088 ---> 6772
4089 ---> 6773
4090 ---> 6774
4091 ---> 6775
4092 ---> 6776
4094 ---> 6777
4095 ---> 6778
4096 ---> 6779
4097 ---> 6780
4098 ---> 6781
4099 ---> 6782
4100 ---> 6783
4101 ---> 6784
4103 ---> 6785
4105 ---> 6786
4106 ---> 6787
4107 ---> 6788
4109 ---> 6789
4110 ---> 6790
4111 ---> 6791
4113 ---> 6792
4114 ---> 6793
4117 ---> 6794
4118 ---> 6795
4120 ---> 6796
4122 ---> 6797
4123 ---> 6798
4124 ---> 6799
4125 ---> 6800
4126 ---> 6801
4129 ---> 6802
4131 ---> 6803
4133 ---> 6804
4135 ---> 6805
4138 ---> 6806
4139 ---> 6807
4140 ---> 6808
4141 ---> 6809
4142 ---> 6810
4144 ---> 6811
4146 ---> 6812
4147 ---> 6813
4148 ---> 6814
4149 ---> 6815
4150 ---> 6816
4151 ---> 6817
4153 ---> 6818
4156 ---> 6819
4157 ---> 6820
4158 ---> 6821
4159 ---> 6822
4160 ---> 6823
4161 ---> 6824
4163 ---> 6825
4164 ---> 6826
4165 ---> 6827
4166 ---> 6828
4167 ---> 6829
4168 ---> 6830
4169 ---> 6831
4171 ---> 6832
4172 ---> 6833
4173 ---> 6834
4175 ---> 6835
4176 ---> 6836
4177 ---> 6837
4179 ---> 6838
4181 ---> 6839
4182 ---> 6840
4183 ---> 6841
4189 ---> 6842
4190 ---> 6843
4194 ---> 6844
4195 ---> 6845
4196 ---> 6846
4197 ---> 6847
4198 ---> 6848
4199 ---> 6849
4201 ---> 6850
4202 ---> 6851
4203 ---> 6852
4204 ---> 6853
4205 ---> 6854
4206 ---> 6855
4207 ---> 6856
4208 ---> 6857
4209 ---> 6858
4210 ---> 6859
4211 ---> 6860
4212 ---> 6861
4213 ---> 6862
4214 ---> 6863
4215 ---> 6864
4219 ---> 6865
4222 ---> 6866
4223 ---> 6867
4225 ---> 6868
4226 ---> 6869
4227 ---> 6870
4228 ---> 6871
4235 ---> 6872
4238 ---> 6873
4239 ---> 6874
4243 ---> 6875
4244 ---> 6876
4245 ---> 6877
4246 ---> 6878
4247 ---> 6879
4248 ---> 6880
4249 ---> 6881
4250 ---> 6882
4251 ---> 6883
4252 ---> 6884
4255 ---> 6885
4256 ---> 6886
4259 ---> 6887
4260 ---> 6888
4262 ---> 6889
4263 ---> 6890
4266 ---> 6891
4268 ---> 6892
4269 ---> 6893
4271 ---> 6894
4273 ---> 6895
4274 ---> 6896
4276 ---> 6897
4277 ---> 6898
4278 ---> 6899
4280 ---> 6900
4282 ---> 6901
4283 ---> 6902
4285 ---> 6903
4287 ---> 6904
4289 ---> 6905
4290 ---> 6906
4291 ---> 6907
4292 ---> 6908
4293 ---> 6909
4294 ---> 6910
4296 ---> 6911
4299 ---> 6912
4302 ---> 6913
4304 ---> 6914
4306 ---> 6915
4307 ---> 6916
4308 ---> 6917
4309 ---> 6918
4312 ---> 6919
4313 ---> 6920
4314 ---> 6921
4316 ---> 6922
4317 ---> 6923
4318 ---> 6924
4321 ---> 6925
4330 ---> 6926
4331 ---> 6927
4333 ---> 6928
4334 ---> 6929
4336 ---> 6930
4337 ---> 6931
4338 ---> 6932
4339 ---> 6933
4340 ---> 6934
4341 ---> 6935
4342 ---> 6936
4343 ---> 6937
4344 ---> 6938
4345 ---> 6939
4346 ---> 6940
4347 ---> 6941
4351 ---> 6942
4353 ---> 6943
4354 ---> 6944
4355 ---> 6945
4356 ---> 6946
4357 ---> 6947
4358 ---> 6948
4360 ---> 6949
4362 ---> 6950
4365 ---> 6951
4366 ---> 6952
4368 ---> 6953
4372 ---> 6954
4373 ---> 6955
4378 ---> 6956
4381 ---> 6957
4383 ---> 6958
4384 ---> 6959
4386 ---> 6960
4389 ---> 6961
4392 ---> 6962
4399 ---> 6963
4400 ---> 6964
4402 ---> 6965
4404 ---> 6966
4407 ---> 6967
4408 ---> 6968
4409 ---> 6969
4410 ---> 6970
4411 ---> 6971
4412 ---> 6972
4413 ---> 6973
4414 ---> 6974
4415 ---> 6975
4417 ---> 6976
4419 ---> 6977
4422 ---> 6978
4423 ---> 6979
4424 ---> 6980
4425 ---> 6981
4426 ---> 6982
4427 ---> 6983
4428 ---> 6984
4431 ---> 6985
4432 ---> 6986
4433 ---> 6987
4434 ---> 6988
4436 ---> 6989
4437 ---> 6990
4440 ---> 6991
4441 ---> 6992
4443 ---> 6993
4445 ---> 6994
4447 ---> 6995
4450 ---> 6996
4452 ---> 6997
4453 ---> 6998
4454 ---> 6999
4457 ---> 7000
4458 ---> 7001
4461 ---> 7002
4464 ---> 7003
4465 ---> 7004
4466 ---> 7005
4467 ---> 7006
4469 ---> 7007
4470 ---> 7008
4471 ---> 7009
4472 ---> 7010
4473 ---> 7011
4475 ---> 7012
4476 ---> 7013
4477 ---> 7014
4478 ---> 7015
4480 ---> 7016
4481 ---> 7017
4483 ---> 7018
4484 ---> 7019
4485 ---> 7020
4486 ---> 7021
4487 ---> 7022
4488 ---> 7023
4489 ---> 7024
4490 ---> 7025
4492 ---> 7026
4493 ---> 7027
4495 ---> 7028
4498 ---> 7029
4500 ---> 7030
4501 ---> 7031
4504 ---> 7032
4506 ---> 7033
4508 ---> 7034
4509 ---> 7035
4510 ---> 7036
4511 ---> 7037
4512 ---> 7038
4513 ---> 7039
4514 ---> 7040
4521 ---> 7041
4522 ---> 7042
4523 ---> 7043
4526 ---> 7044
4532 ---> 7045
4534 ---> 7046
4539 ---> 7047
4544 ---> 7048
4545 ---> 7049
4547 ---> 7050
4548 ---> 7051
4549 ---> 7052
4553 ---> 7053
4555 ---> 7054
4556 ---> 7055
4557 ---> 7056
4559 ---> 7057
4560 ---> 7058
4561 ---> 7059
4562 ---> 7060
4563 ---> 7061
4564 ---> 7062
4567 ---> 7063
4568 ---> 7064
4569 ---> 7065
4570 ---> 7066
4571 ---> 7067
4577 ---> 7068
4578 ---> 7069
4579 ---> 7070
4582 ---> 7071
4586 ---> 7072
4588 ---> 7073
4590 ---> 7074
4591 ---> 7075
4592 ---> 7076
4593 ---> 7077
4594 ---> 7078
4595 ---> 7079
4596 ---> 7080
4599 ---> 7081
4603 ---> 7082
4604 ---> 7083
4605 ---> 7084
4607 ---> 7085
4609 ---> 7086
4610 ---> 7087
4612 ---> 7088
4616 ---> 7089
4618 ---> 7090
4619 ---> 7091
4621 ---> 7092
4623 ---> 7093
4624 ---> 7094
4626 ---> 7095
4627 ---> 7096
4628 ---> 7097
4629 ---> 7098
4631 ---> 7099
4632 ---> 7100
4633 ---> 7101
4634 ---> 7102
4635 ---> 7103
4637 ---> 7104
4640 ---> 7105
4643 ---> 7106
4645 ---> 7107
4648 ---> 7108
4649 ---> 7109
4650 ---> 7110
4652 ---> 7111
4653 ---> 7112
4655 ---> 7113
4658 ---> 7114
4660 ---> 7115
4661 ---> 7116
4663 ---> 7117
4664 ---> 7118
4666 ---> 7119
4667 ---> 7120
4669 ---> 7121
4672 ---> 7122
4674 ---> 7123
4675 ---> 7124
4676 ---> 7125
4677 ---> 7126
4678 ---> 7127
4679 ---> 7128
4683 ---> 7129
4684 ---> 7130
4685 ---> 7131
4686 ---> 7132
4687 ---> 7133
4688 ---> 7134
4689 ---> 7135
4691 ---> 7136
4693 ---> 7137
4694 ---> 7138
4695 ---> 7139
4696 ---> 7140
4697 ---> 7141
4698 ---> 7142
4699 ---> 7143
4700 ---> 7144
4701 ---> 7145
4702 ---> 7146
4703 ---> 7147
4704 ---> 7148
4705 ---> 7149
4707 ---> 7150
4708 ---> 7151
4709 ---> 7152
4710 ---> 7153
4711 ---> 7154
4712 ---> 7155
4713 ---> 7156
4714 ---> 7157
4715 ---> 7158
4716 ---> 7159
4717 ---> 7160
4721 ---> 7161
4722 ---> 7162
4723 ---> 7163
4724 ---> 7164
4725 ---> 7165
4726 ---> 7166
4727 ---> 7167
4730 ---> 7168
4731 ---> 7169
4732 ---> 7170
4734 ---> 7171
4736 ---> 7172
4738 ---> 7173
4739 ---> 7174
4742 ---> 7175
4743 ---> 7176
4744 ---> 7177
4745 ---> 7178
4746 ---> 7179
4747 ---> 7180
4748 ---> 7181
4749 ---> 7182
4751 ---> 7183
4752 ---> 7184
4753 ---> 7185
4754 ---> 7186
4755 ---> 7187
4756 ---> 7188
4757 ---> 7189
4759 ---> 7190
4760 ---> 7191
4761 ---> 7192
4762 ---> 7193
4764 ---> 7194
4765 ---> 7195
4766 ---> 7196
4767 ---> 7197
4768 ---> 7198
4770 ---> 7199
4773 ---> 7200
4774 ---> 7201
4775 ---> 7202
4776 ---> 7203
4778 ---> 7204
4779 ---> 7205
4781 ---> 7206
4783 ---> 7207
4784 ---> 7208
4785 ---> 7209
4786 ---> 7210
4787 ---> 7211
4788 ---> 7212
4790 ---> 7213
4791 ---> 7214
4792 ---> 7215
4794 ---> 7216
4795 ---> 7217
4796 ---> 7218
4798 ---> 7219
4799 ---> 7220
4800 ---> 7221
4803 ---> 7222
4804 ---> 7223
4806 ---> 7224
4807 ---> 7225
4808 ---> 7226
4809 ---> 7227
4811 ---> 7228
4812 ---> 7229
4813 ---> 7230
4815 ---> 7231
4816 ---> 7232
4817 ---> 7233
4819 ---> 7234
4820 ---> 7235
4822 ---> 7236
4823 ---> 7237
4825 ---> 7238
4826 ---> 7239
4830 ---> 7240
4832 ---> 7241
4833 ---> 7242
4834 ---> 7243
4835 ---> 7244
4837 ---> 7245
4839 ---> 7246
4840 ---> 7247
4841 ---> 7248
4844 ---> 7249
4845 ---> 7250
4846 ---> 7251
4847 ---> 7252
4848 ---> 7253
4849 ---> 7254
4850 ---> 7255
4851 ---> 7256
4852 ---> 7257
4853 ---> 7258
4854 ---> 7259
4855 ---> 7260
4856 ---> 7261
4857 ---> 7262
4859 ---> 7263
4860 ---> 7264
4861 ---> 7265
4862 ---> 7266
4863 ---> 7267
4864 ---> 7268
4865 ---> 7269
4866 ---> 7270
4867 ---> 7271
4869 ---> 7272
4871 ---> 7273
4872 ---> 7274
4874 ---> 7275
4875 ---> 7276
4881 ---> 7277
4883 ---> 7278
4884 ---> 7279
4887 ---> 7280
4892 ---> 7281
4893 ---> 7282
4896 ---> 7283
4905 ---> 7284
4906 ---> 7285
4907 ---> 7286
4908 ---> 7287
4909 ---> 7288
4910 ---> 7289
4913 ---> 7290
4914 ---> 7291
4918 ---> 7292
4919 ---> 7293
4920 ---> 7294
4921 ---> 7295
4927 ---> 7296
4935 ---> 7297
4937 ---> 7298
4938 ---> 7299
4939 ---> 7300
4942 ---> 7301
4946 ---> 7302
4952 ---> 7303
4954 ---> 7304
4955 ---> 7305
4956 ---> 7306
4957 ---> 7307
4958 ---> 7308
4959 ---> 7309
4960 ---> 7310
4961 ---> 7311
4962 ---> 7312
4964 ---> 7313
4965 ---> 7314
4966 ---> 7315
4967 ---> 7316
4968 ---> 7317
4969 ---> 7318
4970 ---> 7319
4971 ---> 7320
4973 ---> 7321
4975 ---> 7322
4976 ---> 7323
4977 ---> 7324
4981 ---> 7325
4982 ---> 7326
4983 ---> 7327
4988 ---> 7328
4989 ---> 7329
4991 ---> 7330
4992 ---> 7331
4995 ---> 7332
4996 ---> 7333
4997 ---> 7334
4998 ---> 7335
4999 ---> 7336
5000 ---> 7337
5001 ---> 7338
5003 ---> 7339
5004 ---> 7340
5006 ---> 7341
5007 ---> 7342
5009 ---> 7343
5010 ---> 7344
5012 ---> 7345
5013 ---> 7346
5017 ---> 7347
5019 ---> 7348
5020 ---> 7349
5021 ---> 7350
5023 ---> 7351
5024 ---> 7352
5025 ---> 7353
5026 ---> 7354
5028 ---> 7355
5030 ---> 7356
5031 ---> 7357
5033 ---> 7358
5035 ---> 7359
5036 ---> 7360
5038 ---> 7361
5039 ---> 7362
5040 ---> 7363
5041 ---> 7364
5042 ---> 7365
5044 ---> 7366
5045 ---> 7367
5046 ---> 7368
5047 ---> 7369
5048 ---> 7370
5049 ---> 7371
5052 ---> 7372
5053 ---> 7373
5059 ---> 7374
5060 ---> 7375
5061 ---> 7376
5068 ---> 7377
5070 ---> 7378
5071 ---> 7379
5072 ---> 7380
5073 ---> 7381
5075 ---> 7382
5076 ---> 7383
5081 ---> 7384
5082 ---> 7385
5084 ---> 7386
5086 ---> 7387
5087 ---> 7388
5088 ---> 7389
5091 ---> 7390
5093 ---> 7391
5094 ---> 7392
5095 ---> 7393
5097 ---> 7394
5098 ---> 7395
5099 ---> 7396
5101 ---> 7397
5103 ---> 7398
5105 ---> 7399
5107 ---> 7400
5110 ---> 7401
5111 ---> 7402
5113 ---> 7403
5115 ---> 7404
5116 ---> 7405
5117 ---> 7406
5118 ---> 7407
5120 ---> 7408
5121 ---> 7409
5123 ---> 7410
5125 ---> 7411
5126 ---> 7412
5127 ---> 7413
5129 ---> 7414
5131 ---> 7415
5132 ---> 7416
5133 ---> 7417
5135 ---> 7418
5136 ---> 7419
5137 ---> 7420
5138 ---> 7421
5140 ---> 7422
5141 ---> 7423
5143 ---> 7424
5144 ---> 7425
5146 ---> 7426
5147 ---> 7427
5148 ---> 7428
5149 ---> 7429
5150 ---> 7430
5151 ---> 7431
5152 ---> 7432
5153 ---> 7433
5154 ---> 7434
5155 ---> 7435
5161 ---> 7436
5162 ---> 7437
5163 ---> 7438
5165 ---> 7439
5166 ---> 7440
5168 ---> 7441
5171 ---> 7442
5172 ---> 7443
5173 ---> 7444
5175 ---> 7445
5182 ---> 7446
5183 ---> 7447
5184 ---> 7448
5185 ---> 7449
5186 ---> 7450
5187 ---> 7451
5188 ---> 7452
5189 ---> 7453
5194 ---> 7454
5201 ---> 7455
5202 ---> 7456
5205 ---> 7457
5207 ---> 7458
5209 ---> 7459
5211 ---> 7460
5213 ---> 7461
5216 ---> 7462
5221 ---> 7463
5224 ---> 7464
5230 ---> 7465
5232 ---> 7466
5236 ---> 7467
5238 ---> 7468
5239 ---> 7469
5240 ---> 7470
5241 ---> 7471
5242 ---> 7472
5245 ---> 7473
5248 ---> 7474
5251 ---> 7475
5252 ---> 7476
5253 ---> 7477
5254 ---> 7478
5259 ---> 7479
5262 ---> 7480
5263 ---> 7481
5264 ---> 7482
5268 ---> 7483
5271 ---> 7484
5273 ---> 7485
5275 ---> 7486
5276 ---> 7487
5278 ---> 7488
5280 ---> 7489
5281 ---> 7490
5283 ---> 7491
5284 ---> 7492
5287 ---> 7493
5289 ---> 7494
5294 ---> 7495
5295 ---> 7496
5296 ---> 7497
5297 ---> 7498
5299 ---> 7499
5300 ---> 7500
5301 ---> 7501
5303 ---> 7502
5304 ---> 7503
5305 ---> 7504
5307 ---> 7505
5308 ---> 7506
5309 ---> 7507
5310 ---> 7508
5311 ---> 7509
5312 ---> 7510
5314 ---> 7511
5316 ---> 7512
5317 ---> 7513
5318 ---> 7514
5319 ---> 7515
5320 ---> 7516
5325 ---> 7517
5328 ---> 7518
5329 ---> 7519
5330 ---> 7520
5331 ---> 7521
5332 ---> 7522
5333 ---> 7523
5334 ---> 7524
5336 ---> 7525
5338 ---> 7526
5340 ---> 7527
5341 ---> 7528
5342 ---> 7529
5343 ---> 7530
5344 ---> 7531
5345 ---> 7532
5346 ---> 7533
5347 ---> 7534
5349 ---> 7535
5350 ---> 7536
5351 ---> 7537
5353 ---> 7538
5354 ---> 7539
5355 ---> 7540
5359 ---> 7541
5360 ---> 7542
5361 ---> 7543
5363 ---> 7544
5365 ---> 7545
5367 ---> 7546
5369 ---> 7547
5370 ---> 7548
5371 ---> 7549
5373 ---> 7550
5375 ---> 7551
5376 ---> 7552
5378 ---> 7553
5379 ---> 7554
5380 ---> 7555
5381 ---> 7556
5382 ---> 7557
5383 ---> 7558
5384 ---> 7559
5385 ---> 7560
5386 ---> 7561
5387 ---> 7562
5388 ---> 7563
5389 ---> 7564
5392 ---> 7565
5397 ---> 7566
5400 ---> 7567
5401 ---> 7568
5402 ---> 7569
5404 ---> 7570
5405 ---> 7571
5406 ---> 7572
5407 ---> 7573
5410 ---> 7574
5412 ---> 7575
5413 ---> 7576
5414 ---> 7577
5416 ---> 7578
5417 ---> 7579
5418 ---> 7580
5420 ---> 7581
5422 ---> 7582
5425 ---> 7583
5431 ---> 7584
5435 ---> 7585
5436 ---> 7586
5437 ---> 7587
5439 ---> 7588
5440 ---> 7589
5443 ---> 7590
5444 ---> 7591
5445 ---> 7592
5448 ---> 7593
5449 ---> 7594
5450 ---> 7595
5452 ---> 7596
5453 ---> 7597
5454 ---> 7598
5455 ---> 7599
5457 ---> 7600
5458 ---> 7601
5459 ---> 7602
5461 ---> 7603
5463 ---> 7604
5464 ---> 7605
5466 ---> 7606
5467 ---> 7607
5470 ---> 7608
5471 ---> 7609
5473 ---> 7610
5477 ---> 7611
5484 ---> 7612
5486 ---> 7613
5487 ---> 7614
5491 ---> 7615
5494 ---> 7616
5497 ---> 7617
5498 ---> 7618
5499 ---> 7619
5500 ---> 7620
5502 ---> 7621
5504 ---> 7622
5505 ---> 7623
5506 ---> 7624
5508 ---> 7625
5511 ---> 7626
5512 ---> 7627
5513 ---> 7628
5514 ---> 7629
5515 ---> 7630
5516 ---> 7631
5518 ---> 7632
5519 ---> 7633
5520 ---> 7634
5521 ---> 7635
5522 ---> 7636
5523 ---> 7637
5524 ---> 7638
5526 ---> 7639
5527 ---> 7640
5528 ---> 7641
5528 ---> 7641
5530 ---> 7642
5531 ---> 7643
5532 ---> 7644
5534 ---> 7645
5538 ---> 7646
5540 ---> 7647
5542 ---> 7648
5544 ---> 7649
5545 ---> 7650
5547 ---> 7651
5548 ---> 7652
5549 ---> 7653
5553 ---> 7654
5555 ---> 7655
5556 ---> 7656
5558 ---> 7657
5559 ---> 7658
5561 ---> 7659
5562 ---> 7660
5563 ---> 7661
5564 ---> 7662
5565 ---> 7663
5568 ---> 7664
5569 ---> 7665
5570 ---> 7666
5571 ---> 7667
5572 ---> 7668
5573 ---> 7669
5574 ---> 7670
5575 ---> 7671
5576 ---> 7672
5578 ---> 7673
5579 ---> 7674
5580 ---> 7675
5582 ---> 7676
5583 ---> 7677
5584 ---> 7678
5585 ---> 7679
5586 ---> 7680
5587 ---> 7681
5588 ---> 7682
5591 ---> 7683
5592 ---> 7684
5593 ---> 7685
5594 ---> 7686
5595 ---> 7687
5596 ---> 7688
5598 ---> 7689
5599 ---> 7690
5602 ---> 7691
5604 ---> 7692
5606 ---> 7693
5607 ---> 7694
5611 ---> 7695
5612 ---> 7696
5614 ---> 7697
5616 ---> 7698
5619 ---> 7699
5621 ---> 7700
5622 ---> 7701
5625 ---> 7702
5626 ---> 7703
5629 ---> 7704
5630 ---> 7705
5631 ---> 7706
5632 ---> 7707
5635 ---> 7708
5636 ---> 7709
5637 ---> 7710
5638 ---> 7711
5639 ---> 7712
5640 ---> 7713
5641 ---> 7714
5642 ---> 7715
5643 ---> 7716
5644 ---> 7717
5645 ---> 7718
5646 ---> 7719
5649 ---> 7720
5650 ---> 7721
5651 ---> 7722
5652 ---> 7723
5654 ---> 7724
5656 ---> 7725
5658 ---> 7726
5659 ---> 7727
5663 ---> 7728
5664 ---> 7729
5665 ---> 7730
5666 ---> 7731
5667 ---> 7732
5668 ---> 7733
5672 ---> 7734
5674 ---> 7735
5675 ---> 7736
5676 ---> 7737
5678 ---> 7738
5681 ---> 7739
5682 ---> 7740
5683 ---> 7741
5684 ---> 7742
5685 ---> 7743
5687 ---> 7744
5688 ---> 7745
5692 ---> 7746
5694 ---> 7747
5696 ---> 7748
5697 ---> 7749
5701 ---> 7750
5704 ---> 7751
5707 ---> 7752
5714 ---> 7753
5718 ---> 7754
5719 ---> 7755
5723 ---> 7756
5724 ---> 7757
5725 ---> 7758
5727 ---> 7759
5729 ---> 7760
5730 ---> 7761
5732 ---> 7762
5733 ---> 7763
5734 ---> 7764
5737 ---> 7765
5740 ---> 7766
5747 ---> 7767
5750 ---> 7768
5752 ---> 7769
5753 ---> 7770
5755 ---> 7771
5756 ---> 7772
5760 ---> 7773
5761 ---> 7774
5762 ---> 7775
5763 ---> 7776
5764 ---> 7777
5765 ---> 7778
5767 ---> 7779
5768 ---> 7780
5769 ---> 7781
5770 ---> 7782
5771 ---> 7783
5772 ---> 7784
5773 ---> 7785
5774 ---> 7786
5775 ---> 7787
5776 ---> 7788
5778 ---> 7789
5779 ---> 7790
5780 ---> 7791
5783 ---> 7792
5789 ---> 7793
5792 ---> 7794
5795 ---> 7795
5796 ---> 7796
5798 ---> 7797
5811 ---> 7798
5815 ---> 7799
5819 ---> 7800
5825 ---> 7801
5827 ---> 7802
5829 ---> 7803
5830 ---> 7804
5834 ---> 7805
5835 ---> 7806
5836 ---> 7807
5837 ---> 7808
5842 ---> 7809
5843 ---> 7810
5844 ---> 7811
5845 ---> 7812
5846 ---> 7813
5847 ---> 7814
5849 ---> 7815
5851 ---> 7816
5853 ---> 7817
5854 ---> 7818
5855 ---> 7819
5856 ---> 7820
5857 ---> 7821
5858 ---> 7822
5859 ---> 7823
5867 ---> 7824
5868 ---> 7825
5871 ---> 7826
5873 ---> 7827
5874 ---> 7828
5876 ---> 7829
5880 ---> 7830
5883 ---> 7831
5885 ---> 7832
5887 ---> 7833
5890 ---> 7834
5893 ---> 7835
5895 ---> 7836
5896 ---> 7837
5897 ---> 7838
5899 ---> 7839
5900 ---> 7840
5901 ---> 7841
5902 ---> 7842
5903 ---> 7843
5907 ---> 7844
5908 ---> 7845
5910 ---> 7846
5911 ---> 7847
5914 ---> 7848
5916 ---> 7849
5918 ---> 7850
5919 ---> 7851
5920 ---> 7852
5921 ---> 7853
5923 ---> 7854
5924 ---> 7855
5926 ---> 7856
5927 ---> 7857
5929 ---> 7858
5930 ---> 7859
5931 ---> 7860
5934 ---> 7861
5936 ---> 7862
5937 ---> 7863
5940 ---> 7864
5943 ---> 7865
5947 ---> 7866
5948 ---> 7867
5949 ---> 7868
5951 ---> 7869
5952 ---> 7870
5953 ---> 7871
5954 ---> 7872
5955 ---> 7873
5956 ---> 7874
5959 ---> 7875
5961 ---> 7876
5962 ---> 7877
5963 ---> 7878
5964 ---> 7879
5965 ---> 7880
5967 ---> 7881
5970 ---> 7882
5971 ---> 7883
5973 ---> 7884
5974 ---> 7885
5975 ---> 7886
5976 ---> 7887
5977 ---> 7888
5978 ---> 7889
5984 ---> 7890
5988 ---> 7891
5989 ---> 7892
5991 ---> 7893
5992 ---> 7894
5993 ---> 7895
5994 ---> 7896
5996 ---> 7897
5998 ---> 7898
6000 ---> 7899
6001 ---> 7900
6002 ---> 7901
6005 ---> 7902
6006 ---> 7903
6007 ---> 7904
6008 ---> 7905
6009 ---> 7906
6010 ---> 7907
6011 ---> 7908
6012 ---> 7909
6013 ---> 7910
6014 ---> 7911
6015 ---> 7912
6016 ---> 7913
6018 ---> 7914
6019 ---> 7915
6020 ---> 7916
6022 ---> 7917
6023 ---> 7918
6025 ---> 7919
6026 ---> 7920
6028 ---> 7921
6029 ---> 7922
6031 ---> 7923
6032 ---> 7924
6033 ---> 7925
6034 ---> 7926
6035 ---> 7927
6036 ---> 7928
6038 ---> 7929
6040 ---> 7930
6042 ---> 7931
6043 ---> 7932
6044 ---> 7933
6046 ---> 7934
6047 ---> 7935
6049 ---> 7936
6051 ---> 7937
6052 ---> 7938
6056 ---> 7939
6057 ---> 7940
6058 ---> 7941
6059 ---> 7942
6060 ---> 7943
6061 ---> 7944
6063 ---> 7945
6066 ---> 7946
6067 ---> 7947
6068 ---> 7948
6070 ---> 7949
6071 ---> 7950
6072 ---> 7951
6073 ---> 7952
6074 ---> 7953
6075 ---> 7954
6076 ---> 7955
6077 ---> 7956
6078 ---> 7957
6079 ---> 7958
6082 ---> 7959
6086 ---> 7960
6087 ---> 7961
6088 ---> 7962
6089 ---> 7963
6091 ---> 7964
6092 ---> 7965
6093 ---> 7966
6096 ---> 7967
6099 ---> 7968
6100 ---> 7969
6101 ---> 7970
6103 ---> 7971
6104 ---> 7972
6105 ---> 7973
6106 ---> 7974
6107 ---> 7975
6108 ---> 7976
6109 ---> 7977
6110 ---> 7978
6111 ---> 7979
6112 ---> 7980
6113 ---> 7981
6114 ---> 7982
6116 ---> 7983
6117 ---> 7984
6119 ---> 7985
6121 ---> 7986
6122 ---> 7987
6123 ---> 7988
6124 ---> 7989
6125 ---> 7990
6126 ---> 7991
6127 ---> 7992
6129 ---> 7993
6131 ---> 7994
6132 ---> 7995
6133 ---> 7996
6139 ---> 7997
6140 ---> 7998
6141 ---> 7999
6142 ---> 8000
6143 ---> 8001
6144 ---> 8002
6146 ---> 8003
6152 ---> 8004
6153 ---> 8005
6154 ---> 8006
6155 ---> 8007
6156 ---> 8008
6157 ---> 8009
6158 ---> 8010
6169 ---> 8011
6170 ---> 8012
6171 ---> 8013
6172 ---> 8014
6173 ---> 8015
6175 ---> 8016
6176 ---> 8017
6177 ---> 8018
6178 ---> 8019
6179 ---> 8020
6182 ---> 8021
6183 ---> 8022
6184 ---> 8023
6185 ---> 8024
6186 ---> 8025
6187 ---> 8026
6188 ---> 8027
6189 ---> 8028
6190 ---> 8029
6191 ---> 8030
6192 ---> 8031
6193 ---> 8032
6194 ---> 8033
6195 ---> 8034
6196 ---> 8035
6197 ---> 8036
6198 ---> 8037
6199 ---> 8038
6201 ---> 8039
6203 ---> 8040
6204 ---> 8041
6205 ---> 8042
6207 ---> 8043
6210 ---> 8044
6211 ---> 8045
6212 ---> 8046
6213 ---> 8047
6214 ---> 8048
6215 ---> 8049
6216 ---> 8050
6217 ---> 8051
6218 ---> 8052
6219 ---> 8053
6220 ---> 8054
6221 ---> 8055
6222 ---> 8056
6223 ---> 8057
6224 ---> 8058
6225 ---> 8059
6226 ---> 8060
6227 ---> 8061
6228 ---> 8062
6229 ---> 8063
6236 ---> 8064
6237 ---> 8065
6239 ---> 8066
6240 ---> 8067
6241 ---> 8068
6243 ---> 8069
6244 ---> 8070
6245 ---> 8071
6247 ---> 8072
6248 ---> 8073
6249 ---> 8074
6250 ---> 8075
6251 ---> 8076
6253 ---> 8077
6255 ---> 8078
6257 ---> 8079
6258 ---> 8080
6259 ---> 8081
6260 ---> 8082
6261 ---> 8083
6262 ---> 8084
6264 ---> 8085
6267 ---> 8086
6269 ---> 8087
6272 ---> 8088
6273 ---> 8089
6274 ---> 8090
6277 ---> 8091
6278 ---> 8092
6279 ---> 8093
6280 ---> 8094
6281 ---> 8095
6282 ---> 8096
6286 ---> 8097
6291 ---> 8098
6293 ---> 8099
6294 ---> 8100
6295 ---> 8101
6296 ---> 8102
6298 ---> 8103
6299 ---> 8104
6301 ---> 8105
6305 ---> 8106
6306 ---> 8107
6307 ---> 8108
6312 ---> 8109
6314 ---> 8110
6316 ---> 8111
6317 ---> 8112
6318 ---> 8113
6321 ---> 8114
6322 ---> 8115
6325 ---> 8116
6326 ---> 8117
6327 ---> 8118
6328 ---> 8119
6329 ---> 8120
6330 ---> 8121
6331 ---> 8122
6332 ---> 8123
6333 ---> 8124
6334 ---> 8125
6335 ---> 8126
6336 ---> 8127
6337 ---> 8128
6338 ---> 8129
6339 ---> 8130
6340 ---> 8131
6344 ---> 8132
6345 ---> 8133
6346 ---> 8134
6348 ---> 8135
6349 ---> 8136
6350 ---> 8137
6352 ---> 8138
6355 ---> 8139
6357 ---> 8140
6359 ---> 8141
6360 ---> 8142
6363 ---> 8143
6364 ---> 8144
6365 ---> 8145
6369 ---> 8146
6370 ---> 8147
6371 ---> 8148
6372 ---> 8149
6373 ---> 8150
6374 ---> 8151
6375 ---> 8152
6376 ---> 8153
6381 ---> 8154
6385 ---> 8155
6389 ---> 8156
6390 ---> 8157
6391 ---> 8158
6392 ---> 8159
6393 ---> 8160
6394 ---> 8161
6395 ---> 8162
6397 ---> 8163
6398 ---> 8164
6400 ---> 8165
6404 ---> 8166
6406 ---> 8167
6412 ---> 8168
6413 ---> 8169
6414 ---> 8170
6416 ---> 8171
6419 ---> 8172
6425 ---> 8173
6428 ---> 8174
6429 ---> 8175
6433 ---> 8176
6437 ---> 8177
6438 ---> 8178
6439 ---> 8179
6440 ---> 8180
6445 ---> 8181
6447 ---> 8182
6448 ---> 8183
6449 ---> 8184
6458 ---> 8185
6459 ---> 8186
6465 ---> 8187
6466 ---> 8188
6472 ---> 8189
6473 ---> 8190
6476 ---> 8191
6477 ---> 8192
6478 ---> 8193
6484 ---> 8194
6485 ---> 8195
6488 ---> 8196
6489 ---> 8197
6490 ---> 8198
6491 ---> 8199
6492 ---> 8200
6494 ---> 8201
6495 ---> 8202
6496 ---> 8203
6497 ---> 8204
6498 ---> 8205
6499 ---> 8206
6503 ---> 8207
6505 ---> 8208
6507 ---> 8209
6510 ---> 8210
6513 ---> 8211
6514 ---> 8212
6516 ---> 8213
6517 ---> 8214
6523 ---> 8215
6524 ---> 8216
6528 ---> 8217
6533 ---> 8218
6534 ---> 8219
6535 ---> 8220
6536 ---> 8221
6537 ---> 8222
6538 ---> 8223
6540 ---> 8224
6541 ---> 8225
6542 ---> 8226
6543 ---> 8227
6544 ---> 8228
6545 ---> 8229
6549 ---> 8230
6550 ---> 8231
6551 ---> 8232
6553 ---> 8233
6554 ---> 8234
6555 ---> 8235
6556 ---> 8236
6557 ---> 8237
6558 ---> 8238
6561 ---> 8239
6562 ---> 8240
6564 ---> 8241
6566 ---> 8242
6569 ---> 8243
6571 ---> 8244
6572 ---> 8245
6574 ---> 8246
6576 ---> 8247
6579 ---> 8248
6581 ---> 8249
6583 ---> 8250
6585 ---> 8251
6587 ---> 8252
6588 ---> 8253
6589 ---> 8254
6590 ---> 8255
6591 ---> 8256
6592 ---> 8257
6593 ---> 8258
6595 ---> 8259
6597 ---> 8260
6598 ---> 8261
6601 ---> 8262
6605 ---> 8263
6606 ---> 8264
6607 ---> 8265
6608 ---> 8266
6609 ---> 8267
6610 ---> 8268
6611 ---> 8269
6612 ---> 8270
6614 ---> 8271
6615 ---> 8272
6616 ---> 8273
6617 ---> 8274
6618 ---> 8275
6619 ---> 8276
6625 ---> 8277
6628 ---> 8278
6636 ---> 8279
6637 ---> 8280
6643 ---> 8281
6648 ---> 8282
6649 ---> 8283
6653 ---> 8284
6654 ---> 8285
6657 ---> 8286
6658 ---> 8287
6659 ---> 8288
6661 ---> 8289
6662 ---> 8290
6666 ---> 8291
6668 ---> 8292
6671 ---> 8293
6672 ---> 8294
6673 ---> 8295
6674 ---> 8296
6675 ---> 8297
6679 ---> 8298
6680 ---> 8299
6682 ---> 8300
6683 ---> 8301
6687 ---> 8302
6688 ---> 8303
6692 ---> 8304
6695 ---> 8305
6696 ---> 8306
6697 ---> 8307
6699 ---> 8308
6700 ---> 8309
6702 ---> 8310
6703 ---> 8311
6705 ---> 8312
6707 ---> 8313
6709 ---> 8314
6710 ---> 8315
6711 ---> 8316
6712 ---> 8317
6716 ---> 8318
6718 ---> 8319
6723 ---> 8320
6724 ---> 8321
6725 ---> 8322
6726 ---> 8323
6727 ---> 8324
6730 ---> 8325
6732 ---> 8326
6734 ---> 8327
6737 ---> 8328
6738 ---> 8329
6739 ---> 8330
6746 ---> 8331
6747 ---> 8332
6748 ---> 8333
6749 ---> 8334
6750 ---> 8335
6751 ---> 8336
6758 ---> 8337
6760 ---> 8338
6761 ---> 8339
6763 ---> 8340
6767 ---> 8341
6768 ---> 8342
6770 ---> 8343
6772 ---> 8344
6773 ---> 8345
6776 ---> 8346
6778 ---> 8347
6782 ---> 8348
6783 ---> 8349
6784 ---> 8350
6793 ---> 8351
6795 ---> 8352
6796 ---> 8353
6798 ---> 8354
6803 ---> 8355
6805 ---> 8356
6806 ---> 8357
6809 ---> 8358
6811 ---> 8359
6812 ---> 8360
6813 ---> 8361
6814 ---> 8362
6815 ---> 8363
6817 ---> 8364
6821 ---> 8365
6826 ---> 8366
6827 ---> 8367
6828 ---> 8368
6829 ---> 8369
6831 ---> 8370
6835 ---> 8371
6836 ---> 8372
6837 ---> 8373
6838 ---> 8374
6840 ---> 8375
6841 ---> 8376
6842 ---> 8377
6843 ---> 8378
6848 ---> 8379
6849 ---> 8380
6850 ---> 8381
6851 ---> 8382
6852 ---> 8383
6854 ---> 8384
6855 ---> 8385
6856 ---> 8386
6858 ---> 8387
6862 ---> 8388
6863 ---> 8389
6866 ---> 8390
6868 ---> 8391
6871 ---> 8392
6875 ---> 8393
6877 ---> 8394
6878 ---> 8395
6883 ---> 8396
6887 ---> 8397
6891 ---> 8398
6894 ---> 8399
6895 ---> 8400
6896 ---> 8401
6897 ---> 8402
6898 ---> 8403
6899 ---> 8404
6904 ---> 8405
6907 ---> 8406
6909 ---> 8407
6910 ---> 8408
6911 ---> 8409
6912 ---> 8410
6915 ---> 8411
6916 ---> 8412
6919 ---> 8413
6921 ---> 8414
6922 ---> 8415
6923 ---> 8416
6926 ---> 8417
6927 ---> 8418
6928 ---> 8419
6929 ---> 8420
6934 ---> 8421
6936 ---> 8422
6947 ---> 8423
6950 ---> 8424
6951 ---> 8425
6952 ---> 8426
6953 ---> 8427
6956 ---> 8428
6958 ---> 8429
6960 ---> 8430
6965 ---> 8431
6966 ---> 8432
6970 ---> 8433
6971 ---> 8434
6976 ---> 8435
6978 ---> 8436
6984 ---> 8437
6989 ---> 8438
6995 ---> 8439
6996 ---> 8440
6998 ---> 8441
7000 ---> 8442
7002 ---> 8443
7003 ---> 8444
7004 ---> 8445
7007 ---> 8446
7009 ---> 8447
7010 ---> 8448
7013 ---> 8449
7015 ---> 8450
7016 ---> 8451
7020 ---> 8452
7022 ---> 8453
7023 ---> 8454
7026 ---> 8455
7027 ---> 8456
7030 ---> 8457
7034 ---> 8458
7035 ---> 8459
7037 ---> 8460
7043 ---> 8461
7051 ---> 8462
7054 ---> 8463
7058 ---> 8464
7062 ---> 8465
7065 ---> 8466
7070 ---> 8467
7072 ---> 8468
7075 ---> 8469
7078 ---> 8470
7079 ---> 8471
7082 ---> 8472
7083 ---> 8473
7084 ---> 8474
7089 ---> 8475
7091 ---> 8476
7092 ---> 8477
7102 ---> 8478
7105 ---> 8479
7113 ---> 8480
7114 ---> 8481
7115 ---> 8482
7119 ---> 8483
7120 ---> 8484
7122 ---> 8485
7123 ---> 8486
7125 ---> 8487
7132 ---> 8488
7133 ---> 8489
7134 ---> 8490
7141 ---> 8491
7142 ---> 8492
7145 ---> 8493
7146 ---> 8494
7147 ---> 8495
7151 ---> 8496
7152 ---> 8497
7154 ---> 8498
7156 ---> 8499
7157 ---> 8500
7158 ---> 8501
7169 ---> 8502
7171 ---> 8503
7181 ---> 8504
7184 ---> 8505
7189 ---> 8506
7194 ---> 8507
7195 ---> 8508
7197 ---> 8509
7198 ---> 8510
7199 ---> 8511
7200 ---> 8512
7202 ---> 8513
7203 ---> 8514
7220 ---> 8515
7222 ---> 8516
7226 ---> 8517
7227 ---> 8518
7228 ---> 8519
7229 ---> 8520
7233 ---> 8521
7234 ---> 8522
7235 ---> 8523
7236 ---> 8524
7239 ---> 8525
7240 ---> 8526
7241 ---> 8527
7246 ---> 8528
7247 ---> 8529
7248 ---> 8530
7249 ---> 8531
7251 ---> 8532
7255 ---> 8533
7256 ---> 8534
7257 ---> 8535
7267 ---> 8536
7268 ---> 8537
7272 ---> 8538
7273 ---> 8539
7280 ---> 8540
7282 ---> 8541
7283 ---> 8542
7289 ---> 8543
7290 ---> 8544
7291 ---> 8545
7294 ---> 8546
7301 ---> 8547
7307 ---> 8548
7309 ---> 8549
7310 ---> 8550
7312 ---> 8551
7316 ---> 8552
7318 ---> 8553
7319 ---> 8554
7324 ---> 8555
7326 ---> 8556
7327 ---> 8557
7328 ---> 8558
7331 ---> 8559
7335 ---> 8560
7337 ---> 8561
7338 ---> 8562
7339 ---> 8563
7343 ---> 8564
7345 ---> 8565
7346 ---> 8566
7348 ---> 8567
7349 ---> 8568
7350 ---> 8569
7351 ---> 8570
7354 ---> 8571
7356 ---> 8572
7358 ---> 8573
7360 ---> 8574
7361 ---> 8575
7362 ---> 8576
7363 ---> 8577
7364 ---> 8578
7366 ---> 8579
7367 ---> 8580
7368 ---> 8581
7373 ---> 8582
7375 ---> 8583
7376 ---> 8584
7378 ---> 8585
7381 ---> 8586
7388 ---> 8587
7391 ---> 8588
7392 ---> 8589
7393 ---> 8590
7395 ---> 8591
7396 ---> 8592
7397 ---> 8593
7400 ---> 8594
7401 ---> 8595
7402 ---> 8596
7404 ---> 8597
7405 ---> 8598
7407 ---> 8599
7408 ---> 8600
7411 ---> 8601
7412 ---> 8602
7414 ---> 8603
7415 ---> 8604
7416 ---> 8605
7420 ---> 8606
7421 ---> 8607
7422 ---> 8608
7425 ---> 8609
7426 ---> 8610
7427 ---> 8611
7431 ---> 8612
7432 ---> 8613
7433 ---> 8614
7434 ---> 8615
7435 ---> 8616
7438 ---> 8617
7442 ---> 8618
7443 ---> 8619
7447 ---> 8620
7452 ---> 8621
7453 ---> 8622
7454 ---> 8623
7462 ---> 8624
7463 ---> 8625
7466 ---> 8626
7468 ---> 8627
7472 ---> 8628
7473 ---> 8629
7475 ---> 8630
7476 ---> 8631
7481 ---> 8632
7482 ---> 8633
7483 ---> 8634
7486 ---> 8635
7487 ---> 8636
7491 ---> 8637
7492 ---> 8638
7493 ---> 8639
7494 ---> 8640
7495 ---> 8641
7496 ---> 8642
7497 ---> 8643
7498 ---> 8644
7500 ---> 8645
7501 ---> 8646
7502 ---> 8647
7504 ---> 8648
7505 ---> 8649
7507 ---> 8650
7508 ---> 8651
7510 ---> 8652
7511 ---> 8653
7519 ---> 8654
7520 ---> 8655
7521 ---> 8656
7523 ---> 8657
7524 ---> 8658
7525 ---> 8659
7526 ---> 8660
7531 ---> 8661
7532 ---> 8662
7533 ---> 8663
7534 ---> 8664
7535 ---> 8665
7537 ---> 8666
7538 ---> 8667
7539 ---> 8668
7541 ---> 8669
7543 ---> 8670
7550 ---> 8671
7551 ---> 8672
7555 ---> 8673
7556 ---> 8674
7558 ---> 8675
7563 ---> 8676
7566 ---> 8677
7569 ---> 8678
7570 ---> 8679
7574 ---> 8680
7580 ---> 8681
7581 ---> 8682
7582 ---> 8683
7583 ---> 8684
7584 ---> 8685
7585 ---> 8686
7587 ---> 8687
7588 ---> 8688
7589 ---> 8689
7590 ---> 8690
7592 ---> 8691
7596 ---> 8692
7597 ---> 8693
7599 ---> 8694
7600 ---> 8695
7609 ---> 8696
7610 ---> 8697
7612 ---> 8698
7614 ---> 8699
7617 ---> 8700
7618 ---> 8701
7622 ---> 8702
7623 ---> 8703
7625 ---> 8704
7626 ---> 8705
7627 ---> 8706
7628 ---> 8707
7629 ---> 8708
7630 ---> 8709
7631 ---> 8710
7633 ---> 8711
7634 ---> 8712
7635 ---> 8713
7638 ---> 8714
7640 ---> 8715
7641 ---> 8716
7642 ---> 8717
7643 ---> 8718
7644 ---> 8719
7648 ---> 8720
7649 ---> 8721
7650 ---> 8722
7654 ---> 8723
7656 ---> 8724
7657 ---> 8725
7661 ---> 8726
7667 ---> 8727
7669 ---> 8728
7670 ---> 8729
7671 ---> 8730
7672 ---> 8731
7673 ---> 8732
7675 ---> 8733
7677 ---> 8734
7678 ---> 8735
7680 ---> 8736
7681 ---> 8737
7682 ---> 8738
7683 ---> 8739
7686 ---> 8740
7687 ---> 8741
7689 ---> 8742
7690 ---> 8743
7691 ---> 8744
7692 ---> 8745
7695 ---> 8746
7696 ---> 8747
7698 ---> 8748
7699 ---> 8749
7700 ---> 8750
7701 ---> 8751
7704 ---> 8752
7706 ---> 8753
7707 ---> 8754
7714 ---> 8755
7715 ---> 8756
7722 ---> 8757
7724 ---> 8758
7726 ---> 8759
7727 ---> 8760
7736 ---> 8761
7737 ---> 8762
7739 ---> 8763
7740 ---> 8764
7741 ---> 8765
7742 ---> 8766
7744 ---> 8767
7749 ---> 8768
7750 ---> 8769
7752 ---> 8770
7758 ---> 8771
7759 ---> 8772
7760 ---> 8773
7761 ---> 8774
7763 ---> 8775
7764 ---> 8776
7765 ---> 8777
7769 ---> 8778
7770 ---> 8779
7774 ---> 8780
7776 ---> 8781
7777 ---> 8782
7778 ---> 8783
7779 ---> 8784
7781 ---> 8785
7782 ---> 8786
7783 ---> 8787
7784 ---> 8788
7786 ---> 8789
7787 ---> 8790
7788 ---> 8791
7791 ---> 8792
7793 ---> 8793
7798 ---> 8794
7808 ---> 8795
7812 ---> 8796
7822 ---> 8797
7825 ---> 8798
7836 ---> 8799
7838 ---> 8800
7839 ---> 8801
7840 ---> 8802
7841 ---> 8803
7851 ---> 8804
7853 ---> 8805
7861 ---> 8806
7863 ---> 8807
7867 ---> 8808
7869 ---> 8809
7870 ---> 8810
7871 ---> 8811
7873 ---> 8812
7874 ---> 8813
7875 ---> 8814
7878 ---> 8815
7879 ---> 8816
7881 ---> 8817
7882 ---> 8818
7885 ---> 8819
7886 ---> 8820
7888 ---> 8821
7889 ---> 8822
7892 ---> 8823
7895 ---> 8824
7898 ---> 8825
7901 ---> 8826
7904 ---> 8827
7905 ---> 8828
7907 ---> 8829
7908 ---> 8830
7909 ---> 8831
7912 ---> 8832
7913 ---> 8833
7916 ---> 8834
7918 ---> 8835
7921 ---> 8836
7922 ---> 8837
7923 ---> 8838
7926 ---> 8839
7927 ---> 8840
7928 ---> 8841
7932 ---> 8842
7934 ---> 8843
7936 ---> 8844
7937 ---> 8845
7941 ---> 8846
7942 ---> 8847
7945 ---> 8848
7946 ---> 8849
7947 ---> 8850
7948 ---> 8851
7950 ---> 8852
7956 ---> 8853
7957 ---> 8854
7959 ---> 8855
7961 ---> 8856
7965 ---> 8857
7969 ---> 8858
7975 ---> 8859
7988 ---> 8860
7989 ---> 8861
7990 ---> 8862
7993 ---> 8863
7995 ---> 8864
7996 ---> 8865
7999 ---> 8866
8000 ---> 8867
8003 ---> 8868
8004 ---> 8869
8007 ---> 8870
8008 ---> 8871
8012 ---> 8872
8013 ---> 8873
8014 ---> 8874
8015 ---> 8875
8027 ---> 8876
8028 ---> 8877
8036 ---> 8878
8039 ---> 8879
8041 ---> 8880
8042 ---> 8881
8043 ---> 8882
8047 ---> 8883
8048 ---> 8884
8049 ---> 8885
8050 ---> 8886
8053 ---> 8887
8060 ---> 8888
8062 ---> 8889
8063 ---> 8890
8064 ---> 8891
8065 ---> 8892
8066 ---> 8893
8067 ---> 8894
8072 ---> 8895
8073 ---> 8896
8078 ---> 8897
8084 ---> 8898
8087 ---> 8899
8092 ---> 8900
8099 ---> 8901
8101 ---> 8902
8103 ---> 8903
8105 ---> 8904
8106 ---> 8905
8114 ---> 8906
8116 ---> 8907
8117 ---> 8908
8118 ---> 8909
8126 ---> 8910
8130 ---> 8911
8133 ---> 8912
8138 ---> 8913
8139 ---> 8914
8147 ---> 8915
8148 ---> 8916
8149 ---> 8917
8153 ---> 8918
8155 ---> 8919
8159 ---> 8920
8160 ---> 8921
8162 ---> 8922
8174 ---> 8923
8175 ---> 8924
8177 ---> 8925
8178 ---> 8926
8179 ---> 8927
8183 ---> 8928
8184 ---> 8929
8185 ---> 8930
8187 ---> 8931
8193 ---> 8932
8197 ---> 8933
8202 ---> 8934
8203 ---> 8935
8208 ---> 8936
8209 ---> 8937
8218 ---> 8938
8219 ---> 8939
8226 ---> 8940
8228 ---> 8941
8232 ---> 8942
8233 ---> 8943
8234 ---> 8944
8237 ---> 8945
8238 ---> 8946
8245 ---> 8947
8246 ---> 8948
8247 ---> 8949
8250 ---> 8950
8252 ---> 8951
8256 ---> 8952
8257 ---> 8953
8258 ---> 8954
8263 ---> 8955
8264 ---> 8956
8267 ---> 8957
8270 ---> 8958
8271 ---> 8959
8273 ---> 8960
8274 ---> 8961
8275 ---> 8962
8278 ---> 8963
8279 ---> 8964
8280 ---> 8965
8282 ---> 8966
8288 ---> 8967
8290 ---> 8968
8291 ---> 8969
8295 ---> 8970
8296 ---> 8971
8298 ---> 8972
8299 ---> 8973
8301 ---> 8974
8302 ---> 8975
8304 ---> 8976
8305 ---> 8977
8306 ---> 8978
8307 ---> 8979
8309 ---> 8980
8311 ---> 8981
8316 ---> 8982
8317 ---> 8983
8321 ---> 8984
8322 ---> 8985
8331 ---> 8986
8332 ---> 8987
8334 ---> 8988
8337 ---> 8989
8338 ---> 8990
8340 ---> 8991
8342 ---> 8992
8344 ---> 8993
8358 ---> 8994
8363 ---> 8995
8365 ---> 8996
8366 ---> 8997
8367 ---> 8998
8368 ---> 8999
8369 ---> 9000
8370 ---> 9001
8374 ---> 9002
8375 ---> 9003
8378 ---> 9004
8381 ---> 9005
8386 ---> 9006
8393 ---> 9007
8394 ---> 9008
8395 ---> 9009
8398 ---> 9010
8399 ---> 9011
8405 ---> 9012
8411 ---> 9013
8418 ---> 9014
8421 ---> 9015
8424 ---> 9016
8436 ---> 9017
8438 ---> 9018
8440 ---> 9019
8442 ---> 9020
8445 ---> 9021
8450 ---> 9022
8451 ---> 9023
8456 ---> 9024
8457 ---> 9025
8459 ---> 9026
8462 ---> 9027
8465 ---> 9028
8466 ---> 9029
8467 ---> 9030
8471 ---> 9031
8474 ---> 9032
8477 ---> 9033
8478 ---> 9034
8479 ---> 9035
8483 ---> 9036
8485 ---> 9037
8487 ---> 9038
8490 ---> 9039
8492 ---> 9040
8493 ---> 9041
8496 ---> 9042
8500 ---> 9043
8503 ---> 9044
8511 ---> 9045
8521 ---> 9046
8522 ---> 9047
8523 ---> 9048
8525 ---> 9049
8528 ---> 9050
8529 ---> 9051
8530 ---> 9052
8531 ---> 9053
8532 ---> 9054
8533 ---> 9055
8535 ---> 9056
8540 ---> 9057
8546 ---> 9058
8547 ---> 9059
8548 ---> 9060
8549 ---> 9061
8550 ---> 9062
8551 ---> 9063
8555 ---> 9064
8558 ---> 9065
8559 ---> 9066
8561 ---> 9067
8562 ---> 9068
8563 ---> 9069
8564 ---> 9070
8567 ---> 9071
8569 ---> 9072
8573 ---> 9073
8576 ---> 9074
8577 ---> 9075
8581 ---> 9076
8586 ---> 9077
8590 ---> 9078
8593 ---> 9079
8596 ---> 9080
8599 ---> 9081
8603 ---> 9082
8604 ---> 9083
8605 ---> 9084
8610 ---> 9085
8613 ---> 9086
8617 ---> 9087
8618 ---> 9088
8621 ---> 9089
8622 ---> 9090
8629 ---> 9091
8633 ---> 9092
8636 ---> 9093
8639 ---> 9094
8640 ---> 9095
8644 ---> 9096
8645 ---> 9097
8649 ---> 9098
8650 ---> 9099
8651 ---> 9100
8652 ---> 9101
8655 ---> 9102
8656 ---> 9103
8666 ---> 9104
8667 ---> 9105
8668 ---> 9106
8669 ---> 9107
8671 ---> 9108
8672 ---> 9109
8673 ---> 9110
8676 ---> 9111
8678 ---> 9112
8679 ---> 9113
8680 ---> 9114
8681 ---> 9115
8682 ---> 9116
8683 ---> 9117
8685 ---> 9118
8690 ---> 9119
8694 ---> 9120
8697 ---> 9121
8698 ---> 9122
8699 ---> 9123
8705 ---> 9124
8707 ---> 9125
8709 ---> 9126
8711 ---> 9127
8714 ---> 9128
8717 ---> 9129
8718 ---> 9130
8719 ---> 9131
8720 ---> 9132
8721 ---> 9133
8722 ---> 9134
8723 ---> 9135
8724 ---> 9136
8725 ---> 9137
8726 ---> 9138
8727 ---> 9139
8728 ---> 9140
8733 ---> 9141
8735 ---> 9142
8737 ---> 9143
8738 ---> 9144
8740 ---> 9145
8741 ---> 9146
8743 ---> 9147
8744 ---> 9148
8745 ---> 9149
8746 ---> 9150
8747 ---> 9151
8749 ---> 9152
8752 ---> 9153
8754 ---> 9154
8757 ---> 9155
8758 ---> 9156
8760 ---> 9157
8762 ---> 9158
8764 ---> 9159
8765 ---> 9160
8766 ---> 9161
8767 ---> 9162
8769 ---> 9163
8773 ---> 9164
8774 ---> 9165
8775 ---> 9166
8776 ---> 9167
8778 ---> 9168
8779 ---> 9169
8790 ---> 9170
8792 ---> 9171
8793 ---> 9172
8798 ---> 9173
8800 ---> 9174
8801 ---> 9175
8802 ---> 9176
8803 ---> 9177
8804 ---> 9178
8805 ---> 9179
8806 ---> 9180
8812 ---> 9181
8814 ---> 9182
8815 ---> 9183
8816 ---> 9184
8817 ---> 9185
8818 ---> 9186
8819 ---> 9187
8820 ---> 9188
8823 ---> 9189
8825 ---> 9190
8826 ---> 9191
8829 ---> 9192
8832 ---> 9193
8834 ---> 9194
8835 ---> 9195
8836 ---> 9196
8837 ---> 9197
8838 ---> 9198
8839 ---> 9199
8840 ---> 9200
8841 ---> 9201
8842 ---> 9202
8846 ---> 9203
8847 ---> 9204
8848 ---> 9205
8849 ---> 9206
8851 ---> 9207
8857 ---> 9208
8861 ---> 9209
8867 ---> 9210
8868 ---> 9211
8869 ---> 9212
8870 ---> 9213
8871 ---> 9214
8872 ---> 9215
8873 ---> 9216
8874 ---> 9217
8879 ---> 9218
8883 ---> 9219
8890 ---> 9220
8891 ---> 9221
8892 ---> 9222
8898 ---> 9223
8900 ---> 9224
8903 ---> 9225
8909 ---> 9226
8911 ---> 9227
8917 ---> 9228
8918 ---> 9229
8920 ---> 9230
8921 ---> 9231
8923 ---> 9232
8924 ---> 9233
8927 ---> 9234
8928 ---> 9235
8929 ---> 9236
8930 ---> 9237
8931 ---> 9238
8934 ---> 9239
8935 ---> 9240
8936 ---> 9241
8939 ---> 9242
8956 ---> 9243
8958 ---> 9244
8959 ---> 9245
8963 ---> 9246
8964 ---> 9247
8968 ---> 9248
8972 ---> 9249
8973 ---> 9250
8981 ---> 9251
8983 ---> 9252
8986 ---> 9253
8989 ---> 9254
8998 ---> 9255
8999 ---> 9256
9003 ---> 9257
9004 ---> 9258
9007 ---> 9259
9008 ---> 9260
9017 ---> 9261
9022 ---> 9262
9023 ---> 9263
9027 ---> 9264
9035 ---> 9265
9036 ---> 9266
9037 ---> 9267
9038 ---> 9268
9039 ---> 9269
9041 ---> 9270
9042 ---> 9271
9043 ---> 9272
9046 ---> 9273
9048 ---> 9274
9050 ---> 9275
9051 ---> 9276
9052 ---> 9277
9056 ---> 9278
9060 ---> 9279
9061 ---> 9280
9062 ---> 9281
9064 ---> 9282
9066 ---> 9283
9068 ---> 9284
9072 ---> 9285
9073 ---> 9286
9075 ---> 9287
9082 ---> 9288
9083 ---> 9289
9084 ---> 9290
9085 ---> 9291
9087 ---> 9292
9091 ---> 9293
9092 ---> 9294
9095 ---> 9295
9098 ---> 9296
9103 ---> 9297
9105 ---> 9298
9109 ---> 9299
9110 ---> 9300
9111 ---> 9301
9112 ---> 9302
9113 ---> 9303
9114 ---> 9304
9118 ---> 9305
9119 ---> 9306
9120 ---> 9307
9121 ---> 9308
9124 ---> 9309
9126 ---> 9310
9127 ---> 9311
9128 ---> 9312
9129 ---> 9313
9131 ---> 9314
9132 ---> 9315
9135 ---> 9316
9136 ---> 9317
9138 ---> 9318
9140 ---> 9319
9142 ---> 9320
9143 ---> 9321
9144 ---> 9322
9145 ---> 9323
9149 ---> 9324
9152 ---> 9325
9156 ---> 9326
9157 ---> 9327
9158 ---> 9328
9162 ---> 9329
9165 ---> 9330
9168 ---> 9331
9169 ---> 9332
9170 ---> 9333
9172 ---> 9334
9173 ---> 9335
9176 ---> 9336
9179 ---> 9337
9181 ---> 9338
9183 ---> 9339
9184 ---> 9340
9185 ---> 9341
9186 ---> 9342
9189 ---> 9343
9194 ---> 9344
9195 ---> 9345
9196 ---> 9346
9197 ---> 9347
9200 ---> 9348
9203 ---> 9349
9205 ---> 9350
9206 ---> 9351
9207 ---> 9352
9208 ---> 9353
9209 ---> 9354
9210 ---> 9355
9212 ---> 9356
9215 ---> 9357
9216 ---> 9358
9217 ---> 9359
9218 ---> 9360
9219 ---> 9361
9220 ---> 9362
9221 ---> 9363
9222 ---> 9364
9223 ---> 9365
9224 ---> 9366
9229 ---> 9367
9230 ---> 9368
9231 ---> 9369
9233 ---> 9370
9234 ---> 9371
9235 ---> 9372
9236 ---> 9373
9237 ---> 9374
9238 ---> 9375
9239 ---> 9376
9240 ---> 9377
9241 ---> 9378
9243 ---> 9379
9244 ---> 9380
9245 ---> 9381
9246 ---> 9382
9247 ---> 9383
9248 ---> 9384
9249 ---> 9385
9250 ---> 9386
9253 ---> 9387
9255 ---> 9388
9256 ---> 9389
9257 ---> 9390
9260 ---> 9391
9263 ---> 9392
9268 ---> 9393
9269 ---> 9394
9270 ---> 9395
9271 ---> 9396
9272 ---> 9397
9273 ---> 9398
9274 ---> 9399
9277 ---> 9400
9281 ---> 9401
9282 ---> 9402
9286 ---> 9403
9288 ---> 9404
9289 ---> 9405
9291 ---> 9406
9293 ---> 9407
9295 ---> 9408
9301 ---> 9409
9303 ---> 9410
9304 ---> 9411
9310 ---> 9412
9314 ---> 9413
9319 ---> 9414
9321 ---> 9415
9326 ---> 9416
9328 ---> 9417
9334 ---> 9418
9336 ---> 9419
9337 ---> 9420
9340 ---> 9421
9341 ---> 9422
9342 ---> 9423
9343 ---> 9424
9349 ---> 9425
9351 ---> 9426
9353 ---> 9427
9356 ---> 9428
9357 ---> 9429
9358 ---> 9430
9359 ---> 9431
9361 ---> 9432
9367 ---> 9433
9368 ---> 9434
9369 ---> 9435
9370 ---> 9436
9372 ---> 9437
9375 ---> 9438
9376 ---> 9439
9377 ---> 9440
9378 ---> 9441
9379 ---> 9442
9383 ---> 9443
9385 ---> 9444
9387 ---> 9445
9388 ---> 9446
9389 ---> 9447
9390 ---> 9448
9391 ---> 9449
9395 ---> 9450
9396 ---> 9451
9397 ---> 9452
9400 ---> 9453
9401 ---> 9454
9403 ---> 9455
9404 ---> 9456
9405 ---> 9457
9407 ---> 9458
9408 ---> 9459
9409 ---> 9460
9410 ---> 9461
9411 ---> 9462
9412 ---> 9463
9413 ---> 9464
9414 ---> 9465
9419 ---> 9466
9420 ---> 9467
9426 ---> 9468
9428 ---> 9469
9429 ---> 9470
9431 ---> 9471
9432 ---> 9472
9433 ---> 9473
9434 ---> 9474
9438 ---> 9475
9439 ---> 9476
9440 ---> 9477
9443 ---> 9478
9445 ---> 9479
9448 ---> 9480
9450 ---> 9481
9452 ---> 9482
9454 ---> 9483
9455 ---> 9484
9456 ---> 9485
9457 ---> 9486
9458 ---> 9487
9459 ---> 9488
9461 ---> 9489
9462 ---> 9490
9463 ---> 9491
9464 ---> 9492
9469 ---> 9493
9471 ---> 9494
9472 ---> 9495
9476 ---> 9496
9477 ---> 9497
9478 ---> 9498
9481 ---> 9499
9482 ---> 9500
9486 ---> 9501
9487 ---> 9502
9488 ---> 9503
9489 ---> 9504
9490 ---> 9505
9493 ---> 9506
9497 ---> 9507
9499 ---> 9508
9500 ---> 9509
9501 ---> 9510
9503 ---> 9511
9506 ---> 9512
9508 ---> 9513
9510 ---> 9514
9511 ---> 9515
9512 ---> 9516
9513 ---> 9517
9514 ---> 9518
9515 ---> 9519
9516 ---> 9520
9518 ---> 9521
9519 ---> 9522
9520 ---> 9523
9526 ---> 9524
9527 ---> 9525
9528 ---> 9526
9531 ---> 9527
9533 ---> 9528
9534 ---> 9529
9537 ---> 9530
9538 ---> 9531
9541 ---> 9532
9542 ---> 9533
9544 ---> 9534
9545 ---> 9535
9548 ---> 9536
9550 ---> 9537
9553 ---> 9538
9557 ---> 9539
9558 ---> 9540
9559 ---> 9541
9560 ---> 9542
9561 ---> 9543
9562 ---> 9544
9563 ---> 9545
9564 ---> 9546
9569 ---> 9547
9573 ---> 9548
9577 ---> 9549
9578 ---> 9550
9579 ---> 9551
9581 ---> 9552
9583 ---> 9553
9585 ---> 9554
9586 ---> 9555
9587 ---> 9556
9591 ---> 9557
9593 ---> 9558
9594 ---> 9559
9600 ---> 9560
9601 ---> 9561
9602 ---> 9562
9603 ---> 9563
9605 ---> 9564
9607 ---> 9565
9610 ---> 9566
9613 ---> 9567
9614 ---> 9568
9615 ---> 9569
9616 ---> 9570
9618 ---> 9571
9619 ---> 9572
9620 ---> 9573
9623 ---> 9574
9624 ---> 9575
9628 ---> 9576
9629 ---> 9577
9637 ---> 9578
9638 ---> 9579
9640 ---> 9580
9642 ---> 9581
9643 ---> 9582
9644 ---> 9583
9646 ---> 9584
9648 ---> 9585
9649 ---> 9586
9650 ---> 9587
9651 ---> 9588
9652 ---> 9589
9655 ---> 9590
9656 ---> 9591
9657 ---> 9592
9658 ---> 9593
9659 ---> 9594
9660 ---> 9595
9661 ---> 9596
9664 ---> 9597
9665 ---> 9598
9667 ---> 9599
9668 ---> 9600
9669 ---> 9601
9670 ---> 9602
9671 ---> 9603
9672 ---> 9604
9680 ---> 9605
9687 ---> 9606
9688 ---> 9607
9690 ---> 9608
9691 ---> 9609
9701 ---> 9610
9705 ---> 9611
9706 ---> 9612
9713 ---> 9613
9717 ---> 9614
9718 ---> 9615
9721 ---> 9616
9722 ---> 9617
9729 ---> 9618
9730 ---> 9619
9735 ---> 9620
9736 ---> 9621
9737 ---> 9622
9738 ---> 9623
9740 ---> 9624
9741 ---> 9625
9742 ---> 9626
9745 ---> 9627
9746 ---> 9628
9747 ---> 9629
9748 ---> 9630
9752 ---> 9631
9759 ---> 9632
9760 ---> 9633
9765 ---> 9634
9773 ---> 9635
9776 ---> 9636
9777 ---> 9637
9778 ---> 9638
9779 ---> 9639
9782 ---> 9640
9786 ---> 9641
9790 ---> 9642
9794 ---> 9643
9801 ---> 9644
9802 ---> 9645
9803 ---> 9646
9804 ---> 9647
9806 ---> 9648
9807 ---> 9649
9809 ---> 9650
9811 ---> 9651
9813 ---> 9652
9816 ---> 9653
9817 ---> 9654
9818 ---> 9655
9823 ---> 9656
9824 ---> 9657
9825 ---> 9658
9826 ---> 9659
9827 ---> 9660
9828 ---> 9661
9832 ---> 9662
9833 ---> 9663
9834 ---> 9664
9839 ---> 9665
9841 ---> 9666
9842 ---> 9667
9843 ---> 9668
9850 ---> 9669
9851 ---> 9670
9852 ---> 9671
9853 ---> 9672
9855 ---> 9673
9856 ---> 9674
9859 ---> 9675
9860 ---> 9676
9861 ---> 9677
9864 ---> 9678
9865 ---> 9679
9866 ---> 9680
9867 ---> 9681
9869 ---> 9682
9870 ---> 9683
9874 ---> 9684
9876 ---> 9685
9878 ---> 9686
9879 ---> 9687
9885 ---> 9688
9886 ---> 9689
9890 ---> 9690
9891 ---> 9691
9893 ---> 9692
9894 ---> 9693
9895 ---> 9694
9896 ---> 9695
9897 ---> 9696
9898 ---> 9697
9905 ---> 9698
9908 ---> 9699
9910 ---> 9700
9912 ---> 9701
9915 ---> 9702
9916 ---> 9703
9917 ---> 9704
9918 ---> 9705
9919 ---> 9706
9920 ---> 9707
9921 ---> 9708
9922 ---> 9709
9923 ---> 9710
9924 ---> 9711
9932 ---> 9712
9933 ---> 9713
9936 ---> 9714
9938 ---> 9715
9940 ---> 9716
9941 ---> 9717
9944 ---> 9718
9945 ---> 9719
9946 ---> 9720
9949 ---> 9721
9954 ---> 9722
9955 ---> 9723
9963 ---> 9724
9964 ---> 9725
9965 ---> 9726
9966 ---> 9727
9967 ---> 9728
9968 ---> 9729
9970 ---> 9730
9974 ---> 9731
9975 ---> 9732
9977 ---> 9733
9978 ---> 9734
9979 ---> 9735
9985 ---> 9736
9993 ---> 9737
9994 ---> 9738
9999 ---> 9739
10000 ---> 9740
10002 ---> 9741
10004 ---> 9742
10005 ---> 9743
10006 ---> 9744
10007 ---> 9745
10009 ---> 9746
10010 ---> 9747
10011 ---> 9748
10012 ---> 9749
10013 ---> 9750
10014 ---> 9751
10015 ---> 9752
10020 ---> 9753
10022 ---> 9754
10025 ---> 9755
10026 ---> 9756
10032 ---> 9757
10033 ---> 9758
10034 ---> 9759
10035 ---> 9760
10037 ---> 9761
10038 ---> 9762
10040 ---> 9763
10041 ---> 9764
10042 ---> 9765
10043 ---> 9766
10044 ---> 9767
10045 ---> 9768
10046 ---> 9769
10047 ---> 9770
10048 ---> 9771
10050 ---> 9772
10052 ---> 9773
10053 ---> 9774
10055 ---> 9775
10058 ---> 9776
10059 ---> 9777
10060 ---> 9778
10061 ---> 9779
10063 ---> 9780
10065 ---> 9781
10066 ---> 9782
10067 ---> 9783
10069 ---> 9784
10071 ---> 9785
10074 ---> 9786
10077 ---> 9787
10078 ---> 9788
10079 ---> 9789
10081 ---> 9790
10082 ---> 9791
10083 ---> 9792
10085 ---> 9793
10086 ---> 9794
10087 ---> 9795
10088 ---> 9796
10093 ---> 9797
10094 ---> 9798
10095 ---> 9799
10096 ---> 9800
10098 ---> 9801
10100 ---> 9802
10101 ---> 9803
10102 ---> 9804
10103 ---> 9805
10104 ---> 9806
10105 ---> 9807
10106 ---> 9808
10107 ---> 9809
10108 ---> 9810
10109 ---> 9811
10111 ---> 9812
10112 ---> 9813
10117 ---> 9814
10118 ---> 9815
10119 ---> 9816
10121 ---> 9817
10122 ---> 9818
10123 ---> 9819
10124 ---> 9820
10125 ---> 9821
10129 ---> 9822
10130 ---> 9823
10131 ---> 9824
10132 ---> 9825
10133 ---> 9826
10134 ---> 9827
10135 ---> 9828
10136 ---> 9829
10137 ---> 9830
10138 ---> 9831
10139 ---> 9832
10140 ---> 9833
10142 ---> 9834
10143 ---> 9835
10144 ---> 9836
10145 ---> 9837
10148 ---> 9838
10149 ---> 9839
10150 ---> 9840
10151 ---> 9841
10152 ---> 9842
10153 ---> 9843
10154 ---> 9844
10155 ---> 9845
10156 ---> 9846
10157 ---> 9847
10161 ---> 9848
10162 ---> 9849
10163 ---> 9850
10165 ---> 9851
10166 ---> 9852
10167 ---> 9853
10169 ---> 9854
10170 ---> 9855
10171 ---> 9856
10174 ---> 9857
10176 ---> 9858
10177 ---> 9859
10179 ---> 9860
10184 ---> 9861
10185 ---> 9862
10193 ---> 9863
10194 ---> 9864
10195 ---> 9865
10196 ---> 9866
10197 ---> 9867
10200 ---> 9868
10201 ---> 9869
10202 ---> 9870
10204 ---> 9871
10207 ---> 9872
10208 ---> 9873
10209 ---> 9874
10211 ---> 9875
10213 ---> 9876
10215 ---> 9877
10227 ---> 9878
10229 ---> 9879
10230 ---> 9880
10231 ---> 9881
10232 ---> 9882
10236 ---> 9883
10237 ---> 9884
10240 ---> 9885
10241 ---> 9886
10243 ---> 9887
10247 ---> 9888
10248 ---> 9889
10250 ---> 9890
10253 ---> 9891
10254 ---> 9892
10259 ---> 9893
10260 ---> 9894
10262 ---> 9895
10266 ---> 9896
10267 ---> 9897
10268 ---> 9898
10269 ---> 9899
10270 ---> 9900
10273 ---> 9901
10274 ---> 9902
10276 ---> 9903
10277 ---> 9904
10278 ---> 9905
10281 ---> 9906
10282 ---> 9907
10285 ---> 9908
10286 ---> 9909
10288 ---> 9910
10290 ---> 9911
10291 ---> 9912
10292 ---> 9913
10293 ---> 9914
10295 ---> 9915
10296 ---> 9916
10297 ---> 9917
10298 ---> 9918
10302 ---> 9919
10310 ---> 9920
10311 ---> 9921
10313 ---> 9922
10314 ---> 9923
10318 ---> 9924
10319 ---> 9925
10320 ---> 9926
10322 ---> 9927
10323 ---> 9928
10327 ---> 9929
10329 ---> 9930
10333 ---> 9931
10336 ---> 9932
10338 ---> 9933
10340 ---> 9934
10344 ---> 9935
10345 ---> 9936
10354 ---> 9937
10356 ---> 9938
10357 ---> 9939
10358 ---> 9940
10359 ---> 9941
10360 ---> 9942
10362 ---> 9943
10363 ---> 9944
10364 ---> 9945
10365 ---> 9946
10367 ---> 9947
10372 ---> 9948
10379 ---> 9949
10381 ---> 9950
10382 ---> 9951
10385 ---> 9952
10387 ---> 9953
10389 ---> 9954
10391 ---> 9955
10393 ---> 9956
10394 ---> 9957
10396 ---> 9958
10398 ---> 9959
10399 ---> 9960
10401 ---> 9961
10403 ---> 9962
10405 ---> 9963
10406 ---> 9964
10420 ---> 9965
10421 ---> 9966
10422 ---> 9967
10423 ---> 9968
10424 ---> 9969
10425 ---> 9970
10427 ---> 9971
10428 ---> 9972
10432 ---> 9973
10440 ---> 9974
10442 ---> 9975
10445 ---> 9976
10446 ---> 9977
10448 ---> 9978
10450 ---> 9979
10451 ---> 9980
10452 ---> 9981
10454 ---> 9982
10455 ---> 9983
10456 ---> 9984
10457 ---> 9985
10458 ---> 9986
10459 ---> 9987
10464 ---> 9988
10465 ---> 9989
10466 ---> 9990
10467 ---> 9991
10468 ---> 9992
10469 ---> 9993
10471 ---> 9994
10474 ---> 9995
10475 ---> 9996
10476 ---> 9997
10477 ---> 9998
10478 ---> 9999
10479 ---> 10000
10480 ---> 10001
10481 ---> 10002
10484 ---> 10003
10486 ---> 10004
10487 ---> 10005
10492 ---> 10006
10493 ---> 10007
10496 ---> 10008
10497 ---> 10009
10499 ---> 10010
10501 ---> 10011
10502 ---> 10012
10505 ---> 10013
10506 ---> 10014
10508 ---> 10015
10509 ---> 10016
10511 ---> 10017
10513 ---> 10018
10514 ---> 10019
10515 ---> 10020
10516 ---> 10021
10517 ---> 10022
10521 ---> 10023
10523 ---> 10024
10528 ---> 10025
10529 ---> 10026
10531 ---> 10027
10533 ---> 10028
10536 ---> 10029
10537 ---> 10030
10539 ---> 10031
10548 ---> 10032
10549 ---> 10033
10550 ---> 10034
10551 ---> 10035
10552 ---> 10036
10553 ---> 10037
10554 ---> 10038
10555 ---> 10039
10556 ---> 10040
10563 ---> 10041
10566 ---> 10042
10568 ---> 10043
10581 ---> 10044
10582 ---> 10045
10584 ---> 10046
10592 ---> 10047
10593 ---> 10048
10595 ---> 10049
10598 ---> 10050
10602 ---> 10051
10606 ---> 10052
10607 ---> 10053
10608 ---> 10054
10609 ---> 10055
10614 ---> 10056
10615 ---> 10057
10624 ---> 10058
10628 ---> 10059
10631 ---> 10060
10633 ---> 10061
10637 ---> 10062
10642 ---> 10063
10643 ---> 10064
10644 ---> 10065
10645 ---> 10066
10647 ---> 10067
10649 ---> 10068
10655 ---> 10069
10658 ---> 10070
10659 ---> 10071
10660 ---> 10072
10661 ---> 10073
10663 ---> 10074
10664 ---> 10075
10665 ---> 10076
10666 ---> 10077
10667 ---> 10078
10668 ---> 10079
10669 ---> 10080
10671 ---> 10081
10673 ---> 10082
10675 ---> 10083
10676 ---> 10084
10682 ---> 10085
10683 ---> 10086
10685 ---> 10087
10686 ---> 10088
10692 ---> 10089
10693 ---> 10090
10698 ---> 10091
10701 ---> 10092
10705 ---> 10093
10706 ---> 10094
10707 ---> 10095
10710 ---> 10096
10711 ---> 10097
10714 ---> 10098
10722 ---> 10099
10723 ---> 10100
10727 ---> 10101
10728 ---> 10102
10730 ---> 10103
10734 ---> 10104
10743 ---> 10105
10744 ---> 10106
10751 ---> 10107
10757 ---> 10108
10763 ---> 10109
10771 ---> 10110
10778 ---> 10111
10784 ---> 10112
10792 ---> 10113
10793 ---> 10114
10802 ---> 10115
10803 ---> 10116
10806 ---> 10117
10813 ---> 10118
10816 ---> 10119
10819 ---> 10120
10820 ---> 10121
10821 ---> 10122
10825 ---> 10123
10827 ---> 10124
10830 ---> 10125
10832 ---> 10126
10842 ---> 10127
10845 ---> 10128
10846 ---> 10129
10860 ---> 10130
10861 ---> 10131
10863 ---> 10132
10864 ---> 10133
10865 ---> 10134
10868 ---> 10135
10877 ---> 10136
10879 ---> 10137
10881 ---> 10138
10882 ---> 10139
10883 ---> 10140
10891 ---> 10141
10897 ---> 10142
10904 ---> 10143
10905 ---> 10144
10908 ---> 10145
10911 ---> 10146
10938 ---> 10147
10941 ---> 10148
10942 ---> 10149
10947 ---> 10150
10948 ---> 10151
10950 ---> 10152
10957 ---> 10153
10960 ---> 10154
10961 ---> 10155
10962 ---> 10156
10963 ---> 10157
10964 ---> 10158
10965 ---> 10159
10966 ---> 10160
10969 ---> 10161
10977 ---> 10162
10979 ---> 10163
10981 ---> 10164
10982 ---> 10165
10983 ---> 10166
10985 ---> 10167
10986 ---> 10168
10988 ---> 10169
10989 ---> 10170
10990 ---> 10171
10995 ---> 10172
10996 ---> 10173
11005 ---> 10174
11006 ---> 10175
11009 ---> 10176
11016 ---> 10177
11017 ---> 10178
11019 ---> 10179
11020 ---> 10180
11021 ---> 10181
11028 ---> 10182
11031 ---> 10183
11034 ---> 10184
11044 ---> 10185
11049 ---> 10186
11050 ---> 10187
11051 ---> 10188
11055 ---> 10189
11056 ---> 10190
11057 ---> 10191
11058 ---> 10192
11059 ---> 10193
11066 ---> 10194
11068 ---> 10195
11072 ---> 10196
11073 ---> 10197
11079 ---> 10198
11085 ---> 10199
11086 ---> 10200
11088 ---> 10201
11098 ---> 10202
11100 ---> 10203
11101 ---> 10204
11104 ---> 10205
11105 ---> 10206
11109 ---> 10207
11110 ---> 10208
11111 ---> 10209
11114 ---> 10210
11115 ---> 10211
11126 ---> 10212
11130 ---> 10213
11132 ---> 10214
11139 ---> 10215
11146 ---> 10216
11148 ---> 10217
11151 ---> 10218
11157 ---> 10219
11162 ---> 10220
11163 ---> 10221
11164 ---> 10222
11167 ---> 10223
11168 ---> 10224
11185 ---> 10225
11190 ---> 10226
11194 ---> 10227
11205 ---> 10228
11206 ---> 10229
11209 ---> 10230
11211 ---> 10231
11213 ---> 10232
11214 ---> 10233
11219 ---> 10234
11223 ---> 10235
11230 ---> 10236
11231 ---> 10237
11232 ---> 10238
11250 ---> 10239
11254 ---> 10240
11257 ---> 10241
11259 ---> 10242
11262 ---> 10243
11263 ---> 10244
11264 ---> 10245
11267 ---> 10246
11270 ---> 10247
11271 ---> 10248
11272 ---> 10249
11275 ---> 10250
11276 ---> 10251
11278 ---> 10252
11284 ---> 10253
11288 ---> 10254
11297 ---> 10255
11299 ---> 10256
11300 ---> 10257
11301 ---> 10258
11306 ---> 10259
11307 ---> 10260
11310 ---> 10261
11311 ---> 10262
11315 ---> 10263
11316 ---> 10264
11319 ---> 10265
11320 ---> 10266
11324 ---> 10267
11336 ---> 10268
11351 ---> 10269
11372 ---> 10270
11375 ---> 10271
11376 ---> 10272
11378 ---> 10273
11380 ---> 10274
11386 ---> 10275
11387 ---> 10276
11395 ---> 10277
11397 ---> 10278
11398 ---> 10279
11401 ---> 10280
11402 ---> 10281
11403 ---> 10282
11406 ---> 10283
11410 ---> 10284
11412 ---> 10285
11420 ---> 10286
11421 ---> 10287
11424 ---> 10288
11425 ---> 10289
11429 ---> 10290
11430 ---> 10291
11433 ---> 10292
11437 ---> 10293
11439 ---> 10294
11440 ---> 10295
11441 ---> 10296
11442 ---> 10297
11444 ---> 10298
11446 ---> 10299
11457 ---> 10300
11458 ---> 10301
11459 ---> 10302
11460 ---> 10303
11478 ---> 10304
11479 ---> 10305
11480 ---> 10306
11482 ---> 10307
11485 ---> 10308
11490 ---> 10309
11494 ---> 10310
11499 ---> 10311
11504 ---> 10312
11512 ---> 10313
11515 ---> 10314
11518 ---> 10315
11519 ---> 10316
11520 ---> 10317
11521 ---> 10318
11522 ---> 10319
11523 ---> 10320
11524 ---> 10321
11530 ---> 10322
11531 ---> 10323
11533 ---> 10324
11542 ---> 10325
11543 ---> 10326
11544 ---> 10327
11545 ---> 10328
11549 ---> 10329
11560 ---> 10330
11564 ---> 10331
11566 ---> 10332
11574 ---> 10333
11575 ---> 10334
11578 ---> 10335
11579 ---> 10336
11580 ---> 10337
11581 ---> 10338
11585 ---> 10339
11590 ---> 10340
11593 ---> 10341
11597 ---> 10342
11598 ---> 10343
11599 ---> 10344
11603 ---> 10345
11614 ---> 10346
11616 ---> 10347
11619 ---> 10348
11626 ---> 10349
11633 ---> 10350
11634 ---> 10351
11636 ---> 10352
11643 ---> 10353
11651 ---> 10354
11656 ---> 10355
11663 ---> 10356
11668 ---> 10357
11673 ---> 10358
11679 ---> 10359
11687 ---> 10360
11688 ---> 10361
11700 ---> 10362
11701 ---> 10363
11705 ---> 10364
11709 ---> 10365
11713 ---> 10366
11738 ---> 10367
11756 ---> 10368
11784 ---> 10369
11812 ---> 10370
11822 ---> 10371
11827 ---> 10372
11837 ---> 10373
11842 ---> 10374
11852 ---> 10375
11856 ---> 10376
11874 ---> 10377
11898 ---> 10378
11914 ---> 10379
11918 ---> 10380
11930 ---> 10381
11940 ---> 10382
11945 ---> 10383
11952 ---> 10384
11956 ---> 10385
11961 ---> 10386
11964 ---> 10387
11969 ---> 10388
11977 ---> 10389
11981 ---> 10390
11986 ---> 10391
11990 ---> 10392
11994 ---> 10393
11997 ---> 10394
12004 ---> 10395
12005 ---> 10396
12009 ---> 10397
12057 ---> 10398
12058 ---> 10399
12072 ---> 10400
12089 ---> 10401
12090 ---> 10402
12110 ---> 10403
12115 ---> 10404
12116 ---> 10405
12124 ---> 10406
12129 ---> 10407
12134 ---> 10408
12154 ---> 10409
12155 ---> 10410
12157 ---> 10411
12160 ---> 10412
12163 ---> 10413
12168 ---> 10414
12169 ---> 10415
12173 ---> 10416
12175 ---> 10417
12182 ---> 10418
12187 ---> 10419
12207 ---> 10420
12219 ---> 10421
12221 ---> 10422
12233 ---> 10423
12234 ---> 10424
12251 ---> 10425
12255 ---> 10426
12257 ---> 10427
12262 ---> 10428
12263 ---> 10429
12264 ---> 10430
12267 ---> 10431
12269 ---> 10432
12270 ---> 10433
12272 ---> 10434
12275 ---> 10435
12282 ---> 10436
12287 ---> 10437
12288 ---> 10438
12289 ---> 10439
12296 ---> 10440
12298 ---> 10441
12299 ---> 10442
12300 ---> 10443
12304 ---> 10444
12318 ---> 10445
12319 ---> 10446
12320 ---> 10447
12324 ---> 10448
12325 ---> 10449
12328 ---> 10450
12333 ---> 10451
12340 ---> 10452
12341 ---> 10453
12349 ---> 10454
12354 ---> 10455
12385 ---> 10456
12400 ---> 10457
12415 ---> 10458
12422 ---> 10459
12433 ---> 10460
12444 ---> 10461
12454 ---> 10462
12457 ---> 10463
12459 ---> 10464
12467 ---> 10465
12470 ---> 10466
12476 ---> 10467
12478 ---> 10468
12480 ---> 10469
12482 ---> 10470
12488 ---> 10471
12493 ---> 10472
12522 ---> 10473
12525 ---> 10474
12557 ---> 10475
12558 ---> 10476
12559 ---> 10477
12570 ---> 10478
12571 ---> 10479
12575 ---> 10480
12576 ---> 10481
12612 ---> 10482
12614 ---> 10483
12615 ---> 10484
12621 ---> 10485
12627 ---> 10486
12628 ---> 10487
12632 ---> 10488
12633 ---> 10489
12635 ---> 10490
12648 ---> 10491
12653 ---> 10492
12654 ---> 10493
12656 ---> 10494
12660 ---> 10495
12663 ---> 10496
12665 ---> 10497
12673 ---> 10498
12675 ---> 10499
12676 ---> 10500
12678 ---> 10501
12679 ---> 10502
12680 ---> 10503
12681 ---> 10504
12683 ---> 10505
12684 ---> 10506
12689 ---> 10507
12692 ---> 10508
12693 ---> 10509
12694 ---> 10510
12695 ---> 10511
12696 ---> 10512
12699 ---> 10513
12701 ---> 10514
12702 ---> 10515
12703 ---> 10516
12704 ---> 10517
12705 ---> 10518
12706 ---> 10519
12713 ---> 10520
12714 ---> 10521
12716 ---> 10522
12723 ---> 10523
12736 ---> 10524
12749 ---> 10525
12751 ---> 10526
12764 ---> 10527
12777 ---> 10528
12794 ---> 10529
12795 ---> 10530
12799 ---> 10531
12808 ---> 10532
12821 ---> 10533
12842 ---> 10534
12846 ---> 10535
12849 ---> 10536
12850 ---> 10537
12853 ---> 10538
12854 ---> 10539
12856 ---> 10540
12857 ---> 10541
12858 ---> 10542
12860 ---> 10543
12870 ---> 10544
12872 ---> 10545
12873 ---> 10546
12877 ---> 10547
12885 ---> 10548
12886 ---> 10549
12888 ---> 10550
12890 ---> 10551
12892 ---> 10552
12894 ---> 10553
12895 ---> 10554
12905 ---> 10555
12910 ---> 10556
12915 ---> 10557
12919 ---> 10558
12933 ---> 10559
12941 ---> 10560
12943 ---> 10561
12951 ---> 10562
12957 ---> 10563
12959 ---> 10564
12960 ---> 10565
12961 ---> 10566
12962 ---> 10567
12963 ---> 10568
12966 ---> 10569
12967 ---> 10570
12969 ---> 10571
12977 ---> 10572
12979 ---> 10573
12980 ---> 10574
12981 ---> 10575
12982 ---> 10576
13034 ---> 10577
13038 ---> 10578
13080 ---> 10579
13120 ---> 10580
13159 ---> 10581

---

### Documentation Issue Mappings Toolset.Mapping (`documentation/issue-mappings/toolset.mapping.txt`)

https://github.com/dotnet/toolset/issues/XXXX ---> https://github.com/dotnet/sdk/issues/YYYY
8 ---> 4250
11 ---> 4251
20 ---> 4252
22 ---> 4253
345 ---> 4254
412 ---> 4255
440 ---> 4256
1178 ---> 4258
1256 ---> 4259
2056 ---> 4260
2866 ---> 4261
3184 ---> 4262
3235 ---> 4263
3480 ---> 4264
3486 ---> 4265
3492 ---> 4266
3493 ---> 4267
3563 ---> 4268
3572 ---> 4269
3668 ---> 4270
3740 ---> 4271
3741 ---> 4272
3743 ---> 4273
3766 ---> 4274
3801 ---> 4275
3802 ---> 4276
3806 ---> 4277
3850 ---> 4278
4023 ---> 4279
4114 ---> 4280
4196 ---> 4281
4204 ---> 4282

---

### Documentation Project Docs Localization (`documentation/project-docs/Localization.md`)

# Localization
## Summary
The .NET SDK is translated into 14 languages. In our codebase, you can see the primary resx file lists the strings to be translated. 

### Making changes
The local dev build automatically generates updates to the xlf files that contain the translations. You can see the UpdateXlf task in the binlog to see that in action. 

When making string changes, update the resx, build, and check in all xlf file changes. Developers should never need to update the xlf files directly and should always rely on the local build for updates to those files. This will leave the files in english initially and they will get translated eventually.

#### Automated XLF Updates via GitHub Actions

If you've modified `.resx` files in a pull request and need to update the corresponding `.xlf` files but don't want to clone the branch locally, you can use the automated GitHub Action:

**Comment `/updatexlf` on your pull request** and the workflow will:
1. Check out your PR branch
2. Run the UpdateXlf build target
3. Commit any updated `.xlf` files directly to your PR branch

This is particularly useful when CI is failing due to outdated XLF files.

For internal folks, see https://aka.ms/allaboutloc

### Loc issues
Never manually update the xlf file even if a translation is wrong. Report a bug instead.

External -- https://aka.ms/provide-feedback
Internal -- https://aka.ms/icxLocFeedback

When diagnosing a missing translation in the Native AOT CLI, compare the same
command with `DOTNET_CLI_ENABLEAOT=true` and `false` in the same complete SDK
installation. Set `DOTNET_CLI_UI_LANGUAGE` to the affected culture, and check a
translated string as well as output parity: both paths can otherwise fall back
to English and appear to match. For example, `dotnet build --help` with `zh-CN`
should show `.NET 生成器` (dotnet/sdk#55820). Also verify a localized first-run
message using a fresh CLI home with developer-certificate generation and global
tool PATH changes disabled.

### Loc Updates
These are triggered automatically by the loc system as new translations come in. We generally accept these unless we notice it removing translations.
https://github.com/dotnet/sdk/pulls?q=is%3Apr+author%3Adotnet-bot+onelocbuild

### Loc Builds
We typically only localize the primary development branch. We move to vNext once we get to RC1 and only then, localize all new strings introduced in that release. That way we can continue to add messages in the 4xx release of an SDK.

This is controlled by the OneLocBuild stage in [`.vsts-ci.yml`](../../.vsts-ci.yml) and requires a change both there and in the loc system to align branches.

### Translation directives
There are a ton of translations directives our localization system understands. Here are some of the most common in this repo:

#### Locking translations
If a string or partial string should not be translated, add `{Locked=""}` with the details in the appropriate resx files. If `{Locked}` is used the entire string is locked. This can be specified multiple times, each locking different sections.

#### Contextual comments
You can use `<comment>` elements inside the `<data>` tags to provide context to translators.

### String formatting constraints
You can use `{StrBegins=}`, `{StrContains=}` and `{StrEnds=}` to ensure that after translation the string contains the specified values

---

### Documentation Project Docs SDK PR Guide (`documentation/project-docs/SDK-PR-guide.md`)

# SDK PR Guide

## Branching & Release Schedules
See the [versions](https://learn.microsoft.com/en-us/dotnet/core/porting/versioning-sdk-msbuild-vs#lifecycle) document for more details on how SDK versions map to MSBuild and Visual Studio. The Visual Studio schedule is available on the devdiv internal Azure DevOps wiki and the .NET schedule is communicated through the internal .NET Tactics alias.

### Major releases
The .NET SDK has yearly major releases aligning with the .NET Runtime in November.  These releases will be of the form `N.0.1xx`. The feature work for major releases will be done in `main`. 

Typically, previews for each major release start in February of each year.  For each preview, we will snap a new branch off of main approximately midway through the prior month.

During .NET 7, for example, the preview branches were created around the 21st of each month prior, with the later previews forking earlier to provide more time for stabilization and codeflow.
The `main` branch's major version will be set to match the next year's major release in August. (For example, the switch from `.NET 7` to `.NET 8` occurred in August of 2022, while .NET 8 was set for release in 2023.) Warning: This process can take a bit for those waiting to develop features for the next major release. In prior releases it has taken 1-3 months before the new branch could be fully used to target the new .NET Runtime version.

### Minor releases
The .NET SDK has quarterly minor releases that align with Visual Studio releases. For example, two different quarterly releases in the same schedule would be: `7.0.200` vs `7.0.300`. These SDK releases are open to all bug fixes and some features work as well. 
These quarterly releases should avoid breaking changes if at all possible. Breaking changes instead should be included in the major releases and be tied to customer `TargetFramework` updates when possible. We do this to limit the pain of breaking changes, as customers need to take action (upgrading the `TargetFramework`) before they are broken. 

Minor releases lock down after preview 3 for each release.  Preview 3 is typically 1 month prior to GA and locks down by the end of the month before the preview release.

#### Transition from minor release to servicing
After the minor release locks down, it transitions into servicing / "QB" (Quarterback) mode. This typically happens around the `preview 3` release to allow time for any late public changes we want feedback on. The next release after `preview 3` is typically GA and done as a servicing release. The following steps are done when transitioning from minor release previews to servicing:
- [ ] Follow the new branch check list for creating a new minor release (steps listed on internal OneNote)
- [ ] Set [`StabilizePackageVersion`](https://github.com/dotnet/sdk/blob/main/eng/Versions.props#L18) to true
- [ ] Enable internal runtime `darc` subscriptions and trigger them

### Servicing releases
The .NET SDK has monthly servicing releases (e.g.`7.0.100` VS `7.0.101`) aligning with the .NET Runtime servicing releases. These are for top fixes and security updates only to limit risk.
Any servicing release is open for check-ins from the day the [branding PRs](https://github.com/dotnet/sdk/pulls?q=is%3Apr+branding) are merged (~1st Tuesday of each month) and when code complete is (typically two weeks later).
The .NET 8 and .NET 9 servicing branches are locked from the time of code complete to the next branding in case we need to respin any monthly release. We use the `Branch Lockdown` label to mark PRs that should go into the next servicing release but the branch is currently not open. Final signoffs are typically in the last week of each month. We have a workflow that will automatically mark any PR targeting a servicing branch outside of the first to third Tuesday window: https://github.com/dotnet/sdk/blob/main/.github/workflows/add-lockdown-label.yml
### Schedule
| Release Type | Frequency    | Lockdown Release  | Branch Open | Lockdown Date (estimate) |
| -------------|--------------|-------------------|-------------|--------------------------|
| Major        | Yearly (Nov) | RC2               | ~August     | Mid-September            |
| Minor        | Quarterly    | Preview 3         | ~Prior release Preview 3 date | End of the month prior to Preview 3 (~7 weeks prior to release) |
| Servicing (8/9) | Monthly   | N/A               | After branding, ~1st Tuesday of the prior month | Third Tuesday of prior month (signoff is ~28th of each month) |
| Servicing (10+) | Monthly   | N/A               | Primary Nxx branch remains open; fork dotnet/dotnet shortly after code complete | N/A |

**NOTE:** Servicing branches starting in 10 no longer have lockdown dates. Instead, we fork the `dotnet/dotnet` repo shortly after code complete. Any remaining changes have to be made (or flowed) directly to the new version-specific branch. The primary `Nxx` branch is then open for all changes.

### Tactics approval
Even releases that are in lockdown can still take changes as long as they are approved and the final build isn't complete. To bring a change through tactics, mark it with the label `servicing-consider` and update the description to include 5 sections (Description, Customer Impact, Regression?, Risk, Testing). See previously approved bugs for examples by looking for the [servicing-approved](https://github.com/dotnet/sdk/pulls?q=is%3Apr+label%3AServicing-approved+is%3Aclosed) label.

Any PR that targets a version-like servicing branch (`release/[0-9]*`, e.g. `release/8.0.4xx`, `release/10.0`) and is not a codeflow PR or a test-only change will automatically have the `Servicing-consider` label applied by the [add-servicing-consider-label](https://github.com/dotnet/sdk/blob/main/.github/workflows/add-servicing-consider-label.yml) workflow. This prevents accidental merging of new features without tactics approval. The following PR types are exempt from automatic labeling:
- PRs from automated codeflow bots (inter-branch merge flow, darc subscriptions) — but **not** backport PRs, which are also bot-authored and do require servicing approval.
- PRs that only modify files in the `test/` directory.
- PRs authored by `vseanreesermsft` (branding and internal-to-public flow).

For servicing changes to other repos like MSBuild and NuGet, we recommend getting approval from tactics before the PR is merged. For codeflow, we do not gate codeflow on approvals as many codeflows are just infra work that doesn't require approval. Separating those out would add additional complexity we want to avoid.

Once your bug is ready for approval (has sign-off and the template details in the description), you can come to tactics for live approval or send email to the tactics alias. If you get tactics approval offline from the .NET QB, remove the `servicing-consider` label, add the `servicing-approved` label, set the milestone to match the runtime release this ships with, and merge if the branch is open.

## External contributions
External contributions are encouraged and welcome. There are so many teams working in this repo that it can be hard to track. Contributors looking to learn more about how to contribute should check out the [Developer Guide](https://github.com/dotnet/sdk/blob/main/documentation/project-docs/developer-guide.md).

- Ping `@dotnet/domestic-cat` when ready for a review
- Make sure all tests and checks are passing
- Make sure to add a new test for the scenario (when it makes sense)

Triage and PR review meetings are Wednesdays each week. If your PR is passing checks and has been reviewed by then, that's when we typically merge.

## Codeflow
Codeflow is handled by [darc](https://github.com/dotnet/arcade/blob/main/Documentation/Darc.md). Codeflow comes from three runtime branches and a dozen tools branches.
`@dotnet/domestic-cat` will monitor codeflow and approve passing PRs (as all PRs require 1 approver) and ping the owning team for any failures.

### Reviewer assignment for dependency flow PRs
Some dependency sources are reviewed by a specific team rather than by `@dotnet/domestic-cat`. For PRs authored by the trusted Maestro bot, the [assign-dependency-flow-reviewers](https://github.com/dotnet/sdk/blob/main/.github/workflows/assign-dependency-flow-reviewers.yml) workflow inspects titles of the form `Update dependencies from <org>/<repo>` (including the `[branch] ` prefixed variant) and requests a review from the owning team:

| Dependency source | Reviewer team |
| --- | --- |
| `microsoft/testfx` | `@dotnet/dotnet-testing` |

To route another dependency source, add an entry to the `reviewerTeamsBySourceRepo` map in that workflow.

## Internal Builds

The .NET SDK [Installer](https://github.com/dotnet/installer) is what allows the .NET SDK to be installed on a machine for usage in a proper developer environment, rather than for developing the .NET SDK itself. The installer has nightly builds that align with the .NET SDK which you can find [here](https://github.com/dotnet/installer#installers-and-binaries).
The number of the build may be of particular interest. The build numbers match the internal build numbers with some caveats. YYYY MM DD are squashed to 5 digits. The first 2 digits represent the final 2 digits of the year. The next 3 digits represent the month and year: 50*The_Month_Number + the day of the month. The final suffix after the decimal value is the number of the build for that given day. 

Example:
`23080.2` is 2023, January 30th (1*50) + 30, and the second internal build of the SDK for that day. 

## Internal Branching
All monthly servicing releases are done of our internal branches in case there are security changes that have to go out. That means all flows from runtime branches into the SDK and from SDK to installer are done internally.
That is why we have removed all servicing builds from the installer main page as those builds do not include any changes from any repo other than the installer repo so are very limited.
Internal codeflow is merged into public GitHub repos on patch Tuesday each month to ensure we are updated.

## Inter-branch codeflow
In the SDK repo, we have automated codeflow set up for each non-preview release branch flowing from the oldest branch all the way to main. You can see the configuration for that in [github-merge-flow.jsonc](https://github.com/dotnet/sdk/blob/main/github-merge-flow.jsonc). The workflow configuration is in [inter-branch-merge-flow.yml](https://github.com/dotnet/sdk/blob/main/.github/workflows/inter-branch-merge-flow.yml)
You can see the existing open branch codeflows [here](https://github.com/dotnet/sdk/issues?q=is%3Apr%20is%3Aopen%20author%3Aapp%2Fgithub-actions%20%20Merge%20branch)

### Further updates
These PRs will not get updated as new changes come in. This allows time to run PR checks, review, and merge. Once the existing PR is merged and all changes since that PR was created will be generated in a new PR. This leads to [failed](https://github.com/dotnet/sdk/actions/workflows/inter-branch-merge-flow.yml) workflow automation but that's expected. The workflow will report this message: _hint: Updates were rejected because the tip of your current branch is behind_.

### Reviewing and merging inter-branch codeflow
Generally we will check the commit list and scan the changes for anything out of the ordinary. We take a special look for any conflict merges that were done in getting the PR building.
> [!Important]
> Make sure to create a merge commit. *Do not squash*. If you squash, the next inter-branch PR will list all of the same commits.

**NOTE** Some inter-branch flow will have 0 changes once the merge conflicts are resolved. This is likely when the only changes were to version numbers in the eng/*. These can be closed to save time and resources or merged to catch the commit history up (the next codeflow will have fewer commits). There is no preference either way.

---

### Documentation Project Docs Breaking Change Guidelines (`documentation/project-docs/breaking-change-guidelines.md`)

# SDK Breaking Change and Diagnostic Guidelines

This document provides guidelines for introducing new diagnostics or breaking changes to the .NET SDK, which configuration knobs are available, what criteria should guide the decision around severity, timeline for introduction, and deprecation of diagnostics, and what steps are required by the .NET release process.

## What is a breaking change in the .NET SDK?

A .NET SDK breaking change is when a customer upgrades to a newer .NET SDK, while changing nothing else in their environment, and experiences a disruption to their product build or execution.

## General guidance

In general, we want to make updating the .NET SDK as smooth as possible for developers. This extends to updating .NET tooling such as IDEs and code editors which may have a different release schedule and cadence. For example, the .NET 9 SDK (which was a new major version) was released with Visual Studio 17.12 (which was a new minor version). In this example, breaking changes in the .NET 9 SDK could disproportionally impact Visual Studio users who are expecting incremental, non-breaking, changes in the new minor version. Same applies to other IDEs and code editors from the wider .NET community.

This means:
* Introducing new changes in a staged/gradual way.
* Tying new analyzers/diagnostics to a mechanism that requires explicit opt-in.
* Providing a way to opt out of a change entirely.

## Examples of .NET SDK breaking changes

* New MSBuild warnings and errors (props/targets).
* New NuGet warnings and errors. 
  * For example, NuGet Audit.
* Changes to Roslyn Analyzers and CodeFixes that apply to existing TFMs.
* Behavioral/implementation changes.
  * MSBuild engine changes like MSBuild Server.
  * Implementation changes for MSBuild Tasks.
  * NuGet Restore algorithm enhancements.
  * Changes to DotNet CLI behavior or output.
  * Changes to DotNet CLI grammar.
  * Changes to defaults in CLI flags that impact behavior.
    * For example, `--configuration` flag defaulting to `Release` instead of `Debug`.

## Configuration Knobs

The following knobs are available to enable/disable these changes (some may not apply to all kinds of changes):

* [TargetFramework](https://learn.microsoft.com/en-us/dotnet/standard/frameworks)
* [SdkAnalysisLevel](https://learn.microsoft.com/en-us/dotnet/core/project-sdk/msbuild-props#sdkanalysislevel)
* EditorConfig (for Analyzers)
* AnalysisLevel (for Analyzers/CodeFixes)
* WarningLevel
* [Change waves](https://learn.microsoft.com/en-us/visualstudio/msbuild/change-waves) (for MSBuild engine behavior)
* [LangVer](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version)

## Deciding how to Surface Changes

### Support new and old commands in the first release

For changes in the CLI grammar, fully support both commands in one release, add a message to the old command in the subsequent release, and remove the old command in the release after that. This allows users to migrate to the new command at their own pace.

Specific example: When the `dotnet new --list` command was changed to `dotnet new list` to adhere to CLI design guidelines,
the old command was still the default supported and a warning was written to the console when the old form was used pointing users to the new form. This allowed users and scripts to continue using the old form and gradually migrate to the new.

### Implement changes in an informational/non-blocking way initially

What this means will vary change-to-change. For example, for a change expressed as an Analyzer or MSBuild diagnostic, consider
Informational level severities initially. For a behavioral change on a CLI, consider an informational message written to the
stderr channel on the console instead of making the stdout output unparseable by tools.

### Gradually increase severity over each release

If a change in introduced in an informational/non-blocking way, determine the time frame where it is safe to increase the severity. For Analyzers, this may mean tying it to the next value of AnalysisLevel (which is downstream of TFM). For small MSBuild and NuGet diagnostics, this may mean tying it to the next Warning Level or SdkAnalysisLevel. For CLI changes, this may mean tying it to the next LTS major version of the SDK. Ideally the way you would structure this increase would be automated and documented so that users know what's coming down the pipe.

### Cut-over to new behavior after a long introduction period

After the change has been introduced in a gradual way, cut over to the new behavior. This may mean removing the old behavior entirely, or it may mean making the new behavior the default and providing a way to opt out of it. It is important that you
provide enough time for users to adapt - for example the `dotnet new --list` example above took an entire major release to make the new forms the default.

### Always provide a way to opt out of the change

Have some kind of knob that allows users to opt out of the change entirely. Preferably, this would be a project property, but, for depending on the change, other mechanisms would be more appropriate. For example, an environment variable for MsBuild engine changes or a CLI argument to opt out of a new output format. This allows users to continue using the old behavior if they need to in exceptional situations.

It is important to document the opt out mechanism in the SDK documentation, as well as document the timeline for when this opt out mechanism will be removed entirely, forcing users to adopt the new behavior. For systems like Analyzers, that time may be _never_, because the cost of detection is so low. This is a product-level decision that is hard to give universal guidance for.

### Hook into the unified SdkAnalysisLevel knob to allow users to easily opt out of all changes

This knob exists so that users can safely and consistently say "for whatever reason, I just need you to act like SDK version X". This is the one-stop shop - users no longer need to know about all the individual knobs that are available to them.

### Tie potentially impactful changes to the target TFM

Changes that are expected to cause significant disruption should only be introduced behind the Target Framework knob. This ensures business continuity and allows developers to address changes needed as part of scheduled work to migrate a codebase to a new TFM. In general, new warnings/errors that only apply to a new TFM are not considered breaking changes. 

Examples:
* NuGet warnings for vulnerable transitive dependencies were introduced in the .NET 10 SDK only for projects targeting .NET 10 and higher.
* New Roslyn analyzers tied to a new target TFM.

## Required process for all .NET SDK breaking changes 

* Create an issue in the appropriate GitHub repository to track the change, if one does not already exist.
* Add the breaking-change label to the issue. This label should be available in all .NET repositories that ship as part of the .NET SDK. If the label is not available, please file an issue in [dotnet/sdk](https://github.com/dotnet/sdk).
* Consider creating and pinning an issue in the appropriate GitHub repository where the community can provide feedback.
* Once a Pull Request is submitted for the issue, add the breaking-change label to the Pull Request as well. This will trigger a message with instructions. In addition, you are invited to work with the SDK team to publish a blog post for the change.

---

### Documentation Project Docs Cli Guidelines (`documentation/project-docs/cli-guidelines.md`)

## CLI Guidelines for the dotnet CLI and related commands

The `dotnet` CLI is the entrypoint for the .NET experience for all users, and as such it needs to be usable, performance, and consistent.
This document outlines a series of UX guidelines, CLI grammars, and behavioral expectations for the `dotnet` CLI and related commands so that
users have consistent experiences with all `dotnet` commands - even those that do not ship directly with the SDK like dotnet tools.

- [CLI Guidelines for the dotnet CLI and related commands](#cli-guidelines-for-the-dotnet-cli-and-related-commands)
- [Common Options](#common-options)
  - [Verbosity](#verbosity)
  - [Framework selection](#framework-selection)
  - [RID selection](#rid-selection)
    - [Explicit RID](#explicit-rid)
    - [OS-specific RID](#os-specific-rid)
    - [Architecture-specific RID](#architecture-specific-rid)
    - [SDK-matching RID](#sdk-matching-rid)
  - [MSBuild Properties](#msbuild-properties)
  - [Output modes/formatting](#output-modesformatting)
- [NuGet-related options](#nuget-related-options)
  - [NuGet.Config File selection](#nugetconfig-file-selection)
  - [Package source management](#package-source-management)
    - [Additive package sources](#additive-package-sources)
    - [Exclusive package sources](#exclusive-package-sources)
  - [Feed Authentication support](#feed-authentication-support)
- [Contextual behaviors](#contextual-behaviors)
  - [Implicit project/solution file discovery](#implicit-projectsolution-file-discovery)
  - [Determining interactive sessions](#determining-interactive-sessions)
- [Interaction patterns](#interaction-patterns)
  - [Support structured (JSON) output](#support-structured-json-output)
  - [StdOut/StdErr usage](#stdoutstderr-usage)
  - [Advanced terminal output capabilities](#advanced-terminal-output-capabilities)
  - [Disabling advanced terminal output capabilities](#disabling-advanced-terminal-output-capabilities)
- [References](#references)

## Common Options

These options are present on a (sub)set of commands, and should be consistent in their behavior and usage regardless of the context in which they are used. Users expect these kinds of options to be generally available and will often unconsciously reach for them as best guesses/first attempts.

### Verbosity

Short Form: `-v`

Long Form: `--verbosity`

Allowed values: `[q]uiet`, `[m]inimal`, `[n]ormal`, `[d]etailed`, `[diag]nostic`

The CLI uses MSBuild verbosity level names. Commands should at minimum have support for three of these:
* `quiet` mode should output nothing except the specific data output of the command.
* `normal` mode should include high-priority messages in addition to the output
* `diagnostic` mode should include all messages, including low-priority/debug/verbose messages.

If you only support a subset of these values, map the missing ones to the closest semantic match.
For example, if you don't support `minimal`, map it to `quiet`. If you don't support `detailed`, map it to `diagnostic`.

For feedback on when to write to stderr or stdout, see the [StdOut/StdErr usage](#stdoutstderr-usage) section.
For guidance on laying out output for users, see the [Advanced terminal output capabilities](#advanced-terminal-output-capabilities) section.

### Framework selection

Short form: `-f <TFM>`

Long form: `--framework <TFM>`

### RID selection

#### Explicit RID

Short form: `-r <RID>`

Long form: `--runtime <RID>`

#### OS-specific RID

Short form: `-o <OS>`

Long form: `--os <OS>`

#### Architecture-specific RID

Short form: `-a <ARCH>`

Long form: `--arch <ARCH>`

#### SDK-matching RID

Short form: `--ucr`

Long form: `--use-current-runtime`

### MSBuild Properties

Short form: `-p <MSBuild property expression(s)>`

Long form: `--property <MSBuild property expression(s)>`

If at all possible we _strongly encourage_ not parsing the `<MSBuild property expression(s)>` syntax yourself. It is much more complex than you think it is.
At _best_ you should detect and forward along any of these arguments to any MSBuild invocations you make.

### Output modes/formatting

Long form: `--format`

Allowed values: `text`, `json`, others are relevant for your use case

Users value scriptability of CLI commands, and some form of structured output is key to supporting this. JSON is a common structured output format,
but other formats may be more appropriate for your use case. If you use a structured format like `csv`, please for the love of Turing use a proper
CSV writer and not just a hand-rolled comma-separated list of values so that you don't break [RFC 4180][4180].

When you write JSON outputs you are explicitly creating a data contract with users. Be _very intentional_ about changes to the format of this contract.
Design up-front for extensibility. For example, instead of just emitting a list of versions as an array of strings, consider emitting them as an
array of objects with a named property: `[{"workload_set_version": "1.0.0"}]` instead of `"1.0.0"`.

## NuGet-related options

NuGet is key to delivering package management and security functionality to end users. We should strive to make the NuGet experience as consistent
as possible across all `dotnet` commands, by following the same patterns and behaviors.

### NuGet.Config File selection

Long form: `--config-file`

Default value: directory-based probing implemented in the [`NuGet.Configuration`][nuget-configuration] library

### Package source management

There are two semantics of behaviors that we have adopted in the dotnet CLI: additive and exclusive package sources.

#### Additive package sources

Long form: `--add-source <source_uri>`

When this is used, you should load the sources list from the NuGet configuration (using the [libraries][nuget-configuration]) and create a
 new `PackageSource` to add to that set. This should be additive and not destructive.

#### Exclusive package sources

Long form: `--source <source_uri>`

When this is used, you should ONLY use the sources supplied by this parameter and ignore any sources in the NuGet configuration. This is useful
for scenarios where you want to ensure that you're only using a specific source for a specific operation.

### Feed Authentication support

Long form: `--interactive <bool>`

Default value: `true` when in an [interactive session](#determining-interactive-sessions), `false` otherwise

NuGet authentication often requires some interactive action like going to a browser page. You should 'prime' the NuGet credential services by calling
`NuGet.Credentials.DefaultCredentialServiceUtility.SetupDefaultCredentialService(ILogger logger, bool nonInteractive)` with the value of `nonInteractive`
being the inverted value of this parameter. This will ensure that the credential service is set up correctly for the current session type.

## Contextual behaviors

### Implicit project/solution file discovery

When a command is run in a directory that contains a project or solution file, the command should automatically use that file as the
target for the command.
If the command is run in a directory that contains multiple project or solution files, the command should fail with an error message
indicating that the user should specify which file to use.

Consider the use of an option like `--project <path to project or solution>` to allow for executing the command against a specific
project or solution file at an arbitrary location - but be aware that many mechanisms in .NET are hierarchical from Current Working
Directory and may have different behaviors when used in this detached mode.

### Determining interactive sessions

Commands should be able to determine if they are running in an interactive session or not. This is important for determining

* whether to prompt the user for input or not,
* what the default value for NuGet's `--interactive` option should be
* how to format output (along with terminfo probing)

In general the easiest way to check this is if the `stdin` file descriptor is a TTY, or in .NET Terms: `Console.IsInputRedirected` is `false`.

## Interaction patterns

### Support structured (JSON) output

All commands should support structured (JSON) output. This is a key part of the CLI experience and allows for easier scripting and automation of the CLI.
See the [`--format`](#output-modesformatting) option for more details. When structured output is requested, the command should output the structured
data to `stdout` and any non-structured data to `stderr` - this is to make it easier to parse the structured data without having to deal with the
non-structured data.

### StdOut/StdErr usage

StdErr is a perfectly reasonable output channel. It should be the default channel for

* warnings and errors
* verbose logging
* outputs that aren't directly related to the command's primary purpose - for example 'workload manifest update' notices

There is some contention here because older versions of PowerShell treat any stderr output as an error, but this is not the
case in modern PowerShell (> 7.3) via the [$PSNativeCommandUseErrorActionPreference](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_preference_variables#psnativecommanduseerroractionpreference) preference setting.

### Advanced terminal output capabilities

You are encouraged to make use of advanced terminal capabilities like colors, weights, and other formatting options to make your output
more readable. Instead of writing entire lines of text as a single color, consider how the use of color and formatting present the
output to the user. When performing long-running operations, provide a progress bar or ticker or some other form of feedback to the user.

DO NOT rely entirely on color to convey information. Colorblind users will not be able to distinguish between different colors. Instead,
consider color, symbols, and layout holistically to convey information.

### Disabling advanced terminal output capabilities

If stderr or stdout are redirected, do not emit color/weight/progress on those channels.
If NO_COLOR is set, do not emit color/weight/progress on any channel.
If TERM is `dumb`, do not emit color/weight/progress on any channel.

## References

[Command-line interface guidelines][clig]

[clig]: https://clig.dev/
[4180]: https://www.loc.gov/preservation/digital/formats/fdd/fdd000323.shtml
[nuget-configuration]: https://nuget.org/packages/NuGet.Configuration
[pwsh-output-streams]: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_output_streams

---

### Documentation Project Docs Developer Guide (`documentation/project-docs/developer-guide.md`)

Developer Guide
===============

## Prerequisites

In order to build and test the .NET Core Command-line Interface (CLI), you need the following installed on you machine:

### For Windows

1. git (available from the [Git Website](http://www.git-scm.com/)) on the PATH.
2. Visual Studio "Desktop development with C++" workload with all defaults (see [Native AOT prerequisites](https://learn.microsoft.com/dotnet/core/deploying/native-aot/?tabs=windows%2Cnet8#prerequisites)).

### For Linux

1. git (available from your package manager or the [Git Website](http://www.git-scm.com/)) on the PATH.

### For macOS

1. git (available from [Homebrew](https://brew.sh) or the [Git Website](http://www.git-scm.com/)) on the PATH.

## Building

### Windows

Run the following command from the root of the repository:

```
build.cmd
```

The build script will output a `dotnet` installation to `artifacts\bin\redist\Debug\dotnet` that will include any local changes to the .NET Core CLI.

As part of the build, some intermediate files will get generated which may run into long-path issues. If you encounter a build failure with an error message similar to `Resource file [filename].resx cannot be found.`, [enable long paths in Windows](https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=cmd#enable-long-paths-in-windows-10-version-1607-and-later) and in Git (`git config core.longpaths true`), then try again.

#### Using Visual Studio

The simple way to launch Visual Studio after building via `build.cmd` is to double-click the `VS with sdk.slnx` Windows shortcut in the `artifacts` folder. This will load the generated environment automatically and launch Visual Studio with the `sdk.slnx` solution.

Alternatively, to open the solution in Visual Studio, be sure to build with `build.cmd` and run the generated environment for your shell. If you're using `cmd`, then run `artifacts\sdk-build-env.bat`. If you're using PowerShell, you need to 'dot source' `artifacts/sdk-build-env.ps1`. Finally, open Visual Studio with `devenv sdk.slnx`.

In addition, Visual Studio must have the following option set (this option is automatically set in preview Visual Studio builds):



Go to `Tools` -> `Options` to make sure "Use previews of the .NET SDK (requires restart)" is checked and restart VS.

> [!NOTE]
> If you're building main, we may be using a preview version of the SDK to build as specified in [global.json](../../global.json#L3). We only test preview SDKs with the latest Visual Studio previews so would recommend installing the latest preview build. You can see the preview versions we test with [here](https://learn.microsoft.com/en-us/dotnet/core/porting/versioning-sdk-msbuild-vs#preview-versioning)

### Linux and macOS

Run the following command from the root of the repository:

```
./build.sh
```

The build script will output a .NET Core installation to `artifacts\bin\redist\Debug\dotnet` that will include any local changes to the .NET Core CLI.

## SDK process entry points

Changes under `src/Cli` must support three process entry points of equal importance:

| Entry point | Source | Host |
| --- | --- | --- |
| Managed CLI | [`src/Cli/dotnet/Program.cs`](../../src/Cli/dotnet/Program.cs) | CoreCLR runs the full command implementation. |
| Native AOT CLI | [`src/Cli/dotnet-aot/NativeEntryPoint.cs`](../../src/Cli/dotnet-aot/NativeEntryPoint.cs) | The native `dotnet` host calls the exported `dotnet_execute`. Unsupported operations can continue in the managed CLI. See the [NativeAOT design](../../src/Cli/dotnet-aot/DESIGN.md). |
| MSBuild logger | [`src/Cli/dotnet/Commands/MSBuild/MSBuildLogger.cs`](../../src/Cli/dotnet/Commands/MSBuild/MSBuildLogger.cs) | MSBuild loads the logger type from `dotnet.dll` as an `INodeLogger`. [`MSBuildForwardingApp`](../../src/Cli/dotnet/Commands/MSBuild/MSBuildForwardingApp.cs) adds the `-distributedlogger` argument. |

### MSBuild logger lifecycle

The MSBuild logger is a separate process entry point. It is not a standalone executable.
The logger can run in the managed CLI process, a child MSBuild process, or a persistent
MSBuild server. Code called through the logger must not assume that a CLI bootstrap
initialized process-wide state.

Use `BuildStarted` and `BuildFinished` to manage state for one build. `Shutdown` completes
one logger instance. It does not necessarily end the process. A persistent server can run
multiple builds in one process. Refresh the environment and trace context for each build.

## Running tests

### Windows

Run the following command from the root of the repository to run all the .NET Core CLI tests:

```
build.cmd -test
```

### Linux and macOS

Run the following command from the root of the repository to run all the .NET Core CLI tests:

```
./build.sh --test
```

## Using the built dotnet

The `dotnet` executable in the artifacts directory can be run directly.

However, it's easier to configure a test environment to run the built `dotnet`. This test environment is managed by dogfood.
The dogfood script starts a new Powershell with the environment configured to redirect SDK resolution to your build.

From that shell your SDK will be available in:

- any Visual Studio instance launched (via `& devenv.exe`)
- `dotnet build`
- `msbuild`

### Windows

Run the following commands from the root of the repository to setup the test environment:

```
eng\dogfood.cmd
```

Ensure the `dotnet` being used is from the artifacts directory:

```
where dotnet
```

This should output `..\artifacts\bin\redist\Debug\dotnet\dotnet.exe`.

You can now run `dotnet` commands to test changes.

### Linux and macOS

Run the following commands from the root of the repository to setup the test environment:

```
source ./eng/dogfood.sh
```

NOTE: If you are running on MacOS you will need to use a `bash` shell rather than the default `zsh`. You can either change your default shell or type `bash` before executing the above command.

Ensure the `dotnet` being used is from the artifacts directory:

```
which dotnet
```

This should output `.../artifacts/bin/redist/Debug/dotnet/dotnet`.

You can now run `dotnet` commands to test changes.

### Debugging

Run "dotnet --debug <command>" which will launch dotnet and pause waiting for user input. This will give you time to attach a debugger to the running dotnet process, set the breakpoints you want to stop at in your built copy of the sdk, and then you can hit enter for the dotnet command to continue.

## Run tests from the command line

```powershell
build.cmd # to have a full build first
.\.dotnet\dotnet.exe scripts\RunTests.cs -- `
  --project test\YOURTEST.Tests\YOURTEST.Tests.csproj `
  --filter "FullyQualifiedName~TESTNAME"
```

The runner builds the selected test project incrementally and retains its TRX and MSBuild
binlog paths under `artifacts/log/test-runs/`. Pass `--repeat N` to build once and run
the selected tests repeatedly, with separate TRX output and timing for each iteration.

For process-output assertions, process exit does not imply that stdout and stderr
callbacks have finished. Complete the output channel only after both streams reach EOF
and drain queued lines before reporting missing output. Prefer deterministic tests that
hold an output callback past process exit over sleeps or retries; see
[the output-drain regression tests](../../test/dotnet-watch.Tests/TestUtilities/AwaitableProcessTests.cs).

## Run tests in Visual Studio

Use developer command prompt for Visual Studio or put devenv on you PATH

```shell
build.cmd # to have a full build first
.\artifacts\sdk-build-env.bat
devenv sdk.slnx
```

Note again that in Visual studio "Use previews of the .NET SDK (requires restart)" must be checked. See the above comment for how to enable this.

## A simple test

Using the `dotnet` built in the previous steps:

```
mkdir test
cd test
dotnet new console
dotnet run
```

This should print `Hello World!`.

## Locked files

If you see error like ` error MSB3021: Unable to copy file "sdk-tasks.dll" to "sdk-tasks.dll". The process cannot access the file 'sdk-tasks.dll' because it is being used by another process.`

You could run the following to stop all dotnet related processes

```batch
taskkill /F /IM dotnet.exe /T ||
taskkill /F /IM VSTest.Console.exe /T ||
taskkill /F /IM msbuild.exe /T
```

## CI workflow telemetry correlation

Set `DOTNET_CLI_TELEMETRY_SESSIONID` in every CI workflow and pipeline entry point.
Set the variable at the workflow or pipeline scope. You can use job scope in a
single-job workflow. The CLI uses this value to correlate telemetry from separate
`dotnet` processes in one run.

Use this value in GitHub Actions workflows under
[`.github/workflows`](../../.github/workflows):

```yaml
env:
  DOTNET_CLI_TELEMETRY_SESSIONID: gha-${{ github.repository_id }}-${{ github.run_id }}-${{ github.run_attempt }}
```

Use this value in Azure DevOps pipeline entry points:

```yaml
variables:
- name: DOTNET_CLI_TELEMETRY_SESSIONID
  value: azdo-$(System.CollectionId)-$(System.TeamProjectId)-$(Build.BuildId)
```

When you add or change a CI entry point, preserve this variable and its provider-specific
format. For CLI behavior, see the
[telemetry documentation](telemetry.md#related-environment-variables).

## Automated PR Maintenance Commands

The SDK repository includes GitHub Actions workflows that automate common maintenance tasks directly from pull requests.

### `/xlf` or `/updatexlf` - Update Translation Files

- Workflow: [Update XLF files on command](https://github.com/dotnet/sdk/actions/workflows/update-xlf-on-comment.yml)
- Source: [update-xlf-on-comment.yml](../../.github/workflows/update-xlf-on-comment.yml)

When you modify `.resx` resource files, the corresponding `.xlf` translation files need to be updated. Instead of manually running the build locally, comment `/xlf` or `/updatexlf` on the PR and the GitHub Action will:

1. Check out the PR branch
2. Run `./build.sh /t:UpdateXlf` (or full build if needed)
3. Commit any updated `.xlf` files directly to the PR branch

This is useful when you've changed localized strings and the CI build is failing due to outdated XLF files.

See also: [Localization documentation](Localization.md)

### `/completions` or `/fixcompletions` - Update CLI Completion Snapshots

- Workflow: [Fix completion snapshots on command](https://github.com/dotnet/sdk/actions/workflows/fix-completions-on-comment.yml)
- Source: [fix-completions-on-comment.yml](../../.github/workflows/fix-completions-on-comment.yml)

The CLI includes snapshot-based tests for shell completions (bash, zsh, pwsh, etc.). When you add or modify CLI commands, these snapshots need to be updated. Comment `/completions` or `/fixcompletions` on the PR and the GitHub Action will:

1. Build the repository
2. Run the completion tests
3. Update the verified snapshot files
4. Commit the changes directly to the PR branch

This is useful when you've added new commands or options and the completion snapshot tests are failing.

See also: [Snapshot-based testing documentation](snapshot-based-testing.md)

### `/backport to <branch>`

- Workflow: [Backport PR to branch](https://github.com/dotnet/sdk/actions/workflows/backport.yml)
- Source: [backport.yml](../../.github/workflows/backport.yml)

Comment `/backport to <branch>` on a merged PR to create a new pull request that cherry-picks the changes onto the target branch. The backport PR will be labeled with `backport` and will CC the original PR participants.

### `/ba-g <reason>` - Bypass Build Analysis

Comment `/ba-g <reason>` on a PR to unconditionally turn the Build Analysis check green. The reason
is captured by telemetry and should be descriptive - avoid non-specific justifications like
"unrelated issues". This is useful when CI failures are caused by known flaky tests or
infrastructure issues unrelated to the PR.

Example reasons:

- `/ba-g deadletter` - Helix work item crashed with "DeadLetter" status.
- `/ba-g insufficient info in logs` - No good unique pattern in the logs to open a known issue.
- `/ba-g recently fixed known issue #<number>` - The known issue fix was already merged, but CI ran
  before it.
- `/ba-g failures are from known issues #<number1>, #<number2>` - All failures have known issues
  filed, but Build Analysis isn't turning green.

For details on triaging CI failures and filing known issues, see the [runtime failure analysis
documentation](https://github.com/dotnet/runtime/blob/main/docs/workflow/ci/failure-analysis.md).
The [Build Analysis Known Issue Helper](https://helix.dot.net/BuildAnalysis/CreateKnownIssues) can
assist in creating known issue reports with the correct labels and JSON format.

## Adding a Command

The dotnet CLI supports several models for adding new commands:

1. In the CLI itself via `dotnet.dll`.
2. Through a [.NET Core Global Tool](https://docs.microsoft.com/en-us/dotnet/core/tools/global-tools).
3. Through MSBuild tasks & targets in a NuGet package.
4. Through executables prefixed with `dotnet-` on the `PATH`.

### Commands in dotnet.dll

Developers are generally encouraged to avoid adding commands to `dotnet.dll` or the CLI installer directly. This is appropriate for very general commands such as `restore`, `build`, `publish`, `test`, and `clean`, but is generally too broad of a distribution mechanism for new commands.

Create an issue and engage the repository maintainers if you feel there is a missing core command that you would like to add.

### .NET Core Global Tools

A [.NET Core Global Tool](https://docs.microsoft.com/en-us/dotnet/core/tools/global-tools) can be used to install a `dotnet-` prefixed tool to the `PATH`.

The CLI will then treat the remainder of the tool name as a `dotnet` command.  For example, a tool with the name `dotnet-hello` could be executed by `dotnet hello`.

### MSBuild tasks & targets

NuGet allows adding tasks and targets to a project through a NuGet package.  Extending the CLI through this model has several advantages:

1. Targets have access to the MSBuild Project Context, allowing them to reason about the files and properties being used to build a particular project.
2. Targets are not CLI-specific, making them easy to share across command-line and IDE environments

Commands added as targets can be invoked once the target project adds a reference to the containing NuGet package and restores.

Targets are invoked by calling `dotnet msbuild /t:{TargetName}`

### Commands on the PATH

The dotnet CLI considers any executable on the path named `dotnet-{commandName}` to be a command it can call out to.

---

### Documentation Project Docs External Component Telemetry (`documentation/project-docs/external-component-telemetry.md`)

# Responsibly managing telemetry in external components

Many components are _delivered_ with or by the .NET SDK but want to collect and
manage telemetry. The SDK has telemetry collection mechanisms that may appear
attractive, but present down-sides for these authors.

This document clarifies some guidelines for authors of components that are consumed by the .NET SDK but want to own their own telemetry.

## Sending telemetry

### DO create and manage your own MSBuild Task for sending telemetry

This allows you to have full control over the telemetry you send, where it is
sent, and any PII masking requirements that are unique to your product.
Attempting to use the .NET SDK's `AllowEmptyTelemetry` mechanism is not
recommended for most internal partners and all external users. This is because
`AllowEmptyTelemetry`
  * is allow-listed for known events only, so your telemetry will not be sent
  * sends to the SDK's telemetry storage, which your team may not have access to
  * is dependent on the SDK version the user uses, which may lag behind the latest available

### DO NOT use the MSBuild Engine telemetry APIs for logging telemetry

These APIs, while convenient, require the MSBuild Engine Host (`dotnet build`,
`msbuild.exe`, Visual Studio Project system) to have configured a telemetry
collector. This is not guaranteed to be the case for all users of your component,
and the collector configured may not send telemetry in the manner you expect, or
to destinations you expect.

## Managing telemetry

### DO adhere to the SDK telemetry opt-out

The SDK has an [opt out](https://learn.microsoft.com/dotnet/core/tools/telemetry#how-to-opt-out) mechanism for telemetry that all SDK-generated
telemetry should adhere to. When running in the context of the SDK that means your
telemetry should adhere to this signal as well. This opt-out mechanism is an
environment variable, but the default value of this variable changes for
Microsoft-authored and source-built SDKs. The SDK should provide a unified
mechanism for tooling authors to rely on instead of probing for this value.

---

### Documentation Project Docs Issue Filing Guide (`documentation/project-docs/issue-filing-guide.md`)

Filing issues for .NET Core CLI
===============================

As you may notice based on our issues page, the CLI repo is what is known as a 
"high-profile" and "high-volume" repo; we 
get a lot of issues. This, in turn, may mean that some issues get 
lost in the noise and/or are not reacted on with the needed speed. 

In order to help with the above situation, we need to have a certain way to file 
issues so that the core team of maintainers can react as fast as 
possible and can triage effectively. 

The below steps are something that we believe is not a huge increase in process, 
but would help us react much faster to any issues that are filed. 

1. Check if the [known issues](https://github.com/dotnet/core/blob/main/release-notes/2.0/2.0.0-known-issues.md) cover the issue you are running 
into. We are collecting issues that are known and that have workarounds, so it 
could be that you can get unblocked pretty easily. 

4. /cc the person that the issue should be assigned to (or @blackdwarf) so that person 
would get notified. In this way the correct person can immediately jump on the 
issue and triage it.

5. For bugs, be as concrete as possible on what is working, what 
is not working. Things like operating system, the version of the tools, the 
version of the installer and when you installed all help us determine the 
potential problem and allows us to easily reproduce the problem at hand.

6. For enhancements be as concrete as possible on what is the addition 
you would like to see, what scenario it covers and especially why the current 
tools cannot satisfy that scenario. 

Thanks and happy filing! :)

## Providing the repro for bugs
For bugs, what we need more than anything is a good repro of the defective 
behavior. We would like to go towards the "clone, run, repro" model. In short:

1. If you find a bug, package up a repro in a git repo somewhere (GitHub is 
usually a good place :)). 
2. Inside the issue, specify what needs to be done (steps) to get an accurate 
repro of the bug. Ideally, this should be "here is how to build, these are the 
commands you run from the dotnet tools".
3. We use the above to get the repro, investigate and fix!

---

### Documentation Project Docs Pr Test Filtering (`documentation/project-docs/pr-test-filtering.md`)

# PR Test Filtering

Not all tests need to run on every PR. This document describes the framework for
conditionally running tests based on what changes in a pull request — skipping expensive
or unrelated test suites when the source paths they cover have not changed, while always
running the full suite on CI builds (e.g. `main`, release branches).

## Motivation

The dotnet/sdk repository is consistently one of the top consumers of Helix compute
resources — typically second only to dotnet/runtime. A single PR validation run consumes
on the order of **2,000 minutes of Helix compute** across all platforms and test legs.
This has real consequences:

- **Cost**: The cumulative Helix compute consumed by SDK builds is substantial. Every PR
  build runs the full test suite across multiple platforms (Windows x64, Linux x64,
  macOS arm64, .NET Framework), and each minute of unnecessary test execution adds up.
- **Queue pressure**: Helix compute capacity is finite and shared across the .NET
  organization. There are frequent periods where agent availability is constrained and
  queue times become significant. When SDK PRs occupy agents running tests that are
  irrelevant to the change, jobs across the organization wait longer to start.
- **PR velocity**: Even when agents are available, running all tests unconditionally means
  PRs take longer to validate than necessary, slowing down the development loop.

Conditionally running tests based on what changed in a PR is an effective mechanism to
reduce compute consumption. However, there is no single "smoking gun" test suite whose
removal would drastically change the picture. Instead, the gains come from collectively
applying conditional filtering across many areas. Some of the initial candidates include:

- Filtering **TemplateEngine** tests saves on the order of **40 minutes** per PR.
- Filtering **NetAnalyzers** tests saves on the order of **160 minutes** per PR.
- Filtering **dotnet-watch** tests saves on the order of **120 minutes** per PR.
- Filtering **ILLink** tests saves on the order of **100 minutes** per PR.
- Filtering **ApiCompat/ApiDiff** tests saves on the order of **30 minutes** per PR.

Even these five scopes together represent only ~22% of the total 2,000-minute budget.
Meaningful overall reduction requires applying this pattern broadly across many test
areas — but each scope added compounds the savings and frees capacity for the rest of
the organization.

The goal is to define scopes covering a minimum of one-third to one-half of total PR test time.
Beyond that, additional scopes are a return-on-investment decision — if a scope is
straightforward to define with reliable trigger paths, it should be added; if it
requires complex dependency analysis or invasive refactoring, the effort may not be
justified.

Longer-term, better solutions may emerge — for example, AI-based test selection
(as offered by CloudTest), or improved incremental build support that avoids rebuilding
and rerunning test assemblies whose inputs have not changed. These would provide a
better experience but are aspirational today. PR velocity is the primary driver to
address this now, and this manual, declarative approach is the pragmatic solution
available to do so.

## Filtering mechanisms

There are several levels at which tests can be conditionally excluded:

### Project-level filtering

Entire test projects are excluded from Helix submission. This is the coarsest and
simplest mechanism — the `.csproj` is removed from the set of projects sent to Helix,
so none of its tests run. Best suited for subsystems that have their own dedicated test
project(s) (e.g. TemplateEngine tests).

### Class-level filtering (future)

Individual test classes are excluded via `[TestCategory]` attributes and MSTest filter
expressions. The test project still runs on Helix, but specific classes are skipped.
This is useful when expensive tests live in a shared test assembly alongside cheaper
tests. Not yet implemented.

### Method-level filtering (future)

Similar to class-level but targeting individual test methods. Likely too granular to be
practical in most cases. Not yet implemented.

## Current implementation

The framework currently supports **project-level filtering** with a **RunAlways=CI**
condition. The definitive source of truth for what scopes exist and how they are
configured is:

> **[`test/ConditionalTests.props`](../../test/ConditionalTests.props)**

Refer to that file for the list of active scopes, their trigger paths, and which test
projects they control.

### How it works

1. **`test/ConditionalTests.props`** — MSBuild props file that defines
   `ConditionalTestScope` items and a `GlobalTriggerPaths` property.

   Each **conditional test scope** specifies:
   - `Mechanism`: how tests are excluded (currently only `project` is supported)
   - `TestProjects`: the test `.csproj` file(s) controlled by this scope
   - `TriggerPaths`: glob patterns for source/test paths that activate this scope
   - `RunAlways`: conditions under which the scope always runs regardless of changed
     files. The only supported value today is `CI` (non-PR builds). Flowed-in package
     dependencies are handled globally: `eng/Version.Details.xml` is a `GlobalTriggerPaths`
     entry, so any dependency update forces all scopes to run — see
     [Handling flowed-in dependencies](#handling-flowed-in-dependencies).

   **Global trigger paths** are an escape mechanism: if any changed file matches a
   `GlobalTriggerPaths` pattern, all scopes are forced active and no tests are filtered.
   Use this for shared infrastructure that all code/tests depend on (e.g. the shared test
   framework assemblies).

2. **`scripts/EvaluateConditionalTestScopes.cs`** — C# script that runs before test
   submission. It reads `ConditionalTests.props`, computes the git diff against the
   target branch, and determines which scopes to skip. It outputs the
   `SkippedTestScopes` Azure DevOps pipeline variable. When more than one scope is
   skipped, the scope names are joined with `|` rather than `;`. Azure DevOps decodes
   `%3B` back to `;` when it parses the `##vso[task.setvariable]` command, so an escaped
   semicolon cannot survive, and a raw `;` would be split by MSBuild's `/p:` property-list
   parser when the pipeline passes `/p:SkippedTestScopes=<value>`. `ConditionalTests.targets`
   normalizes `|` back to `;`.

3. **`test/UnitTests.proj`** — imports `ConditionalTests.props` and defines a Target
   (`RemoveSkippedConditionalTestProjects`) that removes skipped test projects from
   the `SDKCustomTestProject` item group before Helix submission.

### Decision flow

```text
Is this a PR build?
├── No (CI) → RunAlways=CI → nothing skipped, all tests run
└── Yes (PR) →
    ├── Do changed files match any GlobalTriggerPaths? → Nothing skipped, all tests run
    └── No global match → For each scope:
        ├── Do changed files match any TriggerPaths? → Scope runs (not skipped)
        └── No match → Scope skipped, test projects excluded
```

### Safe defaults

- **Local development**: `SkippedTestScopes` is not set → no projects are
  removed → all tests run.
- **Git diff failure**: the script returns an empty changed-file list → no scopes
  are skipped (safe fallback).
- **Global trigger match**: shared infrastructure changed → variable is not set →
  all tests run.
- **Non-PR builds**: `RunAlways=CI` ensures no scopes are skipped on `main` / release
  branches.

### Use a scope for targeted local tests

Agents and contributors should use the same `TestProjects` mappings for local targeted
validation rather than maintaining a second area-to-project list. Expand a configured
scope into concrete project paths with:

```shell
./.dotnet/dotnet run scripts/EvaluateConditionalTestScopes.cs -- \
  --repo-root . \
  --list-test-projects TemplateEngine
```

The command writes one repo-relative `Targeted test project:` line for each project
matched by the scope's `TestProjects` globs. Run those projects individually so a
failure identifies the affected project. The
[`run-tests`](../../.github/skills/run-tests/SKILL.md) agent skill provides the
runner and fallback mappings for change areas that do not yet have a `ConditionalTestScope`.

If a changed file matches `GlobalTriggerPaths`, do not use an individual conditional
scope to claim complete coverage: PR validation deliberately runs all tests for those
shared changes.

## Adding a new scope

1. Add a `<ConditionalTestScope>` item in `test/ConditionalTests.props`.
2. Reconcile the fallback table in the
   [`run-tests`](../../.github/skills/run-tests/SKILL.md) agent skill. Remove an
   entry when the new scope now covers that area, or update it if test-project ownership
   changed. Do not copy configured mappings into the fallback table.
3. The evaluation script and `UnitTests.proj` are generic and require no per-scope
   changes.

Example:

```xml
<ConditionalTestScope Include="MyFeature">
  <Mechanism>project</Mechanism>
  <TestProjects>MyFeature.Tests\MyFeature.Tests.csproj</TestProjects>
  <TriggerPaths>
    src/MyFeature/**;
    test/MyFeature.Tests/**
  </TriggerPaths>
  <RunAlways>CI</RunAlways>
</ConditionalTestScope>
```

### Choosing trigger paths

Trigger paths are not simply "the folder containing the feature's source code." When
defining a scope, consider whether changes to **dependencies** of that feature should
also trigger its tests. For example:

- If `dotnet-watch` has a `ProjectReference` to `Microsoft.DotNet.Cli.Definitions`, a
  change to that project could break watch behavior — so the watch scope's trigger paths
  should include both `src/Dotnet.Watch/**` and
  `src/Cli/Microsoft.DotNet.Cli.Definitions/**`.
- Shared infrastructure or utility projects that multiple features depend on may need to
  appear in multiple scopes' trigger paths.
- Test assets (e.g. `test/TestAssets/TestProjects/`, `test/TestAssets/TestPackages/`)
  that a test suite consumes at runtime should also be included. These are easy to
  overlook because they are not referenced via `ProjectReference` — they are looked up
  by name at test runtime via `TestAssetsManager.CopyTestAsset("AssetName")`. A change
  to a test asset can silently break tests even when no source file in the scope's
  `TriggerPaths` has changed.

  **How to find them**: search the test files for string literals passed to
  `CopyTestAsset`, `GetTestAsset`, or similar helpers. Any asset name found in
  `test/TestAssets/TestProjects/` or `test/TestAssets/TestPackages/` that is unique to
  (or primarily used by) this test suite should be added as an explicit trigger path
  (e.g. `test/TestAssets/TestProjects/MyAsset/**`). For broadly shared assets
  used across dozens of unrelated test suites (e.g. `HelloWorld`), use judgment
  — whether to include them is a trade-off between trigger precision and the risk
  that a shared asset change breaks this suite without activating any other scope
  that would otherwise catch the regression.

**Runtime behavior vs. compile-time dependencies**: not all dependencies need to be in
trigger paths. Ask whether a change to that dependency could cause a test to silently
*pass when it should fail*. If yes, it is a runtime behavior dependency and belongs in
`TriggerPaths`. If a change would instead cause a *compilation failure* (e.g. a shared
constants file, a resx, a helper primarily used for test parameterization such as `[DynamicData]`),
it is a compile-time dependency and does not need to be listed — the build will fail
loudly before any tests run, making the gap immediately visible.

Use judgment here. If a feature has complex or far-reaching dependencies that make it
difficult to define a reliable set of trigger paths, it may not be a good candidate for
conditional filtering — it is better to run tests unconditionally than to skip them when
a dependency change would have caused a failure.

#### Handling flowed-in dependencies

Some scopes build against packages that arrive through dependency flow (Roslyn, the
runtime, MSTest, etc.) rather than source in this repo. Every dependency update — whether
a VMR flow (`dotnet/dotnet`) or an external one such as `microsoft/testfx` — rewrites
`eng/Version.Details.xml`.

Rather than asking each scope to add that file to its own trigger paths, it is a
**`GlobalTriggerPaths`** entry: any change to `eng/Version.Details.xml` forces **all**
scopes to run. This is intentional and errs on the side of caution:

- A VMR flow bumps the compiler, runtime, and other packages that essentially every test
  area depends on — a genuinely repo-wide change worth validating broadly.
- Making it global is safe-by-default: new scopes are covered automatically, with no risk
  of an author forgetting to opt in and silently skipping tests a dependency bump could break.

The trade-off is that dependency-flow PRs get no filtering savings, but those are a
minority of PRs and exactly the ones where full validation is most valuable. If this proves
too coarse, it can be tuned later — see [Future enhancements](#future-enhancements).

## Design principles

- **Single source of truth**: `test/ConditionalTests.props` defines everything about a
  scope — trigger paths, projects, and conditions. The
  [`run-tests`](../../.github/skills/run-tests/SKILL.md) skill reads these mappings
  directly; its separate fallback table contains only common unscoped areas and must be
  reconciled when scopes or test-project ownership change.
- **Safe by default**: when in doubt, tests run. The system only skips tests when it has
  positive evidence that no relevant files changed.
- **No extra build legs**: filtering happens within the existing build/test pipeline.
  Projects are excluded from Helix submission but the build leg itself is unchanged,
  avoiding the compute cost of building everything twice.
- **Generic infrastructure**: `UnitTests.proj` and the evaluation script have no
  knowledge of specific scopes. All scope-specific configuration lives in the props file.

## Future enhancements

- **Per-repo dependency conditions**: `eng/Version.Details.xml` is a global trigger path, so
  *every* dependency update runs the full suite, even flows from a repo a given scope doesn't
  depend on. A finer-grained `RunAlways=Dependency:<owner>/<repo>` condition could force only the
  scopes that depend on the repo whose dependency actually changed. Identifying which repo a change
  came from is the hard part, and there are a couple of possible implementations — inspecting the
  `eng/Version.Details.xml` diff to see which dependencies changed, or detecting that the PR itself
  is a dependency flow (e.g. from its author/branch/body) and which repo it flows from. Both are
  non-trivial and somewhat fragile. This was explored but **intentionally not adopted**: there is no
  return on investment today. Only two dependency flows exist (the VMR and `microsoft/testfx`), and
  running the full suite on either is desirable anyway — a VMR flow is a large, wide-reaching change,
  and a testfx flow updates the test infrastructure itself. The machinery to distinguish them adds
  meaningful complexity for savings that, at present, do not materialize. If additional, more
  isolated dependency flows appear where broadly running tests is genuinely wasteful, revisiting a
  per-repo condition (and narrowing the global trigger) would make sense.
- **Force all tests from a PR**: Contributors may want to override conditional
  filtering and run the full test suite on a specific PR. If this proves desirable, one
  possible approach is a PR label (e.g. `run-all-tests`) that the pipeline checks before
  evaluating scopes. Locally, all tests run by default, and manually queued CI runs can
  override the `SkippedTestScopes` pipeline variable.

---

### Documentation Project Docs Repro Helix Failure (`documentation/project-docs/repro-helix-failure.md`)

# Repro Helix Failure

## General

Most test failures on helix should repro locally. Try following the [developer-guide](developer-guide.md) _Run tests from the command line_ section first.

## Repro test as tool layout

Running tests on Helix reuses the "test as tool" infrastructure. All tests projects are published  as tools that accept xunit command line arguments. The SDK under test, the published test project, and other dependencies are copied to a helix machine. This step changes the repo structure. Most of the helix-only failures are caused by tests depending on the repo structure or having dependencies that are not carried by the test project publishing step. The following steps help you to repro the test layout that is used on the helix machine. And you can run the individual test to discover the cause.

### repro the test layout as in the helix machine

```cmd
REM fully build first
.\build.cmd

REM use build env to have stage 0 dotnet on the PATH
.\artifacts\sdk-build-env.bat

REM run the special test target CreateLocalHelixTestLayout. To have the test layout created on disk.
dotnet msbuild /restore /t:CreateLocalHelixTestLayout .\test\UnitTests.proj /p:creator=dotnetsdkdev  /p:CustomHelixTargetQueue=Windows.Server.Amd64.VS2019.Pre.Open /bl
```

Copy the result of `artifacts\bin\localHelixTestLayout` to another directory or VM. For example to `C:\helix\localHelixTestLayout`. See "Folders under localHelixTestLayout" for the content. This is _correlation_ payload in helix term.

Publish the test project you want to repro. For example Microsoft.NET.Build.Tests.

```cmd
dotnet publish test\Microsoft.NET.Build.Tests\
```

The output is in `artifacts\bin\Tests\Microsoft.NET.Build.Tests\Debug\publish`. Copy this folder to another directory or VM. For example `C:\helix\payload-dir`. This is the "workitem payload" in helix term.

On the other machine or directory

```cmd
cd C:\helix\payload-dir

REM HELIX_CORRELATION_PAYLOAD would be set to correlation payload by real helix machine
set HELIX_CORRELATION_PAYLOAD=C:\helix\localHelixTestLayout

REM "true" is full framework test. Without "true", it is dotnet core tests. RunTestsOnHelix.cmd is the same script will setup the helix environment.
C:\helix\localHelixTestLayout\t\RunTestsOnHelix.cmd true
```

Example of running a specific method. "Microsoft.NET.Build.Tests.dll" need to match the test project target output dll.

```cmd
dotnet Microsoft.NET.Build.Tests.dll -testExecutionDirectory %TestExecutionDirectory% -msbuildAdditionalSdkResolverFolder %HELIX_CORRELATION_PAYLOAD%\r -html testResults.html -method "Microsoft.NET.Build.Tests.GivenThatWeWantToBuildADesktopExeWithFSharp.It_builds_a_simple_net50_app"
```

## Folders under localHelixTestLayout

Due to Helix long path problem. The folders under localHelixTestLayout all have one letter name.

- d - stage 2 dotnet
- ex - msbuildExtensions
- r - Microsoft.DotNet.MSBuildSdkResolver
- t - other loose file needed to recreate the environment like global.json and eng folder (used to find VS or xcopy msbuild), NuGet.config, RunTestsOnHelix.cmd (used to set up environment variable on helix).

## Other possible cause of Helix-only failure

- Helix machine does not have the same pre-installed dependencies as the host machine. Ideally the dependencies should be declared by the SDK repo itself. At the time the document is written. The build queue and the helix queue should have the same Visual Studio version. If they are diverged, we should contact arcade team.

- New test environment variable introduced has not been reflected in RunTestsOnHelix.cmd.

- To test out changes to the Helix tasks, you can run the unit test project directly: `dotnet -t:Test .\test\UnitTests.proj /p:CustomHelixTargetQueue=foo /bl` It won't be able to push the files into helix but it will let you view what helix work items are getting created.

---

### Documentation Project Docs Snapshot Based Testing (`documentation/project-docs/snapshot-based-testing.md`)

# Guide to snapshot-based testing in the .NET SDK

Snapshot-based testing is a technique used in the .NET SDK to ensure that the command-line interface (CLI) behaves as expected. This document provides an overview of how snapshot-based testing works, particularly for CLI completions, and how to manage and update snapshots.

## CLI Completions Snapshot Testing

The point of the tests is to keep an eye on the CLI, since it is our user interface. When the CLI changes in a way that impacts completions (new commands, options, defaults) we need to inspect and reconcile the baselines. Most of this happens in the [dotnet.Tests][dotnet.Tests] project, in the [Microsoft.DotNet.Cli.Completions.Tests.DotnetCliSnapshotTests][snapshot-tests] tests.

These tests use [Verify][Verify] to perform snapshot testing - storing the results of a known good 'baseline' as a snapshot and comparing the output of the same action performed with changes in your PR. Verify calls these baselines 'verified' files. When the test computes a new snapshot for comparison, this is called a 'received' file. Verify compares the 'verified' file to the 'received' file for each test, and if they are not the same provides a git-diff in the console output for the test.

To fix these tests, you need to diff the two files and visually inspect the changes. If the changes to the 'received' file are what you want to see (new commands, new options, renames, etc) then you rename the 'received' file to 'verified' and commit that change to the 'verified' file. There are two MSBuild Targets on the dotnet.Tests project that you can use to help you do this, both of which are intended to be run after you run the snapshot tests locally:

* [CompareCliSnapshots][compare] - this Target copies the .received. files from the artifacts directory, where they are created due to the way we run tests, to the [snapshots][snapshots] directory in the dotnet.Tests project. This makes it much easier to diff the two.
* [UpdateCliSnapshots][update] - this Target renames the .received. files to .verified. in the local [snapshots][snapshots] directory, and so acts as a giant 'I accept these changes' button. Only use this if you've diffed the snapshots and are sure they match your expectations.

### Automated Snapshot Updates via GitHub Actions

If you've modified CLI commands in a pull request and the completion snapshot tests are failing, but you don't want to clone the branch locally to update the snapshots, you can use the automated GitHub Action:

**Comment `/fixcompletions` on your pull request** and the workflow will:
1. Build the repository
2. Run the completion tests to generate new snapshots
3. Run the `CompareCliSnapshots` and `UpdateCliSnapshots` targets
4. Commit the updated verified snapshot files directly to your PR branch

This is particularly useful when you've added new commands, options, or modified existing CLI functionality.

[dotnet.Tests]: ../../test/dotnet.Tests/
[snapshot-tests]: ../../test/dotnet.Tests/CompletionTests/DotnetCliSnapshotTests.cs
[snapshots]: ../../test/dotnet.Tests/CompletionTests/snapshots/
[Verify]: https://github.com/VerifyTests/Verify
[compare]: ../../test/dotnet.Tests/dotnet.Tests.csproj#L100
[update]: ../../test/dotnet.Tests/dotnet.Tests.csproj#L107

---

### Documentation Project Docs Telemetry (`documentation/project-docs/telemetry.md`)

# .NET SDK Telemetry Documentation

## Table of Contents

- [.NET SDK Telemetry Documentation](#net-sdk-telemetry-documentation)
  - [Table of Contents](#table-of-contents)
  - [How to Control Telemetry](#how-to-control-telemetry)
  - [CLI Activity Duration Metrics](#cli-activity-duration-metrics)
  - [Common Properties Collected](#common-properties-collected)
    - [Copilot session correlation](#copilot-session-correlation)
  - [Telemetry Events](#telemetry-events)
    - [Core CLI Events](#core-cli-events)
    - [Test Events](#test-events)
    - [Template Engine Events](#template-engine-events)
    - [SDK-Collected Build Events](#sdk-collected-build-events)
    - [MSBuild Engine Telemetry](#msbuild-engine-telemetry)
    - [Container Events](#container-events)
    - [`dotnet new` Command MSBuild Evaluation](#dotnet-new-command-msbuild-evaluation)
  - [How to update this document](#how-to-update-this-document)

## How to Control Telemetry

### Disabling Telemetry

The .NET SDK telemetry can be disabled using the following environment variable:

- **`DOTNET_CLI_TELEMETRY_OPTOUT`**: Set to `1`, `true`, or `yes` to opt-out of telemetry collection
  - Example: `export DOTNET_CLI_TELEMETRY_OPTOUT=1` (Linux/macOS)
  - Example: `set DOTNET_CLI_TELEMETRY_OPTOUT=1` (Windows)
  - Note: this value is defaulted to `true` on non-Microsoft-provided builds of the .NET SDK (e.g. those provided by our Linux Distro partners, through Source Build, etc.)

### Related Environment Variables

- **`DOTNET_NOLOGO`**: Set to `true` to hide .NET welcome and telemetry messages on first run
  - Values: `true`, `1`, or `yes` to mute messages
  - Values: `false`, `0`, or `no` to allow messages
  - Default: `false` (messages are displayed)
  - Note: This flag does not affect telemetry collection itself
- **`DOTNET_CLI_TELEMETRY_SESSIONID`**: Seeds the initial telemetry session ID
  - When set, the CLI uses this value instead of generating a new GUID for the first `TelemetryClient` created in the process
  - This is useful for correlating multiple `dotnet` invocations that belong to the same CI workflow, job, or higher-level user session
  - If not set, the CLI generates a new GUID per process as before

- **`COPILOT_AGENT_SESSION_ID`**: Supplies the executing Copilot session ID for
  [`CopilotAgentSessionId`](#copilot-session-correlation). It does not replace the SDK's own session ID
  or enable telemetry.

- **`DOTNET_CLI_TELEMETRY_DISABLE_TRACE_EXPORT`**: Set to `1`, `true`, or `yes` to disable exporting trace
  telemetry to Azure Monitor (both persistence and upload). Metrics/OTLP export and the local disk log are
  unaffected. This does not disable telemetry collection itself — use `DOTNET_CLI_TELEMETRY_OPTOUT` for that.

- **`DOTNET_CLI_TELEMETRY_STORAGE_PATH`**: Overrides the base directory used by Azure Monitor to persist trace
  telemetry (see [Telemetry Delivery](#telemetry-delivery)). Defaults to `TelemetryStorageService` under the .NET
  user profile folder (e.g. `~/.dotnet/TelemetryStorageService`). Azure creates its own partitioned subdirectories.

- **`DOTNET_CLI_TELEMETRY_LOG_PATH`**: When set, trace telemetry activities are also written to this path as a
  local JSON log (used for diagnostics and testing). This does not affect Azure Monitor delivery.

### Telemetry Configuration

- **Default Behavior**:
  - For Microsoft official builds: Telemetry is **enabled by default** (opt-out model)
  - For non-Microsoft builds: Telemetry is **disabled by default** (controlled by `MICROSOFT_ENABLE_TELEMETRY` compile flag)

- **Connection String**: Telemetry data is sent to Application Insights with instrumentation key: `74cc1c9e-3e6e-4d05-b3fc-dde9101d0254`

### OpenTelemetry OTLP Exporter

In addition to the default Application Insights exporter, the SDK can also export telemetry via the [OpenTelemetry Protocol (OTLP)](https://opentelemetry.io/docs/specs/otel/protocol/exporter/). The OTLP exporter is enabled when either of the following conditions is met:

- The SDK-specific `DOTNET_CLI_TELEMETRY_ENABLE_EXPORTER` environment variable is set to `1`, `true`, or `yes`, **or**
- Any of the standard OpenTelemetry OTLP exporter environment variables are set:
  - `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`
  - `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL`, `OTEL_EXPORTER_OTLP_METRICS_PROTOCOL`
  - `OTEL_EXPORTER_OTLP_HEADERS`, `OTEL_EXPORTER_OTLP_TRACES_HEADERS`, `OTEL_EXPORTER_OTLP_METRICS_HEADERS`
  - `OTEL_EXPORTER_OTLP_TIMEOUT`, `OTEL_EXPORTER_OTLP_TRACES_TIMEOUT`, `OTEL_EXPORTER_OTLP_METRICS_TIMEOUT`

  and of course the overall OTel SDK disablement flag OTEL_SDK_DISABLED must not be `true`

When the OTLP exporter is enabled, all standard OpenTelemetry OTLP environment variables (endpoint, protocol, headers, timeout, etc.) are honored by the OpenTelemetry SDK's `OtlpExporterOptions` to configure the export destination.

### Telemetry Delivery

The CLI uses Azure Monitor OpenTelemetry Exporter 1.9.0 or later for trace serialization, persistent storage,
and delivery. [TelemetryClient](../../src/Cli/dotnet/Telemetry/TelemetryClient.cs) registers the exporter through
`AddAzureMonitorTraceExporter`, which installs Azure's shutdown-aware batch processor.

1. **Local invocations.** On orderly shutdown, Azure persists queued trace batches before starting a background
  drain. The SDK sets `Azure.Monitor.OpenTelemetry.Exporter.ShutdownDrainBudgetMilliseconds` to zero, so it does
  not wait for that drain on successful exits. When a command returns a nonzero exit code, the SDK temporarily
  sets the drain budget to 300 ms and calls trace-provider `Shutdown(300)`, giving persistence and background
  delivery a bounded opportunity to finish. This is a maximum requested wait, not a sleep or delivery guarantee.
  The previous drain setting is restored afterward; metrics retain their separate 10-ms shutdown allowance.
  Both managed and Native AOT entry points pass the actual command exit code. A managed fallback can therefore
  use a separate 300-ms trace allowance in each runtime; there is no cross-runtime deadline coordination.
  Normal exports before shutdown remain network-first; this is not synchronous
  persistence of every ended span, and abrupt termination can lose queued spans. An upload already in flight
  can still delay shutdown. Successful local shutdown gives the trace batch processor 100 ms to finalize
  persistence; the zero drain budget prevents waiting for the subsequent upload. This is long enough for a cold
  exporter to complete its atomic file write without reintroducing an unbounded exit delay. Failed-command
  persistence is subject to the 300-ms timeout.
2. **Subsequent invocations.** Azure schedules an eager background drain after a 50-ms startup delay; actual
  start time also depends on thread scheduling and storage work. The two-minute periodic retry timer remains.
  Accepted payloads are deleted; retryable failures remain for later attempts. Storage partitioning, retention,
  leases, and response handling belong to Azure. Blobs written directly into the storage root by the previous
  SDK-owned exporter are not migrated or automatically consumed by Azure's partitioned store. They are left
  untouched; this migration does not delete old telemetry files.

  Azure names each storage sub directory from the instrumentation key, user name, process name, and
  `AppContext.BaseDirectory`. The base directory differs between `dotnet.dll` and `dotnet-aot`, so without an
  override each entry point would drain only its own backlog. The SDK sets the
  `Azure.Monitor.OpenTelemetry.Exporter.StorageSubDirectory` AppContext value to `dotnet-cli` (see
  [Azure/azure-sdk-for-net#62997](https://github.com/Azure/azure-sdk-for-net/issues/62997)). Every entry point
  for a given user then shares one sub directory and drains telemetry that the others persisted.
3. **CI invocations.** The SDK sets `Azure.Monitor.OpenTelemetry.Exporter.DisablePersistOnShutdown` to true and
  calls `Shutdown` with a finite timeout because another invocation may never run. The default CI
  wait budget is five seconds, shared across trace and metric providers. A positive
  `DOTNET_CLI_TELEMETRY_SHUTDOWN_TIMEOUT_MS` can shorten or extend it. That value also configures Azure's
  network timeout. This selects network-first shutdown, not guaranteed ingestion: retryable failures can still
  be persisted, and a timeout can leave telemetry undelivered.
4. **Persistent MSBuild hosts.** A logger finishes a build request with nonterminal `ForceFlush`, allowing the
  same provider to handle later builds. Locally the SDK enables
  `Azure.Monitor.OpenTelemetry.Exporter.PersistOnForceFlush` and gives trace persistence 100 ms; process exit uses
  `Shutdown`. CI uses a bounded network-first flush. A force-flush result is not an ingestion acknowledgment.

These Azure settings are process-wide. OTLP-enabled invocations retain bounded provider shutdown, and the trace
and metric providers share the configured wait budget. This bounds provider waits, not all process-exit work. Azure's
zero drain-wait setting does not control OTLP delivery. Storage failures and abnormal process termination can
still cause data loss; telemetry delivery remains best-effort.

The lifecycle behavior is covered by
[AzureExporterLifecycleTests](../../test/Microsoft.DotNet.Cli.Telemetry.Tests/AzureExporterLifecycleTests.cs)
using the real exporter, isolated storage, and a controlled HTTP transport. The test-only reflection hooks
disable background drains when asserting persisted payloads and are restored after each test. The retained
[CLI subprocess test](../../test/dotnet.Tests/TelemetryTests/PersistentStorageTelemetryE2ETests.cs) checks the
production managed assembly and normal muxer entry point. Live endpoint acceptance tests are skipped unless
explicitly enabled. Set `DOTNET_CLI_TELEMETRY_E2E_ENABLED=true` (or `1`) to send synthetic telemetry to the SDK's
fixed destination, or set `DOTNET_CLI_TELEMETRY_E2E_CONNECTION_STRING` to opt in with another destination.
`DOTNET_CLI_TELEMETRY_E2E_RUN_ID` supplies a correlation ID for
checking downstream ingestion. HTTP acceptance alone does not verify arrival in a destination table.

1.9.0 or later must be leveraged, as older versions did not work well and we requested fixes. Our requested upstream shutdown fixes are documented in
[azure-sdk-for-net#61818](https://github.com/Azure/azure-sdk-for-net/pull/61818) and
[azure-sdk-for-net#62340](https://github.com/Azure/azure-sdk-for-net/pull/62340). They provide lifecycle-scoped
persistence rather than the public persist-only/manual-drain API proposed in
[azure-sdk-for-net#60838](https://github.com/Azure/azure-sdk-for-net/issues/60838).

This pipeline only applies to **trace** telemetry sent to Azure Monitor. Metrics, OTLP export, and the local disk
log are unaffected. Set `DOTNET_CLI_TELEMETRY_DISABLE_TRACE_EXPORT` to disable it.

- **First Time Use**: Telemetry is only collected after the first-time-use notice has been shown and accepted (tracked via sentinel file)

- **Event Namespace**: All telemetry events are automatically prefixed with `dotnet/cli/`

## CLI Activity Duration Metrics

Performance collectors such as PerfStar can opt into CLI phase timings by enabling
the `dotnet-cli-perf` meter. Built-in SDK telemetry and its OTLP exporter do not
enable this collection.

| Meter | Instrument | Unit | Tag |
| --- | --- | --- | --- |
| `dotnet-cli-perf` | `dotnet.cli.activity.duration` | `s` (seconds) | `activity.name` |

Each completed activity from either source (`dotnet-cli` or `dotnet-cli-perf`)
records its duration, tagged by operation name. To collect activity spans, subscribe to the relevant activity source. Skipped phases emit no activity; failed invocations still record their duration.

The `dotnet-cli-perf` source contains these activities:

| Activity | Measured work |
| --- | --- |
| `msbuild-submission` | Synchronous MSBuild invocation, including child/server wait time. For file-based projects, covers `BeginBuild` through `EndBuild`. |
| `release-property-discovery` | Project/solution discovery and `PackRelease` / `PublishRelease` evaluation to choose the default configuration. |
| `project-selection` | Run/test project loading, evaluation when needed, and project-instance creation, including cached snapshots. |
| `device-discovery` | Optional restore, `ComputeAvailableDevices` execution, and reading its results. |
| `test-project-discovery` | Microsoft.Testing.Platform (MTP) outer- and inner-framework project evaluation for automatic device selection. |
| `test-target-framework-discovery` | MTP framework evaluation when `--device` is given without a target framework. |
| `test-environment-discovery` | MTP environment-variable support checks and properties-file preparation before a project build. |

## Common Properties Collected

Every telemetry event automatically includes these common properties:

| Property | Description | Example Value |
|----------|-------------|---------------|
| **OS Version** | Operating system version | `Microsoft Windows 10.0.14393` |
| **OS Platform** | Operating system platform | `Windows`, `Linux`, `OSX` |
| **OS Architecture** | Operating system architecture | `X64`, `X86`, `Arm64` |
| **Output Redirected** | Whether console output is redirected | `True` or `False` |
| **Runtime Id** | .NET runtime identifier | `win10-x64`, `linux-x64` |
| **Product Version** | .NET SDK version | `8.0.100` |
| **Telemetry Profile** | Custom telemetry profile (if set via env var) | Custom value or null |
| **Docker Container** | Whether running in Docker container | `True` or `False` |
| **CI** | Whether running in CI environment | `True` or `False` |
| **LLM** | Detected LLM/assistant environment identifiers (comma-separated) | `claude`, `cursor`, `gemini`, `copilot`, `codex`, `aider`, `plandex`, `amp`, `qwen`, `droid`, `opencode`, `zed`, `kimi`, `openhands`, `goose`, `cline`, `roo`, `windsurf`, `generic_agent` |
| **Current Path Hash** | SHA256 hash of current directory path | Hashed value |
| **Machine ID** | SHA256 hash of machine MAC address (or GUID if unavailable) | Hashed value |
| **Machine ID Old** | Legacy machine ID for compatibility | Hashed value |
| **Device ID** | Device identifier | Device-specific ID |
| **Kernel Version** | OS kernel version | `Darwin 17.4.0`, `Linux 4.9.0` |
| **Installation Type** | How the SDK was installed | Installation method |
| **Product Type** | Type of .NET product | Product identifier |
| **Libc Release** | Libc release information | Libc release version |
| **Libc Version** | Libc version information | Libc version number |
| **SessionId** | Unique session identifier | GUID or CI-specific correlation identifier |
| **CopilotAgentSessionId** | Executing Copilot session ID, normalized to match Copilot telemetry, or `not_present` when unavailable | UUID, 64-character lowercase SHA-256 digest, or `not_present` |

### Copilot session correlation

`CopilotAgentSessionId` lets SDK telemetry be correlated with the executing Copilot
session. When telemetry is enabled, it reads `COPILOT_AGENT_SESSION_ID` and follows
[Copilot's normalization](https://github.com/github/copilot-agent-runtime/blob/1fc45d2c2a0a978ebbd068e0eec79715cf5dd417/src/native/primitives/crypto_helpers.rs#L23-L62):

| Environment value | Telemetry value |
| --- | --- |
| UUID recognized by Copilot | Original string, including letter case |
| Other nonempty value | SHA-256 of the original UTF-8 bytes, as lowercase hex; no trimming or case normalization |
| Missing or empty | `not_present` |

A missing telemetry field means collection support is unknown, including older SDKs.
`not_present` means no Copilot context was observed, not proof of a human invocation.
A literal `not_present` environment value is hashed. Context is captured before each
event is queued, including in reused MSBuild hosts. Existing telemetry opt-out settings
and the SDK's own `SessionId` are unchanged.

### Microsoft-internal user classification

When telemetry is enabled, the CLI asynchronously determines whether the current user is
internal to Microsoft and enriches trace activities with these tags:

| Tag | Description |
| --- | --- |
| `dotnet.cli.is_microsoft_internal` | `true` when a probe finds Microsoft-internal evidence. It is `false` when detection completes without that evidence. |
| `dotnet.cli.microsoft_internal_source` | The probe that found the evidence. Emitted only for a positive result. |
| `dotnet.cli.microsoft_internal_alias` | A normalized local account alias when local identity evidence supplies one. Emitted only for a positive result outside CI. |
| `dotnet.cli.microsoft_internal_domain` | A normalized corporate domain when local identity evidence supplies one. Emitted only for a positive result outside CI. |

The detector first uses local OS and account evidence. Outside CI, it can also use
existing GitHub CLI, Copilot CLI, or GitHub-token environment credentials to ask GitHub
whether the authenticated account is a member of the `microsoft` organization. Tokens
are sent only to GitHub's API for that check; they are not cached or added to telemetry.
GitHub logins are not used as telemetry aliases. GitHub identity probes are skipped in
CI, and alias and domain tags are suppressed in CI.

The implementation of this classification is isolated in the AOT-compatible
[`Microsoft.DotNet.Cli.InternalMicrosoft`](../../src/Cli/Microsoft.DotNet.Cli.InternalMicrosoft)
library. It does not reference OpenTelemetry or emit telemetry. Each detection mechanism
implements
[`IInternalMicrosoftDetectionProvider`](../../src/Cli/Microsoft.DotNet.Cli.InternalMicrosoft/Internal/InternalMicrosoftDetectionProvider.cs).
The detector filters providers by platform and CI support, groups them into ordered
stages, and owns orchestration, deadlines, result selection, and caching.

The CLI telemetry adapter maps the classification result to tags on normal CLI
activities. It does not emit separate detector-health activities.

Results are cached for six hours under
`~/.dotnet/internal-microsoft/detector.json` (relative to the configured .NET user
profile). The cache contains the classification, source, CI mode, and timestamp. Outside
CI, it can also contain an optional local alias and domain. The cache never contains
credentials. Failed or timed-out detection is not cached. Probe execution, diagnostics,
and shutdown waiting are bounded. Detection begins after telemetry-provider construction,
is not synchronously awaited during startup, and cannot indefinitely delay command
completion. See
[`InternalMicrosoftDetector`](../../src/Cli/Microsoft.DotNet.Cli.InternalMicrosoft/InternalMicrosoftDetector.cs)
and
[`InternalMicrosoftTelemetry`](../../src/Cli/dotnet/Telemetry/InternalMicrosoft/InternalMicrosoftTelemetry.cs)
for the separate detection and telemetry integration layers.

## Telemetry Events

### Core CLI Events

#### `command/finish`

**When fired**: At the end of every dotnet CLI command execution

**Properties**:

- `exitCode`: The exit code of the command

**Description**: Tracks the completion status of any dotnet command

---

#### `schema`

**When fired**: When CLI schema is generated or accessed

**Properties**:

- `command`: The command hierarchy as a string

**Description**: Tracks schema generation for the CLI

---

#### `toplevelparser/command`

**When fired**: For every top-level dotnet command

**Properties**:

- `verb`: Top-level command name (build, restore, publish, etc.)

**Measurements**: Performance data (startup time, parse time, etc.)

**Description**: Tracks usage patterns of main dotnet commands

---

#### `sublevelparser/command`

**When fired**: For subcommands and specific command options

**Properties**: Various depending on command (verbosity, configuration, framework, etc.)

**Description**: Tracks detailed command option usage

---

#### `commandresolution/commandresolved`

**When fired**: When a command is resolved through the command factory

**Properties**:

- `commandName`: SHA256 hash of command name
- `commandResolver`: Type of command resolver used

**Description**: Tracks how commands are resolved in the CLI

---

#### `install/reportsuccess`

**When fired**: When installation success is reported

**Properties**:

- `exeName`: Name of the install method that was used - one of `debianpackage`, a specific macOS `.pkg` file name, or a specific Windows exe installer file name.

**Description**: Tracks successful tool installations

---

#### `mainCatchException/exception`

**When fired**: When unhandled exceptions occur in the main CLI

**Properties**:

- `exceptionType`: Type of exception
- `detail`: Exception details (sensitive message removed)

**Description**: Tracks unhandled exceptions for diagnostics

### Test Events

#### `test/artifact-post-processing`

**When fired**: Once per `dotnet test` Microsoft.Testing.Platform run that planned at least one artifact post-processing job. Runs that plan nothing (no mergeable artifacts) emit nothing.

**Properties**:

- `jobs_planned`: Number of elected test-application relaunches planned
- `jobs_executed`: Number of jobs actually attempted (differs from `jobs_planned` only when the run was cancelled mid-way)
- `jobs_failed`: Number of jobs that reported a failure
- `artifact_count`: Total number of input artifacts across all planned groups
- `kinds`: Semicolon-separated, sorted, distinct artifact kinds that were merged; any kind outside a fixed well-known list is reported as `other`
- `extensions`: Semicolon-separated, sorted, distinct file extensions from file-extension fallback groups; any extension outside a fixed well-known list is reported as `other`
- `duration_ms`: Total wall-clock time spent post-processing, in milliseconds

**Description**: Tracks how often artifact post-processing runs and on which shipped formats. No file paths, artifact contents, project names, or user-defined identifiers are collected — that is why unknown kinds and extensions are bucketed as `other`.

### Template Engine Events

#### `template/new-install`

**When fired**: During template package installation

**Properties**:

- `CountOfThingsToInstall`: Number of template packages being installed

**Description**: Tracks template package installation operations

---

#### `template/new-create-template`

**When fired**: When creating a new project from template

**Properties**:

- `language`: Template language (C#, F#, VB, etc)
- `argument-error`: Whether there were argument errors ("True"/"False")
- `framework`: Framework choice (only sent for Microsoft-authored templates)
- `template-name`: SHA256 hash of template identity
- `template-short-name`: SHA256 hash of template short names
- `package-name`: SHA256 hash of package name
- `package-version`: SHA256 hash of package version
- `is-template-3rd-party`: Whether template is third-party
- `create-success`: Whether creation succeeded
- `auth`: Authentication choice (only sent for Microsoft-authored templates)

**Description**: Tracks template usage and creation success

### SDK-Collected Build Events

[`MSBuildLogger`](../../src/Cli/dotnet/Commands/MSBuild/MSBuildLogger.cs) collects the
existing events below. MSBuild loads the logger from the SDK. The logger can run in the
CLI process, a child MSBuild process, or a persistent MSBuild server.

The logger creates an internal activity for each build. When trace context is available,
the activity is a child of the invoking CLI trace. Server reuse changes telemetry delivery
and correlation only. It does not change the listed data points or properties.

The activity remains open through logger shutdown because MSBuild emits the final `build`
telemetry event after `BuildFinished` (see
[dotnet/sdk#55749](https://github.com/dotnet/sdk/issues/55749)).
`TelemetryHostMatrixTests` validates the real OTLP export path for cold and hot MSBuild
servers, in-process builds, server fallback, and telemetry opt-out. The test installs the
pinned Aspire CLI version from the repository's configured feeds, runs its dashboard on
loopback endpoints, and verifies exported events through the dashboard telemetry API.

#### `msbuild/roslyn/compilercache`

**When fired**: When the Roslyn [compiler output cache](https://github.com/dotnet/roslyn/blob/main/docs/compilers/Design/compiler-output-cache-experiment.md)
is enabled and a compilation runs on the compiler server through the MSBuild `Csc` or `Vbc` task

**Properties**:

- `cachestatus`: Cache lookup result: `hit` or `miss`
- `storeresult`: Cache store result: `none`, `stored`, `skippedrace`, `skippedexists`, or `failed`
- `language`: Compiler language: `C#` or `Visual Basic`
- `keycomputems`: Milliseconds spent computing the deterministic cache key
- `restorems`: Milliseconds spent attempting to restore a cached result
- `storems`: Milliseconds spent storing the result; omitted when no store was attempted
- `compilems`: Milliseconds spent compiling and emitting on a cache miss; omitted on a cache hit or when compilation failed

**Description**: Tracks the effectiveness and performance of the experimental Roslyn compiler output cache

---

#### `msbuild/targetframeworkeval`

**When fired**: When target framework is evaluated

**Properties**:

- `TargetFrameworkVersion`: Target framework version
- `RuntimeIdentifier`: Runtime identifier
- `SelfContained`: Whether self-contained
- `UseApphost`: Whether using app host
- `OutputType`: Output type (Exe, Library, etc.)
- `UseArtifactsOutput`: Whether using artifacts output
- `ArtifactsPathLocationType`: Artifacts path location type - one of `Explicitly Specified`, `DirectoryBuildPropsFolder`, or `ProjectFolder`.

**Description**: Tracks target framework configurations

---

#### `taskBaseCatchException`

**When fired**: When exceptions occur in SDK-provided MSBuild tasks

**Properties**:

- `exceptionType`: Exception type
- `detail`: Exception details (message removed)

**Description**: Tracks exceptions in MSBuild task execution

---

#### `PublishProperties`

**When fired**: During the Publish Target

**Properties**: Gathers the values of the following MSBuild Properties if they are set in the project file or via command line:

- PublishReadyToRun
- PublishSingleFile
- PublishTrimmed
- PublishAot
- PublishProtocol

**Description**: Tracks publish-related properties

---

#### `WorkloadPublishProperties`

**When fired**: During workload publish operations

**Properties**: Gathers the values of the following MSBuild Properties if they are set in the project file or via command line:

- TargetPlatformIdentifier: TargetPlatformIdentifier
- RuntimeIdentifier: RuntimeIdentifier
- BlazorWasm: _WorkloadUsesBlazorWasm
- WasmSDK: _WorkloadUsesWasmSDK
- UsesMaui: UseMaui
- UsesMobileSDKOnly: _WorkloadUsesMobileSDKOnly
- UsesOtherMobileSDK: _WorkloadUsesOther
- MonoAOT: _WorkloadUsesMonoAOT
- NativeAOT: _WorkloadUsesNativeAOT
- Interp: _WorkloadUsesInterpreter
- LibraryMode: _WorkloadUsesLibraryMode
- ResolvedRuntimePack: _MonoWorkloadRuntimePackPackageVersion
- StripILAfterAOT: _WorkloadUsesStripILAfterAOT

**Description**: Tracks workload-specific publish properties

---

#### `ReadyToRun`

**When fired**: During ReadyToRun compilation

**Properties**: Gathers the values of the following MSBuild Properties and Items if they are set in the project file or via command line:

- PublishReadyToRunUseCrossgen2: PublishReadyToRunUseCrossgen2
- Crossgen2PackVersion: ResolvedCrossgen2Pack.NuGetPackageVersion
- CompileListCount: _ReadyToRunCompileList->Count()
- FailedCount: _ReadyToRunCompilationFailures->Count()

**Description**: Tracks ReadyToRun compilation usage

---

### MSBuild Engine Telemetry

See [MSBuild Telemetry Documentation](https://github.com/dotnet/msbuild/blob/main/documentation/wiki/CollectedTelemetry.md) for details on these events.

### Container Events

See [Container Telemetry Documentation](https://github.com/dotnet/sdk-container-builds/blob/main/docs/Telemetry.md) for details.

### `dotnet new` Command MSBuild Evaluation

#### `new/msbuild-eval`

**When fired**: When MSBuild project evaluation occurs during `dotnet new`

**Properties** (hashed):

- `ProjectPath`: Project path
- `SdkStyleProject`: Whether it's SDK-style project
- `Status`: Evaluation status
- `TargetFrameworks`: Target frameworks

**Measurements**:

- `EvaluationTime`: Total evaluation time in milliseconds
- `InnerEvaluationTime`: Inner evaluation time in milliseconds

**Description**: Tracks MSBuild evaluation performance for new projects

## How to update this document

- Ensure that all telemetry events and properties are accurately documented
- Review and update common properties as needed
- Add new events or properties as they are introduced in the .NET SDK
- Follow the pre-existing format

---

### Documentation Specs ProcessFrameworkReferences Outputs (`documentation/specs/ProcessFrameworkReferences-outputs.md`)

# ProcessFrameworkReferences Task Output Specification

## Overview

The `ProcessFrameworkReferences` MSBuild task is responsible for resolving framework references and determining which NuGet packages need to be downloaded to support compilation and publishing scenarios. This task produces several output item groups that represent different types of packages required for the build.

## Output Item Groups

The task produces the following output collections:

- **`TargetingPacks`**: Reference assemblies used during compilation
- **`RuntimePacks`**: Runtime-specific implementations of framework libraries
- **`PackagesToDownload`**: Packages that need to be restored via direct PackageDownload mechanism
- **`RuntimeFrameworks`**: Framework dependencies to be written to runtimeconfig.json
- **`ImplicitPackageReferences`**: Build-time tool packages that need to be restored via PackageReference mechanism (ILLink, Crossgen2, ILCompiler)
- **`Crossgen2Packs`**: Ready-to-Run compilation tools
- **`HostILCompilerPacks`**: Native AOT compiler tools for the host platform
- **`TargetILCompilerPacks`**: Native AOT compiler tools for the target platform
- **`UnavailableRuntimePacks`**: Framework packs not available for the specified RID

## Expected Outputs by Scenario

### Base Scenario: Framework-Dependent Projects

For all projects that reference frameworks (via `<FrameworkReference>` items):

**Expected Outputs:**
- ✅ `TargetingPacks`: One entry per framework reference per target framework
  - Contains the targeting pack name and version
  - Used for compile-time reference resolution
- ✅ `RuntimeFrameworks`: One entry per framework reference per target framework
  - Written to runtimeconfig.json to specify runtime dependencies

**Example:**
```xml
<FrameworkReference Include="Microsoft.NETCore.App" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
```

Results in:
- `TargetingPacks`: `Microsoft.NETCore.App.Ref`, `Microsoft.AspNetCore.App.Ref`
- `RuntimeFrameworks`: `Microsoft.NETCore.App`, `Microsoft.AspNetCore.App`

---

### Scenario 1: Self-Contained Deployment (`SelfContained=true`, `PublishSelfContained=true`)

When `RuntimeIdentifier` is specified explicitly:

**Expected Outputs:**
- ✅ `TargetingPacks`: One per framework reference per TFM
- ✅ `RuntimePacks`: One per framework reference per TFM for the specified RID
  - Contains RID-specific runtime libraries
  - Example: `Microsoft.NETCore.App.Runtime.linux-x64`
- ✅ `PackagesToDownload`: Includes both targeting packs and runtime packs
- ✅ `RuntimeFrameworks`: One per framework reference per TFM

**Key Properties:**
```xml
<SelfContained>true</SelfContained>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
```

**Behavior:**
- Runtime packs are resolved for the primary `RuntimeIdentifier`
- RID-specific assets are included in the publish output

---

### Scenario 2: Self-Contained with multiple RuntimeIdentifiers (`RuntimeIdentifiers` property)

When multiple RIDs are specified via `RuntimeIdentifiers`:

**Expected Outputs:**
- ✅ `TargetingPacks`: One per framework reference per TFM
- ✅ `RuntimePacks`: 
  - For the primary RID (if `RuntimeIdentifier` is set): Full runtime pack metadata
  - For additional RIDs: Runtime packs are downloaded but not added to `RuntimePacks` output
- ✅ `PackagesToDownload`: Runtime packs for ALL RIDs in `RuntimeIdentifiers`
- ✅ `RuntimeFrameworks`: One per framework reference per TFM

**Key Properties:**
```xml
<SelfContained>true</SelfContained>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<RuntimeIdentifiers>linux-x64;linux-arm64;win-x64</RuntimeIdentifiers>
```

**Behavior:**
- All runtime packs for all RIDs are downloaded to support multi-RID publishing
- Only the primary RID's runtime packs appear in the `RuntimePacks` output for consumption

---

### Scenario 3: Ready-to-Run Compilation (`ReadyToRunEnabled=true`, `ReadyToRunUseCrossgen2=true`)

For projects using Ready-to-Run (R2R) compilation:

**Expected Outputs:**
- ✅ `TargetingPacks`: One per framework reference per TFM
- ✅ `RuntimePacks`: One per framework reference per TFM for the specified RID
- ✅ `Crossgen2Packs`: RID-specific Crossgen2 compiler for the host platform
  - Example: `Microsoft.NETCore.App.Crossgen2.linux-x64`
- ✅ `PackagesToDownload`: Includes targeting packs, runtime packs (if applicable), and Crossgen2 pack
- ✅ `RuntimeFrameworks`: One per framework reference per TFM

**Key Properties:**
```xml
<SelfContained>true</SelfContained>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<ReadyToRunEnabled>true</ReadyToRunEnabled>
<ReadyToRunUseCrossgen2>true</ReadyToRunUseCrossgen2>
```

**Behavior:**
- Crossgen2 pack is resolved based on the SDK's runtime identifier (host RID)
- Enables ahead-of-time compilation of IL to native code for faster startup

---

### Scenario 4: Publish with Trimming (`PublishTrimmed=true`, `RequiresILLinkPack=true`)

For projects that trim unused code during publish:

**Expected Outputs:**
- ✅ `TargetingPacks`: One per framework reference per TFM
- ✅ `RuntimePacks`: One per framework reference per TFM for the specified RID
  - **Required even when `SelfContained=false`** because trimming requires RID-specific analysis
- ✅ `ImplicitPackageReferences`: `Microsoft.NET.ILLink.Tasks`
  - Contains MSBuild targets and tasks for trimming
- ✅ `PackagesToDownload`: Includes targeting packs, runtime packs, and ILLink pack
- ✅ `RuntimeFrameworks`: One per framework reference per TFM

**Key Properties:**
```xml
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<PublishTrimmed>true</PublishTrimmed>
<RequiresILLinkPack>true</RequiresILLinkPack>
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
```

**Behavior:**
- Runtime packs are required for trimming analysis even in framework-dependent deployments
- ILLink pack provides the trimming engine and MSBuild integration
- For .NET 6+, trim analyzer warnings are enabled by default

---

### Scenario 5: Trim and AOT Analysis Support (`IsTrimmable=true`, `EnableTrimAnalyzer=true`, `IsAotCompatible=true`, `EnableAotAnalyzer=true`)

For libraries that want to support trimming and AOT:

**Expected Outputs:**
- ✅ `TargetingPacks`: One per framework reference per TFM
- ✅ `ImplicitPackageReferences`: `Microsoft.NET.ILLink.Tasks`
  - Provides analyzers for trim and AOT compatibility
- ✅ `PackagesToDownload`: Includes targeting packs and ILLink pack
- ✅ `RuntimeFrameworks`: One per framework reference per TFM

**Key Properties:**
```xml
<IsTrimmable>true</IsTrimmable>
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
<IsAotCompatible>true</IsAotCompatible>
<EnableAotAnalyzer>true</EnableAotAnalyzer>
<RequiresILLinkPack>true</RequiresILLinkPack>
```

**Behavior:**
- No RID specified, so no runtime packs are downloaded
- ILLink pack provides compile-time analyzers for library authors
- Warnings/errors guide developers to make code trim/AOT-compatible

---

### Scenario 6: Native AOT Publishing (`PublishAot=true`)

For projects using Native AOT compilation:

**Expected Outputs:**
- ✅ `TargetingPacks`: One per framework reference per TFM
- ✅ `RuntimePacks`: One per framework reference per TFM for the specified RID
  - **Required even when `SelfContained=false`** because AOT requires RID-specific compilation
- ✅ `HostILCompilerPacks`: ILCompiler pack for the host/SDK RID
  - Example: `runtime.linux-x64.Microsoft.DotNet.ILCompiler`
  - Used to run the AOT compiler
- ✅ `TargetILCompilerPacks`: ILCompiler pack for the target RID (if different from host)
  - Example: `runtime.linux-arm64.Microsoft.DotNet.ILCompiler`
  - Contains target-specific compilation assets
- ✅ `ImplicitPackageReferences`: `Microsoft.NET.ILLink.Tasks`
  - ILLink is used as part of the AOT compilation pipeline
- ✅ `PackagesToDownload`: Includes targeting packs, runtime packs, and ILCompiler packs
- ✅ `RuntimeFrameworks`: One per framework reference per TFM

**Key Properties:**
```xml
<RuntimeIdentifier>linux-arm64</RuntimeIdentifier>
<PublishAot>true</PublishAot>
<RequiresILLinkPack>true</RequiresILLinkPack>
```

**Behavior:**
- Runtime packs are required for AOT compilation regardless of `SelfContained` setting
- Host ILCompiler pack must match the SDK's RID to run the compiler
- Target ILCompiler pack must match the `RuntimeIdentifier` for cross-compilation scenarios
- Native AOT produces a single native executable with no runtime dependencies

---

### Scenario 7: Combined Scenarios

Projects can combine multiple publish features:

#### Self-Contained + Ready-to-Run + Trimming

**Key Properties:**
```xml
<SelfContained>true</SelfContained>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<ReadyToRunEnabled>true</ReadyToRunEnabled>
<ReadyToRunUseCrossgen2>true</ReadyToRunUseCrossgen2>
<PublishTrimmed>true</PublishTrimmed>
<RequiresILLinkPack>true</RequiresILLinkPack>
```

**Expected Outputs:**
- ✅ `TargetingPacks`
- ✅ `RuntimePacks` (for the specified RID)
- ✅ `Crossgen2Packs` (for R2R compilation)
- ✅ `ImplicitPackageReferences` (ILLink for trimming)
- ✅ `PackagesToDownload` (all of the above)

#### Multi-RID + Ready-to-Run + Trimming

**Key Properties:**
```xml
<SelfContained>true</SelfContained>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<RuntimeIdentifiers>linux-x64;linux-arm64;win-x64</RuntimeIdentifiers>
<ReadyToRunEnabled>true</ReadyToRunEnabled>
<ReadyToRunUseCrossgen2>true</ReadyToRunUseCrossgen2>
<PublishTrimmed>true</PublishTrimmed>
<RequiresILLinkPack>true</RequiresILLinkPack>
```

**Expected Outputs:**
- ✅ `TargetingPacks`
- ✅ `RuntimePacks` (for the primary RID only)
- ✅ `Crossgen2Packs` (for the host RID)
- ✅ `ImplicitPackageReferences` (ILLink for trimming)
- ✅ `PackagesToDownload` (runtime packs for ALL RIDs, plus Crossgen2 and ILLink)

---

## Current Issues and Expected Fixes

### Issue #51667: Runtime Packs Not Resolved for PublishTrimmed/PublishAot Without SelfContained

**Problem:**
Currently, when `PublishTrimmed=true` or `PublishAot=true` is set without `SelfContained=true`, the task does not resolve runtime packs. This causes publish failures because trimming and AOT require runtime-specific assets.

**Current Behavior:**
```csharp
var runtimeRequiredByDeployment
    = (SelfContained || ReadyToRunEnabled) &&
      !string.IsNullOrEmpty(EffectiveRuntimeIdentifier) &&
      !string.IsNullOrEmpty(selectedRuntimePack?.RuntimePackNamePatterns);
```

**Expected Behavior:**
Runtime packs should be resolved when:
- `SelfContained=true`, OR
- `ReadyToRunEnabled=true`, OR
- `PublishTrimmed=true`, OR
- `PublishAot=true`

**AND** a `RuntimeIdentifier` is specified.

**Proposed Fix:**
```csharp
var runtimeRequiredByDeployment
    = (SelfContained || ReadyToRunEnabled || PublishAot || RequiresILLinkPack) &&
      !string.IsNullOrEmpty(EffectiveRuntimeIdentifier) &&
      !string.IsNullOrEmpty(selectedRuntimePack?.RuntimePackNamePatterns);
---

## Implementation Details

### Key Decision Points

The task uses the following logic to determine which packs to include:

1. **Targeting Packs**: Always included for all framework references matching the target framework
2. **Runtime Packs**: Included when `runtimeRequiredByDeployment` is true OR `RuntimePackAlwaysCopyLocal` is set
3. **Tool Packs**: Included based on specific properties:
   - Crossgen2: When `ReadyToRunEnabled && ReadyToRunUseCrossgen2`
   - ILCompiler: When `PublishAot`
   - ILLink: When `RequiresILLinkPack`

### RID Resolution

The task uses the runtime graph (`RuntimeGraphPath`) to find the best matching RID from the available runtime packs:

1. For the primary `RuntimeIdentifier`, full runtime pack metadata is generated
2. For additional `RuntimeIdentifiers`, only download entries are created
3. Portable RIDs are preferred over non-portable RIDs when appropriate for tool packs

### Version Selection

Runtime framework versions follow this precedence:
1. `RuntimeFrameworkVersion` metadata on `FrameworkReference` item
2. `RuntimeFrameworkVersion` MSBuild property
3. `LatestRuntimeFrameworkVersion` (if `TargetLatestRuntimePatch=true`)
4. `DefaultRuntimeFrameworkVersion` (if `TargetLatestRuntimePatch=false`)

---

## Testing Scenarios

The following test scenarios validate the expected outputs:

1. ✅ **Self-contained deployment** resolves runtime packs for the specified RID
2. ❌ **PublishTrimmed without SelfContained** should resolve runtime packs (currently fails)
3. ❌ **PublishAot without SelfContained** should resolve runtime packs (currently fails)
4. ✅ **Multiple RuntimeIdentifiers** downloads runtime packs for all RIDs
5. ✅ **Ready-to-Run** includes Crossgen2 packs
6. ✅ **Combined scenarios** include all necessary packs

Tests are located in: `src/Tasks/Microsoft.NET.Build.Tasks.UnitTests/ProcessFrameworkReferencesTests.cs`

---

## Related Documentation

- [Runtime Identifier Catalog](https://learn.microsoft.com/dotnet/core/rid-catalog)
- [Framework-dependent vs Self-contained deployment](https://learn.microsoft.com/dotnet/core/deploying/)
- [Trim self-contained deployments](https://learn.microsoft.com/dotnet/core/deploying/trimming/trim-self-contained)
- [Native AOT deployment](https://learn.microsoft.com/dotnet/core/deploying/native-aot/)
- [ReadyToRun compilation](https://learn.microsoft.com/dotnet/core/deploying/ready-to-run)

---

## Revision History

- **2025-01-14**: Initial specification documenting expected outputs and identifying issue #51667

---

### Documentation Specs Canonical (`documentation/specs/canonical.md`)

Canonical scenarios
===================

# Contents

* [Overview](#overview)
* [Acquisition](#acquisition)
* Scenarios
  * [Starting a new console application](#starting-a-new-console-application)
  * [Starting a new class library](#starting-a-new-class-library)
  * [Adding 3rd party dependencies to the projects](#adding-3rd-party-dependencies-to-the-projects)
  * [Running unit tests](#running-unit-tests)
  * [Publishing a shared runtime console application](#publishing-a-shared-runtime-console-application)
  * [Publishing a self-contained console application for all platforms](#publishing-a-self-contained-console-application-for-all-platforms)
  * [Packaging a class library](#packaging-a-class-library)
  * [Installing `dotnet` extensions as tools](#installing-dotnet-extensions-as-tools)

# Overview

This document outlines the End-to-End canonical scenarios for the CLI tooling. The scenarios outline the planned steps that the developer needs to do to work with her applications. 

Each scenario is organized around a narrative, which provides an explanation on what the developers are trying to do, steps that are needed for the user to achieve the needed narrative. Steps are organized as commands that the developer would need to execute on the command line to achieve the result.

These scenarios are focused on console applications and libraries.

# Acquisition
All of the scenarios below assume that the CLI tools have been acquired in some way. The acquisition of the CLI tools is explained in detail in a [separate specification](cli-installation-scenarios.md). This document only contains a very short summary of that document.

There are two main ways to acquire the CLI toolset:
1. Using targeted platform's native installers - this approach is used by developers who want to get stable bits on their development machines and don't mind the system-wide installation and need for elevated privileges. 
2. Using a local install (a zip/tarball) - this approach is used by developers who want to enable their build servers to use CLI toolset or who want to have multiple, side-by-side installs.

The bits that are gotten are same modulo potential differences in stability of the bits, however, the smoothness of the experience is not. With native installers the installers themselves do as much as possible to set up a working environment (installing dependencies where possible, setting needed environment variables etc.). Local installs require all of the work to be done by developers after dropping bits on the machine.

The below scenarios must work regardless of the way used to acquire the tools. 



# Starting a new console application

## Narrative
The developer would like to kick the tires on .NET Core by writing a console application. She would like to use the new .NET Core CLI tooling to help her get started, manage dependencies and quickly test out the console application by running it from source. She would then like to try building the code and running it using the shared host that is installed with the CLI toolset. 

## Steps
1. Create a C# console application via `dotnet new` command

```
/myapp> dotnet new myapp 

```
2. Edit  the C# code 

```
  namespace myapp
  {
      public static class Program
      {
          public static void Main(string[] args)
          {
              Console.WriteLine("Hello, World!");
          }
      }
  }
```

3. Restore packages
  ```
  /myapp> dotnet restore
  
  [messages about restore progress]
  
  Writing lock file /myapp/project.lock.json
  
  /myapp> 
  ```

4. Run from source for a quick test

```
/myapp> dotnet run

Hello World!

/myapp>
```

5. Build a binary that can be executed by the shared host

```
/myapp> dotnet build

[information about the build]

  Creating build output:
    /myapp/bin/Debug/netstandardapp1.5/myapp.dll
    /myapp/bin/Debug/netstandardapp1.5/myapp.deps
    /myapp/bin/Debug/netstandardapp1.5/[All dependencies' IL assemblies].dll

/myapp>
```

6. Run the built version using the shared host in the installed toolset

```
/myapp> dotnet run /myapp/bin/Debug/netstandardapp1.5/myapp.dll
Hello World!
```

 
# Starting a new class library

## Narrative 
Once started, the developer wants to also include a class library in order to have a place to share common code. She wants to use the CLI toolset to bootstrap this effort as well. 

## Steps

1. Create a new class library using `dotnet new`

```
/> dotnet new mylib --type lib

Creating a "mylib" class library in "mylib"

/mylib> 
```

2. Restore the dependencies

  ```
  /mylib> dotnet restore
  
  [messages about restore progress]
  
  Writing lock file /mylib/project.lock.json
  
  /mylib> 
  ```


3. Edit the `MyLib.cs` file

```
  namespace mylib
  {
      public class mylib
      {
          public void Method1()
          {
          }
      }
  }
```

4. Build the code

```
/mylib> dotnet build

[information about the build]

  Creating build output:
    /mylib/bin/Debug/netstandardapp1.5/mylib.dll
    /mylib/bin/Debug/netstandardapp1.5/mylib.deps
    /mylib/bin/Debug/netstandardapp1.5/[All dependencies' IL assemblies].dll

/mylib>

```

# Adding 3rd party dependencies to the projects

## Narrative
Working towards a complete application, the developer realizes she needs to add good JSON parsing support. Searching across the internet, she finds JSON.NET to be the most recommended choice. She now uses the CLI tooling to install a dependency off of NuGet. 

>**NOTE:** the shape of the commands used in this scenario is still being discussed. 

## Steps

1. Install the package

```
/myapp> dotnet pkg install Newtonsoft.Json --version 8.0.2

[lots of messages about getting JSON.NET]

Writing lock file /tests/project.lock.json

/myapp>
```

2. Change the code to use the new dependency

```
   using Newtonsoft.Json;
   namespace myapp
  {
      public static class Program
      {
          public static void Main(string[] args)
          {
              var thing = JsonConvert.DeserializeObject("{ 'item': 1 }");
              Console.WriteLine("Hello, World!");
              Console.WriteLine(thing.item);
          }
      }
  }
```

3. Run code from source 

```
/myapp> dotnet run
Hello, World!
1
/myapp>
```

# Running unit tests

## Narrative
Writing tests is important, and our developer knows that. She is now writing out the shared logic in her class library and she wants to make sure that she has test coverage. Investigating the manuals, she realizes that the CLI toolset comes with support for MSTest tests including the test runner.

## Steps

1. Create a new MSTest test project using `dotnet new`

```
/> dotnet new mstest -o tests
Created "tests" MSTest test project in "tests".

/tests>
```
2. Restore the runner and dependencies

  ```
  /tests> dotnet restore
  
  [messages about restore progress]
  
  Writing lock file /tests/project.lock.json
  
  [messages about tool dependencies restore]
  
  /tests> 
  ```

3. Add a test to the test class
```
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace tests
{
    [TestClass]
    public class Tests
    {
        [TestMethod]
        public void AssertTrue()
        {
            Assert.IsTrue(true);
        }
    }
}
```

3. Run tests using `dotnet test`

```
/tests> dotnet test

[information about discovery of tests]

=== TEST EXECUTION SUMMARY ===
   test  Total: 1, Errors: 0, Failed: 0, Skipped: 0, Time: 0.323s
 
/tests>
```

# Publishing a shared runtime console application

## Narrative
Coding away on the application has proven worthwhile and our developer wants to share her progress with another developer on her team. She wants to give just the application and its dependencies. Luckily, another developer can easily install the .NET Core SDK and get a shared host, which would be enough to run the application. The CLI toolset allows our developer to publish just the application's code (in IL) and dependencies. 

## Steps

1. Publish the application
```
  /myapp> dotnet publish --output /pubapp
  
  [Lots of messages about publishing stuff]
  
  Creating publish output:
    /pubapp/myapp/myapp.dll
    /pubapp/myapp/myapp.deps
    /pubapp/myapp/[All dependencies' IL assemblies].dll
  
  /myapp> 
  ```

2. Run the project publish output:
  ```
  /myapp> cd /pubapp/myapp
  /pubapp/myapp> dotnet ./myapp.dll
  Hello, World!
  
  /published/myapp> 
  ```
3. The published application can be transferred over to a machine that has the .NET Core shared host installed and it is possible for it to be ran. 

# Publishing a self-contained console application for all platforms

## Narrative
After getting feedback from her colleague developer, our developer decides to test on another machine. However, this machine doesn't have the shared host installed and she cannot get it installed. Luckily, she realizes that .NET Core has support for self-contained applications 

**NOTE**: some of the behaviours in this scenario are still being discussed with the relevant stakeholders. 

## Steps

1. Modify the project file to enable it to be published as a standalone, platform-specific application (one that doesn't require `dotnet` on the target machine to run) for the desired platforms by adding the `"runtimes"` section:
  ```
  {
    "imports": {
      "Microsoft.ProjectType.ConsoleApplication": "1.0.0"
    },
    "runtimes": {
      "linux-x64": { },
      "win7-x64": { }
    }
  }
  ```

2. Restore the project's dependencies again to ensure the platform-specific dependencies for the specified runtimes are acquired:
  ```
  /myapp> dotnet restore
  
  [lots of messages about restoring stuff]
  
  Writing lock file /myapp/project.lock.json
  
  /myapp> 
  ```



3. Publish the project again. In this case, the publish will publish for each runtime in the `project.json` file
  ```
  /myapp> dotnet publish --output /published/myapp
  
  [Lots of messages about publishing stuff]
  
  Creating publish output for (linux-x64):
    /published/myapp-linux-x64/myapp
    /published/myapp-linux-x64/myapp.dll
    /published/myapp-linux-x64/myapp.deps
    /published/myapp-linux-x64/[All dependencies' IL & platform-specific assemblies, inc. stdlib]

  Creating publish output for (win7-x64):
    /published/myapp-win7-x64/myapp
    /published/myapp-win7-x64/myapp.dll
    /published/myapp-win7-x64/myapp.deps
    /published/myapp-win7-x64/[All dependencies' IL & platform-specific assemblies, inc. stdlib]
  
  /myapp> 
 
  ```
  
4. Any of the outputs above can be xcopied to the platform in question and it will work without having to have the shared host installed. 
  
5. Publish the project for a specific platform (win7-x64):

```
  /myapp> dotnet publish --output /win7/myapp --runtime win7-x64
  
  [Lots of messages about publishing stuff]
  
  Creating publish output for (win7-x64):
    /published/myapp-win7-x64/myapp
    /published/myapp-win7-x64/myapp.dll
    /published/myapp-win7-x64/myapp.deps
    /published/myapp-win7-x64/[All dependencies' IL & platform-specific assemblies, inc. stdlib]
  
  /myapp> 
  ```

# Packaging a class library 

## Narrative 
The developer wants to take the library she built and package it up as a NuGet package in order to share it with the rest of the ecosystem. Again, she would like to use the CLI toolset to achieve this. Since she wants to be sure that all her code is in a pristine condition, she will also build it one more time, run tests and then package it. 

## Steps 
1. Build the code to make sure no build errors have crept in

```
/mylib> dotnet build

[information about the build]

  Creating build output:
    /myapp/bin/Debug/netstandardapp1.5/myapp.dll
    /myapp/bin/Debug/netstandardapp1.5/myapp.deps
    /myapp/bin/Debug/netstandardapp1.5/[All dependencies' IL assemblies].dll

/mylib>

```

2. Switch to the test project and run unit tests

```console
[switch to the directory containing unit tests]
/mytests> dotnet test

[info about tests flies around]

=== TEST EXECUTION SUMMARY ===
   test  Total: 50, Errors: 0, Failed: 0, Skipped: 0, Time: 5.323s

/mytests>

``` 

3. Package the library 

```console
[switch to the library directory]

/mylib> dotnet pack

[information about build is shown]

Producing nuget package "mylib.1.0.0" for mylib
mylib -> /mylib/bin/Debug/mylib.1.0.0.nupkg
Producing nuget package "mylib.1.0.0.symbols" for mylib
mylib -> /mylib/bin/Debug/mylib.1.0.0.symbols.nupkg

/mylib> 
```

# Installing `dotnet` extensions as tools 

## Narrative
As our developer is going further with her usage of the CLI tools, she figures out that there is an easy way to extend the CLI tools on her machine by adding project-level tools to her `project.json`. She uses the CLI to work with the tools and she is able to extend the default toolset to further fit her needs. 

## Steps 
>**TODO:** at this point, this needs more work to figure out how it will surface; it is listed here so it is not forgotten.

---

### Documentation Specs Cli Installation Scenarios (`documentation/specs/cli-installation-scenarios.md`)

Obtaining .NET CLI 
==================

## Contents
* [Overview](#overview)
* [General principles](#general-principles)
* [Components that can be installed](#components-that-can-be-installed)
* [Installation process](#installation-process)
* [Removal process](#removal-process)
* [Upgrading the CLI](#upgrading-the-cli)
* [Layout on disk](#layout-on-disk)
* [Native dependencies](#native-dependencies)
* [Channels](#channels)
* [Funnels and discovery mechanisms for CLI bits](#funnels-and-discovery-mechanisms-for-cli-bits)
  * [Getting Started page](#getting-started-page)
  * [Repo landing page](#repo-landing-page)
* [Acquisition modes](#acquisition-modes)
  * [Native installers](#native-installers)
  * [Installation script](#installation-script)
    * [Windows one-liner](#windows-command)
    * [OSX/Linux one-liner](#osxlinux-shell-command)
  * [Complete manual installation](#complete-manual-installation)
  * [Docker](#docker)
  * [NuGet Packages](#nuget-packages)
* [Acquiring through other products](#acquiring-through-other-products)
  * [IDEs and editors](#ides-and-editors)
  

## Overview
This document/spec outlines the CLI install experience. This covers the technologies being used for install, the principles that are driving the installation experience, the ways users are coming to the installs and what each of the installs contains, in terms of stability and similar. 

## General principles

- Upgrades using the native installers Just Work(tm)
- All user facing materials point to the getting started page
- Defaults are stable bits; users need extra effort to install Future builds
- Only HTTPS links are allowed in any online property 
- Provide native installers for each supported platform
- Provide automation-ready installers for each target platform

## Components that can be installed
Overall, there are two significant installable components:

1. The .NET Core SDK
2. Shared runtime redistributable 

The .NET Core SDK contains the following items:

1. A given version of the CLI toolset - "SDK"
2. A given version of the shared runtime - "redist" - this will be consumed by both end-customers and CLI toolset
3. A given version of the shared host - "muxer" - shared component that is in charge of running the applications and the CLI commands - it should be treated as an implementation detail

## Installation process
Each of the components listed in the previous section will have an installer/package. The dependencies of the installers between themseslves are given in the table below.

| Installer 	| Depends on 	|
|-----------	|------------	|
| SDK       	| redist     	|
| redist    	| muxer      	|
| muxer     	| -          	|

The installation process will depend on the platform and the way of the install. For those installers that don't have automatic dependency resolution (Windows installer, OS X PKG) the installers will chain the installers of the components they depend on. DEB, RPM and similar will declare proper dependencies and the package manager will do the Right Thing(tm) by default. 

From the table, we can see that if you install the SDK using `apt-get` for instance, you will get also a redist and a muxer. They will be separate packages, but will be declared as dependencies (similar for `yum`). Similar for the redist package. 

The muxer is slightly a special case. Though there will be an installer, as mentioned in the previous section, it is an implementation detail. That means that acquiring the muxer should be done through either the SDK or the shared runtime installers. The only situation where this rule would not be true is if there was a major servicing event (e.g. a security update); in that case, the users would use the installer for the muxer directly, as we would rev its version accordingly. 

The script installers are slightly different as they operate on zips/tarballs. The zip/tarball for the SDK will contain the entire set of things needed to be put on the disk.

## Removal process
Removing the bits from the machine **must** follow the order outlined above in installation. If the SDK is installed, it needs to be removed first and then the Redist and only then the muxer. Similar for the Redist.  

## Upgrading the CLI 
The semantics of installing the CLI will be side-by-side by default. This means that each new version will get installed besides any existing versions on disk. The [layout section](#layout-on-disk) covers how that will look like on disk.

Since this is the case, there is no special "upgrade". When the user needs a new version, the user just installs the new version using any of the installers specified in this document. The installer will just drop a new version at the predefined location. 

This, however, does have one specific constraint: **newer versions must be installed in the same location the previous version was in**. This constraint is due to the fact that the "muxer" uses convention to figure out how to find the actual driver that the user requested. 

## Layout on disk
```
<INSTALL_DIR>/ (%PATH%)
    dotnet ("muxer", has platform dependant file extension)
    hostfxr (implementation detail for "muxer", platform dependant file extension)
    sdk/
        <sdk-version-0>/ (i.e. "1.0.0-rc2-002543")
            ... (binaries like: dotnet.dll, csc.dll)
        <sdk-version-1>/
            ... (binaries)
        ...
    shared/ ("redist" or "shared framework")
        <target-framework-name>/ (currently only "Microsoft.NETCore.App")
            <redist-version-0>/ (i.e. "1.0.0-rc2-3002543")
                ... (binaries like: coreclr.dll, mscorlib.ni.dll, System.*.dll, dotnet-hostimpl.dll, dotnet, netcoreapp.deps.json)
            <redist-version-1>/
                ... (binaries)
```

## Native dependencies
.NET Core CLI is built on top of CoreFX and CoreCLR and as such its' dependencies set is defined by the platform that those two combine. Whether or not those dependencies will be installed depends on the installer being used. The table below lists out the installers and whether or not they bring in dependencies. 

| Installer  	| Dependencies Y/N                   |
|------------	|----------------------------------- |
| EXE        	| Y (chains them in) 	             |
| PKG        	| N (need to be manually installed*) |
| apt-get    	| Y                                  |
| rpm        	| Y                                  |

`*` PKG cannot specify and automatically install native dependencies

A list of dependencies can be found on the [.NET dependencies list](https://github.com/dotnet/core/blob/main/release-notes/11.0/dotnet-dependencies.md).

## Channels
Channels represent a way for users who are getting the CLI to reason about the stability and quality of the bits they are getting. This is one more way for the user to be fully aware of the state the bits that are being installed are in and to set proper expectations on first use. 

| Channel         	| Description                                                                                                                                                                                                                                                       	|
|------------------	|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------	|
| LTS              	| Latest long-term supported release. 	|
| Current 	| Most current release - typically 'preview' releases. 	|


## Funnels and discovery mechanisms for CLI bits
There are multiple ways that we will funnel users towards the installers for the CLI:

1. [Getting Started Page](https://aka.ms/dotnetcoregs)
2. [Repo landing page](../../README.md)
3. Package repositories for platforms (`apt-get`, `brew` etc.)
4. IDEs and editors that integrate with CLI (e.g. Visual Studio, VS Code, Sublime etc.)

Out of the above, the first two funnels are under the control of the CLI team so we will go into slightly more details. The rest of the funnels will use a prescribed way to get to the bits and will have guidance on what bits to use.  

### Getting Started page
The page can be found on https://aka.ms/dotnetcoregs. This is the main curated first-run funnel for the dotnet CLI. The intent of the page is to help users test out the CLI quickly and become familiar with what the platform offers. This should be the most stable and curated experience we can offer. 

The Getting Started page should only point users to curated install experiences that can contain only stable or LKG bits. 

The below table shows other pertinent information for installs on the "Getting started" page. 
 
| Property              	| Description                                                  	 |
|-----------------------	|--------------------------------------------------------------- |
| Debian feed           	| Development                                                  	 |
| Brew repo/tap           	| Brew binary repo (https://github.com/Homebrew/homebrew-binary) |
| CentOS feed               | TBD                                                            |


### Repo landing page
The repo landing page can be found on: [Repo landing page](../../README.md). Download links on the landing page should be decreased in importance. First thing for "you want to get started" section should link to the getting started page on the marketing site. The Repo Landing Page should be used primarily by contributors to the CLI. There should be a separate page that has instructions on how to install both the latest stable as well as latest development with proper warnings around it. The separate page is to really avoid the situation from people accidentally installing unstable bits (since search engines can drop them in the repo first). 

The source branches and other items are actually branch specific for the repo landing page. As the user switches branches, the links and badges on the page will change to reflect the builds from that branch.  

## Acquisition modes
There are multiple acquisition modes that the CLI will have:

1. Native installers
2. Install scripts
3. NuGet packages (for use in other people's commands/code)
4. Docker

Let's dig into some details. 

### Native installers
These installation experiences are the primary way new users are getting the bits. The primary way to get information about this mode of installation is the [Getting Started page](#getting-started-page). The native installers are considered to be stable by default; this does not imply lack of bugs, but it does imply predictable behavior. They are generated from the stable branches and are never used to get the Future bits.

There are three main components that will be installed  

The native installers are:

| Platform            	| Installer        	| Status   	| Package name       	|
|---------------------	|------------------	|----------	|--------------------	|
| Windows             	| Bundle installer 	| Done     	| dotnet-{version};    	|
| Ubuntu 14.04/Debian 	| apt-get feed     	| Done     	| dotnet; dotnet-dbg 	|
| OS X                	| PKG              	| Done     	| dotnet             	|
| OS X                	| Homebrew         	| Not done 	| dotnet             	|
| CentOS/RH           	| RPM              	| Not done 	| dotnet             	|



### Installation script
This approach is a shell one-liner that downloads an installation script and runs it. The installation script will download the latest zip/tarball (depending on the script used) and will unpack it to a given location. After that, the script will print out what needs to be set for the entire CLI to work (env variables, $PATH modification etc.).

This install covers the following main scenario: 

* Local installation on a dev machine
* Acquiring tools on a CI build server

  
The features the script needs to support/have are:
* Support for specifying the channel
* Support for specifying the version
* Support for specifying the installation location
* Automatically add the install to $PATH unless --no-path/-NoPath is present

It is recommended to use the stable version that is hosted on [.NET Core main website](https://dot.net). The direct path to the scripts are:

* https://dot.net/v1/dotnet-install.sh (bash, UNIX)
* https://dot.net/v1/dotnet-install.ps1 (powershell, Windows)


#### Installation script features
The following arguments are needed for the installation script:

| dotnet-install.sh arg (Linux, OSX) | dotnet-install.ps1 arg (Windows) | Defaults | Description |
|------------------------------------|----------------------------------|-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| --channel | -Channel | "LTS" | Which channel (i.e. "LTS", "Current", "1.0", "2.0", etc) to install from. |
| --version | -Version | Latest | Which version of CLI to install; you need to specify the version as 3-part version (i.e. 1.0.0-13232). The 'version' parameter supersedes the 'channel' parameter. |
| --install-dir | -InstallDir | .dotnet | Path to where to install the CLI bundle. The directory is created if it doesn't exist. On Linux/OSX this directory is created in the user home directory (`$HOME`). On Windows, this directory is created in `%LocalAppData%`. |
| --no-path | -NoPath | false | Do not export the installdir to the path for the current session. This makes CLI tools available immediately after install. |
| --shared-runtime | -SharedRuntime | false | Install just the shared runtime bits, not the entire SDK. |
| --architecture | -Architecture | Current OS (`<auto>`) | Architecture to install. The possible values are `<auto>`, `x64` and `x86`. |
| --dry-run | -DryRun | false | If set, it will not perform the installation but will show, on standard output, what the invocation of the script will do with the options selected.  |
| --verbose | -Verbose | false | Display diagnostic information. |
| N/A | -ProxyAddress | "" | If set, the installer will use the specified proxy server for all of its invocations.  |

> Note: Powershell arg naming convention is supported on Windows and non-Windows platforms. Non-Windows platforms do additionally support convention specific to their platform.

##### Install the 1.1.0 of the shared runtime

Windows:
```
./dotnet-install.ps1 -SharedRuntime -Version 1.1.0
```

macOS/Linux:
```
./dotnet-install.sh --shared-runtime --version 1.1.0
```

##### Install the latest supported CLI

Windows:
```
./dotnet-install.ps1 -Channel LTS
```
OSX/Linux:
```
./dotnet-install.sh --channel LTS
```

##### Install the latest CLI to specified location

Windows:
```
./dotnet-install.ps1 -Channel Current -InstallDir C:\cli
```
OSX/Linux:
```
./dotnet-install.sh --channel Current --install-dir ~/cli
```

##### Install the latest CLI in the 2.0 channel

Windows:
```
./dotnet-install.ps1 -Channel 2.0
```
OSX/Linux:
```
./dotnet-install.sh --channel 2.0
```

#### Windows obtain one-liner example

```
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "&([scriptblock]::Create((Invoke-WebRequest -useb 'https://dot.net/v1/dotnet-install.ps1'))) <additional installation-script args>"
```

#### OSX/Linux obtain one-liner

```
curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin <additional installation-script args>
```

### Docker 
[Docker](https://docs.docker.com/) has become a pretty good way to use developer tools, from trying them out in an interactive image use to using it for deployment. We have Docker images on DockerHub already. 

Docker images should always be updated as we make new releases. We should have Docker images of stable releases, built from the release branches. 

### NuGet packages
NuGet packages of the CLI bits that make sense are published to relevant feeds. The developer who wishes to use these needs to specify a version. The actual "installation" here is restoring the package as a dependency for a certain project (i.e. `ProjectServer` or similar). 

## Acquiring through other products

### IDEs and editors
Anything that goes into the higher-level tools should always use a stable build of CLI coming frol release branches as required. 

If there exist any mechanism that notifies users of updates of the CLI, it should ideally point users to the Getting Started page to acquire the installers, or, if that is deemed too heavy-handed, it should point people to the last stable release. If there is a need of the URL to be "baked in" to the higher-level tool, that URL should be an aka.ms URL because it needs to be stable on that end.  

Cross-platform IDEs/editors will work in similar way as above. The notification should also point people to the Getting Started page. The reason is simple: it is the one page where users can pick and choose their installation experience. 

### Visual Studio 
Visual Studio will not be shipping CLI in-box. However, it will use CLI when installed. The install will be tied into other installs like WET and similar. The URL that is baked in VS should be an aka.ms URL or other stable URL/location.

# Detecting dotnet/cli installation

## Windows

### Requirements for CLI SDK and shared framework installer
- Support side by side installation and can be compatible with older versions of themselves
- Supports removing of any side by side version
- Prerelease versions are compatible only with the same prerelease versions

#### Scenarios
- Installing the product produces registry value informing about full version of the product which is being installed
- Installing the product produces registry values informing about compatible versions of the products
- Removing the product removes the registry keys if none of the versions of the product is supporting the given version. Specifically at least one registry key with full version should be removed.
- Installing older version of the product is possible

#### Registry keys and values
- Full version refers to NuGet semantic version which contains the build number
- Version refers to NuGet semantic version which does *not* contain build number

Registry key should be created under following path:
```
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\<platform>\<installer-name>\[REG_DWORD]<nuget-version>=1
```

`<platform>=(x86|x64)`
`<installer-name>=(sdk|sharedfx)`

Example output (installing CLI SDK x86 with version 1.0.3-123456):

```
HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0=1
HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.1=1
HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.2=1
HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.3=1
HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.3-123456=1
```

Note: 1.0.3 has two entries

Explanation:
CLI SDK version 1.0.3-123456 is compatible with any build of 1.0.3, 1.0.2, 1.0.1 and 1.0.0. If another installer is trying to find if there exists CLI SDK which supports specific version of installer they can check for presence of the value 1 under the registry path.

### Requirements for shared host installer
- Supports only in-place updated and is assumed to be always compatible with older versions of itself

#### Scenarios
- Installing the product produces one registry value containing the latest version
- Installing older version on top of the other is not possible
- Removing removes the product completely with its registry keys, regardless of any previous installations

Registry key should be created under following path:
```
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\<platform>\[REG_SZ]sharedhost=<nuget-semversion>
```

##### Example
```
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\dotnet\Setup\x64\[REG_SZ]sharedhost=1.0.0-rc2-123456
```

### Other Examples

Operations:
`NOP` - key already existed, do nothing with it
`ADD` - add
`DEL` - delete
`RF+` - not adding because key already exist (installer will increase ref count on GUID related to this value)
`RF-` - not deleting because something else is compatible with this (decrease ref count)

#### Scenario 1

Installing 1.0.3-123456 (RTM) to a clean machine

Note: Installer is compatible with all previous versions and all their RCs.

```
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc1=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc2=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.1-rc1=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.1-rc2=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.1=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.2-rc1=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.2-rc2=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.2=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.3-rc1=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.3-rc2=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.3=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.3-123456=1
```

Installing 1.0.4-234567 (RTM) on top of that

```
/* Detailed source-code truncated for AI context efficiency. */
```

Removing 1.0.3-123456

```
/* Detailed source-code truncated for AI context efficiency. */
```

#### Scenario 2

Installing 1.0.0-123456 (RTM) to a clean machine

```
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc1=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc2=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-123456=1
```

Installing 1.1.0-567890 (RTM) which is incompatible since 1.0.2

Note: User is unable to run apps targeting 1.0.1 or 1.0.2 until compatible version is installed.

```
NOP HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc1=1
NOP HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc2=1
NOP HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0=1
NOP HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-123456=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.3-rc1=1 (first back-incompatible version)
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.3-rc2=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.3=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.4-rc1=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.4-rc2=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.4=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.1.0-rc1=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.1.0-rc2=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.1.0=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.1.0-567890=1
```

#### Scenario 3

Installing 1.0.0-rc2-123456 to a clean machine

Note: User is unable to run apps targeting 1.0.0 until RTM is installed.

```
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc1=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc2=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc2-123456=1
```

Installing 1.0.1-rc1-234567

Note: User is still unable to run apps targeting 1.0.0 until any 1.0.0+ RTM is installed.

```
NOP HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc1=1
NOP HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc2=1
NOP HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.0-rc2-123456=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.1-rc1=1
ADD HKLM\SOFTWARE\WOW6432Node\dotnet\Setup\InstalledVersions\x86\sdk\[REG_DWORD]1.0.1-rc1-123456=1
```

---

### Documentation Specs Dotnet Run For Maui (`documentation/specs/dotnet-run-for-maui.md`)

# `dotnet run` and `dotnet test` for .NET MAUI Scenarios

The current state of `dotnet run` for .NET MAUI projects is summarized
by this issue from 2021:

* [Figure out 'dotnet run' CLI experience for iOS and Android](https://github.com/dotnet/xamarin/issues/26)

The pain points being:

* iOS and Android use different properties to select a device,
  emulator, or simulator. It is difficult for developers to make this
  selection as you need to run platform-specific commands along with
  complex MSBuild properties.

* Each platform has different behavior, regards to displaying console
  output, etc.

* Using an MSIX with WindowsAppSDK doesn't support `dotnet run` at all,
  relying completely on IDEs like Visual Studio.

* `dotnet run` does not have a concept of a "deploy" step.

This has become more relevant in the AI era, as someone is going to
expect AIs in "agent mode" to build and run their app. If the
command-line options are difficult, AIs will fail just as badly as
humans do today.

## The `dotnet run` Pipeline

These are the high-level steps during `dotnet run`, that we would like
to make extensible for .NET MAUI (and future) scenarios.

* `restore`: unchanged

* "Pre-run evaluation"

  * If the project is multi-targeted, containing the
    `$(TargetFrameworks)` property _and_ that property has more than
    one item in it, and `-f` was not supplied...

    * Prompt the user to select from a list of the
      `$(TargetFrameworks)`

    * Non-interactive mode will give a friendly error message,
      suggesting to supply the `-f` property, listing available target
      frameworks in the project.

  * Once a `$(TargetFramework)` is selected, either from previous
    steps or `-f`...

    * If a `ComputeAvailableDevices` MSBuild target is available, provided by
      the iOS or Android workload, etc. ...

    * Call the MSBuild target, which returns a list of `@(Devices)` items...

```xml
<ItemGroup>
  
  <Devices Include="emulator-5554"  Description="Pixel 7 - API 35" Type="Emulator" Status="Offline" />
  <Devices Include="emulator-5555"  Description="Pixel 7 - API 36" Type="Emulator" Status="Online" />
  <Devices Include="0A041FDD400327" Description="Pixel 7 Pro"      Type="Device"   Status="Online" />
  
  <Devices Include="94E71AE5-8040-4DB2-8A9C-6CD24EF4E7DE" Description="iPhone 11 - iOS 18.6" Type="Simulator" Status="Shutdown" />
  <Devices Include="FBF5DCE8-EE2B-4215-8118-3A2190DE1AD7" Description="iPhone 14 - iOS 26.0" Type="Simulator" Status="Booted" />
  <Devices Include="23261B78-1E31-469C-A46E-1776D386EFD8" Description="My iPhone 13"         Type="Device"    Status="Unavailable" />
  <Devices Include="AF40CC64-2CDB-5F16-9651-86BCDF380881" Description="My iPhone 15"         Type="Device"    Status="Paired" />
</ItemGroup>
```

_NOTE: each workload can decide which metadata values for `%(Type)`
and `%(Status)` are useful, filtering offline devices, etc. The output
above would be analogous to running `adb devices`, `xcrun simctl list
devices`, or `xcrun devicectl list devices`._

* Continuing on...

  * Prompt the user to select from this list of devices, emulators,
    or simulators.

  * Non-interactive mode will error, suggesting to supply the
    `--device` switch. Listing the options returned by the
    `ComputeAvailableDevices` MSBuild target.

* `build`: unchanged, but is passed `-p:Device`.
  Environment variables from `-e` are passed as `@(RuntimeEnvironmentVariable)` items.

* `deploy`

  * If a `DeployToDevice` MSBuild target is available, provided by the
    iOS or Android workload, etc.

  * Call the MSBuild target, passing in the identifier for the selected
    `-p:Device` global MSBuild property.

  * Environment variables from `-e` are passed as `@(RuntimeEnvironmentVariable)` items.

  * This step needs to run, even with `--no-build`, as you may have
    selected a different device.

* `ComputeRunArguments`: unchanged, but is passed `-p:Device`.
  Environment variables from `-e` are passed as `@(RuntimeEnvironmentVariable)` items.

* `run`: unchanged. `ComputeRunArguments` should have set a valid
  `$(RunCommand)` and `$(RunArguments)` using the value supplied by
  `-p:Device`.

## `dotnet test` Behavior

`dotnet test` on a multi-targeted project already runs tests for all
target frameworks. This is existing behavior which differs from `dotnet
run`, which previously errored when multiple `$(TargetFrameworks)` were
present and `-f` was not supplied.

For .NET MAUI projects, `dotnet test` extends this behavior with
device selection:

* **No `$(TargetFramework)` prompt by default** — unlike `dotnet run`,
  `dotnet test` does _not_ prompt for a target framework. It iterates
  over all `$(TargetFrameworks)` as it does today.

* **Device prompt per target framework** — for each target framework
  that provides a `ComputeAvailableDevices` MSBuild target (e.g.,
  `net11.0-android`, `net11.0-ios`), the user is prompted to select a
  device. This means a project targeting both Android and iOS may
  prompt twice.

  * A single available device is selected automatically. Multiple devices
    in non-interactive mode produce an error suggesting the `--device`
    switch, same as `dotnet run`.

  * If no devices are available, the command fails and identifies the
    project and target framework that failed device selection. Selecting
    an Android device does not limit the run to Android: device selection
    must succeed for every requested device-capable framework before any
    per-framework build or deployment starts. Use `-f` to limit the run
    to a framework supported by the current environment.

* **`--device` forces a `$(TargetFramework)` prompt** — if `--device`
  is passed, the user _must_ be prompted to select a single
  `$(TargetFramework)`, because the device identifier is
  platform-specific and the SDK cannot determine which target framework
  it applies to.

  * In non-interactive mode with `--device` but no `-f`, this will
    error suggesting to supply `-f`.

* **`-f` works as normal** — passing `-f` limits the test run to a
  single target framework. If that framework provides
  `ComputeAvailableDevices`, the user may be prompted for a device.

* **Build per target framework** — the selected `$(Device)` and any
  `$(RuntimeIdentifier)` supplied by `ComputeAvailableDevices` are passed
  to the build for that target framework.

* **Deploy per target framework** — after a successful build and before
  computing the test application's run arguments, `dotnet test` calls
  `DeployToDevice` when the target exists.

  * `DeployToDevice` receives the selected `$(Device)`,
    `$(TargetFramework)`, and `$(RuntimeIdentifier)` as global
    properties.

  * Deployment still runs with `--no-build`, because the user may select
    a different device for an existing build.

  * If `DeployToDevice` does not exist, deployment is skipped.

  * If `DeployToDevice` fails, `dotnet test` exits with an error and does
    not invoke `ComputeRunArguments` or start the test application.

* **`ComputeRunArguments` per target framework** — after deployment,
  `dotnet test` calls `ComputeRunArguments` with the same device,
  target framework, and runtime identifier. The resulting
  `$(RunCommand)` and `$(RunArguments)` are used to start the test
  application.

* **Solutions** — automatic device selection and deployment happen for
  each test project and target framework in a solution. An explicit
  `--device` is rejected with `--solution`; use `--project` because a
  device identifier is project- and platform-specific.

* **`--list-devices`** works the same as with `dotnet run`.

* **`-e` / `--environment`** — environment variables are passed to the test
  process and, for projects that declare the `RuntimeEnvironmentVariableSupport`
  capability, to the build, deployment, and `ComputeRunArguments` targets as
  `@(RuntimeEnvironmentVariable)` items, matching `dotnet run`.

## New Command-line Switches

So far, it feels like no new subcommand is needed. In interactive
mode, `dotnet run` will now prompt to select a `$(TargetFramework)`
for all multi-targeted projects. Platform-specific projects like
Android, iOS, etc. will prompt for device selection. `dotnet test`
shares the `--list-devices` and `--device` switches described below.

`dotnet run --list-devices` (or `dotnet test --list-devices`) will:

* Prompt for `$(TargetFramework)` for multi-targeted projects just
  like when `--list-devices` is omitted.

  * If there is a single `$(TargetFramework)`, skip to the next step.

* Call `ComputeAvailableDevices` if the MSBuild target exists, just
  like when `--list-devices` is omitted.

  * List the available targets by name, a unique identifier, and an
    optional status of the device.

  * Print a friendly message that says how to run `dotnet run` with
    the new `--device` switch.

  * If `ComputeAvailableDevices` does not exist in the project
    (workload), it can print a friendly message and exit.

* `dotnet run --list-devices` will then basically exit early, never
  running any build, deploy, `ComputeRunArguments`, or run steps.

A new `--device` switch will:

* bypass the device-selection portion of the `run` workflow described above

* Pass in the `-p:Device` global MSBuild property to all build,
  deploy, `ComputeRunArguments`, or run steps.

* The iOS and Android workloads will know how to interpret `$(Device)`
  to select an appropriate device, emulator, or simulator.

## Environment Variables

The `dotnet run` and `dotnet test` commands support passing environment variables via the
`-e` or `--environment` option:

```dotnetcli
dotnet run -e FOO=BAR -e ANOTHER=VALUE
dotnet test -e FOO=BAR -e ANOTHER=VALUE
```

These environment variables are:

1. **Passed to the running application** - as process environment
   variables when the app is launched.

2. **Passed to MSBuild during build, deploy, and ComputeRunArguments** -
   as `@(RuntimeEnvironmentVariable)` items that workloads can consume.
   **This behavior is opt-in**: projects must declare the `RuntimeEnvironmentVariableSupport`
   project capability to receive these items.

```xml
<ItemGroup>
  <RuntimeEnvironmentVariable Include="FOO" Value="BAR" />
  <RuntimeEnvironmentVariable Include="ANOTHER" Value="VALUE" />
</ItemGroup>
```

This allows workloads (iOS, Android, etc.) to access environment
variables during the `build`, `DeployToDevice`, and `ComputeRunArguments` target execution.

### Opting In

To receive environment variables as MSBuild items, projects must opt in by declaring
the `RuntimeEnvironmentVariableSupport` project capability:

```xml
<ItemGroup>
  <ProjectCapability Include="RuntimeEnvironmentVariableSupport" />
</ItemGroup>
```

Mobile workloads (iOS, Android, etc.) should declare this capability in their SDK targets
so that all projects using those workloads automatically opt in.

Workloads can consume these items in their MSBuild targets:

```xml
<Target Name="DeployToDevice">
  
  <Message Text="Environment: @(RuntimeEnvironmentVariable->'%(Identity)=%(Value)')" />
</Target>
```

### Implementation Details

For the **build step**, which uses out-of-process MSBuild via `dotnet build`,
environment variables are injected by creating a temporary `.props` file.
The file is created under the selected project intermediate output directory,
or under the project's `obj/` directory when no intermediate output path is
available (for example, `obj/dotnet-run-env.props` for `dotnet run` or
`obj/dotnet-test-env.props` for `dotnet test`).

The file is passed to MSBuild via the `CustomBeforeMicrosoftCommonProps` property,
ensuring the items are available during project evaluation. The CLI creates this
file only after evaluating a project and confirming that it declares the
`RuntimeEnvironmentVariableSupport` capability. Build-time injection is not
performed for solution builds because the capability cannot be evaluated and
applied independently to each solution child through a single global MSBuild
property.
The temporary file is automatically deleted after the build completes.

The generated props file looks like:

```xml
<Project>
  <ItemGroup>
    <RuntimeEnvironmentVariable Include="FOO" Value="BAR" />
    <RuntimeEnvironmentVariable Include="ANOTHER" Value="VALUE" />
  </ItemGroup>
</Project>
```

For the **deploy step** (`DeployToDevice` target) and
**ComputeRunArguments target**, which use in-process MSBuild,
environment variables are added directly as
`@(RuntimeEnvironmentVariable)` items to the `ProjectInstance` before
invoking the target.

## Binary Logs for Device Selection

When using `-bl` with `dotnet run`, all in-process MSBuild operations are
logged to a single binlog file: device selection, deploy, and run argument
computation.

File naming for `dotnet run` binlogs:

* `-bl:filename.binlog` creates `filename-dotnet-run.binlog`
* `-bl` creates `msbuild-dotnet-run.binlog`

`dotnet test` uses the same behavior for its in-process operations,
including per-project and per-target-framework device selection,
deployment, and run argument computation:

* `-bl:filename.binlog` creates `filename-dotnet-test.binlog`
* `-bl` creates `msbuild-dotnet-test.binlog`

The out-of-process build step may also create `msbuild.binlog`
separately. Use `--no-build` with `-bl` to capture only the in-process
run or test operations.

## What about Launch Profiles?

The iOS and Android workloads ignore all
`Properties/launchSettings.json` files and do nothing with them.

WindowsAppSDK requires a launch profile to select between "packaged"
MSIX and an "unpackaged" .exe, and so we currently provide this in the
`dotnet new maui` project template:

```json
{
  "profiles": {
    "Windows Machine": {
      "commandName": "Project",
      "nativeDebugging": false
    }
  }
}
```

Or if you want to be "packaged":

```json
{
  "profiles": {
    "Windows Machine": {
      "commandName": "MsixPackage",
      "nativeDebugging": false
    }
  }
}
```

Launch profiles don't immediately look useful for iOS or Android, as
the identifier you'd put in here would be different per developer --
you wouldn't want the value saved in source control. You could put a
generic selection like device vs emulator/simulator, but that isn't
addressing the problem we are interested in. Full launch profile
support for .NET MAUI projects may be interesting to address in the
future.

## iOS and Android workload behavior

We will work to align as much behavior as possible between the
platforms. Most of this work will happen in the dotnet/android and
dotnet/macios repo, and would be orthogonal to the changes in the .NET
SDK.

## macOS and MacCatalyst Behavior

`dotnet run` "just works" on macOS Desktop, because `$(RunCommand)`
can launch the app directly -- similar to console apps.

## WindowsAppSDK Behavior

Running a `dotnet new maui` project works today because of the default
launch profile in "unpackaged" mode:

```dotnetcli
> dotnet run -f net10.0-windows10.0.19041.0
Using launch settings from D:\src\hellomaui\Properties\launchSettings.json...
```

To improve the behavior for "packaged" / MSIX, we could:

* Implement the `DeployToDevice` MSBuild target.

* `ComputeAvailableDevices` is not needed.

* Implement the `ComputeRunArguments` MSBuild target.

In the future, we can either add this logic into the .NET MAUI
workload or WindowsAppSDK itself.

## Other frameworks: Avalonia, Uno, MonoGame, etc.

When these frameworks run on iOS or Android, they are basically using
the `ios` and `android` workloads _without_ .NET MAUI. Any iOS or
Android-specific behavior would apply to these project types in the
same way a `dotnet new android` or `dotnet new ios` project template
would.

---

### Documentation Specs Dotnet Watch For Maui (`documentation/specs/dotnet-watch-for-maui.md`)

# `dotnet watch` for .NET MAUI Scenarios

## Overview

This spec describes how `dotnet watch` provides Hot Reload for mobile platforms (Android, iOS), which cannot use the standard named pipe transport. Similar to how web applications already use websockets for reloading CSS and JavaScript, we will use the same model for mobile applications.

## Transport Selection

| Platform        | Transport  | Reason                                                                        |
|-----------------|------------|-------------------------------------------------------------------------------|
| Desktop/Console | Named Pipe | Existing implementation, Fast, local IPC                                      |
| Android/iOS     | WebSocket  | Named pipes don't work over the network; `adb reverse` tunnels the connection |

`dotnet-watch` detects WebSocket transport via the `HotReloadWebSockets` capability:

```xml
<ProjectCapability Include="HotReloadWebSockets" />
```

Mobile workloads (Android, iOS) add this capability to their SDK targets. This allows any workload to opt into WebSocket-based hot reload.
Mobile workloads also declare `RuntimeEnvironmentVariableSupport` so that the workload can
include the build-owned public key and launch settings in the app's runtime
environment.

## SDK Changes ([dotnet/sdk#52581](https://github.com/dotnet/sdk/pull/52581))

### WebSocket Details

`dotnet-watch` already has a WebSocket server for web apps: `BrowserRefreshServer`. This server:

- Hosts via Kestrel on `https://localhost:<port>`
- Communicates with JavaScript (`aspnetcore-browser-refresh.js`) injected into web pages
- Sends commands like "refresh CSS", "reload page", "apply Blazor delta"

For mobile, we reuse the Kestrel infrastructure but with a different protocol:

| Server                     | Client                 | Protocol                                   |
|----------------------------|------------------------|--------------------------------------------|
| `BrowserRefreshServer`     | JavaScript in browser  | JSON messages for CSS/page refresh         |
| `WebSocketClientTransport` | Startup hook on device | Binary delta payloads (same as named pipe) |

The mobile transport (`WebSocketClientTransport`) composes a sealed `KestrelWebSocketServer` and speaks the same binary protocol as the named pipe transport, just over WebSocket instead.

### WebSocket Authentication

Mobile uses the same RSA-OAEP-SHA256 exchange as WASM/browser tools:

1. **Build the key pair.** For `.NETCoreApp` projects with `HotReloadWebSockets`,
   [`EnsureHotReloadWebSocketKey`](../../src/Tasks/Microsoft.NET.Build.Tasks/EnsureHotReloadWebSocketKey.cs)
   creates an RSA-2048 pair under `$(IntermediateOutputPath)HotReload/`, in
   `websocket-key.public.json` and `websocket-key.private.json`. It shares
   [`HotReloadKeyPair`](../../src/Common/HotReloadKeyPair.cs) with the browser task.
   Valid keys are reused; missing or invalid keys are regenerated. `Clean` removes
   both files. Design-time builds skip generation; configuration and
   `EnableHotReloadInRuntimeConfigDevFile` do not control it.
2. **Pin the public key.** The build supplies the Base64 SubjectPublicKeyInfo as
   `DOTNET_WATCH_HOTRELOAD_WEBSOCKET_KEY` through a `RuntimeEnvironmentVariable` item.
   The workload consumes it as an app setting, without changing the environment of
   `dotnet run` or its build processes. This also runs before deployment and
   run-argument computation for `--no-build`, and replaces any launch-supplied key.
   The private key stays in the intermediate directory.
3. **Send a secret.** The agent generates 32 random bytes, encrypts them with the
   public key, and sends URL-encoded standard Base64 as the WebSocket subprotocol.
4. **Echo the secret.** Watch loads the current key pair when the app connects.
   It returns HTTP 500 for unusable key files or HTTP 401 for invalid credentials,
   before upgrade. On success, its first WebSocket text message is the decrypted
   secret encoded as Base64.
5. **Verify the provider.** The agent checks the echo before sending initialization
   or accepting updates. The connection timeout covers this check.

This authenticates the provider to the app, not an exclusive client identity.
The transport accepts one app connection per launch; additional connections receive
HTTP 409. Watch passes the endpoint through `DOTNET_WATCH_HOTRELOAD_WEBSOCKET_ENDPOINT`
but does not supply the public key.

### 1. WebSocket Capability Detection

[ProjectGraphUtilities.cs](../../src/Dotnet.Watch/Watch/Build/ProjectGraphUtilities.cs) checks for the `HotReloadWebSockets` capability.

### 2. MobileAppModel

Creates a `DefaultHotReloadClient` with a `WebSocketClientTransport` instead of the default `NamedPipeClientTransport`.

### 3. Environment Variables

`dotnet-watch` launches the app via:

```dotnetcli
dotnet run --no-build \
  -e DOTNET_WATCH=1 \
  -e DOTNET_MODIFIABLE_ASSEMBLIES=debug \
  -e DOTNET_WATCH_HOTRELOAD_WEBSOCKET_ENDPOINT=ws://127.0.0.1:<port> \
  -e DOTNET_STARTUP_HOOKS=<path to DeltaApplier.dll>
```

The port is dynamically assigned (defaults to 0, meaning the OS picks an available port) to avoid conflicts in CI and parallel test scenarios. The `DOTNET_WATCH_AGENT_WEBSOCKET_PORT` environment variable can override this if a specific port is needed.

These environment variables are passed as `@(RuntimeEnvironmentVariable)` MSBuild items to the workload. See [dotnet-run-for-maui.md](dotnet-run-for-maui.md) for details on `dotnet run` and environment variables.

## Android Workload Changes (Example Integration)

### [dotnet/android#10770](https://github.com/dotnet/android/pull/10770) — RuntimeEnvironmentVariable Support

Enables the Android workload to receive env vars from `dotnet run -e`:

- Adds `<ProjectCapability Include="RuntimeEnvironmentVariableSupport" />`
- Adds `<ProjectCapability Include="HotReloadWebSockets" />` to opt into WebSocket-based hot reload
- Configures `@(RuntimeEnvironmentVariable)` items, so they will apply to Android.

### [dotnet/android#10778](https://github.com/dotnet/android/pull/10778) — dotnet-watch Integration

1. **Startup Hook:** Parses `DOTNET_STARTUP_HOOKS`, includes the assembly in the app package, rewrites the path to just the assembly name (since the full path doesn't exist on device)
2. **Port Forwarding:** Runs `adb reverse tcp:<port> tcp:<port>` so the device can reach the host's WebSocket server via `127.0.0.1:<port>` (port is parsed from the endpoint URL)
3. **Prevents Double Connection:** Disables startup hooks in `Microsoft.Android.Run` (the desktop launcher) so only the mobile app connects

## Data Flow

1. **Build:** `dotnet-watch` builds the project, detects `HotReloadWebSockets` capability
2. **Launch:** `dotnet run -e DOTNET_WATCH_HOTRELOAD_WEBSOCKET_ENDPOINT=ws://127.0.0.1:<port> -e DOTNET_STARTUP_HOOKS=...`
3. **Workload:** Android build tasks:
   - Include the startup hook DLL in the APK
   - Set up ADB port forwarding for the dynamically assigned port
   - Rewrite env vars for on-device paths
4. **Device:** App starts → StartupHook loads → `Transport.TryCreate()` reads env vars → `WebSocketTransport` encrypts secret with RSA public key → connects to `ws://127.0.0.1:<port>` with encrypted secret as subprotocol
5. **Server:** `WebSocketClientTransport` reads the build-owned key, decrypts the secret, and echoes it. The app checks the echo before it sends its initialization response.
6. **Hot Reload:** File change → delta compiled → sent over WebSocket → applied on device

## iOS

Similar changes will be made in the iOS workload to opt into WebSocket-based hot reload:

- Add `<ProjectCapability Include="HotReloadWebSockets" />`
- Handle startup hooks and port forwarding similar to Android

## Dependencies

- **[runtime#123964](https://github.com/dotnet/runtime/pull/123964):** [mono] read `$DOTNET_STARTUP_HOOKS` — needed for Mono runtime to honor startup hooks (temporary workaround via `RuntimeHostConfigurationOption`)

---

### Documentation Specs Runtime Configuration File (`documentation/specs/runtime-configuration-file.md`)

# Runtime Configuration Files

The runtime configuration files store the dependencies of an application (formerly stored in the `.deps` file). They also include runtime configuration options, such as the Garbage Collector mode. Optionally they can also include data for runtime compilation (compilation settings used to compile the original application, and reference assemblies used by the application).

## What produces the files and where are they?

There are two runtime configuration files for a particular application. Given a project named `MyApp`, the compilation process produces the following files (on Windows, other platforms are similar):

* `MyApp.dll` - The managed assembly for `MyApp`, including an ECMA-compliant entry point token.
* `MyApp.exe` - A copy of the `apphost.exe` executable. This is present when the application is self-contained, and in newer functionality (2.1.0+) for framework-dependent applications that wish to support platform-specific (non-portable) executables.
* `MyApp.runtimeconfig.json` - An **optional** configuration file containing runtime configuration settings. This file is required for framework-dependent applications, but not for self-contained apps.
* `MyApp.runtimeconfig.dev.json` - An **optional** configuration file containing runtime configuration settings that typically only exists in a non-published output and thus is used for development-time scenarios. This file typically specifies additional probing paths. Depending on the semantics of each setting, the setting is either combined with or overridden by the values from `MyApp.runtimeconfig.json`.
* `MyApp.deps.json` - A list of dependencies, compilation dependencies and version information used to address assembly conflicts. Not technically required, but required to use the servicing or package cache/shared package install features, and to assist during roll-forward scenarios to select the newest version of any assembly that exists more than once in the application and framework(s). If the file is not present, all assemblies in the current folder are used instead.

The `MyApp.runtimeconfig.json` is designed to be user-editable (in the case of an app consumer wanting to change various CLR runtime options for an app, much like the `MyApp.exe.config` XML file works in .NET 4.x today). However, the `MyApp.deps.json` file is designed to be processed by automated tools and should not be user-edited. Having the files as separate makes this clearer. We could use a different format for the deps file, but if we're already integrating a JSON parser into the host, it seems most appropriate to re-use that here. Also, there are diagnostic benefits to being able to read the `.deps.json` file in a simple text editor.

**IMPORTANT**: Framework-dependent applications have some adjustments to this spec which are covered at the end.

## File format

The files are both JSON files stored in UTF-8 encoding. Below are sample files. Note that not all sections are required and some will be opt-in only (see below for more details). The `.runtimeconfig.json` file is completely optional, and in the `.deps.json` file, only the `runtimeTarget`, `targets` and `libraries` sections are required (and within the `targets` section, only the runtime-specific target is required). If no `.deps.json` exists, all assemblies local to the app will be added as TPA (trusted platform assemblies).

### [appname].runtimeconfig.json
```json
{
    "runtimeOptions": {
        "configProperties": {
            "System.GC.Server": true,
            "System.GC.Concurrent": true,
            "System.Threading.ThreadPool.MinThreads": 4,
            "System.Threading.ThreadPool.MaxThreads": 8
        },
        "tfm": "netcoreapp2.1",
        "framework": {
            "name": "Microsoft.NETCore.App",
            "version": "2.1.0"
        },
        "applyPatches": true,
        "rollForwardOnNoCandidateFx": 1
    }
}
```

### [appname].deps.json
```
/* Detailed source-code truncated for AI context efficiency. */
```

## Sections

### `runtimeOptions` Section (`.runtimeconfig.json`)

This section is created when building a project. Settings include:
* `configProperties` - Indicates configuration properties to configure the runtime and the framework
  * Examples:
    * Full list of [configuration properties](https://github.com/dotnet/docs/blob/main/docs/core/runtime-config/index.md) for CoreCLR.
    * `System.GC.Server` (old: `gcServer`) - Boolean indicating if the server GC should be used (Default: `true`).
    * `System.GC.Concurrent` (old: `gcConcurrent`) - Boolean indicating if background garbage collection should be used.
* `framework` - Indicates the `name`, `version`, and other properties of the shared framework to use when activating the application including `applyPatches` and `rollForwardOnNoCandidateFx`. The presence of this section (or another framework in the new `frameworks` section) indicates that the application is a framework-dependent app.
* `rollForward` - Introduced in .NET Core 3.0. Determines roll-forward behavior. Values: `LatestPatch`, `Minor`, `Major`, `LatestMinor`, `LatestMajor`, `Disable`. See [high-level design](https://github.com/dotnet/designs/blob/main/accepted/2019/runtime-binding.md#rollforward) and [detailed design](https://github.com/dotnet/runtime/blob/main/docs/design/features/framework-version-resolution.md) for more information.
* `applyPatches` - **Deprecated in favor of `rollForward`**, please use `rollForward` property instead. When `false`, the most compatible framework version previously found is used. When `applyPatches` is unspecified or `true`, the framework from either the same or a higher version that differs only by the patch field will be used. See [roll-forward-on-no-candidate documentation](https://github.com/dotnet/runtime/blob/main/docs/design/features/roll-forward-on-no-candidate-fx.md) for more information.
* `rollForwardOnNoCandidateFx` - **Deprecated in favor of `rollForward`**, please use `rollForward` property instead - Determines roll-forward behavior. Only applies to `production` releases. Values: 0(Off), 1 (roll forward on [minor] or [patch]), 2 (Roll forward on [major], [minor] or [patch])
 See [roll-forward-on-no-candidate documentation](https://github.com/dotnet/runtime/blob/main/docs/design/features/roll-forward-on-no-candidate-fx.md) for more information.
* `frameworks` - This is an optional array added in 3.0 that allows multiple frameworks to be specified. The `name`, `version`, `rollForward` (.NET Core 3.0 +), `applyPatches` (deprecated) and `rollForwardOnNoCandidateFx` (deprecated) properties are available. The `framework` section is no longer necessary in 3.0, but if present is treated as if it was the first framework in the `frameworks` section. The presence of frameworks in this section (or the `framework` section) indicates that the application is a framework-dependent app. See the notes at the end of this document for more information.
* `additionalProbingPaths` - Optional property which specifies additional paths to consider when looking for dependencies. The value is either a single string, or an array of strings.
* `tfm` - Optional string value which specifies the Target Framework Moniker.

These settings are read by host (apphost or dotnet executable) to determine how to initialize the runtime. All versions of the host **must ignore** settings in this section that they do not understand (thus allowing new settings to be added in later versions).

### `compilationOptions` Section (`.deps.json`)

This section is created during build from the project's settings. The exact settings found here are specific to the compiler that produced the original application binary. Some example settings include: `defines`, `languageVersion` (e.g. the version of C# or VB), `allowUnsafe` (a C# option), etc.
This section is ignored by the runtime host. It is only potentially used by the application itself.

### `runtimeTarget` Section (`.deps.json`)

This property contains the name of the target from `targets` that should be used by the runtime. This is present to simplify the host so that it does not have to parse or understand target names and the meaning thereof.

### `targets` Section (`.deps.json`)

Each property under `targets` describes a "target", which is a collection of libraries required by the application when run or compiled in a certain framework and platform context. A target **must** specify a Framework name, and **may** specify a Runtime Identifier. Targets without Runtime Identifiers represent the dependencies and assets which are platform agnostic. These targets can also represent dependencies and assets which are used for compiling the application for a particular framework. Targets with Runtime Identifiers represent the dependencies and assets used for running the application under a particular framework and on the platform defined by the Runtime Identifier.
In the example above, the `.NETCoreApp,Version=v2.1` target lists the dependencies and assets used to run and compile the application for `netcoreapp2.1`.
If the app was published specifically for 64-bit Mac OS X 10.10 machine, it would also contain a target `.NETCoreApp,Version=v2.1/osx.10.10-x64` which would list the dependencies and assets used to run the application on that specific platform.

There will always at least one target in the `[appname].deps.json` file: the platform neutral list of runtime and compilation dependencies. In cases of a platform specific application there would be two targets: a compilation target, and a runtime target. The compilation target will be named with the framework name used for the compilation (`.NETCoreApp,Version=v2.1` in the example above). The runtime target will be named with the framework name and runtime identifier used to execute the application (`.NETCoreApp,Version=v2.5/osx.10.10-x64` in the example above). However, the runtime target will also be identified by name in the `runtimeOptions` section, so that the host does not need to parse and understand target names.

The content of each target property in the JSON is a JSON object. Each property of that JSON object represents a single dependency required by the application when compiled for/run on that target. The name of the property contains the ID and Version of the dependency in the form `[Id]/[Version]`. The content of the property is another JSON object containing metadata about the dependency.

The `dependencies` property of a dependency object defines the ID and Version of direct dependencies of this node. It is a JSON object where the property names are the ID of the dependency and the content of each property is the Version of the dependency.

The `runtime` property of a dependency object lists the relative paths to Managed Assemblies required to be available at runtime in order to satisfy this dependency. The paths are relative to the location of the Dependency (see below for further details on locating a dependency).

The `resources` property of a dependency object lists the relative paths and locales of Managed Satellite Assemblies which provide resources for other languages. Each item contains a `locale` property specifying the [IETF Language Tag](https://en.wikipedia.org/wiki/IETF_language_tag) for the satellite assembly (or more specifically, a value usable in the Culture field for a CLR Assembly Name).

The `native` property of a dependency object lists the relative paths to Native Libraries required to be available at runtime in order to satisfy this dependency. The paths are relative to the location of the Dependency (see below for further details on locating a dependency).

The `runtimeTargets` property of a dependency object lists RID-specific assets. This is only used for framework dependent applications. See the description of framework dependent apps below for more details.

The `compile` property of a dependency object lists the relative paths to Reference Assemblies which were used to compile the application.

If a given dependency is only listed for compilation, then its `runtime`, `resources` and `native` properties is omitted. Similarly if the dependency is only listed for runtime, then its `compile` property is omitted.

Only dependencies with a `type` value of `package` (as per the `libraries` section described below) should be considered by the host. There may be other items, used for other purposes (for example, Projects, Reference Assemblies, etc). Note that currently host basically ignores the `type` property.

### `libraries` Section (`.deps.json`)

This section contains a union of all the dependencies found in the various targets, and contains common metadata for them. Specifically, it contains:
* `type` - the type of the library. `package` for NuGet packages. `project` for a project reference. Can be other things as well.
* `path` - in the `package` library this is a relative path where to find the assets.
* `serviceable` - a boolean indicating if the library can be serviced (only for `package`-typed libraries)
* `sha512` - SHA-512 hash of the package file (`package`-typed libraries).
* `hashPath` - in the `package` library this is a relative path to the `.nupkg.sha512` hash file.

### `runtimes` Section (`.deps.json`)

This section is only present in the root framework's (so `Microsoft.NETCore.App`) `.deps.json` and it contains the RID fallback graph. See below for detailed description of this section. Example (trimmed):
```json
{
    "runtimes": {
        "win-x64": [
            "win",
            "any",
            "base"
        ]
    }
}
```


## How the file is used

The file is read by two different components:

* The host uses it to determine what to place on the TPA and Native Library Search Path lists, as well as what runtime settings to apply (GC type, etc.).
* `Microsoft.Extensions.DependencyModel` uses it to allow a running managed application to query various data about it's dependencies. For example:
  * To find all dependencies that depend on a particular package (used by ASP.NET MVC and other plugin-based systems to identify assemblies that should be searched for possible plugin implementations)
  * To determine the reference assemblies used by the application when it was compiled in order to allow runtime compilation to use the same reference assemblies (used by ASP.NET Razor to compile views)
  * To determine the compilation settings used by the application in order to allow runtime compilation to use the same settings (also used by ASP.NET Razor views).

## Opt-In Compilation Data

Some of the sections in the `.deps.json` file contain data used for runtime compilation. This data is not provided in the file by default. Instead, an MSBuild property `PreserveCompilationContext` must be set to `true` (typically in the project file) in order to ensure this data is added. Without this setting, the `compilationOptions` will not be present in the file, and the `targets` section will contain only the runtime dependencies.
Note that ASP.NET projects (those using `Microsoft.NET.Sdk.Web` SDK) has this property set to `true` by default.

## Framework-dependent Deployment Model

An application can be deployed in a "framework-dependent" deployment model. In this case, the RID-specific assets of packages are published within a folder structure that preserves the RID metadata. However the host does not use this folder structure, rather it reads data from the `.deps.json` file.

In the framework-dependent deployment model, the `*.runtimeConfig.json` file will contain the `runtimeOptions.framework` section:

```json
{
    "runtimeOptions": {
        "framework": {
            "name": "Microsoft.NETCore.App",
            "version": "1.0.1"
        }
    }
}
```

This data is used to locate the shared framework folder. The exact mechanics of which version are selected are defined in the [shared framework lookup](https://github.com/dotnet/core-setup/blob/main/Documentation/design-docs/multilevel-sharedfx-lookup.md) document. In general, it locates the shared runtime in the `shared` folder located beside it by using the relative path `shared/[runtimeOptions.framework.name]/[runtimeOptions.framework.version]`. Once it has applied any version roll-forward logic and come to a final path to the shared framework, it locates the `[runtimeOptions.framework.name].deps.json` file within that folder and loads it **first**.

Note, starting with 3.0, the "framework" section is optional and a new "frameworks" section supports multiple frameworks:
```json
{
    "runtimeOptions": {
        "frameworks": [
            {
                "name": "Microsoft.AspNetCore.All",
                "version": "3.0.0"
            },
            {
                "name": "Microsoft.Forms",
                "version": "3.0.0"
            }
        ]
    }
}
```

Next, the deps file from the application is loaded and (conceptually) merged into this deps file. Data from the app-local deps file trumps data from the shared framework.

The shared framework's deps file will also contain a `runtimes` section defining the fallback logic for all RIDs known to that shared framework. For example, a shared framework deps file installed into a Ubuntu machine may look something like the following:

```json
{
    "runtimeTarget": {
        "name": ".NETStandardApp,Version=v1.5",
        "portable": false
    },
    "targets": {
        ".NETStandardApp,Version=v1.5": {
            "System.Runtime/4.0.0": {
                "runtime": "lib/netstandard1.5/System.Runtime.dll"
            },
            "... other libraries ...": {}
        }
    },
    "libraries": {
        "System.Runtime/4.0.0": {
            "type": "package",
            "serviceable": true,
            "sha512": "[base64 string]"
        },
        "... other libraries ...": {}
    },
    "runtimes": {
        "ubuntu.15.04-x64": [ "ubuntu.14.10-x64", "ubuntu.14.04-x64", "debian.8-x64", "linux-x64", "linux", "unix", "any", "base" ],
        "ubuntu.14.10-x64": [ "ubuntu.14.04-x64", "debian.8-x64", "linux-x64", "linux", "unix", "any", "base" ],
        "ubuntu.14.04-x64": [ "debian.8-x64", "linux-x64", "linux", "unix", "any", "base" ]
    }
}
```

The host will detect the RID at runtime (for example, `ubuntu.14.04-x64` for Ubuntu 14.04 64bit). It will look up the corresponding entry in the `runtimes` section to identify what the fallback list is for `ubuntu.14.04-x64`. The fallbacks are identified from most-specific to least-specific. In the case of `ubuntu.14.04-x64` and the example above, the fallback list is: `"debian.8-x64", "linux-x64", "linux", "unix", "any", "base"` (note that an exact match on the RID itself is the first preference, followed by the first item in the fallback list, then the next item, and so on).

In the app-local deps file for a `framework-dependent` application, the package entries may have an additional `runtimeTargets` section detailing RID-specific assets. The host should use this data, along with the current RID and the RID fallback data defined in the `runtimes` section of the shared framework deps file to select one **and only one** RID value out of each package individually. The most specific RID present within the package should always be selected.

Consider an application built for `ubuntu.14.04-x64` and the following snippet from an app-local deps file (some sections removed for brevity).

```
/* Detailed source-code truncated for AI context efficiency. */
```

When setting up the TPA and native library lists, it will do the following for the `System.Data.SqlClient` entry in the example above:

1. Add all entries from the root `runtime` and `native` sections (not present in the example). (Note: This is essentially the current behavior for the existing deps file format)
2. Add all appropriate entries from the `runtimeTargets` section, based on the `rid` property of each item:
  1. Attempt to locate any item for the RID `ubuntu.14.04-x64`. If any asset is matched, take **only** the items matching that RID exactly and add them to the appropriate lists based on the `assetType` value (`runtime` for managed code, `native` for native code)
  2. Reattempt the previous step using the first RID in the list provided by the list in the `runtimes."ubuntu.14.04-x64"` section of the shared framework deps file. If any asset is matched, take **only** the items matching that RID exactly and add them to the appropriate lists
  3. Continue to reattempt the previous search for each RID in the list, from left to right until a match is found or the list is exhausted. Exhausting the list without finding an asset, when a `runtimeTargets` section is present is **not** an error, it simply indicates that there is no need for a runtime-specific asset for that package.

Note one important aspect about asset resolution: The resolution scope is **per-package**, **not per-application**, **nor per-asset**. For each individual package, the most appropriate RID is selected, and **all** assets taken from that package must match the selected RID exactly. For example, if a package provides both a `linux-x64` and a `unix` RID (in the `ubuntu.14.04-x64` example above), **only** the `linux-x64` asset would be selected for that package. However, if a different package provides only a `unix` RID, then the asset from the `unix` RID would be selected.

The path to a runtime-specific asset is resolved in the same way as a normal asset (first check Servicing, then Package Cache, App-Local, Global Packages Location, etc.) with **one exception**. When searching app-local, rather than just looking for the simple file name in the app-local directory, a runtime-specific asset is expected to be located in a subdirectory matching the relative path information for that asset in the lock file. So the `native` `sni.dll` asset for `win7-x64` in the `System.Data.SqlClient` example above would be located at `APPROOT/runtimes/win7-x64/native/sni.dll`, rather than the normal app-local path of `APPROOT/sni.dll`.

Each entry in the `runtime` or `runtimeTargets` sections can also have `assemblyVersion` and `fileVersion` properties. These specify the assembly and file version of the assembly being referenced. These versions are used when resolving assemblies based on roll-forward settings. See the [Multi Level Shared FX Lookup](https://github.com/dotnet/core-setup/blob/main/Documentation/design-docs/multilevel-sharedfx-lookup.md#hostpolicy-changes-for-21) for more details.

## Additional information on runtimeconfig.json framework settings (3.0+)
With the addition of the `frameworks` section in 3.0, an application (or another framework) can reference multiple frameworks. This is necessary when more than one framework is being used by the application (or framework). Previously, an application or framework could only reference one framework, causing a "chain" of frameworks. Now, with multiple frameworks at each level, a "graph" or "tree" of frameworks is supported.

In addition to specifying a dependency on more than one framework, the `frameworks` section can also be used to override settings from a framework's `runtimeconfig.json`; this should only be done with the understanding of all consequences including preventing roll-forward compatibility to future versions. The settings include `version`, `rollForwardOnNoCandidateFx` and `applyPatches`, with `version` the most likely value to be changed.

Overriding a value is always "most restrictive". This means if `applyPatches` is already `false` in a lower-level framework, then it cannot be changed to `true`. For `rollForwardOnNoCandidateFx` the value 0=off is the most restrictive, then 1=minor\patch, then 2=major\minor\patch. For `version`, the highest version requested will be used.

As an example of overriding settings, assume the following framework layering:
- Application
- Microsoft.AspNetCore.All
- Microsoft.AspNetCore.App
- Microsoft.NetCore.App

Except for Microsoft.NetCore.App (since it does not have a lower-level framework), each layer has a runtimeconfig.json setting specifying a single lower-layer framework's `name`, `version` and optional `rollForwardOnNoCandidateFx` and `applyPatches`.

The normal hierarchy processing for most knobs, such as `rollForwardOnNoCandidateFx`:
 - a) Default value determined by the framework (e.g. roll-forward on [Minor])
 - b) Environment variable override (e.g. `DOTNET_ROLL_FORWARD_ON_NO_CANDIDATE_FX`)
 - c) Each layer's `runtimeOptions` override setting in its runtimeconfig.json, starting with app (e.g. `rollForwardOnNoCandidateFx`). Lower layers can override this.
 - d) The app's `frameworks` section in `[appname].runtimeconfig.json` which allows knobs per-framework.
 - e) A `--` command line value such as `--roll-forward-on-no-candidate-fx`

In a hypothetical example, `Microsoft.AspNetCore.App` references version `2.2.0` of `Microsoft.NetCore.App` in `Microsoft.AspNetCore.App.runtimeconfig.json`:
```json
{
    "runtimeOptions": {
        "framework": {
            "name": "Microsoft.NetCore.App",
            "version": "2.2.0"
        },
     }
}
```
However, if the app requires the newer version `2.2.1` of `Microsoft.NetCore.App`, then mechanism `d` is used. An example of the `frameworks` section for mechanism `d` in the app's `runtimeconfig.json`:
```json
{
    "runtimeOptions": {
        "framework": {
            "name": "Microsoft.AspNetCore.All",
            "version": "1.0.1"
        },
        "frameworks": [
            {
                "name": "Microsoft.AspNetCore.App",
                "version": "2.2.1",
            }
        ]
    }
}
```

---

### Documentation TemplateEngine Api Inside The Template Engine (`documentation/TemplateEngine/api/Inside-the-Template-Engine.md`)

# Inside the Template Engine

The template engine is composed of several different subsystems, which are
designed to separate gathering, instantiating and processing templates.

- [Overview of the subsystems](#overview-of-the-subsystems)
  - [IEngineEnvironmentSettings](#iengineenvironmentsettings)
  - [TemplatePackageManager class](#templatepackagemanager-class)
  - [TemplateCreator class](#templatecreator-class)
    - [Supplying parameters conditions results](#supplying-parameters-conditions-results)
- [Template Engine packages](#template-engine-packages)
- [Components](#components)
  - [Template package providers](#template-package-providers)
  - [Installer](#installer)
  - [Mount point](#mount-point)
  - [Registering the components](#registering-the-components)
- [Microsoft.TemplateEngine.IDE](#microsofttemplateengineide)

# Overview of the subsystems

## [IEngineEnvironmentSettings](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/IEngineEnvironmentSettings.cs) 

This is responsible for holding all properties of the environment.

Template engine provides a default implementation:
[EngineEnvironmentSettings](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/EngineEnvironmentSettings.cs).

It has a single constructor that accepts ITemplateEngineHost and set up settings
based on TemplateEngine.Edge implementation of component manager, paths, and
environment. All this can also be passed in as optional parameters.

### [ITemplateEngineHost](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/ITemplateEngineHost.cs)

The interface is responsible for providing host information to template engine,
managing file system and logging. Host may also provide default parameter
values for templates via `TryGetHostParamDefault` method.

Applications using template engine are often called “hosts”.
The .NET SDK includes one such host: the dotnet new CLI.

Main host properties:

-   Identifier – unique name of the host

-   Version – version of the host

Those properties are used to identify host to various built-in components
explained below.

If you are considering using the template engine core, you need to create an
implementation of this interface representing your host. Template engine
provides the default implementation:
[DefaultTemplateEngineHost](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/DefaultTemplateEngineHost.cs).

#### [IPhysicalFileSystem](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/PhysicalFileSystem/IPhysicalFileSystem.cs)
Abstraction over file system, accessible from ITemplateEngineHost.

Each template engine host should support physical and in-memory file system and
virtualize the file system under a given path. Switching between physical and in-memory
file systems is done via `ITemplateEngineHost.VirtualizePath` method.

Template engine provides default implementation of file systems:
[PhysicalFileSystem](../../../src/TemplateEngine/Microsoft.TemplateEngine.Utils/PhysicalFileSystem.cs)
and
[InMemoryFileSystem](../../../src/TemplateEngine/Microsoft.TemplateEngine.Utils/InMemoryFileSystem.cs).

### [IComponentManager](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/IComponentManager.cs)

`ComponentManager` is responsible for loading [components](#components) provided by the host from
`ITemplateEngineHost.BuiltIns`. Additional components can be added via
`IComponentManager.AddComponent`. Similar to templates, components are also 
dynamically loaded from template packages during scanning. `ComponentManager`
implementation is not publicly accessible; however, it is used when default
implementation of `IEngineEnvironmentSettings` is used.

### [IEnvironment](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/IEnvironment.cs)

Abstraction over environment variables. Default implementation uses system
environment variables.

### [IPathInfo](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/IPathInfo.cs)

Provides the main paths used by template engine: global settings path, host
settings path, host version settings path.

The default locations are:

-   \<home directory\>/.templateengine – global settings

-   \<home directory\>/.templateengine/\<host ID\> – host settings

-   \<home directory\>/.templateengine/\<host ID\>/\<host version\> – host
    version settings

## [TemplatePackageManager](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/Settings/TemplatePackageManager.cs) class

The class responsible for managing templates and templates packages.

-   Gets available providers to install/update/uninstall template packages
    available via IComponentManager

-   Gets available template packages

-   TemplatePackagesChanged which is triggered when list of template packages
    changes

-   Gets available templates

-   Manages template packages cache and template cache.

The host need to instantiate the class when needed. Note that the first-time run
can be time consuming, so consider creating one instance for duration of hosting
application.

## [TemplateCreator](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/Template/TemplateCreator.cs) class

The class responsible for template creation, including dry run. The host need to
instantiate the class when needed.

### Supplying parameters conditions results

It is possible to supply evaluation results of parameters conditions when instantiating template via Edge API [`TemplateCreator.InstantiateAsync`](https://github.com/dotnet/sdk/blob/6423cf7db53/src/TemplateEngine/Microsoft.TemplateEngine.Edge/Template/TemplateCreator.cs#L76). Example use case is instantiation from Visual Studio host, that will leverage condition evaluator integrated within the New Project Dialog. 

This can be achieved by passing the structured [`InputDataSet`](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/Template/InputDataSet.cs) argument that is populated with [`EvaluatedInputParameterData`](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/Template/EvaluatedInputParameterData.cs) objects for evaluated parameters. 

It is currently not possible to provide just partial external evaluation - meaning that the template engine evaluates either all the parameter conditions or none. If the [`InputDataSet`](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/Template/InputDataSet.cs) collection contains at least one [`EvaluatedInputParameterData`](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/Template/EvaluatedInputParameterData.cs) element, results of all parameter conditions are expected to be passed.

Template engine cross checks externally passed evaluations. If it encounteres mismatch between externally passed result and internal evaluation result a failed `ITemplateCreationResult` is returned from `InstantiateAsync` API. Failure is indicated by [`CondtionsEvaluationMismatch`](https://github.com/dotnet/sdk/blob/6423cf7db53/src/TemplateEngine/Microsoft.TemplateEngine.Edge/Template/CreationResultStatus.cs#L57) in [`Status`](https://github.com/dotnet/sdk/blob/6423cf7db53/src/TemplateEngine/Microsoft.TemplateEngine.Edge/Template/ITemplateCreationResult.cs#L39) property.


## [TemplateConstraintManager](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/TemplateConstraintManager.cs) class

The class responsible for loading available constraint components and evaluating the constraints for given template.

# Template Engine packages

Template engine publishes the following packages:

-   [Microsoft.TemplateEngine.Abstractions](https://www.nuget.org/packages/Microsoft.TemplateEngine.Abstractions) – contains interfaces to work with
    template engine

-   [Microsoft.TemplateEngine.Egde](https://www.nuget.org/packages/Microsoft.TemplateEngine.Edge) – enables hosting the template engine in the
    application

-   [Microsoft.TemplateEngine.IDE](https://www.nuget.org/packages/Microsoft.TemplateEngine.IDE) – lightweight API over Edge (optional to use)

-   [Microsoft.TemplateEngine.Orchestrator.RunnableProjects](https://www.nuget.org/packages/Microsoft.TemplateEngine.Orchestrator.RunnableProjects) – template engine
    default generator (a.k.a. the generator of template.json format)

-   [Microsoft.TemplateEngine.Utils](https://www.nuget.org/packages/Microsoft.TemplateEngine.Utils) – different utilities useful for template
    engine usage

# Components

Main purpose of components is to allow template authors and host implementers to
supply their own implementations of different interfaces and to invoke them by
specifying GUID or name that defines component in template.json. Components can
be split into two main categories:

-   the components required to run templates:

    -   macros

    -   post actions (TBD)

    -   generators

    -   constraints

    -   bind source

-   the components required by the host:

    -   template package providers: managed and non-managed

    -   installers

    -   mount points

## Template package providers 

Template package providers responsible for providing template packages the
template engine needs to manage. There are two kinds of providers:

-   Non-managed
    ([ITemplatePackageProvider](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackageProvider.cs))
    – the template engine uses the packages provided by provider however cannot
    modify them

-   Managed
    ([IManagedTemplatePackageProvider](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/TemplatePackage/IManagedTemplatePackageProvider.cs))
    – the template engine can install/update/uninstall packages to provider.

Template engine provides the following providers:

-   Global settings managed provider – the packages available to all template
    engine hosts using built in implementation.

-   (not available yet) host managed provider - the packages available to
    current host.

-   (not available yet) host version managed provider - the packages available
    to current host version.

Template engine also provides [default non-managed provider
implementation](../../../src/TemplateEngine/Microsoft.TemplateEngine.Utils/DefaultTemplatePackageProvider.cs)
that can be used by other hosts to build simple providers or base implementation
on. Here are two examples:
[SdkTemplates](../../../src/Cli/dotnet/Commands/New/BuiltInTemplatePackageProvider.cs)
and
[OptionalWorkloads](../../../src/Cli/dotnet/Commands/New/OptionalWorkloadProvider.cs).

### Prioritizing the providers

Template providers can implement the
[IPrioritizedComponent](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/IPrioritizedComponent.cs)
interface to setup the provider priority. The providers will be read following
the priority with the priority with largest value of priority to be preferred in
case the providers have same templates defined.

The default priority of Global Settings provider is 1000. If priority is not
defined, the provider will be treated as provider with priority 0.

Note: it is possible to define negative priority, then the provider will be
lower priority than default.

When implementing provider, note that the packages returned by provider will be
processed exactly in the same order they provided, in case of template is
available in several packages, the last package will win.

## [Installer](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Installer/IInstaller.cs)

Installer installs, updates and uninstall the template packages that can be feed
to template package providers.

Template engine provides two installer implementations:

-   NuGet – installs the template package from NuGet feed

-   Folder – installs the template package from given folder path

You can use them when implementing your own providers, they are available from
IComponentManager.

When package verification is enabled, downloaded signed NuGet packages are
verified using `dotnet nuget verify --all` before installation. Unsigned packages
are accepted only when NuGet's `signatureValidationMode` is `accept` and the
source does not declare `allRepositorySigned=true`. A client policy of `require`
or a repository signing requirement rejects unsigned packages.

## [Mount point](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Mount/IMountPoint.cs)

Template package location is represented by mount point URI. Mount point that
can load certain type of URI are also components.

Template engine provides two mountpoint factory implementations:

-   Zip/NuGet – manages zip package/NuGet package

-   File System – manages folder on local file system

They are available from IComponentManager.

It is possible to get mount point using bool TryGetMountPoint(string
mountPointUri, out IMountPoint mountPoint) method of IEngineEnvironmentSettings.

## [Constraint](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Constraints/ITemplateConstraint.cs)

The template may define certain constraint(s) under which it can be used. The constraint implementation evaluates those restrictions and whether such template is allowed to be used or is restricted.
Template engine host works with constraint using `TemplateConstraintManager` class.

## [Bind symbol source](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Components/IBindSymbolSource.cs)

The template may define `bind` symbols. Those symbols might be bound to values provided externally using bind symbol source components.
Default sources are:
- host provided parameters - uses prefix `host:`. Binds symbol to parameters provided by the host. 
- environment variables - uses prefix `env:`. Binds symbol to environment variables.

These components are defined in `Microsoft.TemplateEngine.Edge` and are part of mandatory components collection to be loaded.

If the `binding` does not have prefix, or prefixed value cannot be evaluated the evaluation without prefix is performed as the fallback. 
In case there are more than one component which returns the value, the component priority will be used to define the value to be bounded. In case of same priorities, the evaluation results in error.
The template author needs to explicitly specify the prefix in this case. It is possible to restrict usage of prefix with setting `IBindSymbolSource.RequiresPrefixMatch` to `true`. 


## Registering the components

When creating template engine host, all built in components will be registered.

If you’d like to use the runnable projects (template.json) generator available
from Microsoft.TemplateEngine.Orchestrator.RunnableProjects, you need to add it
using AddComponent method of IComponentManager.

You can implement the following own components and register them:

-   [ITemplateEngineProvider](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackageProvider.cs)
    – non-managed template package provider, via
    [ITemplatePackageProviderFactory](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackageProviderFactory.cs)

-   [IManagedTemplateEngineProvider](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/TemplatePackage/IManagedTemplatePackageProvider.cs)
    – managed template package provider, via
    [ITemplatePackageProviderFactory](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackageProviderFactory.cs)

-   [IMountPoint](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Mount/IMountPoint.cs)
    – mount point implementation, via
    [IMountPointFactory](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Mount/IMountPointFactory.cs)

-   [IInstaller](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Installer/IInstaller.cs)
    – template package installer, via
    [IInstallerFactory](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Installer/IInstallerFactory.cs)

-   [ITemplateConstraint](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Constraints/ITemplateConstraint.cs)
    – constraint implementation, via
    [ITemplateConstraintFactory](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Constraints/ITemplateConstraintFactory.cs)

-   [IBindSymbolSource](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/Components/IBindSymbolSource.cs)
    – bind symbol source implementation

It is possible to register additional components to in the following way:

-   Components of
    [ITemplateEngineHost.BuiltInComponents](https://github.com/dotnet/sdk/blob/6423cf7db53/src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/ITemplateEngineHost.cs#L17)
    will be added when loading environment settings. For
    DefaultTemplateEngineHost they can be passed to constructor.

-   You can use
    [IComponentManager.AddComponent](https://github.com/dotnet/sdk/blob/6423cf7db53/src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/IComponentManager.cs#L53)
    method to add the component in runtime.

Note that components are not persisted, so they should be added each time
EngineEnvironmentSettings instance is created.

# Microsoft.TemplateEngine.IDE 

The package provides
[Bootstrapper](../../../src/TemplateEngine/Microsoft.TemplateEngine.IDE/Bootstrapper.cs)
class allowing to setup and access main functionality of template engine via
single entry point.

Note that it is not mandatory to use
[Bootstrapper](../../../src/TemplateEngine/Microsoft.TemplateEngine.IDE/Bootstrapper.cs)
class to use template engine, however if you don’t need advanced features it
might be easier to start with using this API.

Basic workflow:

1.  The application hosting template engine should implement and instantiate
    [ITemplateEngineHost](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/ITemplateEngineHost.cs),
    or instantiate default implementation
    ([DefaultTemplateEngineHost](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/DefaultTemplateEngineHost.cs)).

2.  The application creates the instance of Bootstrapper:

    1.  If session state doesn’t need to be persisted use
        virtualizeConfiguration set to true – all the settings will be stored in
        memory only.

    2.  If the host assumes running default infrastructure, use
        loadDefaultComponents set to true – this will load the default generator
        and default infrastructure (providers, installers, mount points)

3.  If the application has the templates specific to it, the application should
    implement
    [ITemplatePackageProvider](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/TemplatePackage/ITemplatePackageProvider.cs)
    returning available template packages and register it via
    Bootstrapper.AddComponent method or provide it via built-in components of
    the host.

4.  To get template packages, use GetTemplatePackages method.

    Note: these templates are available to all template engine hosting
    applications for the current user.

5.  To manage template packages installed globally, use
    InstallTemplatePackagesAsync, GetLatestVersionAsync,
    UpdateTemplatePackagesAsync, UninstallTemplatePackagesAsync methods.

    Installation supports installing local sources (folder, packages) as well as
    installing NuGet packages from remote feeds.

    Note: these actions impact set of template packages available to all
    template engine hosting applications for the current user.

6.  To available list all templates, use GetTemplatesAsync method.

    The method also supports filters and criterias to filter templates. The
    default filters are available in
    [Utils.WellKnownSearchFilters](../../../src/TemplateEngine/Microsoft.TemplateEngine.Utils/WellKnownSearchFilters.cs)
    class.

7.  To dry run the template, use GetCreationEffectsAsync method.

    This method needs template definition (ITemplateInfo) that can be obtained
    through GetTemplatesAsync.

8.  To run the template, use CreateAsync method.

    This method needs template definition (ITemplateInfo) that can be obtained
    through GetTemplatesAsync.

Note: Bootstrapper class needs to be disposed.

---

### Documentation TemplateEngine Api Api Migration From Net 5 To Net 6 (`documentation/TemplateEngine/api/api-migration-from-net-5-to-net-6.md`)

# Template Engine API: Migration from .NET 3.1/.NET 5 to .NET 6

In .NET 6 the available API set has significantly changed with breaking changes
involved. The required changes when migrating from the earlier versions to .NET
6 are given below.

## Bootstrapper implementation

Most of the methods of
[Bootstrapper](../../../src/TemplateEngine/Microsoft.TemplateEngine.IDE/Bootstrapper.cs)
are obsolete now, preserving backward compatibility when possible. Please ensure
you use new methods when migrating to .NET 6, the obsolete messages in the code
will point to new version of method.

## Template package management

With .NET 6 a new way of template package management was introduced. Now the
template packages are managed using providers with ability to support several
providers and adding custom implementations of providers when implementing the
host. This was done to fix a bug that CLI templates disappeared on SDK version
update, support Optional Workloads and provide more future flexibility.

Template engine delivers one provider out of box in .NET 6 – global settings
template provider. The templates installed to this provider are available to all
the hosts using IDE/Edge implementations to work with template engine
generators.

(Now obsolete) Install and Uninstall methods of Bootstrapper now install
templates to the global settings template provider, this means the templates
installed via these methods will be available to all the hosts (including dotnet
new host), and other hosts may update or uninstall them. If you wish to
contribute to the common share of templates, so that templates you install are
also available to users of the .NET CLI, Visual Studio and all other hosts, you
do not need to anything immediately, but please replace use of the obsolete
methods at your next opportunity.

If your host implementation requires the template to be installed specifically
for your host without other hosts having access to them, you need to manage it
via template package provider, starting in .NET 6. The basic workflow is:

-   Implement ITemplatePackageProviderFactory and ITemplatePackageProvider
    interface.

    ITemplatePackageProviderFactory has the following members:

    -   property ID – unique Guid representing the component ID.

    -   property DisplayName – string – the display name for the provider

    -   method CreateProvider – creates implemented ITemplatePackageProvider
        with passing IEngineEnvironmentSettings.

ITemplatePackageProvider interface has the following members:

-   method: GetAllTemplatePackagesAsync which returns the list of
    ITemplatePackage. ITemplatePackage has the following properties:

    1.  string MountPointUri – the location of template package (can be local
        folder or local NuGet package).

        1.  DateTime LastChangeTime – date/time the package was changed.

        2.  ITemplatePackageProvider – provider returning the package (itself).

[The default implementation of
ITemplatePackage](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/TemplatePackage/TemplatePackage.cs)
is available in Abstractions assembly.

-   event TemplatePackagesChanged – the event that should be raised if template
    packages returned by provider has changed. Triggering this event will
    trigger update template engine cache in TemplatePackageManager. Implementing
    this event is not mandatory but recommended. If the event is not
    implemented, the cache should be reloaded manually passing force parameter
    when getting packages or templates, or TemplatePackageManager should be
    recreated.

1.  Register the factory using AddComponent method of Bootstrapper or
    IEngineEnvironmentSettings.ComponentManager. The component should be added
    each time Bootstrapper or EngineEnvironmentSettings is instantiated - it is
    not cached by template engine.

The host may implement as many providers as needed.

In future releases we are considering a built-in host template provider and host
version template provider allowing you to install the templates available to
specific host or host version.

## ITemplateEngineHost updates 

[ITemplateEngineHost](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/ITemplateEngineHost.cs)
interface and its default implementation
[DefaultTemplateEngineHost](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/DefaultTemplateEngineHost.cs)
was changed:

-   ILogger Logger and ILoggerFactory LoggerFactory properties were added.
    Template Engine now uses Microsoft.Extensions.Logging to log messages of
    different levels. At the moment, logging is not done in many components,
    however we plan to revise it in next versions and increase the logging
    coverage.

-   Previous logging methods and events are now obsolete.
    OnCriticalError/OnNonCriticalError are now replaced with error/warning log
    messages, respectively. In case you need more details on how to replace
    them, please reach us out in GitHub.

## Loading the components

Boostrapper/IComponentManager methos Register and RegisterMany are now
deprecated. This way of loading components was not performant due to reflection
usage.

If you were using these methods to load default components
(Microsoft.TemplateEngine.Edge, Microsoft.TemplateEngine.RunnableProjects), use
LoadDefaultComponents method instead or pass loadDefaultComponents set to true
in Bootstrapper constructor.

If you were using these methods to load other components, use AddComponent
method instead (pay attention that this should be done each time
Bootstrapper/EngineEnvironmentSettings are instantiated) or pass them in
BuiltInComponents property of you ITemplateEngineHost.

Advanced: if you want to load only some components of
Microsoft.TemplateEngine.Edge or Microsoft.TemplateEngine.RunnableProjects
projects, you may use Components.AllComponents property in these assemblies to
get the list of available components, and then load required components via
AddComponent methods.

The list of components defined in
[Microsoft.TemplateEngine.Edge:](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/Components.cs)

-   Providers (ITemplatePackageProviderFactory)

    -   global settings provider

-   Mount points (IMountPointFactory)

    -   Zip (also supports NuGet packages)

    -   Folder (FileSystemMountPointFactory)

-   Installers (IInstallerFactory)

    -   Folder

    -   NuGet

If you don’t need global settings provider to be loaded, do not include it when
loading the components. In this case installers are not used as well, include
them only if needed for the host. It is recommended to always include default
mount point implementations.

The list of components defined in
[Microsoft.TemplateEngine.Orchestrator.RunnableProjects](../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Components.cs):

-   Generators

    -   Runnable project generator (template.json generator)

-   Macros supported by runnable project generator

-   Operation configs supported by runnable project generator

If you are using runnable project generator, consider adding macros and
operation configs implementation to enable these features.

## ISettingsLoader

(This section is only applicable for those who did not use Bootstrapper class
before)

ISettingsLoader and its implementation is no longer available. It was
multi-purpose and overloaded, that’s why we decided to split it in logical
parts.

For components management, please use IComponentManager and
IEngineEnvironmentSettings.ComponentManager.

For template package and template cache, use new class
[TemplatePackageManager](../../../src/TemplateEngine/Microsoft.TemplateEngine.Edge/Settings/TemplatePackageManager.cs).
It is required to instantiate this class to work with it. It reads all template
packages available to engine and maintains the template cache.
TemplatePackageManager maintains the cache for information received from
providers and read from template cache, so it’s quite performant after the first
call unless providers triggered events on template package change, then
TemplatePackageManager will do rescan available templates and save the updates
to template cache.

## Closing notes

Previously, the Template Engine packages had many public members, including
implementations which were unneeded. This meant future changes had breaking
change concerns, even though we believe these methods do not have a useful
public purpose. We made a lot of implementations and members internal. *If the
class/member you need is not available now, please reach us out via GitHub
issues to find a solution.*

---

### Documentation TemplateEngine Authoring Tools Authoring Tools (`documentation/TemplateEngine/authoring-tools/Authoring-Tools.md`)

# Authoring tools

## Overview

Besides the actual implementation of .NET Template Engine, the repo contains various tools that help to author the templates.
They are not shipped together with .NET SDK, but available on NuGet.org.

|Package name|Description|Documentation|Available since|
|---|---|---|---|
| [`Microsoft.TemplateEngine.Authoring.Tasks`](https://www.nuget.org/packages/Microsoft.TemplateEngine.Authoring.Tasks) | MSBuild tasks for template authoring. These tasks are supposed to be added on template package build. The following tasks are available: <br/> - `Localize` task - creates the localization files for the templates on the package build. <br/> - `Validate` task ([planned](https://github.com/dotnet/templating/issues/2623)) - validates the templates for errors and warnings. | [Localization](Localization.md) | .NET SDK 7.0.200 |
| [`Microsoft.TemplateEngine.Authoring.CLI`](https://www.nuget.org/packages/Microsoft.TemplateEngine.Authoring.CLI) | `dotnet CLI` [tool](https://learn.microsoft.com/en-us/dotnet/core/tools/global-tools) with utilities for template authoring. Offers the following commands: <br/> - `localize` - creates or updates the localization files for the templates.  <br/> - `verify` - allows to test the templates and compare them with expected output (snapshot). <br/> - `validate` ([planned](https://github.com/dotnet/templating/issues/2623)) - validates the template(s) for errors and warnings  |[Localization](Localization.md) </br>[Template testing](Templates-Testing-Tooling.md#cli)| .NET SDK 7.0.200 |
| [`Microsoft.TemplateEngine.Authoring.TemplateVerifier`](https://www.nuget.org/packages/Microsoft.TemplateEngine.Authoring.TemplateVerifier) | The class library containing [snapshot testing framework](Templates-Testing-Tooling.md) for the templates. Facilitates writing the tests for templates using Xunit test framework.|[Template testing](Templates-Testing-Tooling.md#api)| .NET SDK 7.0.200 |
| [`Microsoft.TemplateEngine.Authoring.Templates`](https://www.nuget.org/packages/Microsoft.TemplateEngine.Authoring.Templates) | The template package containing the templates for template authoring: <br/> - `template.json` - a template for template.json configuration file for .NET template. <br/> - `	template-package` - a project for creating a template package containing .NET templates.  || .NET SDK 8.0.100 - preview 1 |

## Template Samples

We have created [dotnet template samples](../Samples), which shows how you can use the template engine to create new templates. The samples are setup to be stand alone for specific examples. Those templates are not published to NuGet.org.


## Notes

Prior to .NET SDK 7.0.2xx, `Microsoft.TemplateEngine.Authoring.Tasks` package was distributed as [`Microsoft.TemplateEngine.Tasks`](https://www.nuget.org/packages/Microsoft.TemplateEngine.Tasks). If you are using old package, please consider switching to new package.

Prior to .NET SDK 7.0.2xx, the `dotnet CLI` tool for localization was distributed as [`Microsoft.TemplateEngine.TemplateLocalizer`](https://www.nuget.org/packages/Microsoft.TemplateEngine.TemplateLocalizer) package. 
If you are using `Microsoft.TemplateEngine.TemplateLocalizer` tool, please consider switching to `Microsoft.TemplateEngine.Authoring.CLI` tool.

---

### Documentation TemplateEngine Authoring Tools Localization (`documentation/TemplateEngine/authoring-tools/Localization.md`)

# Template localization 

.NET Templates are localizable. If a template is localized for the language matching the current locale, its elements will appear in that language in hosts that use the Template Engine libraries, including `dotnet new` and the Visual Studio New Project Dialog.
Localizable elements are:
- name 
- author
- description
- symbols
  - description
  - display name
  - description and display name for choices for  choice parameters
- post actions
  - description
  - manual instructions

Localization files should be located inside the `.template-config\localize` folder. The format of the localization file is JSON, and there should be one file per language.
The naming convention for localization files is: `templatestrings.<lang code>.json`, where the `lang code` should match one of the CultureInfo [names](https://docs.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo.name?view=net-6.0#system-globalization-cultureinfo-name) from the list provided by [GetCultures](https://docs.microsoft.com/dotnet/api/system.globalization.cultureinfo.getcultures?view=net-6.0).
The structure of the localization JSON files consist of key-value pairs, where:
- The key is the reference to an element of `template.json` to be localized. If the element is a child, the full path using `/` delimiter should be given. Example: `symbols/Framework/choices/netstandard2.1/description`.
- The value is the localization of the element given by the key. 

Examples of localization files can be found [here](https://github.com/dotnet/sdk/tree/main/template_feed/Microsoft.DotNet.Common.ItemTemplates/content/EditorConfig/.template.config/localize).

These files are to be parsed by the template engine when loading information about the template. The Template Engine API returns information for localizable properties in language matching the current UI culture (if localization is available) transparently, without explicit user action.

### Post action localization
Ensure that all post actions in `template.json` have an `id` property prior setting up the localization. The `id` should be unique within the template. 
Without the `id` property the localization files cannot be created.
In case the post action uses more than one `manualInstructions`, `id` should be also added for each manual instruction.

## Automatic generation of localization files

The localization files can be generated automatically as part of a build using the `LocalizeTemplates` MSBuild task from the [`Microsoft.TemplateEngine.Tasks`](https://www.nuget.org/packages/Microsoft.TemplateEngine.Authoring.Tasks) package.
The task is meant to be used in template package project and will create the JSON files after the project is built.
The task supports the configuration using following properties:
- `LocalizableTemplatesPath` - the folder containing templates to be localized. Default value: `.`.
- `TemplateLanguages` - the languages to create files for. Default value: `cs;de;en;es;fr;it;ja;ko;pl;pt-BR;ru;tr;zh-Hans;zh-Hant`.


Example of usage:
```xml
<PropertyGroup>
   <LocalizeTemplates>true</LocalizeTemplates>
   <TemplateLanguages>en;de</TemplateLanguages>
</PropertyGroup>

<ItemGroup>
   <PackageReference Include="Microsoft.TemplateEngine.Authoring.Tasks" Version="1.0.0.0" PrivateAssets="all" IsImplicitlyDefined="true" />
</ItemGroup>
```

This example will generate localization files for English and German languages for all templates in the package.

## 1st party templates localization

Prerequisite: the repo should be onboarded for OneLocBuild to localize the template content.
See the [link](https://aka.ms/AllAboutLoc) for more details.

### Repo is using arcade

`Microsoft.TemplateEngine.Authoring.Tasks` is included to `Microsoft.DotNet.Arcade.Sdk`.
To start localizing the templates, enable the following property in template package project: `<UsingToolTemplateLocalizer>true</UsingToolTemplateLocalizer>`. This enables generating localization JSON files on the build.
Arcade has all the configuration applied that allows to automatically detect template package project and handover JSON files for localization and receive the back.
After the translation is done, the repo receives the PR replacing original English values in generated files with localized one.

### Repo is not using arcade
`Microsoft.TemplateEngine.Authoring.Tasks` may be still manually added to engineering or directly to template package project as explained above.
In addition to that, localization handover process should be changed as following:
- `LocalizeTemplates` task generates ready files to be used including `<lang code>` in filename. OneLocBuild should receive the file without language code: `templatestrings.json`. The localization pipeline should rename the `templatestrings.en.json` to `templatestrings.json` and include it to localization project JSON to be translated.
- please work with your localization developer advocate to ensure that
  - localization files are handed back in JSON format and to original location
After the translation is done, the repo should receive the PR replacing original English values in generated JSON files with localized ones. It is important to ensure that files are handed over to original location (`.template.config\localize` folder).

It is recommended to setup a way to update `Microsoft.TemplateEngine.Authoring.Tasks` package version, however it is not recommended to update it on each daily build. 
The package is released with each build of the dotnet/sdk repo, even if there are no changes. Therefore, updating the version on each build might be superfluous. It is recommended to update the version when the next preview or stable version is released.

## 3rd party templates localization

- Include `LocalizeTemplates` task from `Microsoft.TemplateEngine.Authoring.Tasks` as explained above. `Microsoft.TemplateEngine.Authoring.Tasks` is available on [NuGet.org](https://www.nuget.org/packages/Microsoft.TemplateEngine.Authoring.Tasks).
- Control the languages to be used with `TemplateLanguages` property.
- Translate the content in generated JSON files using any suitable means prior to distributing template package.

 It is recommended to update `Microsoft.TemplateEngine.Authoring.Tasks` package version when the next preview or stable version is released.


 ## Notes

 Prior to .NET SDK 7.0.2xx, `Microsoft.TemplateEngine.Authoring.Tasks` package was distributed as [`Microsoft.TemplateEngine.Tasks`](https://www.nuget.org/packages/Microsoft.TemplateEngine.Tasks). Please consider switching to new package.

---

### Documentation TemplateEngine Authoring Tools Templates Testing Tooling (`documentation/TemplateEngine/authoring-tools/Templates-Testing-Tooling.md`)

# Overview

Templates Testing Tooling is an engine for snapshot testing of templates instantiations - simplifying automated detection of regressions. It is surfaced via [API](#api) and [CLI tool](#cli).

Tooling currently uses [Verify](https://github.com/VerifyTests/Verify) as an underlying engine to manage the snapshots generation and verification. The API surface of Verify is however intentionally hidden and not accessible. The way how snapshots are being created, managed and diffed is unchanged - so to learn more about underlying diffing functionality refer to [DiffEngine](https://github.com/VerifyTests/DiffEngine) documentation.

Engine creates a serialized version of outputs of tested scenario and compares those with stored snapshot (if any) and reports success or any found discrepancies. Snapshot created during the first run can be used as a baseline for future runs of the test scenario.

Serialized snapshots are not mandatory - custom verification callback can be injected via [`CustomDirectoryVerifier`](#CustomDirectoryVerifier) which will not create nor validate any snapshot files, instead validation is expected to be performed by the injected custom logic.

## Naming of snapshots

All snapshots are stored in a single folder that is by default named `Snapshots` and is located in a folder with test code (in case of API usage) or current folder (in case of CLI) usage. Location of the snapshots directory can be optionaly specified in API via [SnapshotsDirectory](#SnapshotsDirectory) parameter or in CLI via [-d|--snapshots-directory](#--snapshots-directory) option.

All the files consisting a single snapshot of single scenario are stored in a single folder that is named with following convention: 

```
<caller_method>.<template_name>.<user_passe_scenario_name>.<encoded_input_args>.<scenario_differentiator>.<received|verified>
```

 - `<caller_method>` - not used in CLI. Added by default in API. Can be opted out via [`DoNotPrependCallerMethodNameToScenarioName`](#DoNotPrependCallerMethodNameToScenarioName)

 - `<template_name>` - used by default. Can be opted out in API via [`DoNotPrependTemplateNameToScenarioName`](#DoNotPrependTemplateNameToScenarioName)

  - `<user_passe_scenario_name>` - not used by default. Can be opted in in API via specifying [`ScenarioName`](#ScenarioName)

   - `<encoded_input_args>` - used by default. Can be opted out in API via [`DoNotAppendTemplateArgsToScenarioName`](#DoNotAppendTemplateArgsToScenarioName)

  - `<scenario_differentiator>` - not used by default. Can be opted in in CLI via [`--unique-for`](#--unique-for) and in API via [`UniqueFor`](#UniqueFor)

  - `<received|verified>` - suffix, depending on whether the snapshot is a basline for test scenario (then the suffix is '.verified') or created by engine as unexpected/regressing the check (then the suffix is '.received').


## Layout of snapshot files

All files within snapshot has identical filenames and relative folder structure as files in the generated template output.

Snapshot folder has the following layout:

```
<Snapshot_folder_name.received|verified>
  |--<template_name>
  |   |--<file_1 from generated template>
  |   |--<file_2 from generated template>
  |   |-- ... // layout is respecting folder structure of generated template
  |
  |--<std-streams> // present if opted in into verifying command output
      |--stderr.txt
      |--stdout.txt
```

# API

## Setup

1. Add the package reference to `Microsoft.TemplateEngine.Authoring.TemplateVerifier`:
  ```dotnetcli
  dotnet add package Microsoft.TemplateEngine.Authoring.TemplateVerifier
  ```
2. Start using the `TemplateVerifier` in your tests:
  ```cs
using Microsoft.TemplateEngine.Authoring.TemplateVerifier;

namespace MyTests

[TestClass]
public class MyTestClass
{
    [TestMethod]
    public async Task MyTemplate_InstantiationTest()
    {
        TemplateVerifierOptions options = new(templateName: templateShortName)
        {
            TemplateSpecificArgs = new[] { "--arg1", "true" },
        };
        
        VerificationEngine engine = new(_logger);
        await engine.Execute(options).ConfigureAwait(false);
    }
}
  ```

## VerificationEngine

Type to be used to execute the test scenarios. Can be constructed by passing `Microsoft.Extensions.Logging.ILogger` or `Microsoft.Extensions.Logging.ILoggerFactory` (the latter one leads to usage of separate log instances for the `dotnet new` process execution and for the actual verification engine).

### Test scenario execution

```cs
async Task Execute(IOptions<TemplateVerifierOptions> optionsAccessor)
```

Successful run is indicated by `Task` that doesn't throw after awaiting. Failed scenario or snapshot expectation is indicated by `TemplateVerificationException` on the returned `Task`.

### Configuration

Configuration of the scenario run is done via `TemplateVerifierOptions` type.

- **`string TemplateName`** - The name of the template to be verified. Can be already installed template or a template within local path specified with `TemplatePath`

- **`string? TemplatePath`** - Applicable to local (not installed) template. The path to template.json file or containing directory.

- **`IEnumerable<string>? TemplateSpecificArgs`** - Instantiation arguments and options for the template.

- **<a name="SnapshotsDirectory"></a>`string? SnapshotsDirectory`** - Custom location of directory with snapshots. Defaults to `Snapshots`.

- **`bool VerifyCommandOutput`** - If set to true - 'dotnet new' command standard output and error contents will be verified along with the produced template files.

- **`bool IsCommandExpectedToFail`** - If set to true - 'dotnet new' command is expected to return nonzero return code. Otherwise a zero exit code and no error output is expected.

- **`bool DisableDiffTool`** - If set to true - the diff tool won't be automatically started by the `TemplateVerifier` on verification failures.

- **`bool DisableDefaultVerificationExcludePatterns`** - If set to true - all template output files will be verified, unless `VerificationExcludePatterns` are specified. Otherwise a default exclusions (binaries and object files).

- **`IEnumerable<string>? VerificationExcludePatterns`** - Set of patterns defining files to be excluded from verification. [Globs](https://en.wikipedia.org/wiki/Glob_(programming)) patterns are recognized and honored.

- **`IEnumerable<string>? VerificationIncludePatterns`** - Set of patterns defining files to be included into verification (unless excluded by `VerificationExcludePatterns`). By default all files are included (unless excluded). [Globs](https://en.wikipedia.org/wiki/Glob_(programming)) patterns are recognized and honored.

- **`string? OutputDirectory`** - Target directory to output the generated template. If explicitly specified, it won't be cleaned up upon successful run of test scenario.

- **`string? SettingsDirectory`** - Settings directory for template engine (in memory location used if not specified).

- **<a name="UniqueFor"></a>`UniqueForOption? UniqueFor`** - Indicating which scenarios should be differentiated. Differentiation performed by adjusting the snapshots directory name (see )

  Currently supported values:
    - Architecture
    - OsPlatform
    - Runtime
    - RuntimeAndVersion
    - TargetFramework
    - TargetFrameworkAndVersion

- **`string? DotnetExecutablePath`** - Path to custom dotnet executable (e.g. x-copy install scenario).

- **`IReadOnlyDictionary<string, string>? Environment`** - Custom environment variable collection to be passed to execution of dotnet commands.

  Custom environment variables can as well be added via fluent API `WithCustomEnvironment` and `WithEnvironmentVariable`. Sample usage:

  ```cs
  options.WithCustomEnvironment(
	new Dictionary<string, string>() 
	  { 
		  { name1, value1 }, 
		  { name2, value2 },
		  { name3, value3 },
	  }
	);
  ```


- **<a name="ScenarioName"></a>`string? ScenarioName`** - Custom scenario name; if specified it will be used as part of verification snapshot name.

- **<a name="DoNotAppendTemplateArgsToScenarioName"></a>`bool DoNotAppendTemplateArgsToScenarioName`** - `true`, if the instantiation args should not be appended to verification snapshot name.

- **<a name="DoNotPrependTemplateNameToScenarioName"></a>`bool DoNotPrependTemplateNameToScenarioName`** - `true`, if the template name should not be prepended to verification snapshot name.

- **<a name="DoNotPrependCallerMethodNameToScenarioName"></a></a>`bool DoNotPrependCallerMethodNameToScenarioName`** - `true`, if the caller method name should not be prepended to verification snapshot name.

- **`string? StandardOutputFileExtension`** - Extension of autogeneratedfiles with stdout and stderr content. Defaults to `.txt`.

- **`ScrubbersDefinition? CustomScrubbers`** - Delegates that perform custom scrubbing of template output contents before verifications.

  Scrubbers can as well be added via fluent API `WithCustomScrubbers`. Sample usage:
  ```cs
  options.WithCustomScrubbers(
	ScrubbersDefinition.Empty
		.AddScrubber(sb => sb.Replace("bb", "xx"), "cs")
		.AddScrubber(sb => sb.Replace("cc", "yy"), "csproj")
		// scrubber applicable to all files
		.AddScrubber(sb => sb.Replace("aa", "zz"))
		// supports multiple scrubbers per extension
		.AddScrubber(sb => sb.Replace("cc", "**"), "cs")
		// callback scrubber based on content filename or/and location
		.AddScrubber((path, content) =>
		{
			if (Path.GetExtension(path).Equals(".txt", StringComparison.OrdinalIgnoreCase))
			{
				content.Replace("MyTemplate", "%TEMPLATE_NAME%");
			}
		}));
  ```

- **<a name="CustomDirectoryVerifier"></a>`VerifyDirectory? CustomDirectoryVerifier`** - Delegate that performs custom verification of template output contents.

  Custom verifier can as well be defined via fluent API `WithCustomDirectoryVerifier`. Sample usage:

  ```cs
  options.WithCustomDirectoryVerifier(
	async (contentDirectory, contentFetcher) =>
	{
		await foreach (var (filePath, scrubbedContent) in contentFetcher.Value)
		{
			// Asserting on scrubbed file content
		}
	});
  ```



# CLI

## Setup

1. If you haven't setup your tools manifest file yet - set it up by running:
  ```dotnetcli
  dotnet new tool-manifest
  ```
2. Install the templeting authoring toolset:
  ```dotnetcli
  dotnet tool install Microsoft.TemplateEngine.Authoring.CLI
  ```

## Synopsis

```dotnetcli
dotnet dotnet-template-authoring verify <template-short-name>  [--template-args <template-args>] [-p|--template-path <template-path>] [-o|--output <output>] [-d|--snapshots-directory <snapshots-directory>] [--scenario-name <scenario-name>] [--disable-diff-tool] [--disable-default-exclude-patterns] [--exclude-pattern <exclude-pattern>] [--include-pattern <include-pattern>] [--verify-std] [--fail-expected] [--unique-for <Architecture|OsPlatform|Runtime|RuntimeAndVersion|TargetFramework|TargetFrameworkAndVersion>]
    [-h|--help]
```

## Description

The `dotnet dotnet-template-authoring verify` command instantiates the specified while passing specified arguments, collects the resulting files (while applying filtering based on default and explicit exclude and include patterns) compares them to stored snapshots and reports the result.

If there are differences or snapashot files are missing altogether (first run), the set of files is created within a folder with a `.received` suffix, that can be used to prepare proper snapshot files (those should be placed in folder with `.verified` suffix).



## Arguments
- **`<template-short-name>`**

  Name of the template to be verified. Can be already installed template or a template within local path specified with `-p|--template-path option`.

## Options

- **`--template-args <template-args>`**

  Template specific arguments - all joined into single enquoted string. Any needed quotations of actual arguments has to be escaped.


- **`-p|--template-path <template-path>`**

  Specifies the path to the directory with template to be verified.

- **`-o|-output<output>`**

  Specifies the path to target directory to output the generated template to.

- **<a name="--snapshots-directory"></a>`-d|--snapshots-directory <snapshots-directory>`**

  Specifies path to the directory with snapshot files.

- **`--scenario-name <scenario-name>`**

  Specifies optional scenario name to be used in the snapshot folder name.

- **`--disable-diff-tool`**

  If set to true - the diff tool won't be automatically started by the Verifier on verification failures.

- **`--disable-default-exclude-patterns`**

  If set to true - all template output files will be verified, unless --exclude-pattern option is used.

- **`--exclude-pattern <exclude-pattern>`**

  Specifies pattern(s) defining files to be excluded from verification.

- **`--include-pattern <include-pattern>`**

  Specifies pattern(s) defining files to be included to verification (all files are included if not specified).

- **`--verify-std`**

  If set to true - 'dotnet new' command standard output and error contents will be verified along with the produced template files.

- **`--fail-expected`**

  If set to true - 'dotnet new' command is expected to return non-zero return code.

- **<a name="--unique-for"></a>`--unique-for <Architecture|OsPlatform|Runtime|RuntimeAndVersion|TargetFramework|TargetFrameworkAndVersion>`**

  Sets the Verifier expectations directory naming convention, by indicating which scenarios should be differentiated.



  ## Examples

- Get the help for `verify` command
  
  ```dotnetcli
  dotnet dotnet-template-authoring verify --help
  ```

- Run the test of instantiation scenario for already installed template:
 
  ```dotnetcli
  dotnet dotnet-template-authoring verify my-template-name --template-args "--arg1 value1 --arg2 \"multi word value\""
  ```
    
- Run the test of instantiation scenario for an installed template with verification of standard output and standard error streams of `dotnet new` process, while disabling automatic opening of a diff tool for snapshots:
 
  ```dotnetcli
  dotnet dotnet-template-authoring verify console --verify-std --disable-diff-tool
  ```

---

### Documentation TemplateEngine Contributing How To Create New Generated Symbol (`documentation/TemplateEngine/contributing/how-to-create-new-generated-symbol.md`)

# How to create new generated symbol type

Available generated symbol types are described [here](../Available-Symbols-Generators.md).
Generated symbols are processed by a corresponding macro component that can generate new variables before the template is instantiated. New variables can be created from other variables (usually parameters) or independently.

We appreciate creating new types of generated symbols and macros by the community. 

Generated symbols follow the following syntax:
```json
{
   "symbols":
   {
        "symbolName":
        {
            "type": "generated",
            "generator": "your-type", //type of generated symbol; should be same as type of the macro implementing it
            "dataType": "string", //data type of the value that symbol generates: "string", "choice", "bool", "float", "int", "hex", "text"
            "parameters":
            {
                "name": "value" //key-value parameters for the symbol. The value may be JSON array or object, if more complicated configuration is needed.
            },
            "replaces": "to-be-replaced", // the text to replace with the value of this symbol in template content
            "fileRename": "to-be-replaced", // defines the portion of file name which will be replaced by symbol value
        }

   }
}
```

To create new generated symbol type, follow the following guideline

1. Implement [`Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Abstractions.IGeneratedSymbolMacro<T>`](../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Abstractions/IGeneratedSymbolMacro.cs) interface.

Any macro implementation is a component ([`IIdentifiedComponent`](../../../src/TemplateEngine/Microsoft.TemplateEngine.Abstractions/IIdentifiedComponent.cs)) and will be loaded by template engine.
The existing implementation macro components are located in [`Macros`](../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros) folder of `Microsoft.TemplateEngine.Orchestrator.RunnableProjects` projects.

The implementation should have:
- `Id` property - unique GUID for component 
- `Type` property - unique `string` name, matching generated symbol type
- `Evaluate(IEngineEnvironmentSettings environmentSettings, IVariableCollection variables, T config)` method - evaluates the variables based on `config` specified
- `Evaluate(IEngineEnvironmentSettings environmentSettings, IVariableCollection variables, IGeneratedSymbolConfig generatedSymbolConfig)` method - evaluates the variables based on `generatedSymbolConfig` specified
- `CreateConfig(IEngineEnvironmentSettings environmentSettings, IGeneratedSymbolConfig generatedSymbolConfig)` method - creates macro-specific configuration from `generatedSymbolConfig`, that later on can be passed to `Evaluate` method.

The implementation of macro config may have:
- Properties/methods derived from `IMacroConfigDependency` interface:
    `ResolveSymbolDependencies(IReadOnlyList<string> symbols)` - the method should identify the dependencies of macro configuration on symbols, and populate `Dependencies` property of the macro with dependent symbol names.

You may want to derive your own implementation from `BaseGeneratedSymbolMacro<T>` base class that offers some common logic. Configuration of the macro may derive from `BaseMacroConfig` class, that already have some utilities to parse the JSON configuration.
When using base class, you need to implement the following members:
- `Id` and `Type` properties assigned to constant unique values
- `Evaluate` method: the method should create new variables to `IVariableCollection variableCollection` using parsed `config` and existing variables. It is recommended to log errors and debug information using logger available from `environmentSettings`. If you need to access the file system, do so via `environmentSettings.Host.FileSystem` abstraction.
- `CreateConfig` method - creates macro specific config from `IGeneratedSymbolConfig` config.

The very basic implementation may be:
```
/* Detailed source-code truncated for AI context efficiency. */
```

`IMacroConfigDependency` interface depicts macro capability to derive it value(s) from other macros.
Dependencies are defined based on passed `IReadOnlyList<string> symbols` collection. An example of implementation can be find here: [`CoalesceMacroConfig.cs`](../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Macros/CoalesceMacroConfig.cs).

`IGeneratedSymbolConfig` config already contains the pre-parsed JSON from template.json. It has properties for: symbol name, data type (if specified) and parameters collection. 
Parameters collection contains parameter key-value pairs from JSON. Note that value is in JSON format, i.e. if the parameter value is string, then it contains `"\"string-value\""`.
It is recommend to get `JToken` using `JToken.Parse` on this value when parsing the value or use helper methods available in `BaseMacroConfig` that can parse the data.

2. Once the macro is implemented, add it to [components collection](../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Components.cs).

3. [optional] Update [JSON schema](../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Schemas/JSON/template.json) with new generated symbol syntax.
If you do so, also add [a new test case](../../../test/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/SchemaTests/GeneratorTest.json) for testing the syntax.

4. Add unit tests for new implementation. Macro related unit tests are located in [this folder](../../../test/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/MacroTests/).
For more complete scenario, consider adding the full template generation tests to [`RunnableProjectGeneratorTests.cs`](../../../test/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/RunnableProjectGeneratorTests.cs).

5. Update documentation in [docs folder](../Available-Symbols-Generators.md).

---

### Documentation TemplateEngine Contributing How To Create New Value Form (`documentation/TemplateEngine/contributing/how-to-create-new-value-form.md`)

# How to create a new value form

Available value forms are described [here](../Value-Forms.md).
Value form represent the form of the parameter, usually related to specific casing.

We appreciate creating new value forms by the community. 

Value forms follow the following syntax:
```json
{
   "forms":
   {
        "nameOfTheForm":
        {
            "identifier": "name-unique", //type of value form; should be unique value
            "param1": "value1", //key-value parameters for the form. The value may be JSON array or object, if more complicated configuration is needed.
            "param2": "value2"
        }
   }
}
```

To create new value form, follow the following guideline:

1. Implement [`Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms.IValueFormFactory`](../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms/IValueFormFactory.cs) interface.

The existing implementation of value form are located in [`ValueForms`](../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueForms) folder of `Microsoft.TemplateEngine.Orchestrator.RunnableProjects` projects.

The implementation should have:
- `Identifier` property - unique identifier of the form
- `Type` property - unique `string` name, matching generated symbol type
- `Create(string? name = null)` method - creates the form for default configuration
- `FromJObject(string name, JObject? configuration = null)` method - creates the form for json configuration

The `IValueForm` has `Identifier` property that matches factory `Identifier`, `Name` corresponding the name of the form in JSON and `Process` method that create the form for the passed `value`.

You may want to derive your own implementation from one of the base classes:
- `BaseValueFormFactory` - basic features
- `ActionableValueFormFactory`- the form that just does the action without configuration
- `ConfigurableValueFormFactory`- the form that performs the action and based on configuration
- `DependantValueFormFactory` - the form that needs other forms for processing

The very basic implementation may be:
```CSharp
    internal class HelloValueForm : ActionableValueFormFactory
    {
        internal const string FormIdentifier = "hello";

        public HelloValueForm() : base(FormIdentifier)
        {
        }

        protected override string Process(string value) => $"Hello {value}!";
    }
```

2. Once the value form is implemented, add it to [value form collection](../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/ValueFormRegistry.cs).

3. [optional] Update [JSON schema](../../../src/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects/Schemas/JSON/template.json) with new value form syntax.
If you do so, also add [a new test case](../../../test/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/SchemaTests/) for testing the syntax.

4. Add unit tests for new implementation. Macro related unit tests are located in [this folder](../../../test/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/ValueFormTests/).
For more complete scenario, consider adding the full template generation tests to [`RunnableProjectGeneratorTests.cs`](../../../test/TemplateEngine/Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests/RunnableProjectGeneratorTests.cs).

5. Update documentation in [docs folder](../Value-Forms.md).

---

### Documentation Dotnetup Breaking Changes Dotnetup 0.2.0 Default Hive Location Break (`documentation/dotnetup/breaking_changes/dotnetup-0.2.0-default-hive-location-break.md`)

# [Breaking change]: dotnetup default hive moves under its data directory

## Description

The default dotnetup-managed .NET install root moves under the dotnetup data directory. This daily-build change does not automatically migrate existing installations. See the [default hive location decision](../../general/dotnetup/designs/default-hive-location.md).

## Version

Daily dotnetup `0.2.0` builds.

## Previous behavior

The default root was the `dotnet` subdirectory of the platform-local data directory, such as `%LocalAppData%\dotnet` on Windows or `~/.local/share/dotnet` on Linux. This generic location could contain installations not owned by dotnetup.

## New behavior

The default root is the `dotnet` subdirectory of the dotnetup data directory, such as `%LocalAppData%\dotnetup\dotnet` on Windows or `~/.local/share/dotnetup/dotnet` on Linux. Explicit `--install-path` and `global.json` SDK paths are unchanged.

Existing roots in `dotnetup_manifest.json` are not moved or removed. They remain visible to `dotnetup list` and are still processed by `dotnetup update` without `--install-path`, but new default installs, `dotnetup dotnet`, and `dotnetup env` use the new root.

## Type of breaking change

Behavioral change.

## Reason for change

The product-owned directory avoids collisions with existing user or installer content and keeps dotnetup metadata and managed installations under one root.

## Recommended action

Install the required SDKs and runtimes again with the new dotnetup build. Run `dotnetup env set` to reapply the stored environment configuration with the new default. Existing shell-profile configuration also resolves the new default automatically when a new shell starts.

The `everywhere` mode is Windows-only. Windows users of that mode must reapply `dotnetup env set everywhere` because it also persists the absolute managed root in the user-level `PATH` and `DOTNET_ROOT` used by command prompts and GUI applications.

After reinstalling anything needed from the old root in the new path, delete the old folder.

## Feature area

dotnetup.

## Affected APIs

None.

---

### Documentation Format Docs 3rd Party Analyzers (`documentation/format/docs/3rd-party-analyzers.md`)

# 3rd Party Analyzers

## How to add analyzers to a project

3rd party analyzers are discovered from the `<PackageReferences>` specified in the workspace project files.

*Example:*

Add the StyleCop analyzer package to a simple console project file.

```diff
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

+ <ItemGroup>
+    <PackageReference Include="StyleCop.Analyzers" Version="1.1.118" />
+  </ItemGroup>

</Project>
```

## How to configure analyzer severity

The options specified in .editorconfig files are recognized by the pattern `dotnet_diagnostic.<diagnostic-id>.severity = <value>`. `<diagnostic-id>` represents the diagnostic ID matched by the compiler, case-insensitively, to be configured. `<value>` must be one of the following: error, warn, info, hidden, suppress. Please read the [Code Analysis documentation](https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/configuration-options#severity-level) for more details.

*Example:*

Configure the StyleCop analyzer so that empty comments are errors.

```ini
[*.{cs,vb}]

# The C# comment does not contain any comment text.
dotnet_diagnostic.SA1120.severity = error
```

---

### Documentation Format Docs Supported .Editorconfig Options (`documentation/format/docs/Supported-.editorconfig-options.md`)

# Supported .editorconfig options
The dotnet-format global tool supports the core set of [EditorConfig options](https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties)* as well as the [.NET coding convention settings for EditorConfig](https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2019).

## Core options
- indent_style
- indent_size
- tab_width
- end_of_line
- charset
- insert_final_newline
- root

[*] The options `trim_trailing_whitespace` and `max_line_length` are not supported. Currently insignificant whitespace is **always** removed by the formatter.

## Removing unnecessary imports
In order to remove unnecessary imports the IDE0005 (unnecessary import) diagnostic id must be configured in your .editorconfig. When running dotnet-format specify a severity that includes the configured IDE0005 severity.

*Example:*

.editorconfig
```ini
root = true

[*.{cs,vb}]
dotnet_diagnostic.IDE0005.severity = warning
```

command
```console
dotnet format ./format.sln --severity warn
```

---

### Documentation Format Docs Integrations (`documentation/format/docs/integrations.md`)

# Integrations
Collection of advice how to auto check/format. Every sample expects dotnet format installed as local tool, unless otherwise noted.

## Git pre-commit hook to reformat

Create file `.git/hooks/pre-commit` with following contents:
```sh
#!/bin/sh
LC_ALL=C
# Select files to format
FILES=$(git diff --cached --name-only --diff-filter=ACM "*.cs" | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0

# Format all selected files
echo "$FILES" | cat | xargs | sed -e 's/ /,/g' | xargs dotnet format --include

# Add back the modified files to staging
echo "$FILES" | xargs git add

exit 0

```

These instructions originally authored by [randulakoralage82](https://medium.com/@randulakoralage82/format-your-net-code-with-git-hooks-a0dc33f68048).


## Check on PR in Azure Dev Ops

Add following to your build file:

```yaml
- task: UseDotNet@2
  displayName: 'Use .NET 6 sdk'
  inputs:
    packageType: 'sdk'
    version: '6.0.x'
    includePreviewVersions: true

- task: DotNetCoreCLI@2
  displayName: 'dotnet-format'
  inputs:
    command: 'custom'
    custom: 'format'
    arguments: '--verify-no-changes'
```

These instructions originally authored by [leotsarev](https://github.com/joinrpg/joinrpg-net/).


## [pre-commit.com](https://pre-commit.com/) hook to reformat

Add the following block to the `repos` section of your `.pre-commit-config.yaml` file:

```yaml
-   repo: https://github.com/dotnet/format
    rev: ""  # Specify a tag or sha here, or run "pre-commit autoupdate"
    hooks:
    -   id: dotnet-format
```
Note that this will compile and install dotnet format to an isolated environment, using the system installation of the dotnet CLI. See the [pre-commit.com documentation](https://pre-commit.com/#dotnet) for more details. The problem is that dotnet format is using *preview* SDK (even for 5.x versions), and you have to install preview SDK on your machine for compiling it. Another option is to use local feature of pre-commit, as follows:

```yaml
-   repo: local
    hooks:
    #Use dotnet format already installed on your machine
    -   id: dotnet-format
        name: dotnet-format
        language: system 
        entry: dotnet format --include 
        types_or: ["c#", "vb"]
```

These instructions originally authored by [rkm](https://github.com/rkm) & [leotsarev](https://github.com/joinrpg/joinrpg-net/).


## Rider reformat on save

1. Open Settings -> Tools -> File Watchers
1. Press The “Plus Sign” to Add a Custom watcher
1. Set the name to i.e. “dotnet format on save”
1. FileType: C#
1. Scope: Open Files
1. Program: Write dotnet-format
1. Arguments: $SolutionPath$ --verbosity diagnostic --include $FileRelativePath$
1. (Optionally) Append --fix-style warning to fix any style issues automatically on save.
1. (Optionally) Append --fix-analyzers warning to fix any analyzer warnings on save.
1. Disable all advanced option checkboxes.
1. All other values were left default

These instructions originally authored by [Nils Henrik Hals](https://strepto.github.io/Pause/blog/dotnet-format-rider/).

---

### Documentation General Dotnetup Choose Dotnetup (`documentation/general/dotnetup/choose-dotnetup.md`)

---
title: When to use dotnetup
description: Compare dotnetup with other ways to install .NET and decide which method fits your scenario.
ms.topic: conceptual
ms.date: 10/09/2026
---

# When to use dotnetup

> [!IMPORTANT]
> `dotnetup` is in public preview. Its features and behavior might change
> before general availability.

You can install .NET in several ways. `dotnetup` installs and manages .NET
SDKs and runtimes for your user account. This article helps you decide whether
`dotnetup` fits your scenario or another installation method is a better
choice.

## Scenarios that fit dotnetup

Consider `dotnetup` when you want to:

- Install .NET without administrator rights and without a system package
  manager.
- Keep several SDK and runtime versions side by side and update them together.
- Follow a channel, such as `lts`, `10.0`, or `10.0.1xx`, so updates move to
  the newest matching version.
- Install the SDK that a repository's `global.json` file requires.
- Try preview or daily builds without changing the machine-wide installation.
- Use the same commands on Windows, macOS, and Linux.

## Scenarios that fit other methods

Another installation method might be a better choice when you:

- **Need a supported, generally available installation method.** For production
  machines, use the .NET installers, a package manager, or Visual Studio.
- **Develop with Visual Studio.** Visual Studio installs and services its own
  machine-wide copy of .NET. For more information, see
  [Install .NET on Windows](https://learn.microsoft.com/dotnet/core/install/windows).
- **Need machine-wide .NET installations.** On Windows, use Microsoft Update
  or update the package with WinGet. On Linux, use your distribution's package
  manager. On macOS, run the .NET installer again to install a newer version.
- **Manage and remove .NET installations across an organization's Windows
  devices.** Use the
  [.NET Install Manager](https://learn.microsoft.com/dotnet/core/additional-tools/dnim-overview).

## Compare installation methods

| Capability | dotnetup | .NET installers and package managers | dotnet-install scripts |
| --- | --- | --- | --- |
| Installation scope | User | Usually machine | Any folder that you choose |
| Requires administrator rights | No, except to change the system `PATH` on Windows in `everywhere` mode | Depends on the platform and method | No |
| Tracks installations | Yes | Depends on the platform and method | No |
| Updates installations | Yes, with `dotnetup update` | Depends on the platform and method | No. Run the script again. |
| Removes unused installations | Yes | Depends on the platform and method | No |
| Reads `global.json` | Yes | No | Yes, with the `--jsonfile` option |
| Installs daily builds | Yes | No | Yes |
| Support status | Public preview | Generally available | Generally available |

## Use dotnetup with other installations

`dotnetup` doesn't remove or change machine-wide installations. How the two
installations interact depends on the access mode that you choose:

- In `none` and `shell` modes, processes that don't use the dotnetup
  environment configuration continue to use the machine-wide installation.
- In `everywhere` mode on Windows, the dotnetup-managed installation takes
  precedence over the machine-wide installation. Migrate the machine-wide SDKs
  and runtimes that you need into the dotnetup-managed installation.

For more information, see
[dotnetup environment configuration](concepts/environment.md).

## Next steps

- [Get started with dotnetup](README.md)
- [How dotnetup works](concepts/how-dotnetup-works.md)

---

### Documentation General Dotnetup Dotnetup Channel Policy (`documentation/general/dotnetup/dotnetup-channel-policy.md`)

# `dotnetup` Release Channel Definitions

## Overview

`dotnetup` refers exclusively to the standalone developer toolchain that manages .NET.

This document describes the intended audience and quality bar for each `dotnetup` release channel to help you choose a channel. It is not an official support policy. The [.NET Support Policy](https://dotnet.microsoft.com/platform/support/policy) page will contain the official `dotnetup` policy when one is available.

## Channels

The term `channel` in this document refers to one of three `dotnetup` release qualities. Each channel has a different audience and quality bar.

`channel` may also refer to the .NET SDK or .NET Runtime version subscribed to by `dotnetup`, which is better outlined in [the getting started documentation](README.md#choose-an-sdk-channel).

`dotnetup` is a standalone tool with a lifecycle that is independent of the .NET SDK lifecycle.
`dotnetup` releases in three channels:

- `daily`
- `preview`
- `stable`

Unlike the .NET SDK or .NET Runtime, `dotnetup` is a tip-only product, meaning only the latest version per supported `channel` is maintained.

Supported fixes and updates are only provided through the latest `stable` channel version. When a new `stable` version is published, it immediately supersedes the previous `stable` version. New `daily` and `preview` versions may continue to be published, but those channels have a lower quality bar and are not recommended for use in production. This intent may change as the product matures or when an official support policy supersedes this document.

### `Daily` Channel Versions

`daily` builds of `dotnetup` will be fresh out of CI, much like the builds of the .NET SDK that are sometimes called "nightly" builds.

We do not recommend using `daily` builds in production. They have no guarantees, no fix timelines, and no support. Features may be added, changed, or removed without notice. Breaking changes may be added with or without documentation or notice.

`daily` is a slight misnomer, as multiple `daily` builds may be published in one day.

### `Preview` Channel Versions

`preview` versions are not officially supported but they are offered for public testing ahead of a promotion to a `stable` release. At our discretion, a selected `daily` build will be used to produce a separately versioned `preview` build.

Breaking change notices may be published in the [.NET Docs](https://github.com/dotnet/docs) if we expect high impact. However, `preview` versions may contain breaking changes without notice. No service-level agreement or fix timeline applies to a `preview` version.

### `Stable` Channel Versions

Only the most recently published `stable` version of `dotnetup` is supported. Supported in this case means that the latest `stable` version may receive security and bug fixes.

Intentional breaking changes will be documented as breaking change notices in the [.NET Docs](https://github.com/dotnet/docs).

When a new `stable` version of `dotnetup` is published, previous versions no longer receive fixes, updates, or online technical assistance.

At this time, historical `stable` versions of `dotnetup` will remain available for download as official [dotnet releases](https://builds.dotnet.microsoft.com/dotnet/release-metadata/releases-index.json) despite their lack of official support, much like historical .NET versions are available today.

PSAs and CVEs are planned to be announced through the [.NET release notes](https://github.com/dotnet/core), following a similar convention to other .NET releases. Discussions and release tags will exist in the [.NET SDK repository](https://github.com/dotnet/sdk).

## Versioning

`dotnetup` versioning is inspired by [Semantic Versioning](https://semver.org/) but does not strictly implement it. Major, minor, and patch version components communicate the expected scope of a release; they are not compatibility guarantees.

`preview` versions add a prerelease label to the intended release version. For example, `1.2.4-preview.1` identifies a preview of `1.2.4`, while `1.2.4` identifies the stable version.

### Major Releases

Major releases communicate a substantial product change. They may include major feature additions, new functionality or APIs, and significant intentional [breaking changes](https://learn.microsoft.com/dotnet/core/compatibility/breaking-changes).

### Minor Releases

Minor releases communicate a smaller feature release than a major release. They may include new features, functionality, APIs, bug fixes, and intentional breaking changes. A minor version increment does not imply backward compatibility.

### Patch Releases

Patch releases may include security fixes, bug fixes, and updates to the self-contained .NET Runtime embedded in the executable. A patch release is not intended to introduce new features.

`daily` versions are intended for rapid engineering iteration and are not governed by these version-component expectations.

---

### Documentation General Dotnetup Dotnetup In Sdk (`documentation/general/dotnetup/dotnetup_in_sdk.md`)

# dotnetup-in-SDK and the Signing-Policy Servicing Problem

This is a forward-looking note, not a description of current behavior. As of
today, **the .NET SDK knows nothing about `dotnetup`**: `dotnetup` is a separate,
self-contained binary that ships its own copy of `Microsoft.Dotnet.Installation`,
its own pinned trusted-root PEMs, and its own
[`SignatureVerifier`](https://github.com/dotnet/sdk/blob/release/dnup/src/Installer/Microsoft.Dotnet.Installation/Internal/Signing/SignatureVerifier.cs)
policy. Each released `dotnetup` is the policy authority for its own runs, and
the user is always expected to be on the latest `dotnetup` (one of `dotnetup`'s
first acts is to self-update; older builds are not a supported configuration).

That property — *only the latest `dotnetup` is supported* — is what makes the
strict, baked-in algorithm allow-list in
[`signature-verification.md`](signature-verification.md) §4 safe today. New
algorithms, new digest OIDs, new pinned issuer DNs, and new trusted-root PEMs
can be added in a regular SDK PR and reach customers on the normal `dotnetup`
self-update cadence. There is no SDK-installed copy of the verifier that has to
be reasoned about separately.

This document describes what would have to change *if that property goes away*
— specifically, if a future design embeds (or hard-bundles) `dotnetup` into the
.NET SDK such that customers can end up on an SDK-shipped `dotnetup` that is
older than the latest standalone `dotnetup` and is asked to verify a *newer*
release manifest.

## Why this matters

`SignatureVerifier`'s acceptance rules are intentionally hostile to unknown
inputs:

- The digest OID allow-list (`SignatureVerifier.DigestOids.cs` plus the pure-PQC
  OIDs in `SignatureVerifier.PqcOids.cs`) rejects anything not enumerated.
- The signature-algorithm allow-list (RSA-4096+ and the pure-PQC families)
  likewise rejects anything else.
- The signer-issuer and TSA-issuer DNs are pinned to a specific DigiCert
  intermediate CN (`SignatureVerifier.DistinguishedNames.cs`). When DigiCert
  rotates an intermediate, the pin has to be widened.
- The trusted-root PEMs (`src/Layout/redist/trustedroots/codesignctl.pem`,
  `timestampctl.pem`) are loaded as the *only* trust anchors — the OS root
  store is not merged in (§6 / §11 non-goal).

In the current model, all four lists are owned by the running `dotnetup`. If a
.NET release pipeline starts signing with a new digest (e.g. rotates SHA-384 →
SHA-512, or adopts a new PQC composite), an SDK PR updates the list, ships in
the next `dotnetup` build, and customers pick it up on next self-update *before*
they encounter a manifest signed with the new digest.

If `dotnetup` becomes part of the SDK and customers can be stuck on an older,
SDK-bundled `dotnetup`, that ordering breaks. A customer on an N-1 SDK could
download an N manifest signed with a digest, algorithm, or issuer their bundled
verifier was hard-coded to reject — and the install would fail with
`WeakDigest`, `SignatureAlgorithmNotPermitted`, `IssuerMismatch`, or
`ChainBuildFailed`, depending on what rotated.

## What a servicing mechanism would have to provide

Any future design that ships an SDK-bundled `dotnetup` needs an out-of-band
update path for at least the four sets above. Sketch of the design space (none
of these are committed; this is a checklist for whoever picks this up):

1. **Signed policy bundle, fetched at verify time.** A small, separately-signed
   "signing policy" file published alongside the release manifests. It contains
   the current allow-list of digest OIDs, signature-algorithm OIDs, pinned
   issuer DNs, and trusted-root certificates. The bundled `SignatureVerifier`
   loads the bundle, verifies it against a *bootstrap* trust anchor baked into
   the SDK, and uses the bundle's contents as the runtime allow-list. The
   bootstrap anchor itself has to be chosen to outlive the SDK's support
   window (currently 3 years for LTS).

2. **Make the bundled `dotnetup` a transient bootstrapper.** The SDK only ships
   enough of `dotnetup` to self-update to the latest standalone `dotnetup`, then
   immediately defers all signing-policy decisions to that newer binary. The
   SDK-bundled verifier only ever has to validate the *self-update* signature,
   which can be locked to a small, slow-rotating policy. This is the preferred
   option if it is workable, because it preserves today's "only latest
   `dotnetup` is policy" invariant.

3. **Service through SDK servicing releases.** Every supported SDK servicing
   branch updates `SignatureVerifier`'s allow-lists and pinned roots whenever
   a rotation happens upstream. Operationally expensive (a single TSA-cert
   rotation now requires N back-ports), and customers who are slow to take
   servicing updates remain exposed. Only viable as a stopgap.

4. **Permit multiple `SignerInfo`s and let the release pipeline parallel-sign.**
   Per `dtivel`'s review on
   [#54300](https://github.com/dotnet/sdk/pull/54300#discussion_r3331278636),
   allowing parallel signatures (e.g. legacy RSA + new PQC over the same
   content) lets a single manifest satisfy both an old SDK-bundled verifier
   and a new standalone one. This relaxes §2's "exactly one `SignerInfo`"
   rule and §7's single-token assumptions; both would have to be revisited.
   Realistically a complement to one of the above, not a replacement.

Whichever option is chosen, two acceptance-test changes from the current model
are required:

- A test must enumerate the version skew window the design supports (`SDK
  version X` ↔ `manifest signed at time Y`) and validate the verifier inside
  X's bundled `dotnetup` accepts a manifest from Y. Today there is no skew —
  Y is always "today's standalone build" — so this test does not exist.
- The expiration-window test added alongside this doc
  (`PinnedIssuerCertificates_HaveAtLeast90DaysUntilExpiration` in
  [`test/dotnetup.Tests/SignatureVerifierTests.cs`](https://github.com/dotnet/sdk/blob/release/dnup/test/dotnetup.Tests/SignatureVerifierTests.cs))
  becomes load-bearing rather than advisory: under the current model an
  expired issuer just means "ship a `dotnetup` update before customers
  notice"; under a bundled-`dotnetup` model it means "ship a servicing
  update to every supported SDK band before customers notice".

## Until then

No action is required in current `dotnetup` PRs beyond:

1. Updating `SignatureVerifier.DistinguishedNames.cs`, the trusted-root PEMs,
   and the digest / algorithm allow-lists whenever the .NET Release pipeline
   rotates them.
2. Keeping the 90-day pinned-issuer expiration test (see
   [signature-verification.md](signature-verification.md) §4) green, which
   gives the team early warning to push a `dotnetup` update before a pinned
   intermediate's `notAfter` lapses.

When (if) someone proposes embedding `dotnetup` in the SDK, this document is
the open issue list that proposal needs to close.

---

### Documentation General Dotnetup Releasing (`documentation/general/dotnetup/releasing.md`)

# Publishing dotnetup Preview Builds

The `dotnetup` bootstrap scripts install from the `preview` quality by default. Publishing a
build to that quality updates links under:

```text
https://aka.ms/dotnet/dotnetup/preview/
```

Publishing an older build through the same process rolls those links back without rebuilding.

## Select a build

Use a successful
[`dotnet-dnup-official-ci`](https://dev.azure.com/dnceng/internal/_build?definitionId=1544)
run from the `release/dnup` branch. The build's tags include:

```text
BAR ID - <build-id>
```

If the build tags do not include a BAR ID, you can find it at the end of the job `📤 Publish to BAR`, under the step `Publish Using Darc`.

Use that numeric Build Asset Registry (BAR) ID when promoting the build. Normal non-test runs
of the official pipeline are PME-signed and have a `PME Signed` tag. Use the tag to confirm
signing completed; do not promote a test build or a build without the tag.

## Promote the build

Run the
[`Maestro Build Promotion`](https://dev.azure.com/dnceng/internal/_build?definitionId=750)
pipeline with these parameters:

| Parameter | Value |
| --- | --- |
| `BARBuildId` | The BAR ID from the selected build |
| `PromoteToChannelIds` | `10506` (`dotnetup Daily`) |
| `ArtifactsPublishingAdditionalParameters` ( NOT `symbol` parameters ) | `/p:BuildQuality=preview` |

Leave the remaining parameters at their defaults. The Maestro channel retains its historical
`dotnetup Daily` name; `BuildQuality=preview` controls the quality segment in the generated
aka.ms links.

The overall pipeline can report `PartiallySucceeded` because optional artifacts are downloaded
with `continueOnError`. The `Publish packages, blobs and symbols` step must succeed.

## Verify the promotion

Check that the executable link resolves to the selected build's version:

```pwsh
curl.exe -sI https://aka.ms/dotnet/dotnetup/preview/dotnetup-win-x64.exe |
  Select-String Location
```

Then install into an isolated directory and check the running executable:

```pwsh
$script = Join-Path $env:TEMP 'get-dotnetup-preview.ps1'
$installDir = Join-Path $env:TEMP 'dotnetup-preview-test'

Invoke-WebRequest https://aka.ms/dotnet/dotnetup/preview/get-dotnetup.ps1 -OutFile $script
& $script -InstallDir $installDir
& (Join-Path $installDir 'dotnetup.exe') --info
```

---

--- METRICS ---
- Files Extracted: 101
- Estimated Token Budget: ~215169 tokens
- Canonical Reference: https://codewiki.google/github.com/dotnet/sdk
