diff --git a/docs/ai/evaluation/snippets/evaluate-safety/EvaluateResponseSafety.csproj b/docs/ai/evaluation/snippets/evaluate-safety/EvaluateResponseSafety.csproj index 8aa5fe51cd471..1b085277107d9 100644 --- a/docs/ai/evaluation/snippets/evaluate-safety/EvaluateResponseSafety.csproj +++ b/docs/ai/evaluation/snippets/evaluate-safety/EvaluateResponseSafety.csproj @@ -11,7 +11,7 @@ - + diff --git a/docs/ai/quickstarts/build-mcp-server.md b/docs/ai/quickstarts/build-mcp-server.md index 9314c547c0bb2..7879b4ee05c82 100644 --- a/docs/ai/quickstarts/build-mcp-server.md +++ b/docs/ai/quickstarts/build-mcp-server.md @@ -12,7 +12,7 @@ ms.author: alexwolf In this quickstart, you create a minimal Model Context Protocol (MCP) server using the [C# SDK for MCP](https://github.com/modelcontextprotocol/csharp-sdk), connect to it using GitHub Copilot, and publish it to NuGet. MCP servers are services that expose capabilities to clients through the Model Context Protocol (MCP). > [!NOTE] -> The `Microsoft.Extensions.AI.Templates` experience is currently in preview. The template uses the [ModelContextProtocol](https://www.nuget.org/packages/ModelContextProtocol/) library and the [MCP registry `server.json` schema](https://github.com/modelcontextprotocol/registry/blob/main/docs/reference/server-json/generic-server-json.md), which are both in preview. +> The `Microsoft.McpServer.ProjectTemplates` template package is currently in preview. ## Prerequisites diff --git a/docs/ai/quickstarts/snippets/image-generation/azure-openai/ImagesAzureOpenAI.csproj b/docs/ai/quickstarts/snippets/image-generation/azure-openai/ImagesAzureOpenAI.csproj index 71bac9fd92391..358b3e2a7e267 100644 --- a/docs/ai/quickstarts/snippets/image-generation/azure-openai/ImagesAzureOpenAI.csproj +++ b/docs/ai/quickstarts/snippets/image-generation/azure-openai/ImagesAzureOpenAI.csproj @@ -8,10 +8,10 @@ - + - - + + diff --git a/docs/ai/quickstarts/snippets/image-generation/openai/ImagesOpenAI.csproj b/docs/ai/quickstarts/snippets/image-generation/openai/ImagesOpenAI.csproj index 1f89f27228ff7..9cdb68e0563d5 100644 --- a/docs/ai/quickstarts/snippets/image-generation/openai/ImagesOpenAI.csproj +++ b/docs/ai/quickstarts/snippets/image-generation/openai/ImagesOpenAI.csproj @@ -8,7 +8,7 @@ - + diff --git a/docs/ai/quickstarts/snippets/mcp-server/SampleMcpServer.csproj b/docs/ai/quickstarts/snippets/mcp-server/SampleMcpServer.csproj index 26044b768eb55..ec9e291c6be88 100644 --- a/docs/ai/quickstarts/snippets/mcp-server/SampleMcpServer.csproj +++ b/docs/ai/quickstarts/snippets/mcp-server/SampleMcpServer.csproj @@ -33,7 +33,7 @@ - + diff --git a/docs/ai/quickstarts/snippets/text-to-image/azure-openai/TextToImageAzureOpenAI.csproj b/docs/ai/quickstarts/snippets/text-to-image/azure-openai/TextToImageAzureOpenAI.csproj index 477aee6faba3c..3202a211d8d6c 100644 --- a/docs/ai/quickstarts/snippets/text-to-image/azure-openai/TextToImageAzureOpenAI.csproj +++ b/docs/ai/quickstarts/snippets/text-to-image/azure-openai/TextToImageAzureOpenAI.csproj @@ -10,8 +10,8 @@ - - + + diff --git a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CacheResponses/ConsoleAI.CacheResponses.csproj b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CacheResponses/ConsoleAI.CacheResponses.csproj index 971bf45c23f8b..b809b3c9a1c63 100644 --- a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CacheResponses/ConsoleAI.CacheResponses.csproj +++ b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.CacheResponses/ConsoleAI.CacheResponses.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.ConsumeRateLimitingEmbedding/ConsoleAI.ConsumeRateLimitingEmbedding.csproj b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.ConsumeRateLimitingEmbedding/ConsoleAI.ConsumeRateLimitingEmbedding.csproj index 7e663bbd6775f..9cf06c0474bd4 100644 --- a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.ConsumeRateLimitingEmbedding/ConsoleAI.ConsumeRateLimitingEmbedding.csproj +++ b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.ConsumeRateLimitingEmbedding/ConsoleAI.ConsumeRateLimitingEmbedding.csproj @@ -8,7 +8,7 @@ - + diff --git a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.FunctionalityPipelines/ConsoleAI.FunctionalityPipelines.csproj b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.FunctionalityPipelines/ConsoleAI.FunctionalityPipelines.csproj index a0925186d32c0..7b0183aed50fa 100644 --- a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.FunctionalityPipelines/ConsoleAI.FunctionalityPipelines.csproj +++ b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI.FunctionalityPipelines/ConsoleAI.FunctionalityPipelines.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI/ConsoleAI.csproj b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI/ConsoleAI.csproj index 0be7887285cb0..500a556ab17e1 100644 --- a/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI/ConsoleAI.csproj +++ b/docs/ai/snippets/microsoft-extensions-ai/ConsoleAI/ConsoleAI.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/core/diagnostics/observability-applicationinsights.md b/docs/core/diagnostics/observability-applicationinsights.md index 5cef0fa27df22..cdbe212e34cb4 100644 --- a/docs/core/diagnostics/observability-applicationinsights.md +++ b/docs/core/diagnostics/observability-applicationinsights.md @@ -1,6 +1,6 @@ --- title: "Example: Use OpenTelemetry with Azure Monitor and Application Insights" -description: An walkthrough of how to use OpenTelemetry in .NET to export telemetry to Application Insights +description: A walkthrough of how to use OpenTelemetry in .NET to export telemetry to Application Insights ms.date: 8/21/2024 ms.topic: concept-article ms.custom: sfi-ropc-nochange @@ -14,7 +14,7 @@ There are many commercial Application Performance Management (APM) systems avail To make the ASP.NET experience with Azure Monitor easier, a wrapper package (called a Distro in OTel parlance) is provided that does most of the heavy lifting of configuring OpenTelemetry. -This example is based off the [OTLP walkthrough](./observability-otlp-example.md). Follow the steps 1-5 to create the application code using the OTLP exporter. In this example, we will extend the code to send data to Application Insights. +This example is based off the [OTLP walkthrough](./observability-otlp-example.md). Follow the steps 1-5 to create the application code using the OTLP exporter. In this example, you extend the code to send data to Application Insights. Take the same project from [Step 5](./observability-otlp-example.md#5-configure-opentelemetry-with-the-correct-providers) and add the following NuGet package: @@ -27,19 +27,19 @@ Take the same project from [Step 5](./observability-otlp-example.md#5-configure- > [!NOTE] > Replace the version with the latest available -## 2. Setup the exporter +## 2. Set up the exporter Add the following OTel initialization code before `builder.Build();`: :::code language="csharp" source="snippets/OTLP-Example/csharp/Program.cs" id="Snippet_AzureMonitor"::: -[`UseAzureMonitor()`](https://github.com/Azure/azure-sdk-for-net/blob/d51f02c6ef46f2c5d9b38a9d8974ed461cde9a81/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/OpenTelemetryBuilderExtensions.cs#L80) is the magic that will add the common instrumentation libraries and exporters for Application Insights. You just need to add your custom `Meter` and `ActivitySource` names to the registration. +[`UseAzureMonitor()`](https://github.com/Azure/azure-sdk-for-net/blob/d51f02c6ef46f2c5d9b38a9d8974ed461cde9a81/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/src/OpenTelemetryBuilderExtensions.cs#L80) is the magic that adds the common instrumentation libraries and exporters for Application Insights. You just need to add your custom `Meter` and `ActivitySource` names to the registration. The same OTel initialization works for OTLP as for Application Insights, the difference is which exporters you select. You can use both in the same application, and select between them by defining the appropriate environment variables. ## 3. Specify the connection string -If you're not already an Azure customer, you can create a free account at [https://azure.microsoft.com/free/](https://azure.microsoft.com/pricing/purchase-options/azure-account?cid=msft_learn). Log in to the Azure Portal, and either select an existing Application Insights resource or create a new one with [https://ms.portal.azure.com/#create/Microsoft.AppInsights](https://ms.portal.azure.com/#create/Microsoft.AppInsights). +If you're not already an Azure customer, you can create a free account at [https://azure.microsoft.com/free/](https://azure.microsoft.com/pricing/purchase-options/azure-account?cid=msft_learn). Sign in to the Azure portal, and either select an existing Application Insights resource or create a new one with [https://ms.portal.azure.com/#create/Microsoft.AppInsights](https://ms.portal.azure.com/#create/Microsoft.AppInsights). Application Insights identifies which instance to use to store and process data through an instrumentation key and connection string that are found at the top right side of the portal UI. @@ -58,7 +58,7 @@ If you're using Azure App Service, this connection string is automatically passe ## 4. Examine your app in Application Insights -When you run the application, telemetry will be sent to Application Insights. You should now get logs, metrics, and distributed traces for your application. Open the Application Insights resource in the Azure Portal. +When you run the application, telemetry will be sent to Application Insights. You should now get logs, metrics, and distributed traces for your application. Open the Application Insights resource in the Azure portal. :::row::: :::column span=""::: diff --git a/docs/core/diagnostics/observability-otlp-example.md b/docs/core/diagnostics/observability-otlp-example.md index 46e37cc776293..0ea62c3428bf8 100644 --- a/docs/core/diagnostics/observability-otlp-example.md +++ b/docs/core/diagnostics/observability-otlp-example.md @@ -8,11 +8,11 @@ ms.custom: sfi-image-nochange # Example: Use OpenTelemetry with OTLP and the standalone Aspire Dashboard -This is one of a series of examples to illustrate [.NET observability with OpenTelemetry](./observability-with-otel.md). +This article is one of a series of examples to illustrate [.NET observability with OpenTelemetry](./observability-with-otel.md). -In addition to being a standard part of Aspire, the Aspire Dashboard is available as a [standalone docker container](/dotnet/aspire/fundamentals/dashboard/standalone?tabs=powershell), which provides an OTLP endpoint telemetry can be sent to, and it will visualize the logs, metrics and traces. Using the dashboard in this way has no dependency on Aspire, it will visualize telemetry from any application sending it telemetry via OTLP. It works equally well for applications written in Java, GoLang, Python etc. provided that they can send their telemetry to an OTLP endpoint. +In addition to being a standard part of Aspire, the Aspire Dashboard is available as a [standalone Docker container](/dotnet/aspire/fundamentals/dashboard/standalone?tabs=powershell), which provides an OTLP endpoint that telemetry can be sent to. The dashboard visualizes the logs, metrics, and traces. Using the dashboard in this way has no dependency on Aspire, and it visualizes telemetry from any application that sends it telemetry via OTLP. It works equally well for applications written in Java, GoLang, or Python provided they can send their telemetry to an OTLP endpoint. -Using the Aspire Dashboard has less configuration and setup steps than using Open Source solutions such as [Prometheus, Grafana and Jaeger](./observability-prgrja-example.md), but unlike those tools, the Aspire Dashboard is intended as a developer visualization tool, and not for production monitoring. +Using the Aspire Dashboard has less configuration and setup steps than using Open Source solutions such as [Prometheus, Grafana, and Jaeger](./observability-prgrja-example.md). But unlike those tools, the Aspire Dashboard is intended as a developer visualization tool, and not for production monitoring. ## 1. Create the project @@ -30,7 +30,7 @@ The following code defines a new metric (`greetings.count`) for the number of ti ## 3. Create an API endpoint -Insert the following between `builder.Build();` and `app.Run()` +Insert the following code between `builder.Build();` and `app.Run()` :::code language="csharp" source="snippets/OTLP-Example/csharp/Program.cs" id="Snippet_MapGet"::: @@ -39,7 +39,7 @@ Insert the following function at the bottom of the file: :::code language="csharp" source="snippets/OTLP-Example/csharp/Program.cs" id="Snippet_SendGreeting"::: > [!NOTE] -> The endpoint definition does not use anything specific to OpenTelemetry. It uses the .NET APIs for observability. +> The endpoint definition doesn't use anything specific to OpenTelemetry. It uses the .NET APIs for observability. ## 4. Reference the OpenTelemetry packages @@ -73,7 +73,7 @@ It then registers the OTLP exporter using env vars for its configuration. ## 6. Configure OTLP Environment variables -The OTLP exporter can be configured via APIs in code, but its more common to configure it via environment variables. Add the following to _AppSettings.Development.json_ +The OTLP exporter can be configured via APIs in code, but it's more common to configure it via environment variables. Add the following to _AppSettings.Development.json_ ``` json "OTEL_EXPORTER_OTLP_ENDPOINT": "http://localhost:4317", @@ -83,11 +83,11 @@ The OTLP exporter can be configured via APIs in code, but its more common to con You can add additional environment variables for the [.NET OTLP Exporter](https://github.com/open-telemetry/opentelemetry-dotnet/tree/main/src/OpenTelemetry.Exporter.OpenTelemetryProtocol#exporter-configuration) or common OTel variables such as `OTEL_RESOURCE_ATTRIBUTES` to define [resource attributes](https://opentelemetry.io/docs/concepts/resources/). > [!NOTE] -> A common gotcha is to mix up _AppSettings.json_ and _AppSettings.Development.json_, if the latter is present it will be used when you F5 from Visual Studio and any settings in _AppSettings.json_ will be ignored. +> A common gotcha is to mix up _AppSettings.json_ and _AppSettings.Development.json_. If the latter is present, it will be used when you F5 from Visual Studio, and any settings in _AppSettings.json_ will be ignored. ## 7. Start the Aspire Dashboard container -Use docker to download and run the dashboard container. +Use `docker` to download and run the dashboard container. ``` powershell docker run --rm -it ` @@ -97,11 +97,11 @@ docker run --rm -it ` mcr.microsoft.com/dotnet/aspire-dashboard:latest ``` -Data displayed in the dashboard can be sensitive. By default, the dashboard is secured with authentication that requires a token to login. The token is displayed in the resulting output when running the container. +Data displayed in the dashboard can be sensitive. By default, the dashboard is secured with authentication that requires a token to log in. The token is displayed in the resulting output when running the container. [![Aspire Dashboard](./media/aspire-dashboard-auth.png)](./media/aspire-dashboard-auth.png#lightbox) -Copy the url shown, and replace `0.0.0.0` with `localhost`, eg `http://localhost:18888/login?t=123456780abcdef123456780` and open that in your browser, or you can also paste the key after `/login?t=` when the login dialog is shown. The token will change each time you start the container. +Copy the URL shown, and replace `0.0.0.0` with `localhost`, for example, `http://localhost:18888/login?t=123456780abcdef123456780`, and open that in your browser. Or you can also paste the key after `/login?t=` when the login dialog is shown. The token changes each time you start the container. ## 8. Run the project @@ -111,16 +111,16 @@ Run the project and then access the API with the browser or curl. curl -k http://localhost:7275 ``` -Each time you request the page, it will increment the count for the number of greetings that have been made. +Each time you request the page, it increments the count for the number of greetings that have been made. ### 8.1 Log output The logging statements from the code are output using `ILogger`. By default, the [Console Provider](../extensions/logging.md?tabs=command-line#configure-logging) is enabled so that output is directed to the console. -There are a couple of options for how logs can be egressed from .NET: +There are a few options for how logs can be egressed from .NET: - `stdout` and `stderr` output is redirected to log files by container systems such as [Kubernetes](https://kubernetes.io/docs/concepts/cluster-administration/logging/#how-nodes-handle-container-logs). -- Using logging libraries that will integrate with ILogger, these include [Serilog](https://serilog.net/) or [NLog](https://nlog-project.org/). +- Using logging libraries that integrate with ILogger. These libraries include [Serilog](https://serilog.net/) and [NLog](https://nlog-project.org/). - Using logging providers for OTel such as OTLP. The logging section in the code from step 5 adds the OTel provider. The logs are shown in the dashboard as structured logs - any properties you set in the log message are extracted as fields in the log record. @@ -129,24 +129,24 @@ The logs are shown in the dashboard as structured logs - any properties you set ### 8.2 Viewing the metrics -The Aspire dashboard shows metrics on a per resource basis (a resource being the OTel way of talking about sources of telemetry such as a process). When a resource is selected, the dashboard will enumerate each metric that has been sent to its OTLP endpoint by the resource. The list of metrics is dynamic, and will be updated as new metrics are received. +The Aspire dashboard shows metrics on a per resource basis (a resource being the OTel way of talking about sources of telemetry such as a process). When a resource is selected, the dashboard enumerates each metric that has been sent to its OTLP endpoint by the resource. The list of metrics is dynamic, and is updated as new metrics are received. [![Metrics in standalone dashboard](./media/aspire-dashboard-metrics-thumb.png)](./media/aspire-dashboard-metrics.png#lightbox) -The view for the metrics will depend on the type of metric that is being used: +The view for the metrics depends on the type of metric that's being used: -- Counters will be shown directly. -- Histograms which track a value per request, such as a timespan or bytes sent per request, are collected into a series of buckets. The dashboard will graph the P50, P90 and P99 percentiles. Histogram results can include exemplars, which are individual datapoints together with the trace/spanId for that request. These will be shown as dots on the graph. Selecting one will navigate to the respective trace so you can see what happened to cause that value. This is useful for diagnosing outliers. -- Metrics can include dimensions, which are key/value pairs associated with individual values. The values are aggregated per dimension. Using the dropdowns in the view you can filter the results to look at specific dimensions, such as only `GET` requests, or those for a specific URL route in ASP.NET. +- Counters are shown directly. +- Histograms that track a value per request, such as a timespan or bytes sent per request, are collected into a series of buckets. The dashboard graphs the P50, P90, and P99 percentiles. Histogram results can include exemplars, which are individual datapoints together with the trace/spanId for that request. These are shown as dots on the graph. Selecting one navigates to the respective trace so you can see what happened to cause that value. This is useful for diagnosing outliers. +- Metrics can include dimensions, which are key/value pairs associated with individual values. The values are aggregated per dimension. Using the dropdowns in the view, you can filter the results to look at specific dimensions, such as only `GET` requests, or those for a specific URL route in ASP.NET. ### 8.3 Viewing the tracing -The tracing view will show a list of traces - each trace is a set of activities that share the same traceId. Work is tracked with spans which represent a unit of work. Processing an ASP.NET request will create a span. Making an HttpClient request will be a span. By tracking the span's parent, a hierarchy of spans can be visualized. By collecting spans from a each resource (process) we track the work that happens across a series of services. Http requests have a header which is used to pass the traceId and parent spanId to the next service. Each resource needs to collect telemetry and send it to the same collector. It will then aggregate and present a hierarchy of the spans. +The tracing view shows a list of traces. Each trace is a set of activities that share the same traceId. Work is tracked with spans, which represent a unit of work. Processing an ASP.NET request creates a span. Making an HttpClient request is a span. By tracking the span's parent, a hierarchy of spans can be visualized. By collecting spans from each resource (process), you can track the work that happens across a series of services. HTTP requests have a header that's used to pass the traceId and parent spanId to the next service. Each resource needs to collect telemetry and send it to the same collector. It will then aggregate and present a hierarchy of the spans. [![Traces in standalone dashboard](./media/aspire-dashboard-traces-thumb.png)](./media/aspire-dashboard-traces.png#lightbox) -The dashboard will show a list of traces with summary information. Whenever spans with a new traceId are seen, they will get a row in the table. Clicking view will show all the spans in the trace. +The dashboard shows a list of traces with summary information. Whenever spans with a new traceId are seen, they get a row in the table. Clicking view shows all the spans in the trace. [![Spans in standalone dashboard](./media/aspire-dashboard-spans-thumb.png)](./media/aspire-dashboard-spans.png#lightbox) -Selecting a span will show its details including any properties on the span, such as the `greeting` tag we set in [step 3](#3-create-an-api-endpoint). +Selecting a span shows its details including any properties on the span, such as the `greeting` tag that you set in [step 3](#3-create-an-api-endpoint). diff --git a/docs/core/diagnostics/observability-prgrja-example.md b/docs/core/diagnostics/observability-prgrja-example.md index 17ff4ee1e8ce2..b06091c5f4fec 100644 --- a/docs/core/diagnostics/observability-prgrja-example.md +++ b/docs/core/diagnostics/observability-prgrja-example.md @@ -1,6 +1,6 @@ --- title: "Example: Use OpenTelemetry with Prometheus, Grafana, and Jaeger" -description: An walkthrough of how to use OpenTelemetry in .NET to export telemetry to Prometheus, Grafana, and Jaeger +description: A walkthrough of how to use OpenTelemetry in .NET to export telemetry to Prometheus, Grafana, and Jaeger ms.date: 6/14/2023 ms.topic: article --- @@ -30,7 +30,7 @@ The following code defines a new metric (`greetings.count`) for the number of ti :::code language="csharp" source="snippets/OTel-Prometheus-Grafana-Jaeger/csharp/Program.cs" id="Snippet_SendGreeting"::: > [!NOTE] -> The API definition does not use anything specific to OpenTelemetry. It uses the .NET APIs for observability. +> The API definition doesn't use anything specific to OpenTelemetry. It uses the .NET APIs for observability. ## 4. Reference the OpenTelemetry packages @@ -64,17 +64,17 @@ Run the project and then access the API with the browser or curl. curl -k http://localhost:7275 ``` -Each time you request the page, it will increment the count for the number of greetings that have been made. You can access the metrics endpoint using the same base url, with the path `/metrics`. +Each time you request the page, it increments the count for the number of greetings that have been made. You can access the metrics endpoint using the same base URL, with the path `/metrics`. ### 6.1 Log output The logging statements from the code are output using `ILogger`. By default, the [Console Provider](../extensions/logging.md?tabs=command-line#configure-logging) is enabled so that output is directed to the console. -There are a couple of options for how logs can be egressed from .NET: +There are a few options for how logs can be egressed from .NET: - `stdout` and `stderr` output is redirected to log files by container systems such as [Kubernetes](https://kubernetes.io/docs/concepts/cluster-administration/logging/#how-nodes-handle-container-logs). -- Using logging libraries that will integrate with ILogger, these include [Serilog](https://serilog.net/) or [NLog](https://nlog-project.org/). -- Using logging providers for OTel such as OTLP or the Azure Monitor exporter shown further below. +- Using logging libraries that integrate with ILogger. These libraries include [Serilog](https://serilog.net/) and [NLog](https://nlog-project.org/). +- Using logging providers for OTel, such as OTLP, or the Azure Monitor exporter shown later. ### 6.2 Access the metrics @@ -148,7 +148,7 @@ Resource associated with Activity: telemetry.sdk.version: 1.5.0 ``` -The first is the inner custom activity you created. The second is created by ASP.NET for the request and includes tags for the HTTP request properties. You will see that both have the same `TraceId`, which identifies a single transaction and in a distributed system can be used to correlate the traces from each service involved in a transaction. The IDs are transmitted as HTTP headers. ASP.NET Core assigns a `TraceId` if none is present when it receives a request. `HttpClient` includes the headers by default on outbound requests. Each activity has a `SpanId`, which is the combination of `TraceId` and `SpanId` that uniquely identify each activity. The `Greeter` activity is parented to the HTTP activity through its `ParentSpanId`, which maps to the `SpanId` of the HTTP activity. +The first is the inner custom activity you created. The second is created by ASP.NET for the request and includes tags for the HTTP request properties. You will see that both have the same `TraceId`, which identifies a single transaction. In a distributed system, the trace ID can be used to correlate the traces from each service involved in a transaction. The IDs are transmitted as HTTP headers. ASP.NET Core assigns a `TraceId` if none is present when it receives a request. `HttpClient` includes the headers by default on outbound requests. Each activity has a `SpanId`, which is the combination of `TraceId` and `SpanId` that uniquely identify each activity. The `Greeter` activity is parented to the HTTP activity through its `ParentSpanId`, which maps to the `SpanId` of the HTTP activity. In a later stage, you'll feed this data into Jaeger to visualize the distributed traces. @@ -156,7 +156,7 @@ In a later stage, you'll feed this data into Jaeger to visualize the distributed Prometheus is a metrics collection, aggregation, and time-series database system. You configure it with the metric endpoints for each service and it periodically scrapes the values and stores them in its time-series database. You can then analyze and process them as needed. -The metrics data that's exposed in Prometheus format is a point-in-time snapshot of the process's metrics. Each time a request is made to the metrics endpoint, it will report the current values. While current values are interesting, they become more valuable when compared to historical values to see trends and detect if values are anomalous. Commonly, services have usage spikes based on the time of day or world events, such as a holiday shopping spree. By comparing the values against historical trends, you can detect if they are abnormal, or if a metric is slowly getting worse over time. +The metrics data that's exposed in Prometheus format is a point-in-time snapshot of the process's metrics. Each time a request is made to the metrics endpoint, it reports the current values. While current values are interesting, they become more valuable when compared to historical values to see trends and detect if values are anomalous. Commonly, services have usage spikes based on the time of day or world events, such as a holiday shopping spree. By comparing the values against historical trends, you can detect if they're abnormal, or if a metric is slowly getting worse over time. The process doesn't store any history of these metric snapshots. Adding that capability to the process could be resource intensive. Also, in a distributed system you commonly have multiple instances of each node, so you want to be able to collect the metrics from all of them and then aggregate and compare with their historical values. @@ -164,7 +164,7 @@ The process doesn't store any history of these metric snapshots. Adding that cap Download Prometheus for your platform from [https://prometheus.io/download/](https://prometheus.io/download/) and extract the contents of the download. -Look at the top of the output of your running server to get the port number for the **http** endpoint. For example: +Look at the top of the output of your running server to get the port number for the HTTP endpoint. For example: ```dotnetcli info: Microsoft.Hosting.Lifetime[14] @@ -196,7 +196,7 @@ Start Prometheus, and look in the output for the port it's running on, typically ts=2023-06-16T05:29:02.789Z caller=web.go:562 level=info component=web msg="Start listening for connections" address=0.0.0.0:9090 ``` -Open this URL in your browser. In the Prometheus UI you should now be able to query for your metrics. Use the highlighted button in the following image to open the metrics explorer, which shows all the available metrics. +Open this URL in your browser. In the Prometheus UI, you should now be able to query for your metrics. Use the highlighted button in the following image to open the metrics explorer, which shows all the available metrics. [![Prometheus Metrics Explorer](./media/prometheus-metrics-explorer.thumb.png)](./media/prometheus-metrics-explorer.png#lightbox) @@ -208,19 +208,17 @@ Select the `greetings_count` metric to see a graph of values. Grafana is a dashboarding product that can create dashboards and alerts based on Prometheus or other data sources. -Download and install the OSS version of Grafana from [https://grafana.com/oss/grafana/](https://grafana.com/oss/grafana/) following the instructions for your platform. Once installed, Grafana is typically run on port 3000, so open `http://localhost:3000` in your browser. You will need to log in; the default username and password are both `admin`. +Download and install the OSS version of Grafana from [https://grafana.com/oss/grafana/](https://grafana.com/oss/grafana/) following the instructions for your platform. Once installed, Grafana is typically run on port 3000, so open `http://localhost:3000` in your browser. You'll need to log in; the default username and password are both `admin`. -From the hamburger menu choose connections, and then enter the text `prometheus` to select your endpoint type. Select **Create a Prometheus data source** to add a new data source. +From the hamburger menu, choose connections, and then enter the text `prometheus` to select your endpoint type. Select **Create a Prometheus data source** to add a new data source. [![Grafana connection to prometheus](./media/grafana-connections.thumb.png)](./media/grafana-connections.png#lightbox) -You need to set the following properties: - -- Prometheus server URL: `http://localhost:9090/` changing the port as applicable +Set the Prometheus server URL to `http://localhost:9090/`, changing the port as applicable. Select **Save & Test** to verify the configuration. -Once you get a success message, you can configure a dashboard. Click the **building a dashboard** link shown in the popup for the success message. +Once you get a success message, you can configure a dashboard. Select the **building a dashboard** link shown in the popup for the success message. Select **Add a Visualization**, and then choose the Prometheus data source you just added as the data source. @@ -287,15 +285,15 @@ In a distributed system, you want to send traces from all processes to the same You can make your app a little more interesting by having it make HTTP calls to itself. -- Add an `HttpClient` factory to the application +- Add an `HttpClient` factory to the application: :::code language="csharp" source="snippets/OTel-Prometheus-Grafana-Jaeger/csharp/Program.cs" id="Snippet_HttpClientFactory"::: -- Add a new endpoint for making nested greeting calls +- Add a new endpoint for making nested greeting calls: :::code language="csharp" source="snippets/OTel-Prometheus-Grafana-Jaeger/csharp/Program.cs" id="Snippet_MapNested"::: -- Implement the endpoint so that it makes HTTP calls that can also be traced. In this case, it calls back to itself in an artificial loop (really only applicable to demo scenarios). +- Implement the endpoint so that it makes HTTP calls that can also be traced. In this case, it calls back to itself in an artificial loop (really only applicable to demo scenarios): :::code language="csharp" source="snippets/OTel-Prometheus-Grafana-Jaeger/csharp/Program.cs" id="Snippet_SendNestedGreeting"::: diff --git a/docs/core/extensions/httpclient-latency-extensions.md b/docs/core/extensions/httpclient-latency-extensions.md index 7f73b802e2bf4..285e96da9c998 100644 --- a/docs/core/extensions/httpclient-latency-extensions.md +++ b/docs/core/extensions/httpclient-latency-extensions.md @@ -12,7 +12,7 @@ The extension method when configuring your services: @@ -49,7 +51,7 @@ To add HTTP client latency telemetry to your application, call the , collecting detailed latency information for each request. -### Configure telemetry options +## Configure telemetry options You configure telemetry collection through the ([standard options pattern](options.md)). You can supply values either with a delegate or by binding configuration (for example, `appsettings.json`). @@ -57,7 +59,7 @@ The options instance is resolved once per handler pipeline so changes apply to n :::code language="csharp" source="snippets/http/latency/Program.cs" range="23-31" highlight="1-5,8,9"::: -### Configuration options +## Configuration options The class offers the following settings: @@ -65,11 +67,11 @@ The c |--------------------------------|---------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------| | EnableDetailedLatencyBreakdown | Boolean | `true` | Enables fine-grained phase timing for each HttpClient request (for example, connection establishment, headers sent, first byte, completion) to produce a breakdown of total latency. Adds a small extra CPU/time measurement cost, no wire overhead. | Set to `false` only in very high-throughput scenarios where minimal overhead is required and total duration alone is sufficient. | -### Collected telemetry data +## Collected telemetry data When HTTP client latency telemetry is enabled, it captures phase timestamps, selected measures (where supported), and protocol attributes used for performance analysis. -#### Timing checkpoints +### Timing checkpoints Timestamps are recorded for key stages of the HTTP request lifecycle: @@ -83,7 +85,7 @@ Timestamps are recorded for key stages of the HTTP request lifecycle: | Response headers | Http.ResponseHeadersStart | Http.ResponseHeadersEnd | First byte to completion of header parsing. | | Response content | Http.ResponseContentStart | Http.ResponseContentEnd | Reading full response body (to completion or disposal). | -#### Measures (platform dependent) +### Measures (platform dependent) Measures quantify latency contributors that raw phase checkpoints cannot (GC pause overlap, connection churn, other accumulated counts or durations). They are collected in an in‑memory latency context created when you call @@ -100,7 +102,7 @@ to a histogram and connection initiations to a counter, optionally dimensioned b | Http.GCPauseTime | Total GC pause duration overlapping the request. | | Http.ConnectionInitiated | Emitted when a new underlying connection (not pooled reuse) is created. | -#### Tags +### Tags Use tags to attach stable categorical dimensions to each request so you can segment, filter, and aggregate metrics and logs without reprocessing raw data. They are low‑cardinality classification labels (not timings) captured @@ -130,7 +132,7 @@ For example: :::code language="csharp" source="snippets/http/latency/Program.cs" range="58-75" highlight="10,13,16"::: -### Platform considerations +## Platform considerations HTTP client latency telemetry runs on all supported targets (.NET 9, .NET 8, .NET Standard 2.0, and .NET Framework 4.6.2). Core timing checkpoints are always collected. The GC pause metric (Http.GCPauseTime) is emitted only when running on .NET 8 or .NET 9. diff --git a/docs/core/extensions/logging-providers.md b/docs/core/extensions/logging-providers.md index c82d6bdb1a138..1cad48ab08fd1 100644 --- a/docs/core/extensions/logging-providers.md +++ b/docs/core/extensions/logging-providers.md @@ -188,7 +188,7 @@ For more information, see the following resources: - [Application Insights overview](/azure/application-insights/app-insights-overview) - [ApplicationInsightsLoggerProvider for .NET Core ILogger logs](/azure/azure-monitor/app/ilogger) - Start here if you want to implement the logging provider without the rest of Application Insights telemetry. - [Application Insights logging adapters](/azure/azure-monitor/app/asp-net-trace-logs). -- [Install, configure, and initialize the Application Insights SDK](/training/modules/instrument-web-app-code-with-application-insights) - Interactive tutorial on the Microsoft Learn site. +- [Learn how to use the tools offered in Application Insights to enhance the performance and stability of your applications](/training/modules/monitor-app-performance/). ## Logging provider design considerations diff --git a/docs/core/extensions/logging.md b/docs/core/extensions/logging.md index f8b79b97c8bea..0b092407522ec 100644 --- a/docs/core/extensions/logging.md +++ b/docs/core/extensions/logging.md @@ -503,7 +503,7 @@ public void Test(string id) Exception logging is provider-specific. -### Default log level +## Default log level If the default log level isn't set, the default log level value is `Information`. @@ -526,7 +526,7 @@ using IHost host = builder.Build(); await host.RunAsync(); ``` -### Filter function +## Filter function A filter function is invoked for all providers and categories that don't have rules assigned to them by configuration or code: diff --git a/docs/core/extensions/snippets/ratelimit/http/http.csproj b/docs/core/extensions/snippets/ratelimit/http/http.csproj index 725f9f05ada64..c008780ab3cb2 100644 --- a/docs/core/extensions/snippets/ratelimit/http/http.csproj +++ b/docs/core/extensions/snippets/ratelimit/http/http.csproj @@ -8,7 +8,7 @@ - + diff --git a/docs/core/introduction.md b/docs/core/introduction.md index 0cf32601d7fcd..eae1e2a028f8f 100644 --- a/docs/core/introduction.md +++ b/docs/core/introduction.md @@ -83,6 +83,5 @@ There are multiple variants of .NET, each supporting a different type of app. Th ## Next steps * [Choose a .NET tutorial](tutorials/index.md) -* [Try .NET in your browser](../csharp/tour-of-csharp/tutorials/numbers-in-csharp.md) * [Take a tour of C#](../csharp/tour-of-csharp/overview.md) * [Take a tour of F#](../fsharp/tour.md) diff --git a/docs/core/sdk/file-based-apps.md b/docs/core/sdk/file-based-apps.md index fce2cf155d3e2..c50437641ab47 100644 --- a/docs/core/sdk/file-based-apps.md +++ b/docs/core/sdk/file-based-apps.md @@ -30,8 +30,12 @@ Adds a NuGet package reference to your application. ```csharp #:package Newtonsoft.Json #:package Serilog@3.1.1 +#:package Spectre.Console@* ``` +> [!NOTE] +> Omitting the version number after the package name currently only works when you use central package management with a `Directory.Packages.props` file. Otherwise, specify the version number explicitly, or add `@*` after the package name to use the latest version. + ### `#:project` References another project file or directory that contains a project file. @@ -90,12 +94,6 @@ Pass arguments to your application by placing them after `--`: dotnet run file.cs -- arg1 arg2 ``` -Without `--`, arguments go to the `dotnet run` command: - -```dotnetcli -dotnet run file.cs arg1 arg2 -``` - #### Pipe code from stdin Pipe C# code directly to `dotnet run` by using standard input with the `-` argument. The `-` argument indicates that `dotnet run` reads the code from standard input instead of a file. With the `-` argument, `dotnet run` doesn't search the current working directory for other files, such as launch profiles. The current directory is still the working directory to build and run the program. @@ -188,15 +186,12 @@ By default, restore runs implicitly when you build or run your application. Howe File-based apps automatically include specific file types for compilation and packaging. -By default, the following items are included: - -- The single C# file itself. -- ResX resource files in the same directory. +By default, the single C# file is included. Different SDKs include other file types: - `Microsoft.NET.Sdk.Web` includes `*.json` configuration files. -- Other specialized SDKs might include other patterns. +- Non-default SDKs include ResX resource files. ## Native AOT publishing @@ -373,12 +368,6 @@ Caching improves build performance but can cause confusion when: dotnet clean file-based-apps ``` -- Run a full build by using the `--no-cache` flag: - - ```dotnetcli - dotnet build file.cs --no-cache - ``` - - Force a clean build to bypass cache: ```dotnetcli diff --git a/docs/csharp/language-reference/attributes/general.md b/docs/csharp/language-reference/attributes/general.md index e4c3f49a3eb64..3c24b5edba55d 100644 --- a/docs/csharp/language-reference/attributes/general.md +++ b/docs/csharp/language-reference/attributes/general.md @@ -35,7 +35,7 @@ In the following example, `Conditional` is applied to a method to enable or disa :::code language="csharp" source="snippets/trace.cs" ::: -If the `TRACE_ON` identifier isn't defined, the trace output isn't displayed. Explore for yourself in the interactive window. +If the `TRACE_ON` identifier isn't defined, the trace output isn't displayed. The `Conditional` attribute is often used with the `DEBUG` identifier to enable trace and logging features for debug builds but not in release builds, as shown in the following example: diff --git a/docs/csharp/language-reference/builtin-types/default-values.md b/docs/csharp/language-reference/builtin-types/default-values.md index f0f64b5c95cd3..05be1aaee11ff 100644 --- a/docs/csharp/language-reference/builtin-types/default-values.md +++ b/docs/csharp/language-reference/builtin-types/default-values.md @@ -2,7 +2,7 @@ title: "Default values of built-in types" description: "Learn the default values of C# types such as bool, char, int, float, double, and more." ms.date: 11/18/2025 -helpviewer_keywords: +helpviewer_keywords: - "default [C#]" - "parameterless constructor [C#]" --- @@ -10,16 +10,16 @@ helpviewer_keywords: The following table shows the default values of C# types: -|Type|Default value| -|---------|------------------| -|Any [reference type](../keywords/reference-types.md)|`null`| -|Any [built-in integral numeric type](integral-numeric-types.md)|0 (zero)| -|Any [built-in floating-point numeric type](floating-point-numeric-types.md)|0 (zero)| -|[bool](bool.md)|`false`| -|[char](char.md)|`'\0'` (U+0000)| -|[enum](enum.md)|The value produced by the expression `(E)0`, where `E` is the enum identifier.| -|[struct](struct.md)|The value produced by setting all value-type fields to their default values and all reference-type fields to `null`.| -|Any [nullable value type](nullable-value-types.md)|An instance for which the property is `false` and the property is undefined. That default value is also known as the *null* value of a nullable value type.| +| Type | Default value | +|-----------------------------------------------------------------------------|-----------------| +| Any [reference type](../keywords/reference-types.md) | `null` | +| Any [built-in integral numeric type](integral-numeric-types.md) | 0 (zero) | +| Any [built-in floating-point numeric type](floating-point-numeric-types.md) | 0 (zero) | +| [bool](bool.md) | `false` | +| [char](char.md) | `'\0'` (U+0000) | +| [enum](enum.md) | The value produced by the expression `(E)0`, where `E` is the enum identifier. | +| [struct](struct.md) | The value produced by setting all value-type fields to their default values and all reference-type fields to `null`. | +| Any [nullable value type](nullable-value-types.md) | An instance for which the property is `false` and the property is undefined. That default value is also known as the *null* value of a nullable value type. | ## Default value expressions @@ -39,12 +39,12 @@ int a = default; For a value type, the *implicit* parameterless constructor also produces the default value of the type, as the following example shows: -```csharp-interactive +```csharp var n = new System.Numerics.Complex(); Console.WriteLine(n); // output: (0, 0) ``` -At run time, if the instance represents a value type, you can use the method to invoke the parameterless constructor to obtain the default value of the type. +At runtime, if the instance represents a value type, you can use the method to invoke the parameterless constructor to obtain the default value of the type. > [!NOTE] > A [structure type](struct.md) (which is a value type) can have an [explicit parameterless constructor](struct.md#struct-initialization-and-default-values) that might produce a non-default value of the type. Thus, we recommend using the `default` operator or the `default` literal to produce the default value of a type. diff --git a/docs/csharp/language-reference/builtin-types/floating-point-numeric-types.md b/docs/csharp/language-reference/builtin-types/floating-point-numeric-types.md index e263a578edfc4..de855a991bf1d 100644 --- a/docs/csharp/language-reference/builtin-types/floating-point-numeric-types.md +++ b/docs/csharp/language-reference/builtin-types/floating-point-numeric-types.md @@ -27,8 +27,8 @@ The *floating-point numeric types* represent real numbers. All floating-point nu C# supports the following predefined floating-point types: -|C# type/keyword|Approximate range|Precision|Size|.NET type| -|----------|-----------------------|---------------|--------------|--------------| +| C# type/keyword | Approximate range | Precision | Size | .NET type | +|-----------------|-------------------|-----------|------|-----------| |`float`|±1.5 x 10−45 to ±3.4 x 1038|~6-9 digits|4 bytes|| |`double`|±5.0 × 10−324 to ±1.7 × 10308|~15-17 digits|8 bytes|| |`decimal`|±1.0 x 10-28 to ±7.9228 x 1028|28-29 digits|16 bytes|| @@ -53,7 +53,7 @@ You can also mix integral types and the `decimal` type in an expression. In this You cannot mix the `decimal` type with the `float` and `double` types in an expression. In this case, if you want to perform arithmetic, comparison, or equality operations, you must explicitly convert the operands either from or to the `decimal` type, as the following example shows: -```csharp-interactive +```csharp double a = 1.0; decimal b = 2.1m; Console.WriteLine(a + (double)b); @@ -88,7 +88,7 @@ The preceding example also shows the use of `_` as a *digit separator*. You can You can also use scientific notation, that is, specify an exponent part of a real literal, as the following example shows: -```csharp-interactive +```csharp double d = 0.42e2; Console.WriteLine(d); // output 42 diff --git a/docs/csharp/language-reference/builtin-types/reference-types.md b/docs/csharp/language-reference/builtin-types/reference-types.md index 3f2dd12793eb0..27457e22ad3cb 100644 --- a/docs/csharp/language-reference/builtin-types/reference-types.md +++ b/docs/csharp/language-reference/builtin-types/reference-types.md @@ -36,10 +36,10 @@ The `string` type represents a sequence of zero or more Unicode characters. `str Although `string` is a reference type, the [equality operators `==` and `!=`](../operators/equality-operators.md#string-equality) are defined to compare the values of `string` objects, not references. Value based equality makes testing for string equality more intuitive. For example: -```csharp-interactive +```csharp string a = "hello"; string b = "h"; -// Append to contents of 'b' +// Append to contents of 'b'. b += "ello"; Console.WriteLine(a == b); Console.WriteLine(object.ReferenceEquals(a, b)); @@ -71,7 +71,7 @@ char x = str[2]; // x = 's'; In similar fashion, the `[]` operator can also be used for iterating over each character in a string: -```csharp-interactive +```csharp string str = "test"; for (int i = 0; i < str.Length; i++) @@ -155,7 +155,7 @@ Quoted string literals are enclosed in double quotation marks ("): String literals can contain any character literal. Escape sequences are included. The following example uses escape sequence `\\` for backslash, `\u0066` for the letter f, and `\n` for newline. -```csharp-interactive +```csharp string a = "\\\u0066\n F"; Console.WriteLine(a); // Output: diff --git a/docs/csharp/language-reference/keywords/snippets/Extensions.cs b/docs/csharp/language-reference/keywords/snippets/Extensions.cs index c6eed3290828c..bf655c31d5799 100644 --- a/docs/csharp/language-reference/keywords/snippets/Extensions.cs +++ b/docs/csharp/language-reference/keywords/snippets/Extensions.cs @@ -45,7 +45,7 @@ public int Median if (count % 2 == 0) { // Even number of elements: average the two middle elements - return (sortedList[middleIndex - 1] + sortedList[middleIndex]); + return (sortedList[middleIndex - 1] + sortedList[middleIndex]) / 2; } else { diff --git a/docs/csharp/language-reference/operators/index.md b/docs/csharp/language-reference/operators/index.md index 4c6be6c6d89e9..a69fb1b34c688 100644 --- a/docs/csharp/language-reference/operators/index.md +++ b/docs/csharp/language-reference/operators/index.md @@ -2,9 +2,9 @@ title: "Operators and expressions - List all operators and expression" description: "Learn the C# operators and expressions, operator precedence, and operator associativity." ms.date: 11/28/2022 -f1_keywords: +f1_keywords: - "cs.operators" -helpviewer_keywords: +helpviewer_keywords: - "operators [C#]" - "operator precedence [C#]" - "operator associativity [C#]" @@ -54,14 +54,14 @@ You can use an [expression body definition](../../programming-guide/statements-e In an expression with multiple operators, the operators with higher precedence are evaluated before the operators with lower precedence. In the following example, the multiplication is performed first because it has higher precedence than addition: -```csharp-interactive +```csharp var a = 2 + 2 * 2; Console.WriteLine(a); // output: 6 ``` Use parentheses to change the order of evaluation imposed by operator precedence: -```csharp-interactive +```csharp var a = (2 + 2) * 2; Console.WriteLine(a); // output: 8 ``` @@ -102,7 +102,7 @@ When operators have the same precedence, associativity of the operators determin Use parentheses to change the order of evaluation imposed by operator associativity: -```csharp-interactive +```csharp int a = 13 / 5 / 2; int b = 13 / (5 / 2); Console.WriteLine($"a = {a}, b = {b}"); // output: a = 1, b = 6 @@ -112,12 +112,12 @@ Console.WriteLine($"a = {a}, b = {b}"); // output: a = 1, b = 6 Unrelated to operator precedence and associativity, operands in an expression are evaluated from left to right. The following examples demonstrate the order in which operators and operands are evaluated: -| Expression | Order of evaluation | -| ---------- | ------------------- | -|`a + b`|a, b, +| -|`a + b * c`|a, b, c, *, +| -|`a / b + c * d`|a, b, /, c, d, *, +| -|`a / (b + c) * d`|a, b, c, +, /, d, *| +| Expression | Order of evaluation | +|-------------------|---------------------| +| `a + b` | a, b, + | +| `a + b * c` | a, b, c, *, + | +| `a / b + c * d` | a, b, /, c, d, *, + | +| `a / (b + c) * d` | a, b, c, +, /, d, * | Typically, all operator operands are evaluated. However, some operators evaluate operands conditionally. That is, the value of the leftmost operand of such an operator defines if (or which) other operands should be evaluated. These operators are the conditional logical [AND (`&&`)](boolean-logical-operators.md#conditional-logical-and-operator-) and [OR (`||`)](boolean-logical-operators.md#conditional-logical-or-operator-) operators, the [null-coalescing operators `??` and `??=`](null-coalescing-operator.md), the [null-conditional operators `?.` and `?[]`](member-access-operators.md#null-conditional-operators--and-), and the [conditional operator `?:`](conditional-operator.md). For more information, see the description of each operator. diff --git a/docs/csharp/language-reference/tokens/interpolated.md b/docs/csharp/language-reference/tokens/interpolated.md index 949318618c724..5472f8d2c9722 100644 --- a/docs/csharp/language-reference/tokens/interpolated.md +++ b/docs/csharp/language-reference/tokens/interpolated.md @@ -90,7 +90,7 @@ For more information about custom formatting, see the [Custom formatting with IC ## Other resources -If you're new to string interpolation, see the [String interpolation in C#](../../tutorials/string-interpolation.md) interactive tutorial. That tutorial demonstrates how to use interpolated strings to produce formatted strings. +If you're new to string interpolation, see the [String interpolation in C#](../../tutorials/string-interpolation.md) tutorial. That tutorial demonstrates how to use interpolated strings to produce formatted strings. ## Compilation of interpolated strings diff --git a/docs/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix.md b/docs/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix.md index f273ff10e457b..71b3c8d64b028 100644 --- a/docs/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix.md +++ b/docs/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix.md @@ -29,7 +29,7 @@ There are several steps to creating and validating your analyzer: ## Create the solution -- In Visual Studio, choose **File > New > Project...** to display the New Project dialog. +- In Visual Studio, choose **File > New > Project** to display the New Project dialog. - Under **Visual C# > Extensibility**, choose **Analyzer with code fix (.NET Standard)**. - Name your project "**MakeConst**" and click OK. diff --git a/docs/csharp/tour-of-csharp/overview.md b/docs/csharp/tour-of-csharp/overview.md index 81842808187f8..8f386f0d28cf2 100644 --- a/docs/csharp/tour-of-csharp/overview.md +++ b/docs/csharp/tour-of-csharp/overview.md @@ -17,7 +17,7 @@ C# is in the C family of languages. [C# syntax](../language-reference/keywords/i The "Hello, World" program is traditionally used to introduce a programming language. Here it is in C#: ```csharp -// This line prints "Hello, World" +// This line prints "Hello, World" Console.WriteLine("Hello, World"); ``` @@ -25,7 +25,7 @@ The line starting with `//` is a *single line comment*. C# single line comments This alternative format is still valid and contains many of the basic concepts in all C# programs. Many existing C# samples use the following equivalent format: -:::code language="csharp" interactive="try-dotnet" source="./snippets/shared/HelloWorld.cs"::: +:::code language="csharp" source="./snippets/shared/HelloWorld.cs"::: The preceding "Hello, World" program starts with a `using` directive that references the `System` namespace. Namespaces provide a hierarchical means of organizing C# programs and libraries. Namespaces contain types and other namespaces—for example, the `System` namespace contains many types, such as the `Console` class referenced in the program, and many other namespaces, such as `IO` and `Collections`. A `using` directive that references a given namespace enables unqualified use of the types that are members of that namespace. Because of the `using` directive, the program can use `Console.WriteLine` as shorthand for `System.Console.WriteLine`. In the earlier example, that namespace was [implicitly](../language-reference/keywords/using-directive.md#the-global-modifier) included. diff --git a/docs/csharp/tour-of-csharp/tutorials/index.md b/docs/csharp/tour-of-csharp/tutorials/index.md index 267209cd057ce..2027537667400 100644 --- a/docs/csharp/tour-of-csharp/tutorials/index.md +++ b/docs/csharp/tour-of-csharp/tutorials/index.md @@ -1,6 +1,6 @@ --- title: Interactive tutorials -description: Learn C# in your browser, and get started with your own development environment +description: Learn C# using GitHub Codespaces, and get started with your own development environment. ms.date: 12/10/2025 --- # Introduction to C\# @@ -10,9 +10,9 @@ Welcome to the introduction to C# tutorials. These lessons start with interactiv > [!VIDEO https://www.youtube.com/embed/9THmGiSPjBQ?si=3kUKFtOMLpEzeq7J] -The first lessons explain C# concepts by using small snippets of code. You learn the basics of C# syntax and how to work with data types like strings, numbers, and booleans. It's all interactive, and you'll be writing and running code within minutes. These first lessons assume no prior knowledge of programming or the C# language. Each lesson builds on the prior lessons. You should do them in order. However, if you have some programming experience, you can skip or skim the first lessons and start with any new concepts. +The first lessons explain C# concepts by using small snippets of code. You learn the basics of C# syntax and how to work with data types like strings, numbers, and Booleans. It's all interactive, and you'll be writing and running code within minutes. These first lessons assume no prior knowledge of programming or the C# language. Each lesson builds on the prior lessons. You should do them in order. However, if you have some programming experience, you can skip or skim the first lessons and start with any new concepts. -To use GitHub codespaces, you need to create a free [GitHub](https://github.com) account. +To use GitHub Codespaces, you need to create a free [GitHub](https://github.com) account. ## Hello world diff --git a/docs/csharp/tour-of-csharp/tutorials/numbers-in-csharp.md b/docs/csharp/tour-of-csharp/tutorials/numbers-in-csharp.md index 0780a26808b9a..3bd7e5db99a67 100644 --- a/docs/csharp/tour-of-csharp/tutorials/numbers-in-csharp.md +++ b/docs/csharp/tour-of-csharp/tutorials/numbers-in-csharp.md @@ -1,6 +1,6 @@ --- title: Work with Numbers - Introductory tutorial -description: This tutorial teaches you about the numeric types in C#. The tutorial contains a series of lessons that explore numbers and math operations in C#. +description: This tutorial teaches you about the numeric types in C#. The tutorial contains a series of lessons that explore numbers and math operations in C#. ms.date: 12/10/2025 --- # Tutorial: How to use integer and floating point numbers in C\# @@ -247,12 +247,10 @@ Now that you know the different numeric types, write code that calculates the ar You should get an answer between 19 and 20. -When you try it, open the details pane to see how you did: -
-:::code language="csharp" interactive="try-dotnet-method" source="./snippets/NumbersInCsharp/numbers.cs" id="Challenge"::: +:::code language="csharp" source="./snippets/NumbersInCsharp/numbers.cs" id="Challenge":::
diff --git a/docs/fundamentals/runtime-libraries/includes/csharp-interactive-with-utc-note.md b/docs/fundamentals/runtime-libraries/includes/csharp-interactive-with-utc-note.md deleted file mode 100644 index f11659f31533b..0000000000000 --- a/docs/fundamentals/runtime-libraries/includes/csharp-interactive-with-utc-note.md +++ /dev/null @@ -1,5 +0,0 @@ - -> [!NOTE] -> Some C# examples in this article run in the [Try.NET](https://try.dot.net) inline code runner and playground. Select the **Run** button to run an example in an interactive window. Once you execute the code, you can modify it and run the modified code by selecting **Run** again. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages. -> -> The [local time zone](xref:System.TimeZoneInfo.Local) of the [Try.NET](https://try.dot.net) inline code runner and playground is Coordinated Universal Time, or UTC. This may affect the behavior and the output of examples that illustrate the , , and types and their members. diff --git a/docs/orleans/grains/snippets/transactions/Abstractions/Abstractions.csproj b/docs/orleans/grains/snippets/transactions/Abstractions/Abstractions.csproj index 3c26fdd547c1c..8b4e3a1dc852c 100644 --- a/docs/orleans/grains/snippets/transactions/Abstractions/Abstractions.csproj +++ b/docs/orleans/grains/snippets/transactions/Abstractions/Abstractions.csproj @@ -7,8 +7,8 @@ - - + + diff --git a/docs/orleans/grains/snippets/transactions/Client/Client.csproj b/docs/orleans/grains/snippets/transactions/Client/Client.csproj index 627770d120b77..b04ddc9a02397 100644 --- a/docs/orleans/grains/snippets/transactions/Client/Client.csproj +++ b/docs/orleans/grains/snippets/transactions/Client/Client.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/orleans/grains/snippets/transactions/Server/Server.csproj b/docs/orleans/grains/snippets/transactions/Server/Server.csproj index be983be819054..d30eecd11693d 100644 --- a/docs/orleans/grains/snippets/transactions/Server/Server.csproj +++ b/docs/orleans/grains/snippets/transactions/Server/Server.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.Client/BroadcastChannel.Client.csproj b/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.Client/BroadcastChannel.Client.csproj index fd43f59d86532..000cfbd7f34d9 100644 --- a/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.Client/BroadcastChannel.Client.csproj +++ b/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.Client/BroadcastChannel.Client.csproj @@ -8,7 +8,7 @@ - + diff --git a/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.GrainInterfaces/BroadcastChannel.GrainInterfaces.csproj b/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.GrainInterfaces/BroadcastChannel.GrainInterfaces.csproj index a9d0706adff2f..3ff58e3e399f2 100644 --- a/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.GrainInterfaces/BroadcastChannel.GrainInterfaces.csproj +++ b/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.GrainInterfaces/BroadcastChannel.GrainInterfaces.csproj @@ -7,7 +7,7 @@ - + diff --git a/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.Silo/BroadcastChannel.Silo.csproj b/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.Silo/BroadcastChannel.Silo.csproj index 2aecd8871069d..409d12b8fbaa6 100644 --- a/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.Silo/BroadcastChannel.Silo.csproj +++ b/docs/orleans/streaming/snippets/broadcastchannel/BroadcastChannel.Silo/BroadcastChannel.Silo.csproj @@ -8,8 +8,8 @@ - - + + diff --git a/docs/samples-and-tutorials/index.md b/docs/samples-and-tutorials/index.md index ba744f21116b9..c19e38e29a57d 100644 --- a/docs/samples-and-tutorials/index.md +++ b/docs/samples-and-tutorials/index.md @@ -8,7 +8,7 @@ ms.date: 02/01/2021 # .NET samples and tutorials -The .NET documentation contains a set of samples and tutorials that teach you about .NET. This article describes how to find, view, and download .NET, ASP.NET Core, and C# samples and tutorials. Find resources to learn the F# programming language on the [F# Foundation's site](https://fsharp.org/learn/). If you're interested in exploring C# using an online code editor, start with [this interactive tutorial](https://dotnet.microsoft.com/learn/dotnet/in-browser-tutorial/1) and continue with [C# interactive tutorial](../csharp/tour-of-csharp/tutorials/index.md). For instructions on how to view and download sample code, see the [Viewing and downloading samples](#view-and-download-samples) section. +The .NET documentation contains a set of samples and tutorials that teach you about .NET. This article describes how to find, view, and download .NET, ASP.NET Core, and C# samples and tutorials. Find resources to learn the F# programming language on the [F# Foundation's site](https://fsharp.org/learn/). If you're interested in exploring C#, start with [Hello World in 5 minutes](https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/intro) and continue with [Introduction to C# tutorial](../csharp/tour-of-csharp/tutorials/index.md). For instructions on how to view and download sample code, see the [Viewing and downloading samples](#view-and-download-samples) section. ## .NET diff --git a/docs/standard/base-types/choosing-between-anonymous-and-tuple.md b/docs/standard/base-types/choosing-between-anonymous-and-tuple.md index 7ed3f0b9254b9..596c372e6baa9 100644 --- a/docs/standard/base-types/choosing-between-anonymous-and-tuple.md +++ b/docs/standard/base-types/choosing-between-anonymous-and-tuple.md @@ -12,7 +12,7 @@ Choosing the appropriate type involves considering its usability, performance, a Anonymous types were introduced in C# 3.0 with Language-Integrated Query (LINQ) expressions. With LINQ, developers often project results from queries into anonymous types that hold a few select properties from the objects they're working with. Consider the following example, that instantiates an array of objects, and iterates through them projecting into an anonymous type with two properties. -```csharp-interactive +```csharp var dates = new[] { DateTime.UtcNow.AddHours(-1), @@ -48,7 +48,7 @@ internal sealed class f__AnonymousType0 For more information, see [anonymous types](../../csharp/fundamentals/types/anonymous-types.md). The same functionality exists with tuples when projecting into LINQ queries, you can select properties into tuples. These tuples flow through the query, just as anonymous types would. Now consider the following example using the `System.Tuple`. -```csharp-interactive +```csharp var dates = new[] { DateTime.UtcNow.AddHours(-1), @@ -66,7 +66,7 @@ foreach (var tuple in With the , the instance exposes numbered item properties, such as `Item1`, and `Item2`. These property names can make it more difficult to understand the intent of the property values, as the property name only provides the ordinal. Furthermore, the `System.Tuple` types are reference `class` types. The however, is a value `struct` type. The following C# snippet, uses `ValueTuple` to project into. In doing so, it assigns using a literal syntax. -```csharp-interactive +```csharp var dates = new[] { DateTime.UtcNow.AddHours(-1), @@ -93,10 +93,10 @@ You might want to always use over , ### Key differences | Name | Access modifier | Type | Custom member name | Deconstruction support | Expression tree support | -|--------------------------|-----------------|----------|----------------------|------------------------|-------------------------| -| Anonymous types | `internal` | `class` | ✔️ | ❌ | ✔️ | -| | `public` | `class` | ❌ | ❌ | ✔️ | -| | `public` | `struct` | ✔️ | ✔️ | ❌ | +|--------------------------|-----------------|----------|--------------------|------------------------|-------------------------| +| Anonymous types | `internal` | `class` | ✔️ | ❌ | ✔️ | +| | `public` | `class` | ❌ | ❌ | ✔️ | +| | `public` | `struct` | ✔️ | ✔️ | ❌ | ### Serialization diff --git a/docs/standard/base-types/parsing-datetime.md b/docs/standard/base-types/parsing-datetime.md index e067d30f02860..f952034fc02a9 100644 --- a/docs/standard/base-types/parsing-datetime.md +++ b/docs/standard/base-types/parsing-datetime.md @@ -46,9 +46,6 @@ The format provider is also used to interpret an ambiguous numeric date. It's un The following example illustrates the use of the method to convert a `string` into a . This example uses the culture associated with the current thread. If the associated with the current culture can't parse the input string, a is thrown. -> [!TIP] -> All the C# samples in this article run in your browser. Press the **Run** button to see the output. You can also edit them to experiment yourself. - > [!NOTE] > These examples are available in the GitHub docs repo for both [C#](https://github.com/dotnet/docs/tree/main/samples/snippets/csharp/how-to/conversions) and [Visual Basic](https://github.com/dotnet/docs/tree/main/samples/snippets/visualbasic/how-to/conversions). diff --git a/docs/standard/commandline/snippets/define-symbols/csharp/Program.cs b/docs/standard/commandline/snippets/define-symbols/csharp/Program.cs index 23da46085b39c..ebfb05513c909 100644 --- a/docs/standard/commandline/snippets/define-symbols/csharp/Program.cs +++ b/docs/standard/commandline/snippets/define-symbols/csharp/Program.cs @@ -40,12 +40,12 @@ static void DefineOptions(string[] args) // Option delayOption = new("--delay", "-d") { - Description = "An option whose argument is parsed as an int.", + Description = "An option whose argument is parsed as an int", DefaultValueFactory = parseResult => 42, }; Option messageOption = new("--message", "-m") { - Description = "An option whose argument is parsed as a string." + Description = "An option whose argument is parsed as a string" }; RootCommand rootCommand = new(); @@ -88,7 +88,7 @@ static void ParseErrors(string[] args) // Option verbosityOption = new("--verbosity", "-v") { - Description = "Set the verbosity level.", + Description = "Set the verbosity level", }; verbosityOption.AcceptOnlyFromAmong("quiet", "minimal", "normal", "detailed", "diagnostic"); RootCommand rootCommand = new() { verbosityOption }; diff --git a/docs/standard/commandline/snippets/global-options/csharp/Program.cs b/docs/standard/commandline/snippets/global-options/csharp/Program.cs index 7be7807035900..97b13023c808a 100644 --- a/docs/standard/commandline/snippets/global-options/csharp/Program.cs +++ b/docs/standard/commandline/snippets/global-options/csharp/Program.cs @@ -66,7 +66,7 @@ static void VerbosityOptionExample(string[] args) // Add -q as a separate option for quiet verbosity. Option quietOption = new("-q") { - Description = "Set verbosity to quiet (shorthand for --verbosity quiet).", + Description = "Set verbosity to quiet (shorthand for --verbosity quiet)", Recursive = true }; diff --git a/docs/visual-basic/language-reference/runtime-library-members.md b/docs/visual-basic/language-reference/runtime-library-members.md index 3da6c6b884971..e73e6eeee3ec2 100644 --- a/docs/visual-basic/language-reference/runtime-library-members.md +++ b/docs/visual-basic/language-reference/runtime-library-members.md @@ -508,7 +508,6 @@ The `Microsoft.VisualBasic` namespace contains the classes, modules, constants, - - - -- ## Microsoft.VisualBasic.FileSystem Module diff --git a/samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/PrimeService.Tests/PrimeService.Tests.csproj b/samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/PrimeService.Tests/PrimeService.Tests.csproj index 3761a2fa0ad0e..4b507256eb0b7 100644 --- a/samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/PrimeService.Tests/PrimeService.Tests.csproj +++ b/samples/snippets/core/testing/unit-testing-using-dotnet-test/csharp/PrimeService.Tests/PrimeService.Tests.csproj @@ -7,7 +7,7 @@ - + diff --git a/samples/snippets/core/testing/unit-testing-vb-nunit/vb/PrimeService.Tests/PrimeService.Tests.vbproj b/samples/snippets/core/testing/unit-testing-vb-nunit/vb/PrimeService.Tests/PrimeService.Tests.vbproj index cec38eda7db60..c59b50fb63de4 100644 --- a/samples/snippets/core/testing/unit-testing-vb-nunit/vb/PrimeService.Tests/PrimeService.Tests.vbproj +++ b/samples/snippets/core/testing/unit-testing-vb-nunit/vb/PrimeService.Tests/PrimeService.Tests.vbproj @@ -9,7 +9,7 @@ - +