diff --git a/.github/workflows/cleanrepo-orphaned-articles.yml b/.github/workflows/cleanrepo-orphaned-articles.yml index 5660cbf3b0407..88318c251aa3f 100644 --- a/.github/workflows/cleanrepo-orphaned-articles.yml +++ b/.github/workflows/cleanrepo-orphaned-articles.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: dotnet/actions-create-pull-request@v4 + uses: peter-evans/create-pull-request@v7 with: branch: cleanrepo-orphaned-articles title: "Monthly chores: Delete orphaned articles" diff --git a/.github/workflows/cleanrepo-orphaned-images.yml b/.github/workflows/cleanrepo-orphaned-images.yml index fbc34d2bd75f5..46a9fc4bfd5e6 100644 --- a/.github/workflows/cleanrepo-orphaned-images.yml +++ b/.github/workflows/cleanrepo-orphaned-images.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: dotnet/actions-create-pull-request@v4 + uses: peter-evans/create-pull-request@v7 with: branch: cleanrepo-orphaned-images title: "Monthly chores: Delete orphaned images" diff --git a/.github/workflows/cleanrepo-orphaned-includes.yml b/.github/workflows/cleanrepo-orphaned-includes.yml index dbeb16a5a0abb..7e21ec58afe4c 100644 --- a/.github/workflows/cleanrepo-orphaned-includes.yml +++ b/.github/workflows/cleanrepo-orphaned-includes.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: dotnet/actions-create-pull-request@v4 + uses: peter-evans/create-pull-request@v7 with: branch: cleanrepo-orphaned-includes title: "Monthly chores: Delete orphaned include files" diff --git a/.github/workflows/cleanrepo-orphaned-snippets.yml b/.github/workflows/cleanrepo-orphaned-snippets.yml index 86ecb90f64c69..7d31980ec1a4e 100644 --- a/.github/workflows/cleanrepo-orphaned-snippets.yml +++ b/.github/workflows/cleanrepo-orphaned-snippets.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: dotnet/actions-create-pull-request@v4 + uses: peter-evans/create-pull-request@v7 with: branch: cleanrepo-orphaned-snippets title: "Monthly chores: Delete orphaned snippets" diff --git a/.github/workflows/cleanrepo-redirect-hops.yml b/.github/workflows/cleanrepo-redirect-hops.yml index 45e89676f97a0..aa71d5ffa2612 100644 --- a/.github/workflows/cleanrepo-redirect-hops.yml +++ b/.github/workflows/cleanrepo-redirect-hops.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: dotnet/actions-create-pull-request@v4 + uses: peter-evans/create-pull-request@v7 with: branch: cleanrepo-remove-hops title: "Monthly chores: Remove redirect hops" diff --git a/.github/workflows/cleanrepo-relative-links.yml b/.github/workflows/cleanrepo-relative-links.yml index be3e48d1db003..54db1f46fe089 100644 --- a/.github/workflows/cleanrepo-relative-links.yml +++ b/.github/workflows/cleanrepo-relative-links.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: dotnet/actions-create-pull-request@v4 + uses: peter-evans/create-pull-request@v7 with: branch: cleanrepo-relative-links title: "Monthly chores: Use relative links" diff --git a/.github/workflows/cleanrepo-replace-redirects.yml b/.github/workflows/cleanrepo-replace-redirects.yml index 39e85d4621659..9b4341241694d 100644 --- a/.github/workflows/cleanrepo-replace-redirects.yml +++ b/.github/workflows/cleanrepo-replace-redirects.yml @@ -35,7 +35,7 @@ jobs: # Create the PR for the work done by the "clean repo" tool - name: create-pull-request - uses: dotnet/actions-create-pull-request@v4 + uses: peter-evans/create-pull-request@v7 with: branch: cleanrepo-replace-redirects title: "Monthly chores: Replace redirect targets" diff --git a/.github/workflows/dependabot-bot.yml b/.github/workflows/dependabot-bot.yml index 160569e0f8620..0379eab8ace36 100644 --- a/.github/workflows/dependabot-bot.yml +++ b/.github/workflows/dependabot-bot.yml @@ -54,7 +54,7 @@ jobs: dependabot-yml-path: ".github/dependabot.yml" - name: Create pull request if: github.event_name == 'workflow_dispatch' || github.repository_owner == 'dotnet' - uses: dotnet/actions-create-pull-request@v4 + uses: peter-evans/create-pull-request@v7 with: branch: create-dependabotconfig-pull-request/patch title: "Update dependabot.yml - automatically." diff --git a/docs/azure/includes/dotnet-all.md b/docs/azure/includes/dotnet-all.md index 306ebf3a083c7..6f5ff3c96eaf1 100644 --- a/docs/azure/includes/dotnet-all.md +++ b/docs/azure/includes/dotnet-all.md @@ -25,7 +25,7 @@ | Confidential Ledger | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.3.0)
NuGet [1.4.1-beta.2](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.4.1-beta.2) | [docs](/dotnet/api/overview/azure/Security.ConfidentialLedger-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.3.0/sdk/confidentialledger/Azure.Security.ConfidentialLedger/)
GitHub [1.4.1-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.4.1-beta.2/sdk/confidentialledger/Azure.Security.ConfidentialLedger/) | | Container Registry | NuGet [1.2.0](https://www.nuget.org/packages/Azure.Containers.ContainerRegistry/1.2.0) | [docs](/dotnet/api/overview/azure/Containers.ContainerRegistry-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Containers.ContainerRegistry_1.2.0/sdk/containerregistry/Azure.Containers.ContainerRegistry/) | | Content Safety | NuGet [1.0.0](https://www.nuget.org/packages/Azure.AI.ContentSafety/1.0.0) | [docs](/dotnet/api/overview/azure/AI.ContentSafety-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.ContentSafety_1.0.0/sdk/contentsafety/Azure.AI.ContentSafety/) | -| Conversational Language Understanding | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Language.Conversations/1.1.0)
NuGet [2.0.0-beta.4](https://www.nuget.org/packages/Azure.AI.Language.Conversations/2.0.0-beta.4) | [docs](/dotnet/api/overview/azure/AI.Language.Conversations-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_1.1.0/sdk/cognitivelanguage/Azure.AI.Language.Conversations/)
GitHub [2.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_2.0.0-beta.4/sdk/cognitivelanguage/Azure.AI.Language.Conversations/) | +| Conversational Language Understanding | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Language.Conversations/1.1.0)
NuGet [2.0.0-beta.5](https://www.nuget.org/packages/Azure.AI.Language.Conversations/2.0.0-beta.5) | [docs](/dotnet/api/overview/azure/AI.Language.Conversations-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_1.1.0/sdk/cognitivelanguage/Azure.AI.Language.Conversations/)
GitHub [2.0.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_2.0.0-beta.5/sdk/cognitivelanguage/Azure.AI.Language.Conversations/) | | Conversations Authoring | NuGet [1.0.0-beta.2](https://www.nuget.org/packages/Azure.AI.Language.Conversations.Authoring/1.0.0-beta.2) | [docs](/dotnet/api/overview/azure/AI.Language.Conversations.Authoring-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations.Authoring_1.0.0-beta.2/sdk/cognitivelanguage/Azure.AI.Language.Conversations.Authoring/) | | Core - Client - AMQP | NuGet [1.3.1](https://www.nuget.org/packages/Azure.Core.Amqp/1.3.1) | [docs](/dotnet/api/overview/azure/Core.Amqp-readme) | GitHub [1.3.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Core.Amqp_1.3.1/sdk/core/Azure.Core.Amqp/) | | Core - Client - Core | NuGet [1.50.0](https://www.nuget.org/packages/Azure.Core/1.50.0) | [docs](/dotnet/api/overview/azure/Core-readme) | GitHub [1.50.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Core_1.50.0/sdk/core/Azure.Core/) | @@ -60,7 +60,7 @@ | Key Vault - Certificates | NuGet [4.8.0](https://www.nuget.org/packages/Azure.Security.KeyVault.Certificates/4.8.0) | [docs](/dotnet/api/overview/azure/Security.KeyVault.Certificates-readme) | GitHub [4.8.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.KeyVault.Certificates_4.8.0/sdk/keyvault/Azure.Security.KeyVault.Certificates/) | | Key Vault - Keys | NuGet [4.8.0](https://www.nuget.org/packages/Azure.Security.KeyVault.Keys/4.8.0) | [docs](/dotnet/api/overview/azure/Security.KeyVault.Keys-readme) | GitHub [4.8.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.KeyVault.Keys_4.8.0/sdk/keyvault/Azure.Security.KeyVault.Keys/) | | Key Vault - Secrets | NuGet [4.8.0](https://www.nuget.org/packages/Azure.Security.KeyVault.Secrets/4.8.0) | [docs](/dotnet/api/overview/azure/Security.KeyVault.Secrets-readme) | GitHub [4.8.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.KeyVault.Secrets_4.8.0/sdk/keyvault/Azure.Security.KeyVault.Secrets/) | -| Language Text | NuGet [1.0.0-beta.3](https://www.nuget.org/packages/Azure.AI.Language.Text/1.0.0-beta.3) | [docs](/dotnet/api/overview/azure/AI.Language.Text-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Text_1.0.0-beta.3/sdk/cognitivelanguage/Azure.AI.Language.Text/) | +| Language Text | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.AI.Language.Text/1.0.0-beta.4) | [docs](/dotnet/api/overview/azure/AI.Language.Text-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Text_1.0.0-beta.4/sdk/cognitivelanguage/Azure.AI.Language.Text/) | | Load Testing | NuGet [1.0.2](https://www.nuget.org/packages/Azure.Developer.LoadTesting/1.0.2)
NuGet [1.2.0-beta.1](https://www.nuget.org/packages/Azure.Developer.LoadTesting/1.2.0-beta.1) | [docs](/dotnet/api/overview/azure/Developer.LoadTesting-readme) | GitHub [1.0.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Developer.LoadTesting_1.0.2/sdk/loadtestservice/Azure.Developer.LoadTesting/)
GitHub [1.2.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Developer.LoadTesting_1.2.0-beta.1/sdk/loadtestservice/Azure.Developer.LoadTesting/) | | Maps Common | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.Maps.Common/1.0.0-beta.4) | [docs](/dotnet/api/overview/azure/Maps.Common-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Maps.Common_1.0.0-beta.4/sdk/maps/Azure.Maps.Common/) | | Maps Geolocation | NuGet [1.0.0-beta.3](https://www.nuget.org/packages/Azure.Maps.Geolocation/1.0.0-beta.3) | [docs](/dotnet/api/overview/azure/Maps.Geolocation-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Maps.Geolocation_1.0.0-beta.3/sdk/maps/Azure.Maps.Geolocation/) | @@ -77,7 +77,7 @@ | Monitor Ingestion | NuGet [1.2.0](https://www.nuget.org/packages/Azure.Monitor.Ingestion/1.2.0) | [docs](/dotnet/api/overview/azure/Monitor.Ingestion-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Monitor.Ingestion_1.2.0/sdk/monitor/Azure.Monitor.Ingestion/) | | Online Experimentation | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Analytics.OnlineExperimentation/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Analytics.OnlineExperimentation-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Analytics.OnlineExperimentation_1.0.0-beta.1/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/) | | OpenAI Assistants | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.AI.OpenAI.Assistants/1.0.0-beta.4) | [docs](/dotnet/api/overview/azure/AI.OpenAI.Assistants-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.OpenAI.Assistants_1.0.0-beta.4/sdk/openai/Azure.AI.OpenAI.Assistants/) | -| OpenAI Inference | NuGet [2.1.0](https://www.nuget.org/packages/Azure.AI.OpenAI/2.1.0)
NuGet [2.5.0-beta.1](https://www.nuget.org/packages/Azure.AI.OpenAI/2.5.0-beta.1) | [docs](/dotnet/api/overview/azure/AI.OpenAI-readme) | GitHub [2.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.OpenAI_2.1.0/sdk/openai/Azure.AI.OpenAI/)
GitHub [2.5.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.OpenAI_2.5.0-beta.1/sdk/openai/Azure.AI.OpenAI/) | +| OpenAI Inference | NuGet [2.1.0](https://www.nuget.org/packages/Azure.AI.OpenAI/2.1.0)
NuGet [2.7.0-beta.2](https://www.nuget.org/packages/Azure.AI.OpenAI/2.7.0-beta.2) | [docs](/dotnet/api/overview/azure/AI.OpenAI-readme) | GitHub [2.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.OpenAI_2.1.0/sdk/openai/Azure.AI.OpenAI/)
GitHub [2.7.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.OpenAI_2.7.0-beta.2/sdk/openai/Azure.AI.OpenAI/) | | OpenTelemetry AspNetCore | NuGet [1.4.0](https://www.nuget.org/packages/Azure.Monitor.OpenTelemetry.AspNetCore/1.4.0) | [docs](/dotnet/api/overview/azure/Monitor.OpenTelemetry.AspNetCore-readme) | GitHub [1.4.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Monitor.OpenTelemetry.AspNetCore_1.4.0/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/) | | OpenTelemetry Exporter | NuGet [1.5.0](https://www.nuget.org/packages/Azure.Monitor.OpenTelemetry.Exporter/1.5.0) | [docs](/dotnet/api/overview/azure/Monitor.OpenTelemetry.Exporter-readme) | GitHub [1.5.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Monitor.OpenTelemetry.Exporter_1.5.0/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/) | | Personalizer | NuGet [2.0.0-beta.2](https://www.nuget.org/packages/Azure.AI.Personalizer/2.0.0-beta.2) | [docs](/dotnet/api/overview/azure/AI.Personalizer-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [2.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Personalizer_2.0.0-beta.2/sdk/personalizer/Azure.AI.Personalizer/) | @@ -250,7 +250,7 @@ | Resource Management - DNS | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.Dns/1.1.1)
NuGet [1.2.0-beta.2](https://www.nuget.org/packages/Azure.ResourceManager.Dns/1.2.0-beta.2) | [docs](/dotnet/api/overview/azure/ResourceManager.Dns-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Dns_1.1.1/sdk/dns/Azure.ResourceManager.Dns/)
GitHub [1.2.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Dns_1.2.0-beta.2/sdk/dns/Azure.ResourceManager.Dns/) | | Resource Management - DNS Resolver | NuGet [1.2.0](https://www.nuget.org/packages/Azure.ResourceManager.DnsResolver/1.2.0)
NuGet [1.3.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.DnsResolver/1.3.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.DnsResolver-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.DnsResolver_1.2.0/sdk/dnsresolver/Azure.ResourceManager.DnsResolver/)
GitHub [1.3.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.DnsResolver_1.3.0-beta.1/sdk/dnsresolver/Azure.ResourceManager.DnsResolver/) | | Resource Management - Durabletask | NuGet [1.0.0](https://www.nuget.org/packages/Azure.ResourceManager.DurableTask/1.0.0) | [docs](/dotnet/api/overview/azure/ResourceManager.DurableTask-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.DurableTask_1.0.0/sdk/durabletask/Azure.ResourceManager.DurableTask/) | -| Resource Management - Dynatrace | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.Dynatrace/1.1.1) | [docs](/dotnet/api/overview/azure/ResourceManager.Dynatrace-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Dynatrace_1.1.1/sdk/dynatrace/Azure.ResourceManager.Dynatrace/) | +| Resource Management - Dynatrace | NuGet [1.2.0](https://www.nuget.org/packages/Azure.ResourceManager.Dynatrace/1.2.0) | [docs](/dotnet/api/overview/azure/ResourceManager.Dynatrace-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Dynatrace_1.2.0/sdk/dynatrace/Azure.ResourceManager.Dynatrace/) | | Resource Management - Edge Order | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.EdgeOrder/1.1.1) | [docs](/dotnet/api/overview/azure/ResourceManager.EdgeOrder-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.EdgeOrder_1.1.1/sdk/edgeorder/Azure.ResourceManager.EdgeOrder/) | | Resource Management - Edge Zones | NuGet [1.0.0-beta.2](https://www.nuget.org/packages/Azure.ResourceManager.EdgeZones/1.0.0-beta.2) | [docs](/dotnet/api/overview/azure/ResourceManager.EdgeZones-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.EdgeZones_1.0.0-beta.2/sdk/edgezones/Azure.ResourceManager.EdgeZones/) | | Resource Management - Elastic | NuGet [1.1.0](https://www.nuget.org/packages/Azure.ResourceManager.Elastic/1.1.0) | [docs](/dotnet/api/overview/azure/ResourceManager.Elastic-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Elastic_1.1.0/sdk/elastic/Azure.ResourceManager.Elastic/) | @@ -311,7 +311,7 @@ | Resource Management - Monitor | NuGet [1.3.1](https://www.nuget.org/packages/Azure.ResourceManager.Monitor/1.3.1)
NuGet [1.4.0-beta.4](https://www.nuget.org/packages/Azure.ResourceManager.Monitor/1.4.0-beta.4) | [docs](/dotnet/api/overview/azure/ResourceManager.Monitor-readme) | GitHub [1.3.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Monitor_1.3.1/sdk/monitor/Azure.ResourceManager.Monitor/)
GitHub [1.4.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Monitor_1.4.0-beta.4/sdk/monitor/Azure.ResourceManager.Monitor/) | | Resource Management - MySQL | NuGet [1.2.0](https://www.nuget.org/packages/Azure.ResourceManager.MySql/1.2.0) | [docs](/dotnet/api/overview/azure/ResourceManager.MySql-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.MySql_1.2.0/sdk/mysql/Azure.ResourceManager.MySql/) | | Resource Management - Neon Postgres | NuGet [1.0.0](https://www.nuget.org/packages/Azure.ResourceManager.NeonPostgres/1.0.0) | [docs](/dotnet/api/overview/azure/ResourceManager.NeonPostgres-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NeonPostgres_1.0.0/sdk/neonpostgres/Azure.ResourceManager.NeonPostgres/) | -| Resource Management - NetApp Files | NuGet [1.12.0](https://www.nuget.org/packages/Azure.ResourceManager.NetApp/1.12.0)
NuGet [1.13.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.NetApp/1.13.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.NetApp-readme) | GitHub [1.12.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetApp_1.12.0/sdk/netapp/Azure.ResourceManager.NetApp/)
GitHub [1.13.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetApp_1.13.0-beta.1/sdk/netapp/Azure.ResourceManager.NetApp/) | +| Resource Management - NetApp Files | NuGet [1.14.0](https://www.nuget.org/packages/Azure.ResourceManager.NetApp/1.14.0) | [docs](/dotnet/api/overview/azure/ResourceManager.NetApp-readme) | GitHub [1.14.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetApp_1.14.0/sdk/netapp/Azure.ResourceManager.NetApp/) | | Resource Management - Network | NuGet [1.13.0](https://www.nuget.org/packages/Azure.ResourceManager.Network/1.13.0) | [docs](/dotnet/api/overview/azure/ResourceManager.Network-readme) | GitHub [1.13.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Network_1.13.0/sdk/network/Azure.ResourceManager.Network/) | | Resource Management - Network Cloud | NuGet [1.2.0](https://www.nuget.org/packages/Azure.ResourceManager.NetworkCloud/1.2.0)
NuGet [1.3.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.NetworkCloud/1.3.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.NetworkCloud-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetworkCloud_1.2.0/sdk/networkcloud/Azure.ResourceManager.NetworkCloud/)
GitHub [1.3.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetworkCloud_1.3.0-beta.1/sdk/networkcloud/Azure.ResourceManager.NetworkCloud/) | | Resource Management - Network Function | NuGet [1.0.0-beta.5](https://www.nuget.org/packages/Azure.ResourceManager.NetworkFunction/1.0.0-beta.5) | [docs](/dotnet/api/overview/azure/ResourceManager.NetworkFunction-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetworkFunction_1.0.0-beta.5/sdk/networkfunction/Azure.ResourceManager.NetworkFunction/) | @@ -351,7 +351,7 @@ | Resource Management - Resource Health | NuGet [1.0.0](https://www.nuget.org/packages/Azure.ResourceManager.ResourceHealth/1.0.0)
NuGet [1.1.0-beta.5](https://www.nuget.org/packages/Azure.ResourceManager.ResourceHealth/1.1.0-beta.5) | [docs](/dotnet/api/overview/azure/ResourceManager.ResourceHealth-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ResourceHealth_1.0.0/sdk/resourcehealth/Azure.ResourceManager.ResourceHealth/)
GitHub [1.1.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ResourceHealth_1.1.0-beta.5/sdk/resourcehealth/Azure.ResourceManager.ResourceHealth/) | | Resource Management - Resource Manager | NuGet [1.13.2](https://www.nuget.org/packages/Azure.ResourceManager/1.13.2)
NuGet [1.14.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager/1.14.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager-readme) | GitHub [1.13.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager_1.13.2/sdk/resourcemanager/Azure.ResourceManager/)
GitHub [1.14.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager_1.14.0-beta.1/sdk/resourcemanager/Azure.ResourceManager/) | | Resource Management - Resource Mover | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.ResourceMover/1.1.1)
NuGet [1.1.2-beta.2](https://www.nuget.org/packages/Azure.ResourceManager.ResourceMover/1.1.2-beta.2) | [docs](/dotnet/api/overview/azure/ResourceManager.ResourceMover-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ResourceMover_1.1.1/sdk/resourcemover/Azure.ResourceManager.ResourceMover/)
GitHub [1.1.2-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ResourceMover_1.1.2-beta.2/sdk/resourcemover/Azure.ResourceManager.ResourceMover/) | -| Resource Management - Resources | NuGet [1.11.1](https://www.nuget.org/packages/Azure.ResourceManager.Resources/1.11.1) | [docs](/dotnet/api/overview/azure/ResourceManager.Resources-readme) | GitHub [1.11.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Resources_1.11.1/sdk/resources/Azure.ResourceManager.Resources/) | +| Resource Management - Resources | NuGet [1.11.2](https://www.nuget.org/packages/Azure.ResourceManager.Resources/1.11.2) | [docs](/dotnet/api/overview/azure/ResourceManager.Resources-readme) | GitHub [1.11.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Resources_1.11.2/sdk/resources/Azure.ResourceManager.Resources/) | | Resource Management - ScVmm | NuGet [1.0.0-beta.6](https://www.nuget.org/packages/Azure.ResourceManager.ScVmm/1.0.0-beta.6) | [docs](/dotnet/api/overview/azure/ResourceManager.ScVmm-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ScVmm_1.0.0-beta.6/sdk/arc-scvmm/Azure.ResourceManager.ScVmm/) | | Resource Management - Secretsstoreextension | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.SecretsStoreExtension/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.SecretsStoreExtension-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.SecretsStoreExtension_1.0.0-beta.1/sdk/secretsstoreextension/Azure.ResourceManager.SecretsStoreExtension/) | | Resource Management - Security | NuGet [1.1.0](https://www.nuget.org/packages/Azure.ResourceManager.SecurityCenter/1.1.0)
NuGet [1.2.0-beta.6](https://www.nuget.org/packages/Azure.ResourceManager.SecurityCenter/1.2.0-beta.6) | [docs](/dotnet/api/overview/azure/ResourceManager.SecurityCenter-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.SecurityCenter_1.1.0/sdk/securitycenter/Azure.ResourceManager.SecurityCenter/)
GitHub [1.2.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.SecurityCenter_1.2.0-beta.6/sdk/securitycenter/Azure.ResourceManager.SecurityCenter/) | @@ -515,7 +515,7 @@ | Mobile Server - Cross Domain | NuGet [2.0.3](https://www.nuget.org/packages/Microsoft.Azure.Mobile.Server.CrossDomain/2.0.3) | | | | Notification Hubs | NuGet [4.2.0](https://www.nuget.org/packages/Microsoft.Azure.NotificationHubs/4.2.0) | | GitHub [4.2.0](https://github.com/Azure/azure-notificationhubs-dotnet) | | Personalizer | NuGet [1.0.0](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Personalizer/1.0.0) | | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Microsoft.Azure.CognitiveServices.Personalizer_1.0.0/sdk/cognitiveservices/Personalizer) | -| Relay | NuGet [3.0.1](https://www.nuget.org/packages/Microsoft.Azure.Relay/3.0.1) | [docs](/dotnet/api/overview/azure/service-bus-relay) | GitHub [3.0.1](https://github.com/Azure/azure-relay-dotnet/tree/2.0.1) | +| Relay | NuGet [3.1.0](https://www.nuget.org/packages/Microsoft.Azure.Relay/3.1.0) | [docs](/dotnet/api/overview/azure/service-bus-relay) | GitHub [3.1.0](https://github.com/Azure/azure-relay-dotnet/tree/2.0.1) | | Schema Registry - Avro | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Microsoft.Azure.Kafka.SchemaRegistry.Avro/1.0.0-beta.1) | | | | Schema Registry - JSON | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Microsoft.Azure.Kafka.SchemaRegistry.Json/1.0.0-beta.1) | | | | Search - Common | NuGet [10.1.0](https://www.nuget.org/packages/Microsoft.Azure.Search.Common/10.1.0) | | GitHub [10.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Microsoft.Azure.Search.Common_10.1.0/sdk/search/Microsoft.Azure.Search.Common/) | @@ -546,7 +546,7 @@ | Functions extension for Cosmos DB | NuGet [4.11.0](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.CosmosDB/4.11.0)
NuGet [4.12.0-preview.1](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.CosmosDB/4.12.0-preview.1) | | GitHub [4.11.0](https://github.com/Azure/azure-webjobs-sdk-extensions/tree/cosmos-v3.0.7/src/WebJobs.Extensions.CosmosDB) | | Functions extension for DocumentDB | NuGet [1.3.0](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.DocumentDB/1.3.0) | | GitHub [1.3.0](https://github.com/Azure/azure-webjobs-sdk-extensions) | | Functions extension for Durable Task Framework | NuGet [3.8.0](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.DurableTask/3.8.0) | [docs](/dotnet/api/overview/azure/functions) | GitHub [3.8.0](https://github.com/Azure/azure-functions-durable-extension/tree/v2.2.2/src/WebJobs.Extensions.DurableTask) | -| Functions extension for Durable Task Framework - isolated worker | NuGet [1.11.0](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.DurableTask/1.11.0) | | | +| Functions extension for Durable Task Framework - isolated worker | NuGet [1.10.0](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.DurableTask/1.10.0) | | | | Functions extension for HTTP | NuGet [3.2.1](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.Http/3.2.1) | | GitHub [3.2.1](https://github.com/Azure/azure-webjobs-sdk-extensions/tree/v3.0.2/src/WebJobs.Extensions.Http) | | Functions extension for IoT Edge | NuGet [1.0.7](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.EdgeHub/1.0.7) | | GitHub [1.0.7](https://github.com/Azure/iotedge/tree/1.0.7/edge-hub) | | Functions extension for Kafka | NuGet [4.2.0](https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.Kafka/4.2.0) | | GitHub [4.2.0](https://github.com/Azure/azure-functions-kafka-extension/tree/3.0.0/src/Microsoft.Azure.WebJobs.Extensions.Kafka) | diff --git a/docs/azure/includes/dotnet-new.md b/docs/azure/includes/dotnet-new.md index 9f6f9dc91074f..a1ba3a3eb6ed6 100644 --- a/docs/azure/includes/dotnet-new.md +++ b/docs/azure/includes/dotnet-new.md @@ -27,7 +27,7 @@ | Confidential Ledger | NuGet [1.3.0](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.3.0)
NuGet [1.4.1-beta.2](https://www.nuget.org/packages/Azure.Security.ConfidentialLedger/1.4.1-beta.2) | [docs](/dotnet/api/overview/azure/Security.ConfidentialLedger-readme) | GitHub [1.3.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.3.0/sdk/confidentialledger/Azure.Security.ConfidentialLedger/)
GitHub [1.4.1-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.ConfidentialLedger_1.4.1-beta.2/sdk/confidentialledger/Azure.Security.ConfidentialLedger/) | | Container Registry | NuGet [1.2.0](https://www.nuget.org/packages/Azure.Containers.ContainerRegistry/1.2.0) | [docs](/dotnet/api/overview/azure/Containers.ContainerRegistry-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Containers.ContainerRegistry_1.2.0/sdk/containerregistry/Azure.Containers.ContainerRegistry/) | | Content Safety | NuGet [1.0.0](https://www.nuget.org/packages/Azure.AI.ContentSafety/1.0.0) | [docs](/dotnet/api/overview/azure/AI.ContentSafety-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.ContentSafety_1.0.0/sdk/contentsafety/Azure.AI.ContentSafety/) | -| Conversational Language Understanding | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Language.Conversations/1.1.0)
NuGet [2.0.0-beta.4](https://www.nuget.org/packages/Azure.AI.Language.Conversations/2.0.0-beta.4) | [docs](/dotnet/api/overview/azure/AI.Language.Conversations-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_1.1.0/sdk/cognitivelanguage/Azure.AI.Language.Conversations/)
GitHub [2.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_2.0.0-beta.4/sdk/cognitivelanguage/Azure.AI.Language.Conversations/) | +| Conversational Language Understanding | NuGet [1.1.0](https://www.nuget.org/packages/Azure.AI.Language.Conversations/1.1.0)
NuGet [2.0.0-beta.5](https://www.nuget.org/packages/Azure.AI.Language.Conversations/2.0.0-beta.5) | [docs](/dotnet/api/overview/azure/AI.Language.Conversations-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_1.1.0/sdk/cognitivelanguage/Azure.AI.Language.Conversations/)
GitHub [2.0.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations_2.0.0-beta.5/sdk/cognitivelanguage/Azure.AI.Language.Conversations/) | | Conversations Authoring | NuGet [1.0.0-beta.2](https://www.nuget.org/packages/Azure.AI.Language.Conversations.Authoring/1.0.0-beta.2) | [docs](/dotnet/api/overview/azure/AI.Language.Conversations.Authoring-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Conversations.Authoring_1.0.0-beta.2/sdk/cognitivelanguage/Azure.AI.Language.Conversations.Authoring/) | | Core - Client - AMQP | NuGet [1.3.1](https://www.nuget.org/packages/Azure.Core.Amqp/1.3.1) | [docs](/dotnet/api/overview/azure/Core.Amqp-readme) | GitHub [1.3.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Core.Amqp_1.3.1/sdk/core/Azure.Core.Amqp/) | | Core - Client - Core | NuGet [1.50.0](https://www.nuget.org/packages/Azure.Core/1.50.0) | [docs](/dotnet/api/overview/azure/Core-readme) | GitHub [1.50.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Core_1.50.0/sdk/core/Azure.Core/) | @@ -62,7 +62,7 @@ | Key Vault - Certificates | NuGet [4.8.0](https://www.nuget.org/packages/Azure.Security.KeyVault.Certificates/4.8.0) | [docs](/dotnet/api/overview/azure/Security.KeyVault.Certificates-readme) | GitHub [4.8.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.KeyVault.Certificates_4.8.0/sdk/keyvault/Azure.Security.KeyVault.Certificates/) | | Key Vault - Keys | NuGet [4.8.0](https://www.nuget.org/packages/Azure.Security.KeyVault.Keys/4.8.0) | [docs](/dotnet/api/overview/azure/Security.KeyVault.Keys-readme) | GitHub [4.8.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.KeyVault.Keys_4.8.0/sdk/keyvault/Azure.Security.KeyVault.Keys/) | | Key Vault - Secrets | NuGet [4.8.0](https://www.nuget.org/packages/Azure.Security.KeyVault.Secrets/4.8.0) | [docs](/dotnet/api/overview/azure/Security.KeyVault.Secrets-readme) | GitHub [4.8.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Security.KeyVault.Secrets_4.8.0/sdk/keyvault/Azure.Security.KeyVault.Secrets/) | -| Language Text | NuGet [1.0.0-beta.3](https://www.nuget.org/packages/Azure.AI.Language.Text/1.0.0-beta.3) | [docs](/dotnet/api/overview/azure/AI.Language.Text-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Text_1.0.0-beta.3/sdk/cognitivelanguage/Azure.AI.Language.Text/) | +| Language Text | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.AI.Language.Text/1.0.0-beta.4) | [docs](/dotnet/api/overview/azure/AI.Language.Text-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.Language.Text_1.0.0-beta.4/sdk/cognitivelanguage/Azure.AI.Language.Text/) | | Load Testing | NuGet [1.0.2](https://www.nuget.org/packages/Azure.Developer.LoadTesting/1.0.2)
NuGet [1.2.0-beta.1](https://www.nuget.org/packages/Azure.Developer.LoadTesting/1.2.0-beta.1) | [docs](/dotnet/api/overview/azure/Developer.LoadTesting-readme) | GitHub [1.0.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Developer.LoadTesting_1.0.2/sdk/loadtestservice/Azure.Developer.LoadTesting/)
GitHub [1.2.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Developer.LoadTesting_1.2.0-beta.1/sdk/loadtestservice/Azure.Developer.LoadTesting/) | | Maps Common | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.Maps.Common/1.0.0-beta.4) | [docs](/dotnet/api/overview/azure/Maps.Common-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Maps.Common_1.0.0-beta.4/sdk/maps/Azure.Maps.Common/) | | Maps Geolocation | NuGet [1.0.0-beta.3](https://www.nuget.org/packages/Azure.Maps.Geolocation/1.0.0-beta.3) | [docs](/dotnet/api/overview/azure/Maps.Geolocation-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Maps.Geolocation_1.0.0-beta.3/sdk/maps/Azure.Maps.Geolocation/) | @@ -82,7 +82,7 @@ | NUnit ? Microsoft Playwright Testing | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.Developer.MicrosoftPlaywrightTesting.NUnit/1.0.0-beta.4) | | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Developer.MicrosoftPlaywrightTesting.NUnit_1.0.0-beta.4/sdk/playwrighttesting/Azure.Developer.MicrosoftPlaywrightTesting.NUnit/) | | Online Experimentation | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.Analytics.OnlineExperimentation/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/Analytics.OnlineExperimentation-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Analytics.OnlineExperimentation_1.0.0-beta.1/sdk/onlineexperimentation/Azure.Analytics.OnlineExperimentation/) | | OpenAI Assistants | NuGet [1.0.0-beta.4](https://www.nuget.org/packages/Azure.AI.OpenAI.Assistants/1.0.0-beta.4) | [docs](/dotnet/api/overview/azure/AI.OpenAI.Assistants-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.OpenAI.Assistants_1.0.0-beta.4/sdk/openai/Azure.AI.OpenAI.Assistants/) | -| OpenAI Inference | NuGet [2.1.0](https://www.nuget.org/packages/Azure.AI.OpenAI/2.1.0)
NuGet [2.5.0-beta.1](https://www.nuget.org/packages/Azure.AI.OpenAI/2.5.0-beta.1) | [docs](/dotnet/api/overview/azure/AI.OpenAI-readme) | GitHub [2.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.OpenAI_2.1.0/sdk/openai/Azure.AI.OpenAI/)
GitHub [2.5.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.OpenAI_2.5.0-beta.1/sdk/openai/Azure.AI.OpenAI/) | +| OpenAI Inference | NuGet [2.1.0](https://www.nuget.org/packages/Azure.AI.OpenAI/2.1.0)
NuGet [2.7.0-beta.2](https://www.nuget.org/packages/Azure.AI.OpenAI/2.7.0-beta.2) | [docs](/dotnet/api/overview/azure/AI.OpenAI-readme) | GitHub [2.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.OpenAI_2.1.0/sdk/openai/Azure.AI.OpenAI/)
GitHub [2.7.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.AI.OpenAI_2.7.0-beta.2/sdk/openai/Azure.AI.OpenAI/) | | OpenTelemetry AspNetCore | NuGet [1.4.0](https://www.nuget.org/packages/Azure.Monitor.OpenTelemetry.AspNetCore/1.4.0) | [docs](/dotnet/api/overview/azure/Monitor.OpenTelemetry.AspNetCore-readme) | GitHub [1.4.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Monitor.OpenTelemetry.AspNetCore_1.4.0/sdk/monitor/Azure.Monitor.OpenTelemetry.AspNetCore/) | | OpenTelemetry Exporter | NuGet [1.5.0](https://www.nuget.org/packages/Azure.Monitor.OpenTelemetry.Exporter/1.5.0) | [docs](/dotnet/api/overview/azure/Monitor.OpenTelemetry.Exporter-readme) | GitHub [1.5.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Monitor.OpenTelemetry.Exporter_1.5.0/sdk/monitor/Azure.Monitor.OpenTelemetry.Exporter/) | | OpenTelemetry LiveMetrics | NuGet [1.0.0-beta.3](https://www.nuget.org/packages/Azure.Monitor.OpenTelemetry.LiveMetrics/1.0.0-beta.3) | [docs](/dotnet/api/overview/azure/Monitor.OpenTelemetry.LiveMetrics-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.3](https://github.com/Azure/azure-sdk-for-net/tree/Azure.Monitor.OpenTelemetry.LiveMetrics_1.0.0-beta.3/sdk/monitor/Azure.Monitor.OpenTelemetry.LiveMetrics/) | @@ -262,7 +262,7 @@ | Resource Management - DNS | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.Dns/1.1.1)
NuGet [1.2.0-beta.2](https://www.nuget.org/packages/Azure.ResourceManager.Dns/1.2.0-beta.2) | [docs](/dotnet/api/overview/azure/ResourceManager.Dns-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Dns_1.1.1/sdk/dns/Azure.ResourceManager.Dns/)
GitHub [1.2.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Dns_1.2.0-beta.2/sdk/dns/Azure.ResourceManager.Dns/) | | Resource Management - DNS Resolver | NuGet [1.2.0](https://www.nuget.org/packages/Azure.ResourceManager.DnsResolver/1.2.0)
NuGet [1.3.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.DnsResolver/1.3.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.DnsResolver-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.DnsResolver_1.2.0/sdk/dnsresolver/Azure.ResourceManager.DnsResolver/)
GitHub [1.3.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.DnsResolver_1.3.0-beta.1/sdk/dnsresolver/Azure.ResourceManager.DnsResolver/) | | Resource Management - Durabletask | NuGet [1.0.0](https://www.nuget.org/packages/Azure.ResourceManager.DurableTask/1.0.0) | [docs](/dotnet/api/overview/azure/ResourceManager.DurableTask-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.DurableTask_1.0.0/sdk/durabletask/Azure.ResourceManager.DurableTask/) | -| Resource Management - Dynatrace | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.Dynatrace/1.1.1) | [docs](/dotnet/api/overview/azure/ResourceManager.Dynatrace-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Dynatrace_1.1.1/sdk/dynatrace/Azure.ResourceManager.Dynatrace/) | +| Resource Management - Dynatrace | NuGet [1.2.0](https://www.nuget.org/packages/Azure.ResourceManager.Dynatrace/1.2.0) | [docs](/dotnet/api/overview/azure/ResourceManager.Dynatrace-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Dynatrace_1.2.0/sdk/dynatrace/Azure.ResourceManager.Dynatrace/) | | Resource Management - Edge Order | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.EdgeOrder/1.1.1) | [docs](/dotnet/api/overview/azure/ResourceManager.EdgeOrder-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.EdgeOrder_1.1.1/sdk/edgeorder/Azure.ResourceManager.EdgeOrder/) | | Resource Management - Edge Zones | NuGet [1.0.0-beta.2](https://www.nuget.org/packages/Azure.ResourceManager.EdgeZones/1.0.0-beta.2) | [docs](/dotnet/api/overview/azure/ResourceManager.EdgeZones-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.EdgeZones_1.0.0-beta.2/sdk/edgezones/Azure.ResourceManager.EdgeZones/) | | Resource Management - Elastic | NuGet [1.1.0](https://www.nuget.org/packages/Azure.ResourceManager.Elastic/1.1.0) | [docs](/dotnet/api/overview/azure/ResourceManager.Elastic-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Elastic_1.1.0/sdk/elastic/Azure.ResourceManager.Elastic/) | @@ -326,7 +326,7 @@ | Resource Management - Monitor | NuGet [1.3.1](https://www.nuget.org/packages/Azure.ResourceManager.Monitor/1.3.1)
NuGet [1.4.0-beta.4](https://www.nuget.org/packages/Azure.ResourceManager.Monitor/1.4.0-beta.4) | [docs](/dotnet/api/overview/azure/ResourceManager.Monitor-readme) | GitHub [1.3.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Monitor_1.3.1/sdk/monitor/Azure.ResourceManager.Monitor/)
GitHub [1.4.0-beta.4](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Monitor_1.4.0-beta.4/sdk/monitor/Azure.ResourceManager.Monitor/) | | Resource Management - MySQL | NuGet [1.2.0](https://www.nuget.org/packages/Azure.ResourceManager.MySql/1.2.0) | [docs](/dotnet/api/overview/azure/ResourceManager.MySql-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.MySql_1.2.0/sdk/mysql/Azure.ResourceManager.MySql/) | | Resource Management - Neon Postgres | NuGet [1.0.0](https://www.nuget.org/packages/Azure.ResourceManager.NeonPostgres/1.0.0) | [docs](/dotnet/api/overview/azure/ResourceManager.NeonPostgres-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NeonPostgres_1.0.0/sdk/neonpostgres/Azure.ResourceManager.NeonPostgres/) | -| Resource Management - NetApp Files | NuGet [1.12.0](https://www.nuget.org/packages/Azure.ResourceManager.NetApp/1.12.0)
NuGet [1.13.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.NetApp/1.13.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.NetApp-readme) | GitHub [1.12.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetApp_1.12.0/sdk/netapp/Azure.ResourceManager.NetApp/)
GitHub [1.13.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetApp_1.13.0-beta.1/sdk/netapp/Azure.ResourceManager.NetApp/) | +| Resource Management - NetApp Files | NuGet [1.14.0](https://www.nuget.org/packages/Azure.ResourceManager.NetApp/1.14.0) | [docs](/dotnet/api/overview/azure/ResourceManager.NetApp-readme) | GitHub [1.14.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetApp_1.14.0/sdk/netapp/Azure.ResourceManager.NetApp/) | | Resource Management - Network | NuGet [1.13.0](https://www.nuget.org/packages/Azure.ResourceManager.Network/1.13.0) | [docs](/dotnet/api/overview/azure/ResourceManager.Network-readme) | GitHub [1.13.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Network_1.13.0/sdk/network/Azure.ResourceManager.Network/) | | Resource Management - Network Analytics | NuGet [1.0.1](https://www.nuget.org/packages/Azure.ResourceManager.NetworkAnalytics/1.0.1) | [docs](/dotnet/api/overview/azure/ResourceManager.NetworkAnalytics-readme) | GitHub [1.0.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetworkAnalytics_1.0.1/sdk/networkanalytics/Azure.ResourceManager.NetworkAnalytics/) | | Resource Management - Network Cloud | NuGet [1.2.0](https://www.nuget.org/packages/Azure.ResourceManager.NetworkCloud/1.2.0)
NuGet [1.3.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.NetworkCloud/1.3.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.NetworkCloud-readme) | GitHub [1.2.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetworkCloud_1.2.0/sdk/networkcloud/Azure.ResourceManager.NetworkCloud/)
GitHub [1.3.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.NetworkCloud_1.3.0-beta.1/sdk/networkcloud/Azure.ResourceManager.NetworkCloud/) | @@ -368,7 +368,7 @@ | Resource Management - Resource Health | NuGet [1.0.0](https://www.nuget.org/packages/Azure.ResourceManager.ResourceHealth/1.0.0)
NuGet [1.1.0-beta.5](https://www.nuget.org/packages/Azure.ResourceManager.ResourceHealth/1.1.0-beta.5) | [docs](/dotnet/api/overview/azure/ResourceManager.ResourceHealth-readme) | GitHub [1.0.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ResourceHealth_1.0.0/sdk/resourcehealth/Azure.ResourceManager.ResourceHealth/)
GitHub [1.1.0-beta.5](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ResourceHealth_1.1.0-beta.5/sdk/resourcehealth/Azure.ResourceManager.ResourceHealth/) | | Resource Management - Resource Manager | NuGet [1.13.2](https://www.nuget.org/packages/Azure.ResourceManager/1.13.2)
NuGet [1.14.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager/1.14.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager-readme) | GitHub [1.13.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager_1.13.2/sdk/resourcemanager/Azure.ResourceManager/)
GitHub [1.14.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager_1.14.0-beta.1/sdk/resourcemanager/Azure.ResourceManager/) | | Resource Management - Resource Mover | NuGet [1.1.1](https://www.nuget.org/packages/Azure.ResourceManager.ResourceMover/1.1.1)
NuGet [1.1.2-beta.2](https://www.nuget.org/packages/Azure.ResourceManager.ResourceMover/1.1.2-beta.2) | [docs](/dotnet/api/overview/azure/ResourceManager.ResourceMover-readme) | GitHub [1.1.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ResourceMover_1.1.1/sdk/resourcemover/Azure.ResourceManager.ResourceMover/)
GitHub [1.1.2-beta.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ResourceMover_1.1.2-beta.2/sdk/resourcemover/Azure.ResourceManager.ResourceMover/) | -| Resource Management - Resources | NuGet [1.11.1](https://www.nuget.org/packages/Azure.ResourceManager.Resources/1.11.1) | [docs](/dotnet/api/overview/azure/ResourceManager.Resources-readme) | GitHub [1.11.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Resources_1.11.1/sdk/resources/Azure.ResourceManager.Resources/) | +| Resource Management - Resources | NuGet [1.11.2](https://www.nuget.org/packages/Azure.ResourceManager.Resources/1.11.2) | [docs](/dotnet/api/overview/azure/ResourceManager.Resources-readme) | GitHub [1.11.2](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.Resources_1.11.2/sdk/resources/Azure.ResourceManager.Resources/) | | Resource Management - ScVmm | NuGet [1.0.0-beta.6](https://www.nuget.org/packages/Azure.ResourceManager.ScVmm/1.0.0-beta.6) | [docs](/dotnet/api/overview/azure/ResourceManager.ScVmm-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.ScVmm_1.0.0-beta.6/sdk/arc-scvmm/Azure.ResourceManager.ScVmm/) | | Resource Management - Secretsstoreextension | NuGet [1.0.0-beta.1](https://www.nuget.org/packages/Azure.ResourceManager.SecretsStoreExtension/1.0.0-beta.1) | [docs](/dotnet/api/overview/azure/ResourceManager.SecretsStoreExtension-readme?view=azure-dotnet-preview&preserve-view=true) | GitHub [1.0.0-beta.1](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.SecretsStoreExtension_1.0.0-beta.1/sdk/secretsstoreextension/Azure.ResourceManager.SecretsStoreExtension/) | | Resource Management - Security | NuGet [1.1.0](https://www.nuget.org/packages/Azure.ResourceManager.SecurityCenter/1.1.0)
NuGet [1.2.0-beta.6](https://www.nuget.org/packages/Azure.ResourceManager.SecurityCenter/1.2.0-beta.6) | [docs](/dotnet/api/overview/azure/ResourceManager.SecurityCenter-readme) | GitHub [1.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.SecurityCenter_1.1.0/sdk/securitycenter/Azure.ResourceManager.SecurityCenter/)
GitHub [1.2.0-beta.6](https://github.com/Azure/azure-sdk-for-net/tree/Azure.ResourceManager.SecurityCenter_1.2.0-beta.6/sdk/securitycenter/Azure.ResourceManager.SecurityCenter/) | diff --git a/docs/core/compatibility/serialization/7.0/binaryformatter-apis-produce-errors.md b/docs/core/compatibility/serialization/7.0/binaryformatter-apis-produce-errors.md index c5a6d84451bae..7e6f23ef3d374 100644 --- a/docs/core/compatibility/serialization/7.0/binaryformatter-apis-produce-errors.md +++ b/docs/core/compatibility/serialization/7.0/binaryformatter-apis-produce-errors.md @@ -49,7 +49,7 @@ The best course of action is to migrate away from `BinaryFormatter` due to its s If you must suppress the errors, you can do so by following the guidelines in the [original obsoletion article](../5.0/binaryformatter-serialization-obsolete.md#recommended-action). You can also disable the error project-wide by setting a project property that converts the error back to a warning (to match the .NET 5/6 behavior). > [!WARNING] -> Setting this property might change host behavior. See [\ property](#enableunsafebinaryformatterserialization-property). +> Setting this property might change host behavior. See [`` property](#enableunsafebinaryformatterserialization-property). ```csharp @@ -61,7 +61,7 @@ If you must suppress the errors, you can do so by following the guidelines in th > [!NOTE] > If your project compiles with "warnings as errors" enabled, compilation will still fail. (This matches the behavior that shipped in the .NET 5 and .NET 6 SDKs.) If that's the case, you'll still need to suppress the `SYSLIB0011` warning in source or in your project file's `` element. -### \ property +### `` property The `** tag. +An alternative to specifying target manifests with the [`dotnet publish`](../tools/dotnet-publish.md) command is to specify them in the project file as a semicolon-separated list of paths under a `` tag. ```xml @@ -126,7 +126,7 @@ For .NET Core 2.0, the runtime package store feature is used implicitly by an AS The runtime package store is installed on the host when the .NET SDK is installed. Other installers may provide the runtime package store, including Zip/tarball installations of the .NET SDK, `apt-get`, Red Hat Yum, the .NET Core Windows Server Hosting bundle, and manual runtime package store installations. -When deploying a [framework-dependent deployment](index.md#framework-dependent-deployment) app, make sure that the target environment has the .NET SDK installed. If the app is deployed to an environment that doesn't include ASP.NET Core, you can opt out of the implicit store by specifying **\** set to `false` in the project file as in the following example: +When deploying a [framework-dependent deployment](index.md#framework-dependent-deployment) app, make sure that the target environment has the .NET SDK installed. If the app is deployed to an environment that doesn't include ASP.NET Core, you can opt out of the implicit store by specifying `` set to `false` in the project file as in the following example: ```xml @@ -135,7 +135,7 @@ When deploying a [framework-dependent deployment](index.md#framework-dependent-d ``` > [!NOTE] -> For [self-contained deployment](index.md#self-contained-deployment) apps, it's assumed that the target system doesn't necessarily contain the required manifest packages. Therefore, **\** cannot be set to `true` for an self-contained app. +> For [self-contained deployment](index.md#self-contained-deployment) apps, it's assumed that the target system doesn't necessarily contain the required manifest packages. Therefore, `` cannot be set to `true` for an self-contained app. ## See also diff --git a/docs/core/extensions/best-practices-for-developing-world-ready-apps.md b/docs/core/extensions/best-practices-for-developing-world-ready-apps.md index 3123691ed1ff7..ef9988e8c963b 100644 --- a/docs/core/extensions/best-practices-for-developing-world-ready-apps.md +++ b/docs/core/extensions/best-practices-for-developing-world-ready-apps.md @@ -88,7 +88,7 @@ This section describes the best practices to follow when developing world-ready 1. Specify the values for the `requestEncoding`, `responseEncoding`, `fileEncoding`, `culture`, and `uiCulture` attributes in the following three places in an ASP.NET application: - - In the globalization section of a _Web.config_ file. This file is external to the ASP.NET application. For more information, see [\ element](/previous-versions/dotnet/netframework-4.0/hy4kkhe0(v=vs.100)). + - In the globalization section of a _Web.config_ file. This file is external to the ASP.NET application. For more information, see [`` element](/previous-versions/dotnet/netframework-4.0/hy4kkhe0(v=vs.100)). - In a page directive. Note that, when an application is in a page, the file has already been read. Therefore, it is too late to specify fileEncoding and requestEncoding. Only `uiCulture`, `culture`, and `responseEncoding` can be specified in a page directive. - Programmatically in application code. This setting can vary per request. As with a page directive, by the time the application's code is reached, it is too late to specify `fileEncoding` and `requestEncoding`. Only `uiCulture`, `culture`, and `responseEncoding` can be specified in the application code. diff --git a/docs/core/install/includes/linux-install-60-apt.md b/docs/core/install/includes/linux-install-60-apt.md deleted file mode 100644 index 78b4190bea65f..0000000000000 --- a/docs/core/install/includes/linux-install-60-apt.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -author: adegeo -ms.author: adegeo -ms.date: 10/26/2021 -ms.topic: include -ms.custom: linux-related-content ---- - -### Install the SDK - -The .NET SDK allows you to develop apps with .NET. If you install the .NET SDK, you don't need to install the corresponding runtime. To install the .NET SDK, run the following commands: - -```bash -sudo apt-get update && \ - sudo apt-get install -y dotnet-sdk-6.0 -``` - -To learn how to use the .NET CLI, see [.NET CLI overview](../../tools/index.md). - -### Install the Runtime - -The ASP.NET Core Runtime allows you to run apps that were made with .NET that didn't provide the runtime. The following command installs the ASP.NET Core Runtime, which is the most compatible runtime for .NET. In your terminal, run the following commands: - -```bash -sudo apt-get update && \ - sudo apt-get install -y aspnetcore-runtime-6.0 -``` - -As an alternative to the ASP.NET Core Runtime, you can install the .NET Runtime, which doesn't include ASP.NET Core support: replace `aspnetcore-runtime-6.0` in the previous command with `dotnet-runtime-6.0`: - -```bash -sudo apt-get install -y dotnet-runtime-6.0 -``` - -To learn how to use the .NET CLI, see [.NET CLI overview](../../tools/index.md). diff --git a/docs/core/install/includes/linux-ubuntu-80-ms.md b/docs/core/install/includes/linux-ubuntu-80-ms.md deleted file mode 100644 index 5705f1d711e52..0000000000000 --- a/docs/core/install/includes/linux-ubuntu-80-ms.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -author: adegeo -ms.author: adegeo -ms.date: 03/19/2024 -ms.topic: include -ms.custom: linux-related-content ---- - -.NET 8.0 isn't available in the Ubuntu package repository. [Register the Microsoft package repository](../linux-ubuntu-decision.md#register-the-microsoft-package-repository) and use that feed to install .NET through APT. If you use the Microsoft package repository to install .NET, you should deprioritize .NET packages from the Ubuntu repository. For more information, see [I need a version of .NET that isn't provided by my Linux distribution](../linux-package-mixup.md?pivots=os-linux-ubuntu#i-need-a-version-of-net-that-isnt-provided-by-my-linux-distribution). diff --git a/docs/core/install/includes/linux-ubuntu-not-supported.md b/docs/core/install/includes/linux-ubuntu-not-supported.md deleted file mode 100644 index 4ecf995fb2011..0000000000000 --- a/docs/core/install/includes/linux-ubuntu-not-supported.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -author: adegeo -ms.author: adegeo -ms.date: 11/01/2024 -ms.topic: include -ms.custom: linux-related-content ---- - -> [!WARNING] -> This version of Ubuntu is no longer supported. -> -> Running .NET on this version of Ubuntu is no longer supported. diff --git a/docs/core/install/includes/linux-ubuntu-package-feed-ms.md b/docs/core/install/includes/linux-ubuntu-package-feed-ms.md deleted file mode 100644 index 00281277c6ec2..0000000000000 --- a/docs/core/install/includes/linux-ubuntu-package-feed-ms.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -author: adegeo -ms.author: adegeo -ms.date: 03/18/2024 -ms.topic: include -ms.custom: linux-related-content ---- - -The default Ubuntu package repository doesn't contain this version of .NET. Use the [Microsoft package repository instead](../linux-ubuntu-decision.md#register-the-microsoft-package-repository). diff --git a/docs/core/testing/unit-testing-mstest-migration-from-v1-to-v3.md b/docs/core/testing/unit-testing-mstest-migration-from-v1-to-v3.md index e2a59a4980bfc..a6f7e6791cfa3 100644 --- a/docs/core/testing/unit-testing-mstest-migration-from-v1-to-v3.md +++ b/docs/core/testing/unit-testing-mstest-migration-from-v1-to-v3.md @@ -3,7 +3,7 @@ title: MSTest migration to v3 description: Learn about migrating from legacy MSTest (MSTest v1) to latest MSTest (MSTest v3). author: engyebrahim ms.author: enjieid -ms.date: 11/06/2024 +ms.date: 11/28/2025 --- # MSTest v3 migration guide @@ -21,9 +21,9 @@ If your project relies on MSTest for unit testing and includes the above referen ### Why migrate to MSTest v3? -Even if you’re satisfied with your current MSTest setup, upgrading to MSTest v3 unlocks substantial advantages that improve both the quality and future-readiness of your tests. Here’s why making the switch now can be a valuable step forward: +Even if you're satisfied with your current MSTest setup, upgrading to MSTest v3 unlocks substantial advantages that improve both the quality and future-readiness of your tests. Here's why making the switch now can be a valuable step forward: -- **Enhanced security**: MSTest v1 has known security vulnerabilities. With MSTest v3, we’ve implemented extensive security improvements to safeguard your testing environment. +- **Enhanced security**: MSTest v1 has known security vulnerabilities. With MSTest v3, we've implemented extensive security improvements to safeguard your testing environment. - **Immediate Performance Boosts**: MSTest v3 significantly reduces test execution time and optimizes resource usage. This is particularly beneficial in CI/CD pipelines, where faster tests can shorten deployment cycles and cut infrastructure costs. - **Future-Proofing Your Tests**: MSTest v3 offers robust support for modern .NET versions, including .NET 8, and future iterations, along with cross-platform compatibility. This means your tests will be more adaptable and ready for upgrades, avoiding the technical debt of outdated testing frameworks. @@ -36,7 +36,10 @@ Even if you’re satisfied with your current MSTest setup, upgrading to MSTest v - **Greater Flexibility and Extensibility**: MSTest v3 supports advanced testing scenarios, including dynamic data sources and in-assembly parallel execution. This flexibility enables more sophisticated testing approaches and speeds up test suites without complex configurations. -By upgrading, you’re setting up your tests to be faster, more reliable, and adaptable to future .NET developments, positioning your project for long-term success and easier maintenance. +By upgrading, you're setting up your tests to be faster, more reliable, and adaptable to future .NET developments, positioning your project for long-term success and easier maintenance. + +> [!TIP] +> After migrating to MSTest v3, consider taking a further step and migrate to MSTest v4. For more information, see [Migrate from MSTest v3 to v4](./unit-testing-mstest-migration-v3-v4.md). ## Migration steps @@ -54,7 +57,7 @@ In non-SDK style projects, these references are often added through Visual Studi 4. Inside the **References** folder, **find and select** the MSTest DLL references, `Microsoft.VisualStudio.QualityTools.UnitTestFramework` 5. **Right-click** the selected reference(s) and choose **Remove** from the context menu. - ![image](https://github.com/user-attachments/assets/7aff1afb-e26b-4450-bc2e-903a577e3df2) + ![Context menu of the assembly reference](https://github.com/user-attachments/assets/7aff1afb-e26b-4450-bc2e-903a577e3df2) 6. **Save the project** to apply changes. @@ -65,20 +68,20 @@ You can update your project to MSTest v3 in one of two ways: - **Update Packages**: If you have NuGet package references to the [MSTest.TestFramework](https://www.nuget.org/packages/MSTest.TestFramework) and the [MSTest.TestAdapter](https://www.nuget.org/packages/MSTest.TestAdapter/), update them using the NuGet Package Manager in Visual Studio or by running the following command in the NuGet Package Manager Console: ```shell - Update-Package MSTest.TestFramework -Version 3.6.2 - Update-Package MSTest.TestAdapter -Version 3.6.2 + Update-Package MSTest.TestFramework -Version 3.11.1 + Update-Package MSTest.TestAdapter -Version 3.11.1 ``` - **Or Install MSTest Package**: Install the latest [MSTest](https://www.nuget.org/packages/MSTest) package using the NuGet Package Manager in Visual Studio or by running the following command in the NuGet Package Manager Console: ```shell - Install-Package MSTest -Version 3.6.2 + Install-Package MSTest -Version 3.11.1 ``` - **Or update the project file directly** (for SDK-style projects): Update your `.csproj` file to specify the MSTest SDK version. ```xml - + net8.0 @@ -140,7 +143,7 @@ The DataRowAttribute constructors in MSTest v3 have been simplified to enforce t public void MyTestMethod(int number, string text) { ... } ``` -In cases where types don’t match exactly, MSTest v3 will now raise an error rather than attempting a conversion. +In cases where types don't match exactly, MSTest v3 will now raise an error rather than attempting a conversion. ### Timeout settings diff --git a/docs/core/tools/dependencies.md b/docs/core/tools/dependencies.md index ef89001b70290..aebb8f40383cd 100644 --- a/docs/core/tools/dependencies.md +++ b/docs/core/tools/dependencies.md @@ -9,7 +9,7 @@ ms.date: 01/28/2021 This article explains how to add and remove package dependencies by editing the project file or by using the CLI. -## The \ element +## The `` element The `` project file element has the following structure: diff --git a/docs/core/tools/dotnet-test.md b/docs/core/tools/dotnet-test.md index 7ca8c9ffe3e6e..afc075defa5e5 100644 --- a/docs/core/tools/dotnet-test.md +++ b/docs/core/tools/dotnet-test.md @@ -490,7 +490,7 @@ With Microsoft Testing Platform, `dotnet test` operates faster than with VSTest. - **`--max-parallel-test-modules `** - Specifies the maximum number of test modules that can run in parallel. + Specifies the maximum number of test modules that can run in parallel. The default is . - [!INCLUDE [arch](../../../includes/cli-arch.md)] diff --git a/docs/core/tutorials/library-with-visual-studio-code.md b/docs/core/tutorials/library-with-visual-studio-code.md index 8a33d0def7113..27956ba613de4 100644 --- a/docs/core/tutorials/library-with-visual-studio-code.md +++ b/docs/core/tutorials/library-with-visual-studio-code.md @@ -33,7 +33,7 @@ Start by creating a .NET class library project named "StringLibrary" and an asso 1. Name the project **StringLibrary** and select **Create Project**. -1. Press Enter at the prompt **Project will be created in \**. +1. Press Enter at the prompt **Project will be created in \**. 1. Check to make sure that the library targets .NET 9. In **Explorer**, open *StringLibrary/StringLibrary.csproj*. diff --git a/docs/core/unmanaged-api/debugging/icordebug/icordebugprocess6-enablevirtualmodulesplitting-method.md b/docs/core/unmanaged-api/debugging/icordebug/icordebugprocess6-enablevirtualmodulesplitting-method.md index cb56952e6ecee..be749ba2748d8 100644 --- a/docs/core/unmanaged-api/debugging/icordebug/icordebugprocess6-enablevirtualmodulesplitting-method.md +++ b/docs/core/unmanaged-api/debugging/icordebug/icordebugprocess6-enablevirtualmodulesplitting-method.md @@ -42,11 +42,11 @@ The modules found in a container. regular modules Modules that were not merged at build time. They are neither container modules nor sub-modules. -Both container modules and sub-modules are represented by ICorDebugModule interface objects. However, the behavior of the interface is slightly different in each case, as the \ section describes. +Both container modules and sub-modules are represented by `ICorDebugModule` interface objects. However, the behavior of the interface is slightly different in each case. ## Modules and assemblies -Multi-module assemblies are not supported for assembly merging scenarios, so there is a one-to-one relationship between a module and an assembly. Each ICorDebugModule object, regardless of whether it represents a container module or a sub-module, has a corresponding ICorDebugAssembly object. The [ICorDebugModule::GetAssembly](icordebugmodule-getassembly-method.md) method converts from the module to the assembly. To map in the other direction, the [ICorDebugAssembly::EnumerateModules](icordebugassembly-enumeratemodules-method.md) method enumerates only 1 module. Because assembly and module form a tightly coupled pair in this case, the terms assembly and module become largely interchangeable. +Multi-module assemblies are not supported for assembly merging scenarios, so there is a one-to-one relationship between a module and an assembly. Each `ICorDebugModule` object, regardless of whether it represents a container module or a sub-module, has a corresponding ICorDebugAssembly object. The [ICorDebugModule::GetAssembly](icordebugmodule-getassembly-method.md) method converts from the module to the assembly. To map in the other direction, the [ICorDebugAssembly::EnumerateModules](icordebugassembly-enumeratemodules-method.md) method enumerates only 1 module. Because assembly and module form a tightly coupled pair in this case, the terms assembly and module become largely interchangeable. ## Behavioral differences @@ -102,7 +102,7 @@ The following table shows how virtual module splitting affects the behavior of o |[ICorDebugClass::GetModule](icordebugclass-getmodule-method.md)|Returns the sub-module this class was originally defined in.|Returns the container module this class was merged into.| |ICorDebugModuleDebugEvent::GetModule|Returns the container module that was loaded. Sub-modules are not given load events regardless of this setting.|Returns the container module that was loaded.| |[ICorDebugAppDomain::EnumerateAssemblies](icordebugappdomain-enumerateassemblies-method.md)|Returns a list of sub-assemblies and regular assemblies; no container assemblies are included. **Note:** If any container assembly is missing symbols, none of its sub-assemblies will be enumerated. If any regular assembly is missing symbols, it may or may not be enumerated.|Returns a list of container assemblies and regular assemblies; no sub-assemblies are included. **Note:** If any regular assembly is missing symbols, it may or may not be enumerated.| -|[ICorDebugCode::GetCode](icordebugcode-getcode-method.md) (when referring to IL code only)|Returns IL that would be valid in a pre-merge assembly image. Specifically, any inline metadata tokens will correctly be TypeRef or MemberRef tokens when the types being referred to are not defined in the virtual module containing the IL. These TypeRef or MemberRef tokens can be looked up in the [IMetaDataImport](../../metadata/interfaces/imetadataimport-interface.md) object for the corresponding virtual ICorDebugModule object.|Returns the IL in the post-merge assembly image.| +|[ICorDebugCode::GetCode](icordebugcode-getcode-method.md) (when referring to IL code only)|Returns IL that would be valid in a pre-merge assembly image. Specifically, any inline metadata tokens will correctly be TypeRef or MemberRef tokens when the types being referred to are not defined in the virtual module containing the IL. These TypeRef or MemberRef tokens can be looked up in the [IMetaDataImport](../../metadata/interfaces/imetadataimport-interface.md) object for the corresponding virtual `ICorDebugModule` object.|Returns the IL in the post-merge assembly image.| ## Requirements diff --git a/docs/csharp/language-reference/builtin-types/record.md b/docs/csharp/language-reference/builtin-types/record.md index 35a98a1ab5c02..c5be9864c637e 100644 --- a/docs/csharp/language-reference/builtin-types/record.md +++ b/docs/csharp/language-reference/builtin-types/record.md @@ -124,7 +124,7 @@ To implement value equality, the compiler synthesizes several methods, including * An override of . This method can be declared explicitly. -* Overrides of operators `==` and `!=`. It's an error if the operators are declared explicitly. +* Overrides of [operator `==`](../operators/equality-operators.md#equality-operator-) and [operator `!=`](../operators/equality-operators.md#inequality-operator-). It's an error if the operators are declared explicitly. * If the record type is derived from a base record type, `protected override Type EqualityContract { get; };`. This property can be declared explicitly. For more information, see [Equality in inheritance hierarchies](#equality-in-inheritance-hierarchies). @@ -263,4 +263,5 @@ For more information about these features, see the following feature proposal no - [Design guidelines - Choosing between class and struct](../../../standard/design-guidelines/choosing-between-class-and-struct.md) - [Design guidelines - Struct design](../../../standard/design-guidelines/struct.md) - [The C# type system](../../fundamentals/types/index.md) +- [Operator overloading](../operators/operator-overloading.md) - [`with` expression](../operators/with-expression.md) diff --git a/docs/csharp/language-reference/compiler-messages/cs1705.md b/docs/csharp/language-reference/compiler-messages/cs1705.md index 08ecec77e32eb..087b8520b9359 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1705.md +++ b/docs/csharp/language-reference/compiler-messages/cs1705.md @@ -2,141 +2,138 @@ description: "Compiler Error CS1705" title: "Compiler Error CS1705" ms.date: 07/20/2015 -f1_keywords: +f1_keywords: - "CS1705" -helpviewer_keywords: +helpviewer_keywords: - "CS1705" ms.assetid: 3612a542-0256-4fed-b020-41691ef5a052 --- # Compiler Error CS1705 -Assembly 'AssemblyName1' uses 'TypeName' which has a higher version than referenced assembly 'AssemblyName2' - - You are accessing a type that has a higher version number than the version number in a referenced assembly. Typically, this error is caused by the accidental use of two versions of the same assembly. - - For example, suppose that you have two assemblies, Asmb1 and Asmb2. Assembly Asmb1 references version 1.0 of assembly Asmb2. Assembly Asmb1 also uses a class `MyClass` that was added to assembly Asmb2 in version 2.0. The compiler has unification rules for binding references, and a reference to `MyClass` in version 2.0 cannot be satisfied by version 1.0. - -## Examples - - The following more detailed example consists of four code modules: - -- Two DLLs that are identical except for a version attribute. - -- A third DLL that references the first two. - -- A client that references only version 1.0 of the identical DLLs, but accesses a class from version 2.0. - - The following code creates the first of the identical DLLs. For information about how to generate a key file, see [**KeyFile** (C# Compiler Options)](../compiler-options/security.md#keyfile). - -```csharp -// CS1705a.cs - +Assembly 'AssemblyName1' uses 'TypeName' which has a higher version than referenced assembly 'AssemblyName2'. + + You are accessing a type that has a higher version number than the version number in a referenced assembly. Typically, this error is caused by the accidental use of two versions of the same assembly. + + For example, suppose that you have two assemblies, Asmb1 and Asmb2. Assembly Asmb1 references version 1.0 of assembly Asmb2. Assembly Asmb1 also uses a class `MyClass` that was added to assembly Asmb2 in version 2.0. The compiler has unification rules for binding references, and a reference to `MyClass` in version 2.0 cannot be satisfied by version 1.0. + +## Examples + + The following more detailed example consists of four code modules: + +- Two DLLs that are identical except for a version attribute. +- A third DLL that references the first two. +- A client that references only version 1.0 of the identical DLLs, but accesses a class from version 2.0. + + The following code creates the first of the identical DLLs. For information about how to generate a key file, see [**KeyFile** (C# Compiler Options)](../compiler-options/security.md#keyfile). + +```csharp +// CS1705a.cs + // Compile by using the following command: -// csc /target:library /out:C:\\CS1705.dll /keyfile:mykey.snk CS1705a.cs - -// The DLL is created in the C:\ directory. - -// The AssemblyVersion attribute specifies version 1.0 for this DLL. - -[assembly:System.Reflection.AssemblyVersion("1.0")] +// csc /target:library /out:C:\\CS1705.dll /keyfile:mykey.snk CS1705a.cs + +// The DLL is created in the C:\ directory. + +// The AssemblyVersion attribute specifies version 1.0 for this DLL. + +[assembly:System.Reflection.AssemblyVersion("1.0")] public class Class1 -{ - public void Method1() {} -} -``` - - The following code defines version 2.0 of the assembly, as specified by the attribute. - -```csharp -// CS1705b.cs - +{ + public void Method1() {} +} +``` + + The following code defines version 2.0 of the assembly, as specified by the attribute. + +```csharp +// CS1705b.cs + // Compile by using the following command: -// csc /target:library /out:CS1705.dll /keyfile:mykey.snk CS1705b.cs - -// The DLL is created in the current directory. - -// The AssemblyVersion attribute specifies version 2.0 for this DLL. - -[assembly:System.Reflection.AssemblyVersion("2.0")] -public class Class1 -{ - public void Method1() { } -} -``` - - The following code references the two DLL versions that are defined in the preceding code. `AssemblyA` refers to the DLL created by CS1705a.cs (version 1.0). `AssemblyB` refers to the DLL created by CS1705b.cs (version 2.0). In `ClassC`, two methods are defined. The first, `Return1A`, returns an object of type `Class1A`, which is an alias for `Class1` from version 1.0 of the DLL. The second, `Return1B`, returns an object of type `Class1B`, which is an alias for `Class1` from version 2.0 of the DLL. The definition of `Return1A` creates a dependency on version 1.0; the definition of `Return1B` creates a dependency on version 2.0. - -```csharp -// CS1705c.cs - -// Compile by using the following command. AssemblyA refers to the DLL created by -// CS1705a.cs (version 1.0). AssemblyB refers to the DLL created by CS1705b.cs -// (version 2.0). -// csc /target:library /r:AssemblyA=C:\\CS1705.dll /r:AssemblyB=CS1705.dll CS1705c.cs - -extern alias AssemblyA; -extern alias AssemblyB; - +// csc /target:library /out:CS1705.dll /keyfile:mykey.snk CS1705b.cs + +// The DLL is created in the current directory. + +// The AssemblyVersion attribute specifies version 2.0 for this DLL. + +[assembly:System.Reflection.AssemblyVersion("2.0")] +public class Class1 +{ + public void Method1() { } +} +``` + + The following code references the two DLL versions that are defined in the preceding code. `AssemblyA` refers to the DLL created by CS1705a.cs (version 1.0). `AssemblyB` refers to the DLL created by CS1705b.cs (version 2.0). In `ClassC`, two methods are defined. The first, `Return1A`, returns an object of type `Class1A`, which is an alias for `Class1` from version 1.0 of the DLL. The second, `Return1B`, returns an object of type `Class1B`, which is an alias for `Class1` from version 2.0 of the DLL. The definition of `Return1A` creates a dependency on version 1.0; the definition of `Return1B` creates a dependency on version 2.0. + +```csharp +// CS1705c.cs + +// Compile by using the following command. AssemblyA refers to the DLL created by +// CS1705a.cs (version 1.0). AssemblyB refers to the DLL created by CS1705b.cs +// (version 2.0). +// csc /target:library /r:AssemblyA=C:\\CS1705.dll /r:AssemblyB=CS1705.dll CS1705c.cs + +extern alias AssemblyA; +extern alias AssemblyB; + // Class1A is an alias for type Class1 from VS1705a.cs, which is in version 1.0 -// of the assembly. Class1B is an alias for type Class1 from CS1705b.cs, which -// is in version 2.0 of the assembly. - -using Class1A = AssemblyA::Class1; -using Class1B = AssemblyB::Class1; - -// Method Return1A in ClassC returns an object of type Class1A, which is -// Class1 from version 1.0 of the DLL. Method Return1B returns an object -// of type Class1B, which is Class1 from version 2.0 of the DLL. - -public class ClassC -{ - // The following line creates a dependency on version 1.0 of CS1705.dll. - // This is not the source of the problem when ClassC is accessed from +// of the assembly. Class1B is an alias for type Class1 from CS1705b.cs, which +// is in version 2.0 of the assembly. + +using Class1A = AssemblyA::Class1; +using Class1B = AssemblyB::Class1; + +// Method Return1A in ClassC returns an object of type Class1A, which is +// Class1 from version 1.0 of the DLL. Method Return1B returns an object +// of type Class1B, which is Class1 from version 2.0 of the DLL. + +public class ClassC +{ + // The following line creates a dependency on version 1.0 of CS1705.dll. + // This is not the source of the problem when ClassC is accessed from // CS1705d.cs because CS1705d.cs references version 1.0 of the DLL. - // Therefore, type Class1A and the assembly have the same version. - public static Class1A Return1A() { return new Class1A(); } - - // The following line creates a dependency on version 2.0 of CS1705.dll. + // Therefore, type Class1A and the assembly have the same version. + public static Class1A Return1A() { return new Class1A(); } + + // The following line creates a dependency on version 2.0 of CS1705.dll. // This causes compiler error CS1705 when ClassC is accessed from // CS1705d.cs, because CS1705d.cs does not reference version 2.0 of the // DLL. Class1B is the alias for Class1 in version 2.0, and CS1705d.cs - // references version 1.0. - public static Class1B Return1B() { return new Class1B(); } -} -``` - - The following code generates compiler error CS1705. It references the DLL created by CS1705a.cs (version 1.0). However, in the `Main` method, the code accesses `ClassC` from CS1705c.cs. `ClassC` uses a type that is defined in CS1705b.cs (version 2.0). This causes compiler error CS1705 because the type has a version number for CS1705.dll that is higher than the referenced version of CS1705.dll. - -```csharp -// CS1705d.cs - -// Compile by using the following command: -// csc /reference:C:\\CS1705.dll /reference:CS1705c.dll CS1705d.cs - -// C:\\CS1705.dll is version 1.0 of the assembly. - + // references version 1.0. + public static Class1B Return1B() { return new Class1B(); } +} +``` + + The following code generates compiler error CS1705. It references the DLL created by CS1705a.cs (version 1.0). However, in the `Main` method, the code accesses `ClassC` from CS1705c.cs. `ClassC` uses a type that is defined in CS1705b.cs (version 2.0). This causes compiler error CS1705 because the type has a version number for CS1705.dll that is higher than the referenced version of CS1705.dll. + +```csharp +// CS1705d.cs + +// Compile by using the following command: +// csc /reference:C:\\CS1705.dll /reference:CS1705c.dll CS1705d.cs + +// C:\\CS1705.dll is version 1.0 of the assembly. + class Tester -{ - static void Main() - { - // Return1A returns a type defined in version 1.0. - ClassC.Return1A().Method1(); - // Return1B returns a type defined in version 2.0. - ClassC.Return1B().Method1(); - } -} -``` - - You can resolve the error in one of the following ways: - -- Update the code so that all files use the same version of the DLL. - -- Add a reference to version 2.0 of the DLL to CS1705d.cs by using the following command to compile: - - `csc /reference:C:\\CS1705.dll /reference:CS1705.dll /reference:CS1705c.dll CS1705d.cs` - - Although the program compiles when you use this command, it still does not run. To enable the program to run, you can provide an application configuration file that includes a [\ element](../../../framework/configure-apps/file-schema/runtime/dependentassembly-element.md) that uses [\](../../../framework/configure-apps/file-schema/runtime/assemblyidentity-element-for-runtime.md) and [\](../../../framework/configure-apps/file-schema/runtime/codebase-element.md) child elements to specify the location of version 1.0 of the DLL. For more information about configuration files, see [Configuring Apps](../../../framework/configure-apps/index.md). - +{ + static void Main() + { + // Return1A returns a type defined in version 1.0. + ClassC.Return1A().Method1(); + // Return1B returns a type defined in version 2.0. + ClassC.Return1B().Method1(); + } +} +``` + + You can resolve the error in one of the following ways: + +- Update the code so that all files use the same version of the DLL. +- Add a reference to version 2.0 of the DLL to CS1705d.cs by using the following command to compile: + + `csc /reference:C:\\CS1705.dll /reference:CS1705.dll /reference:CS1705c.dll CS1705d.cs` + + Although the program compiles when you use this command, it still does not run. To enable the program to run, you can provide an application configuration file that includes a [`` element](../../../framework/configure-apps/file-schema/runtime/dependentassembly-element.md) that uses [``](../../../framework/configure-apps/file-schema/runtime/assemblyidentity-element-for-runtime.md) and [``](../../../framework/configure-apps/file-schema/runtime/codebase-element.md) child elements to specify the location of version 1.0 of the DLL. For more information about configuration files, see [Configuring Apps](../../../framework/configure-apps/index.md). + ## See also - [extern alias](../keywords/extern-alias.md) diff --git a/docs/csharp/language-reference/compiler-options/index.md b/docs/csharp/language-reference/compiler-options/index.md index 52001f1618464..8f323555e86ae 100644 --- a/docs/csharp/language-reference/compiler-options/index.md +++ b/docs/csharp/language-reference/compiler-options/index.md @@ -2,9 +2,9 @@ description: "C# Compiler Options. Learn the options that control the behavior of the C# compiler." title: "Compiler Options" ms.date: 09/01/2021 -f1_keywords: +f1_keywords: - "cs.build.options" -helpviewer_keywords: +helpviewer_keywords: - "compiler options [C#]" - "csc.exe" - "cl.exe compiler, C# options" @@ -54,7 +54,7 @@ The word for some compiler options changed from *csc.exe* and .NET Framework pro You can invoke the C# compiler by typing the name of its executable file (*csc.exe*) at a command prompt. -For .NET Framework projects, you can also run *csc.exe* from the command line. Every compiler option is available in two forms: **-option** and **/option**. In .NET Framework web projects, you specify options for compiling code-behind in the *web.config* file. For more information, see [\ Element](../../../framework/configure-apps/file-schema/compiler/compiler-element.md). +For .NET Framework projects, you can also run *csc.exe* from the command line. Every compiler option is available in two forms: **-option** and **/option**. In .NET Framework web projects, you specify options for compiling code-behind in the *web.config* file. For more information, see [`` Element](../../../framework/configure-apps/file-schema/compiler/compiler-element.md). If you use the **Developer Command Prompt for Visual Studio** window, all the necessary environment variables are set for you. For information on how to access this tool, see [Developer Command Prompt for Visual Studio](/visualstudio/ide/reference/command-prompt-powershell). diff --git a/docs/csharp/language-reference/toc.yml b/docs/csharp/language-reference/toc.yml index 800bc43316d71..c6e7591069a41 100644 --- a/docs/csharp/language-reference/toc.yml +++ b/docs/csharp/language-reference/toc.yml @@ -1041,7 +1041,7 @@ items: - name: CS0468 href: ../misc/cs0468.md - name: CS0470 - href: ../misc/cs0470.md + href: ./compiler-messages/interface-implementation-errors.md - name: CS0471 href: ../misc/cs0471.md - name: CS0500 @@ -1087,11 +1087,11 @@ items: - name: CS0537 href: ../misc/cs0537.md - name: CS0538 - href: ../misc/cs0538.md + href: ./compiler-messages/interface-implementation-errors.md - name: CS0539 - href: ../misc/cs0539.md + href: ./compiler-messages/interface-implementation-errors.md - name: CS0541 - href: ../misc/cs0541.md + href: ./compiler-messages/interface-implementation-errors.md - name: CS0542 href: ../misc/cs0542.md - name: CS0543 @@ -1109,7 +1109,7 @@ items: - name: CS0549 href: ../misc/cs0549.md - name: CS0551 - href: ../misc/cs0551.md + href: ./compiler-messages/interface-implementation-errors.md - name: CS0569 href: ../misc/cs0569.md - name: CS0570 @@ -1205,11 +1205,11 @@ items: - name: CS0692 href: ../misc/cs0692.md - name: CS0694 - href: ../misc/cs0694.md + href: ./compiler-messages/generic-type-parameters-errors.md - name: CS0695 - href: ../misc/cs0695.md + href: ./compiler-messages/generic-type-parameters-errors.md - name: CS0698 - href: ../misc/cs0698.md + href: ./compiler-messages/generic-type-parameters-errors.md - name: CS0699 href: ../misc/cs0699.md - name: CS0701 diff --git a/docs/csharp/language-reference/xmldoc/recommended-tags.md b/docs/csharp/language-reference/xmldoc/recommended-tags.md index 4c8659e90178b..0111e873bb450 100644 --- a/docs/csharp/language-reference/xmldoc/recommended-tags.md +++ b/docs/csharp/language-reference/xmldoc/recommended-tags.md @@ -166,15 +166,15 @@ If you want angle brackets to appear in the text of a documentation comment, use ## General tags -### \ +### `` ```xml description ``` -The `` tag should be used to describe a type or a type member. Use [\](#remarks) to add supplemental information to a type description. Use the [cref attribute](#cref-attribute) to enable documentation tools such as [DocFX](https://dotnet.github.io/docfx/) and [Sandcastle](https://github.com/EWSoftware/SHFB) to create internal hyperlinks to documentation pages for code elements. The text for the `` tag is displayed in IntelliSense and in the Object Browser window. +The `` tag should be used to describe a type or a type member. Use [``](#remarks) to add supplemental information to a type description. Use the [cref attribute](#cref-attribute) to enable documentation tools such as [DocFX](https://dotnet.github.io/docfx/) and [Sandcastle](https://github.com/EWSoftware/SHFB) to create internal hyperlinks to documentation pages for code elements. The text for the `` tag is displayed in IntelliSense and in the Object Browser window. -### \ +### `` ```xml @@ -182,11 +182,11 @@ description ``` -The `` tag is used to add information about a type or a type member, supplementing the information specified with [\](#summary). This information is displayed in the Object Browser window. This tag can include more lengthy explanations. You might find that using `CDATA` sections for markdown make writing it more convenient. Tools such as [docfx](https://dotnet.github.io/docfx/) process the markdown text in `CDATA` sections. +The `` tag is used to add information about a type or a type member, supplementing the information specified with [``](#summary). This information is displayed in the Object Browser window. This tag can include more lengthy explanations. You might find that using `CDATA` sections for markdown make writing it more convenient. Tools such as [docfx](https://dotnet.github.io/docfx/) process the markdown text in `CDATA` sections. ## Document members -### \ +### `` ```xml description @@ -194,7 +194,7 @@ The `` tag is used to add information about a type or a type member, su The `` tag should be used in the comment for a method declaration to describe the return value. -### \ +### `` ```xml description @@ -204,7 +204,7 @@ The `` tag should be used in the comment for a method declaration to de The `` tag should be used in the comment for a method declaration to describe one of the parameters for the method. To document multiple parameters, use multiple `` tags. The text for the `` tag is displayed in IntelliSense, the Object Browser, and the Code Comment Web Report. -### \ +### `` ```xml @@ -214,7 +214,7 @@ The `` tag should be used in the comment for a method declaration to desc The `` tag gives you a way to indicate that a word in the code comments, for example in a `` or `` block refers to a parameter. The XML file can be processed to format this word in some distinct way, such as with a bold or italic font. -### \ +### `` ```xml description @@ -224,17 +224,17 @@ The `` tag gives you a way to indicate that a word in the code comment The `` tag lets you specify which exceptions can be thrown. This tag can be applied to definitions for methods, properties, events, and indexers. -### \ +### `` ```xml property-description ``` -The `` tag lets you describe the value that a property represents. When you add a property via code wizard in the Visual Studio .NET development environment, it adds a [\](#summary) tag for the new property. You manually add a `` tag to describe the value that the property represents. +The `` tag lets you describe the value that a property represents. When you add a property via code wizard in the Visual Studio .NET development environment, it adds a [``](#summary) tag for the new property. You manually add a `` tag to describe the value that the property represents. ## Format documentation output -### \ +### `` ```xml @@ -247,13 +247,13 @@ The `` tag lets you describe the value that a property represents. When y ``` -The `` tag is for use inside a tag, such as [\](#summary), [\](#remarks), or [\](#returns), and lets you add structure to the text. The `` tag creates a double spaced paragraph. Use the `
` tag if you want a single spaced paragraph. +The `` tag is for use inside a tag, such as [``](#summary), [``](#remarks), or [``](#returns), and lets you add structure to the text. The `` tag creates a double spaced paragraph. Use the `
` tag if you want a single spaced paragraph. Here's an example showing the difference between `` and `
`: :::code language="csharp" source="./snippets/xmldoc/HrefAndBrExamples.cs" id="FormattingExample"::: -### \ +### `` ```xml @@ -282,15 +282,15 @@ When creating a definition list: A list or table can have as many `` blocks as needed. -### \ +### `` ```xml text ``` -The `` tag gives you a way to indicate that text within a description should be marked as code. Use [\](#code) to indicate multiple lines as code. +The `` tag gives you a way to indicate that text within a description should be marked as code. Use [``](#code) to indicate multiple lines as code. -### \ +### `` ```xml @@ -299,9 +299,9 @@ The `` tag gives you a way to indicate that text within a description should ``` -The `` tag is used to indicate multiple lines of code. Use [\](#c) to indicate that single-line text within a description should be marked as code. +The `` tag is used to indicate multiple lines of code. Use [``](#c) to indicate that single-line text within a description should be marked as code. -### \ +### `` ```xml @@ -313,9 +313,9 @@ This shows how to increment an integer. ``` -The `` tag lets you specify an example of how to use a method or other library member. An example commonly involves using the [\](#code) tag. +The `` tag lets you specify an example of how to use a method or other library member. An example commonly involves using the [``](#code) tag. -### \ +### `` ```xml text @@ -323,7 +323,7 @@ The `` tag lets you specify an example of how to use a method or other The `` tag is used to make text bold within documentation comments. This HTML formatting tag is validated by the compiler and Visual Studio, and the formatted text appears in IntelliSense and generated documentation. -### \ +### `` ```xml text @@ -331,7 +331,7 @@ The `` tag is used to make text bold within documentation comments. This HTML The `` tag is used to make text italic within documentation comments. This HTML formatting tag is validated by the compiler and Visual Studio, and the formatted text appears in IntelliSense and generated documentation. -### \ +### `` ```xml text @@ -339,7 +339,7 @@ The `` tag is used to make text italic within documentation comments. This HT The `` tag is used to underline text within documentation comments. This HTML formatting tag is validated by the compiler and Visual Studio, and the formatted text appears in IntelliSense and generated documentation. -### \
+### `
` ```xml Line one
Line two @@ -347,7 +347,7 @@ Line one
Line two The `
` tag is used to insert a line break within documentation comments. Use this tag when you want a single spaced paragraph, as opposed to the `` tag which creates double spaced paragraphs. -### \ +### `` ```xml Link text @@ -360,7 +360,7 @@ The `` tag is used to create hyperlinks within documentation comments. The `h ## Reuse documentation text -### \ +### `` ```xml @@ -378,7 +378,7 @@ Inherit XML comments from base classes, interfaces, and similar methods. Using ` Add your XML comments in base classes or interfaces and let inheritdoc copy the comments to implementing classes. Add your XML comments to your synchronous methods and let inheritdoc copy the comments to your asynchronous versions of the same methods. If you want to copy the comments from a specific member, you use the `cref` attribute to specify the member. -### \ +### `` ```xml @@ -415,7 +415,7 @@ The XML output for this method is shown in the following example: ## Generate links and references -### \ +### `` ```xml @@ -431,13 +431,13 @@ The XML output for this method is shown in the following example: - `href="link"`: A clickable link to a given URL. For example, `GitHub` produces a clickable link with text :::no-loc text="GitHub"::: that links to `https://github.com`. Use `href` instead of `cref` when linking to external web pages, as `cref` is designed for code references and won't create clickable links for external URLs. - `langword="keyword"`: A language keyword, such as `true` or one of the other valid [keywords](../keywords/index.md). -The `` tag lets you specify a link from within text. Use [\](#seealso) to indicate that text should be placed in a See Also section. Use the [cref attribute](#cref-attribute) to create internal hyperlinks to documentation pages for code elements. You include the type parameters to specify a reference to a generic type or method, such as `cref="IDictionary{T, U}"`. Also, ``href`` is a valid attribute that functions as a hyperlink. +The `` tag lets you specify a link from within text. Use [``](#seealso) to indicate that text should be placed in a See Also section. Use the [cref attribute](#cref-attribute) to create internal hyperlinks to documentation pages for code elements. You include the type parameters to specify a reference to a generic type or method, such as `cref="IDictionary{T, U}"`. Also, ``href`` is a valid attribute that functions as a hyperlink. Here's an example showing the difference between `cref` and `href` when referencing external URLs: :::code language="csharp" source="./snippets/xmldoc/HrefAndBrExamples.cs" id="UrlLinkingExample"::: -### \ +### `` ```xml @@ -448,7 +448,7 @@ Here's an example showing the difference between `cref` and `href` when referenc - `cref="member"`: A reference to a member or field that is available to be called from the current compilation environment. The compiler checks that the given code element exists and passes `member` to the element name in the output XML. `member` must appear within quotation marks ("). - `href="link"`: A clickable link to a given URL. For example, `GitHub` produces a clickable link with text :::no-loc text="GitHub"::: that links to `https://github.com`. -The `` tag lets you specify the text that you might want to appear in a **See Also** section. Use [\](#see) to specify a link from within text. You can't nest the `seealso` tag inside the `summary` tag. +The `` tag lets you specify the text that you might want to appear in a **See Also** section. Use [``](#see) to specify a link from within text. You can't nest the `seealso` tag inside the `summary` tag. ### cref attribute @@ -460,7 +460,7 @@ The `href` attribute means a reference to a web page. You can use it to directly ## Generic types and methods -### \ +### `` ```xml The type returned from this method @@ -470,7 +470,7 @@ The `href` attribute means a reference to a web page. You can use it to directly The `` tag should be used in the comment for a generic type or method declaration to describe a type parameter. Add a tag for each type parameter of the generic type or method. The text for the `` tag is displayed in IntelliSense. -### \ +### `` ```xml @@ -483,6 +483,6 @@ Use this tag to enable consumers of the documentation file to format the word in ### User-defined tags All the tags outlined in this article represent those tags recognized by the C# compiler. However, a user is free to define their own tags. -Tools like Sandcastle bring support for extra tags like [\](https://ewsoftware.github.io/XMLCommentsGuide/html/81bf7ad3-45dc-452f-90d5-87ce2494a182.htm) and [\](https://ewsoftware.github.io/XMLCommentsGuide/html/4302a60f-e4f4-4b8d-a451-5f453c4ebd46.htm), +Tools like Sandcastle bring support for extra tags like [``](https://ewsoftware.github.io/XMLCommentsGuide/html/81bf7ad3-45dc-452f-90d5-87ce2494a182.htm) and [``](https://ewsoftware.github.io/XMLCommentsGuide/html/4302a60f-e4f4-4b8d-a451-5f453c4ebd46.htm), and even support [documenting namespaces](https://ewsoftware.github.io/XMLCommentsGuide/html/BD91FAD4-188D-4697-A654-7C07FD47EF31.htm). Custom or in-house documentation generation tools can also be used with the standard tags, and multiple output formats from HTML to PDF can be supported. diff --git a/docs/csharp/misc/cs1570.md b/docs/csharp/misc/cs1570.md index 6063c796757e0..17bea9fe09bd7 100644 --- a/docs/csharp/misc/cs1570.md +++ b/docs/csharp/misc/cs1570.md @@ -13,13 +13,13 @@ XML comment on 'construct' has badly formed XML — 'reason' When using [**DocumentationFile**](../language-reference/compiler-options/output.md#documentationfile), any comments in the source code must be in XML. Any error with your XML markup will generate CS1570. For example: -- If you are passing a string to a **cref**, such as in an [\](../language-reference/xmldoc/recommended-tags.md) tag, the string must be enclosed in double quotation marks. +- If you are passing a string to a **cref**, such as in an [``](../language-reference/xmldoc/recommended-tags.md) tag, the string must be enclosed in double quotation marks. -- If you're using a tag that doesn't have a closing tag, such as [\](../language-reference/xmldoc/recommended-tags.md), you must specify a forward slash before the closing angle bracket. +- If you're using a tag that doesn't have a closing tag, such as [``](../language-reference/xmldoc/recommended-tags.md), you must specify a forward slash before the closing angle bracket. - If you need to use a greater-than or less-than symbol in the text of description, you need to represent them with `>` or `<`. Alternatively, you can use CDATA. -- The file or path attribute on an [\](../language-reference/xmldoc/recommended-tags.md) tag was missing or improperly formed. +- The file or path attribute on an [``](../language-reference/xmldoc/recommended-tags.md) tag was missing or improperly formed. The following sample generates CS1570: diff --git a/docs/csharp/misc/cs1574.md b/docs/csharp/misc/cs1574.md index 3fe6f3660345c..619d853373d81 100644 --- a/docs/csharp/misc/cs1574.md +++ b/docs/csharp/misc/cs1574.md @@ -2,44 +2,44 @@ description: "Compiler Warning (level 1) CS1574" title: "Compiler Warning (level 1) CS1574" ms.date: 07/20/2015 -f1_keywords: +f1_keywords: - "CS1574" -helpviewer_keywords: +helpviewer_keywords: - "CS1574" ms.assetid: 4cd2b474-ab01-4397-aed7-63e5f0081649 --- # Compiler Warning (level 1) CS1574 -XML comment on 'construct' has syntactically incorrect cref attribute 'name' - - A string passed to a cref tag, for example, within an \ tag, referred to a member that is not available within the current build environment. The string that you pass to a cref tag must be the syntactically correct name of a member or field. - - For more information, see [Recommended Tags for Documentation Comments](../language-reference/xmldoc/recommended-tags.md). - - The following sample generates CS1574: - -```csharp -// CS1574.cs -// compile with: /W:1 /doc:x.xml -using System; - -/// An exception class. // CS1574 -// instead, uncomment and try the following line -// /// An exception class. -class EClass : Exception -{ -} - -class TestClass -{ - public static void Main() - { - try - { - } - catch(EClass) - { - } - } -} +XML comment on 'construct' has syntactically incorrect cref attribute 'name' + + A string passed to a cref tag, for example, within an `` tag, referred to a member that is not available within the current build environment. The string that you pass to a cref tag must be the syntactically correct name of a member or field. + + For more information, see [Recommended Tags for Documentation Comments](../language-reference/xmldoc/recommended-tags.md). + + The following sample generates CS1574: + +```csharp +// CS1574.cs +// compile with: /W:1 /doc:x.xml +using System; + +/// An exception class. // CS1574 +// instead, uncomment and try the following line +// /// An exception class. +class EClass : Exception +{ +} + +class TestClass +{ + public static void Main() + { + try + { + } + catch(EClass) + { + } + } +} ``` diff --git a/docs/csharp/misc/cs1589.md b/docs/csharp/misc/cs1589.md index 1bbad2136957f..77f219e2c7108 100644 --- a/docs/csharp/misc/cs1589.md +++ b/docs/csharp/misc/cs1589.md @@ -2,33 +2,33 @@ description: "Compiler Warning (level 1) CS1589" title: "Compiler Warning (level 1) CS1589" ms.date: 07/20/2015 -f1_keywords: +f1_keywords: - "CS1589" -helpviewer_keywords: +helpviewer_keywords: - "CS1589" ms.assetid: bdc47124-93ae-4c6a-81b2-dde8ec4d0ab1 --- # Compiler Warning (level 1) CS1589 -Unable to include XML fragment 'fragment' of file 'file' -- reason - - The syntax (*fragment*) of a [\](../language-reference/xmldoc/recommended-tags.md) tag, which referenced a file (`file`), was incorrect for the specified ***reason***. - - A malformed line will be placed in the generated XML file. - - The following sample generates CS1589: - -```csharp -// CS1589.cs -// compile with: /W:1 /doc:CS1589_out.xml - -/// // CS1589 -// try the following line instead -// /// -class Test -{ - public static void Main() - { - } -} +Unable to include XML fragment 'fragment' of file 'file' -- reason + + The syntax (*fragment*) of a [``](../language-reference/xmldoc/recommended-tags.md) tag, which referenced a file (`file`), was incorrect for the specified ***reason***. + + A malformed line will be placed in the generated XML file. + + The following sample generates CS1589: + +```csharp +// CS1589.cs +// compile with: /W:1 /doc:CS1589_out.xml + +/// // CS1589 +// try the following line instead +// /// +class Test +{ + public static void Main() + { + } +} ``` diff --git a/docs/csharp/misc/cs1590.md b/docs/csharp/misc/cs1590.md index 14885dd82aec2..4034775dfbc07 100644 --- a/docs/csharp/misc/cs1590.md +++ b/docs/csharp/misc/cs1590.md @@ -2,31 +2,31 @@ description: "Compiler Warning (level 1) CS1590" title: "Compiler Warning (level 1) CS1590" ms.date: 07/20/2015 -f1_keywords: +f1_keywords: - "CS1590" -helpviewer_keywords: +helpviewer_keywords: - "CS1590" ms.assetid: 0d6e5594-d6a6-43bf-8aa8-a452fa5748df --- # Compiler Warning (level 1) CS1590 -Invalid XML include element -- Missing file attribute - - A path or doc attribute, passed to the [\](../language-reference/xmldoc/recommended-tags.md) tag, was missing or incomplete. - - The following sample generates CS1590: - -```csharp -// CS1590.cs -// compile with: /W:1 /doc:x.xml - -/// // CS1590 -// try the following line instead -// /// -class Test -{ - public static void Main() - { - } -} +Invalid XML include element -- Missing file attribute + + A path or doc attribute, passed to the [``](../language-reference/xmldoc/recommended-tags.md) tag, was missing or incomplete. + + The following sample generates CS1590: + +```csharp +// CS1590.cs +// compile with: /W:1 /doc:x.xml + +/// // CS1590 +// try the following line instead +// /// +class Test +{ + public static void Main() + { + } +} ``` diff --git a/docs/csharp/misc/cs1592.md b/docs/csharp/misc/cs1592.md index 2d90fda927a54..37ec841a6c213 100644 --- a/docs/csharp/misc/cs1592.md +++ b/docs/csharp/misc/cs1592.md @@ -2,14 +2,14 @@ description: "Compiler Warning (level 1) CS1592" title: "Compiler Warning (level 1) CS1592" ms.date: 07/20/2015 -f1_keywords: +f1_keywords: - "CS1592" -helpviewer_keywords: +helpviewer_keywords: - "CS1592" ms.assetid: 0a6bd30b-b5f2-424b-9683-568d32f3fb17 --- # Compiler Warning (level 1) CS1592 -Badly formed XML in included comments file -- 'reason' - - A problem, reported as ***reason***, was found in the file specified by the [\](../language-reference/xmldoc/recommended-tags.md) tag. +Badly formed XML in included comments file -- 'reason' + + A problem, reported as ***reason***, was found in the file specified by the [``](../language-reference/xmldoc/recommended-tags.md) tag. diff --git a/docs/csharp/misc/cs1712.md b/docs/csharp/misc/cs1712.md index e3cd23c4dc256..5eec6a85d22a6 100644 --- a/docs/csharp/misc/cs1712.md +++ b/docs/csharp/misc/cs1712.md @@ -2,31 +2,31 @@ description: "Learn more about: Compiler Warning (level 4) CS1712" title: "Compiler Warning (level 4) CS1712" ms.date: 07/20/2015 -f1_keywords: +f1_keywords: - "CS1712" -helpviewer_keywords: +helpviewer_keywords: - "CS1712" ms.assetid: d9a8be26-c0ba-41fa-b082-1ce4ba7724b7 --- # Compiler Warning (level 4) CS1712 -Type parameter 'type parameter' has no matching typeparam tag in the XML comment on 'type' (but other type parameters do) - - The documentation of a generic type is missing a **typeparam** tag. For more information, see [\](../language-reference/xmldoc/recommended-tags.md). - -## Example +Type parameter 'type parameter' has no matching typeparam tag in the XML comment on 'type' (but other type parameters do) - The following code generates warning CS1712. To resolve this error, add a **typeparam** tag for the type parameter S. - -```csharp -// CS1712.cs -// compile with: /doc:cs1712.xml -using System; -class Test -{ - public static void Main() {} - /// This is the j parameter. - /// This is the T type parameter. - public void bar(int j) {} // CS1712 -} + The documentation of a generic type is missing a **typeparam** tag. For more information, see [``](../language-reference/xmldoc/recommended-tags.md). + +## Example + + The following code generates warning CS1712. To resolve this error, add a **typeparam** tag for the type parameter S. + +```csharp +// CS1712.cs +// compile with: /doc:cs1712.xml +using System; +class Test +{ + public static void Main() {} + /// This is the j parameter. + /// This is the T type parameter. + public void bar(int j) {} // CS1712 +} ``` diff --git a/docs/csharp/misc/cs1723.md b/docs/csharp/misc/cs1723.md index 5e110014dda4a..7809175a227cf 100644 --- a/docs/csharp/misc/cs1723.md +++ b/docs/csharp/misc/cs1723.md @@ -2,25 +2,25 @@ description: "Learn more about: Compiler Warning (level 1) CS1723" title: "Compiler Warning (level 1) CS1723" ms.date: 07/20/2015 -f1_keywords: +f1_keywords: - "CS1723" -helpviewer_keywords: +helpviewer_keywords: - "CS1723" ms.assetid: d359be86-7daf-4b59-99a3-10b072336bca --- # Compiler Warning (level 1) CS1723 -XML comment has cref attribute 'attribute' that refers to a type parameter - -This error is generated for an XML comment in case of using a [\](../../csharp/language-reference/xmldoc/recommended-tags.md#see) tag with cross reference (cref) to a type parameter instead of the existing type (whether user-defined or built-in) in the code. It's impossible to link to 'attribute' of generic types because at the moment of creating the documentation the future type given as 'attribute' is not yet known. - -To solve this issue [\](../../csharp/language-reference/xmldoc/recommended-tags.md#typeparamref) tag should be used. - -## Example - -The following example contains a comment generating CS1723 as well as a reference that can be linked correctly. - -```csharp +XML comment has cref attribute 'attribute' that refers to a type parameter. + +This error is generated for an XML comment in case of using a [``](../../csharp/language-reference/xmldoc/recommended-tags.md#see) tag with cross reference (cref) to a type parameter instead of the existing type (whether user-defined or built-in) in the code. It's impossible to link to 'attribute' of generic types because at the moment of creating the documentation the future type given as 'attribute' is not yet known. + +To solve this issue, use the [``](../../csharp/language-reference/xmldoc/recommended-tags.md#typeparamref) tag. + +## Example + +The following example contains a comment generating CS1723 as well as a reference that can be linked correctly. + +```csharp public class Point { } @@ -32,11 +32,11 @@ public class Point public class List { } -``` +``` -This example shows how to correctly link both generic type `T` as well as already known user-defined `Point` +The next example shows how to correctly link both generic type `T` as well as already known user-defined `Point`. -```csharp +```csharp public class Point { } @@ -48,4 +48,4 @@ public class Point public class List { } -``` +``` diff --git a/docs/csharp/programming-guide/classes-and-structs/how-to-create-a-new-method-for-an-enumeration.md b/docs/csharp/programming-guide/classes-and-structs/how-to-create-a-new-method-for-an-enumeration.md index de3d6a49a61bd..1353e1451c036 100644 --- a/docs/csharp/programming-guide/classes-and-structs/how-to-create-a-new-method-for-an-enumeration.md +++ b/docs/csharp/programming-guide/classes-and-structs/how-to-create-a-new-method-for-an-enumeration.md @@ -1,7 +1,7 @@ --- title: "How to create a new method for an enumeration" description: Learn how to use extension methods to add functionality to an enum in C#. This example shows an extension method called Passing for an enum called Grades. -ms.date: 04/17/2025 +ms.date: 11/25/2025 helpviewer_keywords: - "enumerations [C#]" - "extension methods [C#], for enums" diff --git a/docs/csharp/programming-guide/classes-and-structs/how-to-use-implicitly-typed-local-variables-and-arrays-in-a-query-expression.md b/docs/csharp/programming-guide/classes-and-structs/how-to-use-implicitly-typed-local-variables-and-arrays-in-a-query-expression.md index c0d8aff8908d1..cc0917b88a140 100644 --- a/docs/csharp/programming-guide/classes-and-structs/how-to-use-implicitly-typed-local-variables-and-arrays-in-a-query-expression.md +++ b/docs/csharp/programming-guide/classes-and-structs/how-to-use-implicitly-typed-local-variables-and-arrays-in-a-query-expression.md @@ -1,11 +1,10 @@ --- title: "How to use implicitly typed local variables and arrays in a query expression" description: Use implicitly typed local variables in C# to have the compiler determine the type of a local variable. You must use them to store anonymous types. -ms.date: 07/20/2015 +ms.date: 11/25/2025 helpviewer_keywords: - "implicitly-typed local variables [C#], how to use" ms.topic: how-to -ms.assetid: 6b7354d2-af79-427a-b6a8-f74eb8fd0b91 --- # How to use implicitly typed local variables and arrays in a query expression (C# Programming Guide) @@ -25,6 +24,6 @@ You can use implicitly typed local variables whenever you want the compiler to d ## See also -- [Extension Methods](./extension-methods.md) +- [Extension members](./extension-methods.md) - [LINQ (Language-Integrated Query)](../../linq/index.md) - [LINQ in C#](../../linq/index.md) diff --git a/docs/csharp/programming-guide/classes-and-structs/snippets/how-to-implement-and-call-a-custom-extension-method/Program.cs b/docs/csharp/programming-guide/classes-and-structs/snippets/how-to-implement-and-call-a-custom-extension-method/Program.cs index 963b4e6c01aaa..5152ded74a133 100644 --- a/docs/csharp/programming-guide/classes-and-structs/snippets/how-to-implement-and-call-a-custom-extension-method/Program.cs +++ b/docs/csharp/programming-guide/classes-and-structs/snippets/how-to-implement-and-call-a-custom-extension-method/Program.cs @@ -1,4 +1,4 @@ -using CustomExtensions; +using CustomExtensions; string s = "The quick brown fox jumped over the lazy dog."; // Call the method as if it were an @@ -13,12 +13,14 @@ namespace CustomExtensions // Extension methods must be defined in a static class. public static class StringExtension { - // This is the extension method. - // The first parameter takes the "this" modifier - // and specifies the type for which the method is defined. - public static int WordCount(this string str) + extension(string str) { - return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length; + // This is the extension member. + // The `str` parameter is declared on the extension declaration. + public int WordCount() + { + return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; + } } } } diff --git a/docs/csharp/programming-guide/classes-and-structs/snippets/how-to-implement-and-call-a-custom-extension-method/how-to-implement-and-call-a-custom-extension-method.csproj b/docs/csharp/programming-guide/classes-and-structs/snippets/how-to-implement-and-call-a-custom-extension-method/how-to-implement-and-call-a-custom-extension-method.csproj index fd4bd08da2987..ed9781c223ab9 100644 --- a/docs/csharp/programming-guide/classes-and-structs/snippets/how-to-implement-and-call-a-custom-extension-method/how-to-implement-and-call-a-custom-extension-method.csproj +++ b/docs/csharp/programming-guide/classes-and-structs/snippets/how-to-implement-and-call-a-custom-extension-method/how-to-implement-and-call-a-custom-extension-method.csproj @@ -2,7 +2,7 @@ Exe - net9.0 + net10.0 enable enable diff --git a/docs/csharp/programming-guide/generics/constraints-on-type-parameters.md b/docs/csharp/programming-guide/generics/constraints-on-type-parameters.md index 0adad6ba44ade..8b4dc2c3b56b7 100644 --- a/docs/csharp/programming-guide/generics/constraints-on-type-parameters.md +++ b/docs/csharp/programming-guide/generics/constraints-on-type-parameters.md @@ -1,7 +1,7 @@ --- title: "Constraints on type parameters" description: Learn about constraints on type parameters. Constraints tell the compiler what capabilities a type argument must have. -ms.date: 10/10/2025 +ms.date: 11/25/2025 f1_keywords: - "defaultconstraint_CSharpKeyword" - "notnull_CSharpKeyword" diff --git a/docs/csharp/programming-guide/generics/snippets/GenericWhereConstraints.cs b/docs/csharp/programming-guide/generics/snippets/GenericWhereConstraints.cs index 06d9d7ce50141..198d070e0b2d4 100644 --- a/docs/csharp/programming-guide/generics/snippets/GenericWhereConstraints.cs +++ b/docs/csharp/programming-guide/generics/snippets/GenericWhereConstraints.cs @@ -175,20 +175,25 @@ unsafe public static byte[] ToByteArray(this T argument) where T : unmanaged // // - public static TDelegate? TypeSafeCombine(this TDelegate source, TDelegate target) - where TDelegate : System.Delegate - => Delegate.Combine(source, target) as TDelegate; + extension(TDelegate source) where TDelegate : System.Delegate + { + public TDelegate? TypeSafeCombine(TDelegate target) + => Delegate.Combine(source, target) as TDelegate; + } // // - public static Dictionary EnumNamedValues() where T : System.Enum + extension(T) where T : System.Enum { - var result = new Dictionary(); - var values = Enum.GetValues(typeof(T)); + public static Dictionary EnumNamedValues() + { + var result = new Dictionary(); + var values = Enum.GetValues(typeof(T)); - foreach (int item in values) - result.Add(item, Enum.GetName(typeof(T), item)!); - return result; + foreach (int item in values) + result.Add(item, Enum.GetName(typeof(T), item)!); + return result; + } } // } diff --git a/docs/csharp/programming-guide/generics/snippets/generics.csproj b/docs/csharp/programming-guide/generics/snippets/generics.csproj index 9d40194d4ea68..07fc2e7e62dcc 100644 --- a/docs/csharp/programming-guide/generics/snippets/generics.csproj +++ b/docs/csharp/programming-guide/generics/snippets/generics.csproj @@ -2,7 +2,7 @@ Exe - net8.0 + net10.0 enable enable true diff --git a/docs/csharp/toc.yml b/docs/csharp/toc.yml index 942cf95b66fcd..5324dd7a241eb 100644 --- a/docs/csharp/toc.yml +++ b/docs/csharp/toc.yml @@ -558,8 +558,6 @@ items: href: programming-guide/classes-and-structs/implicitly-typed-local-variables.md - name: "How to use implicitly typed local variables and arrays in a query expression" href: programming-guide/classes-and-structs/how-to-use-implicitly-typed-local-variables-and-arrays-in-a-query-expression.md - - name: Extension Methods - href: programming-guide/classes-and-structs/extension-methods.md - name: "How to implement and call a custom extension method" href: programming-guide/classes-and-structs/how-to-implement-and-call-a-custom-extension-method.md - name: "How to create a new method for an enumeration" @@ -580,6 +578,8 @@ items: href: programming-guide/classes-and-structs/static-constructors.md - name: "How to write a copy constructor" href: programming-guide/classes-and-structs/how-to-write-a-copy-constructor.md + - name: Extension members + href: programming-guide/classes-and-structs/extension-methods.md - name: Finalizers href: programming-guide/classes-and-structs/finalizers.md - name: Object and Collection Initializers diff --git a/docs/csharp/tutorials/snippets/console-linq/InterimSteps.cs b/docs/csharp/tutorials/snippets/console-linq/InterimSteps.cs new file mode 100644 index 0000000000000..c307108c66e07 --- /dev/null +++ b/docs/csharp/tutorials/snippets/console-linq/InterimSteps.cs @@ -0,0 +1,175 @@ +namespace UnusedCode; + +using LinqFaroShuffle; +internal class InterimSteps +{ + // + static IEnumerable Suits() + { + yield return "clubs"; + yield return "diamonds"; + yield return "hearts"; + yield return "spades"; + } + + static IEnumerable Ranks() + { + yield return "two"; + yield return "three"; + yield return "four"; + yield return "five"; + yield return "six"; + yield return "seven"; + yield return "eight"; + yield return "nine"; + yield return "ten"; + yield return "jack"; + yield return "queen"; + yield return "king"; + yield return "ace"; + } + // + + private static void InitialMain() + { + // + var startingDeck = from s in Suits() + from r in Ranks() + select (Suit: s, Rank: r); + + // Display each card that's generated and placed in startingDeck + foreach (var card in startingDeck) + { + Console.WriteLine(card); + } + // + + // + var top = startingDeck.Take(26); + var bottom = startingDeck.Skip(26); + // + + } + + private void StartShuffling() + { + var startingDeck = from s in Suits() + from r in Ranks() + select (Suit: s, Rank: r); + + // Display each card that's generated and placed in startingDeck + foreach (var card in startingDeck) + { + Console.WriteLine(card); + } + + var top = startingDeck.Take(26); + var bottom = startingDeck.Skip(26); + + // + var shuffledDeck = top.InterleaveSequenceWith(bottom); + + foreach (var c in shuffledDeck) + { + Console.WriteLine(c); + } + // + } + + private void CompareSequences() + { + // + var startingDeck = from s in Suits() + from r in Ranks() + select (Suit: s, Rank: r); + + // Display each card generated and placed in startingDeck in the console + foreach (var card in startingDeck) + { + Console.WriteLine(card); + } + + var top = startingDeck.Take(26); + var bottom = startingDeck.Skip(26); + + var shuffledDeck = top.InterleaveSequenceWith(bottom); + + var times = 0; + // Re-use the shuffle variable from earlier, or you can make a new one + shuffledDeck = startingDeck; + do + { + shuffledDeck = shuffledDeck.Take(26).InterleaveSequenceWith(shuffledDeck.Skip(26)); + + foreach (var card in shuffledDeck) + { + Console.WriteLine(card); + } + Console.WriteLine(); + times++; + + } while (!startingDeck.SequenceEquals(shuffledDeck)); + + Console.WriteLine(times); + // + } + + private void AddLogging() + { + // + var startingDeck = (from s in Suits().LogQuery("Suit Generation") + from r in Ranks().LogQuery("Rank Generation") + select (Suit: s, Rank: r)).LogQuery("Starting Deck"); + + foreach (var c in startingDeck) + { + Console.WriteLine(c); + } + + Console.WriteLine(); + var times = 0; + var shuffle = startingDeck; + + do + { + // Out shuffle + /* + shuffle = shuffle.Take(26) + .LogQuery("Top Half") + .InterleaveSequenceWith(shuffle.Skip(26) + .LogQuery("Bottom Half")) + .LogQuery("Shuffle"); + */ + + // In shuffle + shuffle = shuffle.Skip(26).LogQuery("Bottom Half") + .InterleaveSequenceWith(shuffle.Take(26).LogQuery("Top Half")) + .LogQuery("Shuffle"); + + foreach (var c in shuffle) + { + Console.WriteLine(c); + } + + times++; + Console.WriteLine(times); + } while (!startingDeck.SequenceEquals(shuffle)); + + Console.WriteLine(times); + // + } +} + +// +public static class CardExtensions +{ + extension(IEnumerable sequence) + { + public IEnumerable InterleaveSequenceWith(IEnumerable second) + { + // Your implementation goes here + return default; + } + } +} +// diff --git a/samples/snippets/csharp/getting-started/console-linq/console-linq.csproj b/docs/csharp/tutorials/snippets/console-linq/LInqFaroShuffle.csproj similarity index 62% rename from samples/snippets/csharp/getting-started/console-linq/console-linq.csproj rename to docs/csharp/tutorials/snippets/console-linq/LInqFaroShuffle.csproj index af31fefa23aa5..0ece068f6df1a 100644 --- a/samples/snippets/csharp/getting-started/console-linq/console-linq.csproj +++ b/docs/csharp/tutorials/snippets/console-linq/LInqFaroShuffle.csproj @@ -2,8 +2,9 @@ Exe - net8.0 + net10.0 enable + enable diff --git a/docs/csharp/tutorials/snippets/console-linq/Program.cs b/docs/csharp/tutorials/snippets/console-linq/Program.cs new file mode 100644 index 0000000000000..fb1527fc5552f --- /dev/null +++ b/docs/csharp/tutorials/snippets/console-linq/Program.cs @@ -0,0 +1,83 @@ +using LinqFaroShuffle; + +// +IEnumerable suits() => (Enum.GetValues(typeof(Suit)) as IEnumerable)!; +// + +// +IEnumerable ranks() => (Enum.GetValues(typeof(Rank)) as IEnumerable)!; +// + +// +var startingDeck = (from s in suits().LogQuery("Suit Generation") + from r in ranks().LogQuery("Value Generation") + select new { Suit = s, Rank = r }) + .LogQuery("Starting Deck") + .ToArray(); + +foreach (var c in startingDeck) +{ + Console.WriteLine(c); +} + +Console.WriteLine(); + +var times = 0; +var shuffle = startingDeck; + +do +{ + /* + shuffle = shuffle.Take(26) + .LogQuery("Top Half") + .InterleaveSequenceWith(shuffle.Skip(26).LogQuery("Bottom Half")) + .LogQuery("Shuffle") + .ToArray(); + */ + + shuffle = shuffle.Skip(26) + .LogQuery("Bottom Half") + .InterleaveSequenceWith(shuffle.Take(26).LogQuery("Top Half")) + .LogQuery("Shuffle") + .ToArray(); + + foreach (var c in shuffle) + { + Console.WriteLine(c); + } + + times++; + Console.WriteLine(times); +} while (!startingDeck.SequenceEquals(shuffle)); + +Console.WriteLine(times); +// + +// +public enum Suit +{ + Clubs, + Diamonds, + Hearts, + Spades +} +// + +// +public enum Rank +{ + Two, + Three, + Four, + Five, + Six, + Seven, + Eight, + Nine, + Ten, + Jack, + Queen, + King, + Ace +} +// diff --git a/samples/snippets/csharp/getting-started/console-linq/README.md b/docs/csharp/tutorials/snippets/console-linq/README.md similarity index 100% rename from samples/snippets/csharp/getting-started/console-linq/README.md rename to docs/csharp/tutorials/snippets/console-linq/README.md diff --git a/samples/snippets/csharp/getting-started/console-linq/extensions.cs b/docs/csharp/tutorials/snippets/console-linq/extensions.cs similarity index 57% rename from samples/snippets/csharp/getting-started/console-linq/extensions.cs rename to docs/csharp/tutorials/snippets/console-linq/extensions.cs index 432a05c691e71..88a2c025125ec 100644 --- a/samples/snippets/csharp/getting-started/console-linq/extensions.cs +++ b/docs/csharp/tutorials/snippets/console-linq/extensions.cs @@ -1,15 +1,13 @@ -using System.Collections.Generic; -using System.IO; +namespace LinqFaroShuffle; -namespace LinqFaroShuffle +public static class CardExtensions { - public static class Extensions + extension(IEnumerable sequence) { - #region snippet1 - public static IEnumerable InterleaveSequenceWith - (this IEnumerable first, IEnumerable second) + // + public IEnumerable InterleaveSequenceWith(IEnumerable second) { - var firstIter = first.GetEnumerator(); + var firstIter = sequence.GetEnumerator(); var secondIter = second.GetEnumerator(); while (firstIter.MoveNext() && secondIter.MoveNext()) @@ -18,13 +16,12 @@ public static IEnumerable InterleaveSequenceWith yield return secondIter.Current; } } - #endregion + // - #region snippet2 - public static bool SequenceEquals - (this IEnumerable first, IEnumerable second) + // + public bool SequenceEquals(IEnumerable second) { - var firstIter = first.GetEnumerator(); + var firstIter = sequence.GetEnumerator(); var secondIter = second.GetEnumerator(); while ((firstIter?.MoveNext() == true) && secondIter.MoveNext()) @@ -37,11 +34,10 @@ public static bool SequenceEquals return true; } - #endregion + // - #region snippet3 - public static IEnumerable LogQuery - (this IEnumerable sequence, string tag) + // + public IEnumerable LogQuery(string tag) { // File.AppendText creates a new file if the file doesn't exist. using (var writer = File.AppendText("debug.log")) @@ -51,6 +47,6 @@ public static IEnumerable LogQuery return sequence; } - #endregion + // } } diff --git a/docs/csharp/tutorials/snippets/console-linq/playingcard.cs b/docs/csharp/tutorials/snippets/console-linq/playingcard.cs new file mode 100644 index 0000000000000..1096d7db4bca3 --- /dev/null +++ b/docs/csharp/tutorials/snippets/console-linq/playingcard.cs @@ -0,0 +1,5 @@ +namespace LinqFaroShuffle; + +// +public sealed record PlayingCard(Suit CardSuit, Rank CardRank); +// diff --git a/docs/csharp/tutorials/working-with-linq.md b/docs/csharp/tutorials/working-with-linq.md index c8ffb58e4f5fa..91162bbbca7e6 100644 --- a/docs/csharp/tutorials/working-with-linq.md +++ b/docs/csharp/tutorials/working-with-linq.md @@ -1,26 +1,25 @@ --- title: Working with LINQ description: This tutorial teaches you how to generate sequences with LINQ, write methods for use in LINQ queries, and distinguish between eager and lazy evaluation. -ms.date: 10/29/2018 +ms.date: 11/25/2025 ms.subservice: csharp-linq -ms.assetid: 0db12548-82cb-4903-ac88-13103d70aa77 +ai-usage: ai-assisted --- - # Work with Language-Integrated Query (LINQ) ## Introduction -This tutorial teaches you features in .NET Core and the C# language. You’ll learn how to: +This tutorial teaches you features in .NET and the C# language. You learn how to: - Generate sequences with LINQ. -- Write methods that can be easily used in LINQ queries. +- Write methods that you can easily use in LINQ queries. - Distinguish between eager and lazy evaluation. -You'll learn these techniques by building an application that demonstrates one of the basic skills of any magician: the [faro shuffle](https://en.wikipedia.org/wiki/Faro_shuffle). Briefly, a faro shuffle is a technique where you split a card deck exactly in half, then the shuffle interleaves each one card from each half to rebuild the original deck. +You learn these techniques by building an application that demonstrates one of the basic skills of any magician: the [faro shuffle](https://en.wikipedia.org/wiki/Faro_shuffle). A faro shuffle is a technique where you split a card deck exactly in half, and then the shuffle interleaves each card from each half to rebuild the original deck. Magicians use this technique because every card is in a known location after each shuffle, and the order is a repeating pattern. -For your purposes, it is a light hearted look at manipulating sequences of data. The application you'll build constructs a card deck and then performs a sequence of shuffles, writing the sequence out each time. You'll also compare the updated order to the original order. +This tutorial offers a lighthearted look at manipulating sequences of data. The application constructs a card deck, performs a sequence of shuffles, and writes the sequence out each time. It also compares the updated order to the original order. This tutorial has multiple steps. After each step, you can run the application and see the progress. You can also see the [completed sample](https://github.com/dotnet/samples/blob/main/csharp/getting-started/console-linq) in the dotnet/samples GitHub repository. For download instructions, see [Samples and Tutorials](../../samples-and-tutorials/index.md#view-and-download-samples). @@ -28,331 +27,147 @@ This tutorial has multiple steps. After each step, you can run the application a [!INCLUDE [Prerequisites](../../../includes/prerequisites-basic.md)] -## Create the Application +## Create the application -The first step is to create a new application. Open a command prompt and create a new directory for your application. Make that the current directory. Type the command `dotnet new console` at the command prompt. This creates the starter files for a basic "Hello World" application. +Create a new application. Open a command prompt and create a new directory for your application. Make that the current directory. Type the command `dotnet new console -o LinqFaroShuffle` at the command prompt. This command creates the starter files for a basic "Hello World" application. If you've never used C# before, [this tutorial](console-teleprompter.md) explains the structure of a C# program. You can read that and then return here to learn more about LINQ. -## Create the Data Set - -Before you begin, make sure that the following lines are at the top of the `Program.cs` file generated by `dotnet new console`: - -```csharp -// Program.cs -using System; -using System.Collections.Generic; -using System.Linq; -``` - -If these three lines (`using` directives) aren't at the top of the file, your program might not compile. +## Create the data set > [!TIP] > For this tutorial, you can organize your code in a namespace called `LinqFaroShuffle` to match the sample code, or you can use the default global namespace. If you choose to use a namespace, make sure all your classes and methods are consistently within the same namespace, or add appropriate `using` statements as needed. -Now that you have all of the references that you'll need, consider what constitutes a deck of cards. Commonly, a deck of playing cards has four suits, and each suit has thirteen values. Normally, you might consider creating a `Card` class right off the bat and populating a collection of `Card` objects by hand. With LINQ, you can be more concise than the usual way of dealing with creating a deck of cards. Instead of creating a `Card` class, you can create two sequences to represent suits and ranks, respectively. You'll create a really simple pair of [*iterator methods*](../iterators.md#enumeration-sources-with-iterator-methods) that will generate the ranks and suits as s of strings: +Consider what constitutes a deck of cards. A deck of playing cards has four suits, and each suit has 13 values. Normally, you might consider creating a `Card` class right away and populating a collection of `Card` objects by hand. With LINQ, you can be more concise than the usual way of creating a deck of cards. Instead of creating a `Card` class, create two sequences to represent suits and ranks. Create a pair of [*iterator methods*](../iterators.md#enumeration-sources-with-iterator-methods) that generate the ranks and suits as s of strings: -```csharp -// Program.cs -// The Main() method - -static IEnumerable Suits() -{ - yield return "clubs"; - yield return "diamonds"; - yield return "hearts"; - yield return "spades"; -} - -static IEnumerable Ranks() -{ - yield return "two"; - yield return "three"; - yield return "four"; - yield return "five"; - yield return "six"; - yield return "seven"; - yield return "eight"; - yield return "nine"; - yield return "ten"; - yield return "jack"; - yield return "queen"; - yield return "king"; - yield return "ace"; -} -``` +:::code source="snippets/console-linq/InterimSteps.cs" id="StepOne"::: -Place these underneath the `Main` method in your `Program.cs` file. These two methods both utilize the `yield return` syntax to produce a sequence as they run. The compiler builds an object that implements and generates the sequence of strings as they are requested. +Place these methods under the `Console.WriteLine` statement in your `Program.cs` file. These two methods both use the `yield return` syntax to produce a sequence as they run. The compiler builds an object that implements and generates the sequence of strings as they're requested. -Now, use these iterator methods to create the deck of cards. You'll place the LINQ query in our `Main` method. Here's a look at it: +Now, use these iterator methods to create the deck of cards. Place the LINQ query at the top of the `Program.cs` file. Here's what it looks like: -```csharp -// Program.cs -static void Main(string[] args) -{ - var startingDeck = from s in Suits() - from r in Ranks() - select new { Suit = s, Rank = r }; - - // Display each card that we've generated and placed in startingDeck in the console - foreach (var card in startingDeck) - { - Console.WriteLine(card); - } -} -``` +:::code source="snippets/console-linq/InterimSteps.cs" id="StepTwo"::: -The multiple `from` clauses produce a , which creates a single sequence from combining each element in the first sequence with each element in the second sequence. The order is important for our purposes. The first element in the first source sequence (Suits) is combined with every element in the second sequence (Ranks). This produces all thirteen cards of first suit. That process is repeated with each element in the first sequence (Suits). The end result is a deck of cards ordered by suits, followed by values. +The multiple `from` clauses produce a , which creates a single sequence from combining each element in the first sequence with each element in the second sequence. The order is important for this example. The first element in the first source sequence (Suits) is combined with every element in the second sequence (Ranks). This process produces all 13 cards of first suit. That process is repeated with each element in the first sequence (Suits). The end result is a deck of cards ordered by suits, followed by values. -It's important to keep in mind that whether you choose to write your LINQ in the query syntax used above or use method syntax instead, it's always possible to go from one form of syntax to the other. The above query written in query syntax can be written in method syntax as: +Keep in mind that whether you write your LINQ in the query syntax used in the preceding sample or use method syntax instead, it's always possible to go from one form of syntax to the other. The preceding query written in query syntax can be written in method syntax as: ```csharp -var startingDeck = Suits().SelectMany(suit => Ranks().Select(rank => new { Suit = suit, Rank = rank })); +var startingDeck = Suits().SelectMany(suit => Ranks().Select(rank => (Suit: suit, Rank: rank ))); ``` -The compiler translates LINQ statements written with query syntax into the equivalent method call syntax. Therefore, regardless of your syntax choice, the two versions of the query produce the same result. Choose which syntax works best for your situation: for instance, if you're working in a team where some of the members have difficulty with method syntax, try to prefer using query syntax. +The compiler translates LINQ statements written with query syntax into the equivalent method call syntax. Therefore, regardless of your syntax choice, the two versions of the query produce the same result. Choose the syntax that works best for your situation. For instance, if you're working in a team where some members have difficulty with method syntax, try to prefer using query syntax. -Go ahead and run the sample you've built at this point. It will display all 52 cards in the deck. You may find it very helpful to run this sample under a debugger to observe how the `Suits()` and `Ranks()` methods execute. You can clearly see that each string in each sequence is generated only as it is needed. +Run the sample you built at this point. It displays all 52 cards in the deck. You might find it helpful to run this sample under a debugger to observe how the `Suits()` and `Ranks()` methods execute. You can clearly see that each string in each sequence is generated only as needed. ![A console window showing the app writing out 52 cards.](./media/working-with-linq/console-52-card-application.png) -## Manipulate the Order +## Manipulate the order -Next, focus on how you're going to shuffle the cards in the deck. The first step in any good shuffle is to split the deck in two. The and methods that are part of the LINQ APIs provide that feature for you. Place them underneath the `foreach` loop: +Next, focus on how you shuffle the cards in the deck. The first step in any good shuffle is to split the deck in two. The and methods that are part of the LINQ APIs provide that feature. Place them following the `foreach` loop: -```csharp -// Program.cs -public static void Main(string[] args) -{ - var startingDeck = from s in Suits() - from r in Ranks() - select new { Suit = s, Rank = r }; - - foreach (var c in startingDeck) - { - Console.WriteLine(c); - } - - // 52 cards in a deck, so 52 / 2 = 26 - var top = startingDeck.Take(26); - var bottom = startingDeck.Skip(26); -} -``` +:::code source="snippets/console-linq/InterimSteps.cs" id="StepThree"::: -However, there's no shuffle method to take advantage of in the standard library, so you'll have to write your own. The shuffle method you'll be creating illustrates several techniques that you'll use with LINQ-based programs, so each part of this process will be explained in steps. +However, there's no shuffle method to take advantage of in the standard library, so you need to write your own. The shuffle method you create illustrates several techniques that you use with LINQ-based programs, so each part of this process is explained in steps. -In order to add some functionality to how you interact with the you'll get back from LINQ queries, you'll need to write some special kinds of methods called [extension methods](../programming-guide/classes-and-structs/extension-methods.md). Briefly, an extension method is a special purpose *static method* that adds new functionality to an already-existing type without having to modify the original type you want to add functionality to. +To add functionality to how you interact with the results of LINQ queries, you write some special kinds of methods called [extension methods](../programming-guide/classes-and-structs/extension-methods.md). An extension method is a special purpose *static method* that adds new functionality to an already-existing type without having to modify the original type you want to add functionality to. Give your extension methods a new home by adding a new *static* class file to your program called `Extensions.cs`, and then start building out the first extension method: -```csharp -// Extensions.cs -using System; -using System.Collections.Generic; -using System.Linq; - -namespace LinqFaroShuffle -{ - public static class Extensions - { - public static IEnumerable InterleaveSequenceWith(this IEnumerable first, IEnumerable second) - { - // Your implementation will go here soon enough - } - } -} -``` +:::code source="snippets/console-linq/InterimSteps.cs" id="StepFour"::: > [!NOTE] > If you're using an editor other than Visual Studio (such as Visual Studio Code), you might need to add `using LinqFaroShuffle;` to the top of your _Program.cs_ file for the extension methods to be accessible. Visual Studio automatically adds this using statement, but other editors might not. -Look at the method signature for a moment, specifically the parameters: +The `extension` container specifies the type being extended. The `extension` node declares the type and name of the *receiver parameter* for all members inside the `extension` container. In this example, you're extending `IEnumerable`, and the parameter is named `sequence`. + +Extension member declarations appear as though they're members of the receiver type: ```csharp -public static IEnumerable InterleaveSequenceWith (this IEnumerable first, IEnumerable second) +public IEnumerable InterleaveSequenceWith(IEnumerable second) ``` -You can see the addition of the `this` modifier on the first argument to the method. That means you call the method as though it were a member method of the type of the first argument. This method declaration also follows a standard idiom where the input and output types are `IEnumerable`. That practice enables LINQ methods to be chained together to perform more complex queries. +You call the method as though it were a member method of the extended type. This method declaration also follows a standard idiom where the input and output types are `IEnumerable`. That practice enables LINQ methods to be chained together to perform more complex queries. -Naturally, since you split the deck into halves, you'll need to join those halves together. In code, this means you'll be enumerating both of the sequences you acquired through and at once, *`interleaving`* the elements, and creating one sequence: your now-shuffled deck of cards. Writing a LINQ method that works with two sequences requires that you understand how works. +Since you split the deck into halves, you need to join those halves together. In code, this means you enumerate both of the sequences you acquired through and at once, *interleaving* the elements, and creating one sequence: your now-shuffled deck of cards. Writing a LINQ method that works with two sequences requires that you understand how works. -The interface has one method: . The object returned by has a method to move to the next element, and a property that retrieves the current element in the sequence. You will use those two members to enumerate the collection and return the elements. This Interleave method will be an iterator method, so instead of building a collection and returning the collection, you'll use the `yield return` syntax shown above. +The interface has one method: . The object returned by has a method to move to the next element and a property that retrieves the current element in the sequence. You use those two members to enumerate the collection and return the elements. This Interleave method is an iterator method, so instead of building a collection and returning the collection, you use the `yield return` syntax shown in the preceding code. Here's the implementation of that method: -[!CODE-csharp[InterleaveSequenceWith](../../../samples/snippets/csharp/getting-started/console-linq/extensions.cs?name=snippet1)] +:::code source="snippets/console-linq/extensions.cs" id="snippet1"::: -Now that you've written this method, go back to the `Main` method and shuffle the deck once: +Now that you wrote this method, go back to the `Main` method and shuffle the deck once: -```csharp -// Program.cs -public static void Main(string[] args) -{ - var startingDeck = from s in Suits() - from r in Ranks() - select new { Suit = s, Rank = r }; - - foreach (var c in startingDeck) - { - Console.WriteLine(c); - } - - var top = startingDeck.Take(26); - var bottom = startingDeck.Skip(26); - var shuffle = top.InterleaveSequenceWith(bottom); - - foreach (var c in shuffle) - { - Console.WriteLine(c); - } -} -``` +:::code source="snippets/console-linq/InterimSteps.cs" id="StepFive"::: ## Comparisons -How many shuffles it takes to set the deck back to its original order? To find out, you'll need to write a method that determines if two sequences are equal. After you have that method, you'll need to place the code that shuffles the deck in a loop, and check to see when the deck is back in order. +Determine how many shuffles it takes to set the deck back to its original order. To find out, write a method that determines if two sequences are equal. After you have that method, place the code that shuffles the deck in a loop, and check to see when the deck is back in order. -Writing a method to determine if the two sequences are equal should be straightforward. It's a similar structure to the method you wrote to shuffle the deck. Only this time, instead of `yield return`ing each element, you'll compare the matching elements of each sequence. When the entire sequence has been enumerated, if every element matches, the sequences are the same: +Writing a method to determine if the two sequences are equal should be straightforward. It's a similar structure to the method you wrote to shuffle the deck. However, this time, instead of using `yield return` for each element, you compare the matching elements of each sequence. When the entire sequence is enumerated, if every element matches, the sequences are the same: -[!CODE-csharp[SequenceEquals](../../../samples/snippets/csharp/getting-started/console-linq/extensions.cs?name=snippet2)] +:::code source="snippets/console-linq/extensions.cs" id="snippet2"::: -This shows a second LINQ idiom: terminal methods. They take a sequence as input (or in this case, two sequences), and return a single scalar value. When using terminal methods, they are always the final method in a chain of methods for a LINQ query, hence the name "terminal". +This method shows a second LINQ idiom: terminal methods. They take a sequence as input (or in this case, two sequences) and return a single scalar value. When you use terminal methods, they're always the final method in a chain of methods for a LINQ query. -You can see this in action when you use it to determine when the deck is back in its original order. Put the shuffle code inside a loop, and stop when the sequence is back in its original order by applying the `SequenceEquals()` method. You can see it would always be the final method in any query, because it returns a single value instead of a sequence: +You can see this in action when you use it to determine when the deck is back in its original order. Put the shuffle code inside a loop, and stop when the sequence is back in its original order by applying the `SequenceEquals()` method. You can see it would always be the final method in any query because it returns a single value instead of a sequence: -```csharp -// Program.cs -static void Main(string[] args) -{ - // Query for building the deck - - // Shuffling using InterleaveSequenceWith(); - - var times = 0; - // We can re-use the shuffle variable from earlier, or you can make a new one - shuffle = startingDeck; - do - { - shuffle = shuffle.Take(26).InterleaveSequenceWith(shuffle.Skip(26)); - - foreach (var card in shuffle) - { - Console.WriteLine(card); - } - Console.WriteLine(); - times++; - - } while (!startingDeck.SequenceEquals(shuffle)); - - Console.WriteLine(times); -} -``` +:::code source="snippets/console-linq/InterimSteps.cs" id="StepSix"::: -Run the code you've got so far and take note of how the deck rearranges on each shuffle. After 8 shuffles (iterations of the do-while loop), the deck returns to the original configuration it was in when you first created it from the starting LINQ query. +Run the code you built so far and notice how the deck rearranges on each shuffle. After 8 shuffles (iterations of the do-while loop), the deck returns to the original configuration it was in when you first created it from the starting LINQ query. ## Optimizations -The sample you've built so far executes an *out shuffle*, where the top and bottom cards stay the same on each run. Let's make one change: we'll use an *in shuffle* instead, where all 52 cards change position. For an in shuffle, you interleave the deck so that the first card in the bottom half becomes the first card in the deck. That means the last card in the top half becomes the bottom card. This is a simple change to a singular line of code. Update the current shuffle query by switching the positions of and . This will change the order of the top and bottom halves of the deck: +The sample you built so far executes an *out shuffle*, where the top and bottom cards stay the same on each run. Let's make one change: use an *in shuffle* instead, where all 52 cards change position. For an in shuffle, you interleave the deck so that the first card in the bottom half becomes the first card in the deck. That means the last card in the top half becomes the bottom card. This change requires one line of code. Update the current shuffle query by switching the positions of and . This change switches the order of the top and bottom halves of the deck: ```csharp -shuffle = shuffle.Skip(26).InterleaveSequenceWith(shuffle.Take(26)); +shuffledDeck = shuffledDeck.Skip(26).InterleaveSequenceWith(shuffledDeck.Take(26)); ``` -Run the program again, and you'll see that it takes 52 iterations for the deck to reorder itself. You'll also start to notice some serious performance degradations as the program continues to run. - -There are a number of reasons for this. You can tackle one of the major causes of this performance drop: inefficient use of [*lazy evaluation*](../../standard/linq/deferred-execution-lazy-evaluation.md). +Run the program again, and you see that it takes 52 iterations for the deck to reorder itself. You also notice some serious performance degradation as the program continues to run. -Briefly, lazy evaluation states that the evaluation of a statement is not performed until its value is needed. LINQ queries are statements that are evaluated lazily. The sequences are generated only as the elements are requested. Usually, that's a major benefit of LINQ. However, in a use such as this program, this causes exponential growth in execution time. +There are several reasons for this performance drop. You can tackle one of the major causes: inefficient use of [*lazy evaluation*](../../standard/linq/deferred-execution-lazy-evaluation.md). -Remember that we generated the original deck using a LINQ query. Each shuffle is generated by performing three LINQ queries on the previous deck. All these are performed lazily. That also means they are performed again each time the sequence is requested. By the time you get to the 52nd iteration, you're regenerating the original deck many, many times. Let's write a log to demonstrate this behavior. Then, you'll fix it. +Lazy evaluation states that the evaluation of a statement isn't performed until its value is needed. LINQ queries are statements that are evaluated lazily. The sequences are generated only as the elements are requested. Usually, that's a major benefit of LINQ. However, in a program like this one, lazy evaluation causes exponential growth in execution time. -In your `Extensions.cs` file, type in or copy the method below. This extension method creates a new file called `debug.log` within your project directory and records what query is currently being executed to the log file. This extension method can be appended to any query to mark that the query executed. +Remember that you generated the original deck using a LINQ query. Each shuffle is generated by performing three LINQ queries on the previous deck. All these queries are performed lazily. That also means they're performed again each time the sequence is requested. By the time you get to the 52nd iteration, you're regenerating the original deck many times. Write a log to demonstrate this behavior. Once you gather data, you can improve performance. -[!CODE-csharp[LogQuery](../../../samples/snippets/csharp/getting-started/console-linq/extensions.cs?name=snippet3)] +In your `Extensions.cs` file, type in or copy the method in the following code sample. This extension method creates a new file called `debug.log` within your project directory and records what query is currently being executed to the log file. Append this extension method to any query to mark that the query executed. -You will see a red squiggle under `File`, meaning it doesn't exist. It won't compile, since the compiler doesn't know what `File` is. To solve this problem, make sure to add the following line of code under the very first line in `Extensions.cs`: - -```csharp -using System.IO; -``` - -This should solve the issue and the red error disappears. +:::code source="snippets/console-linq/extensions.cs" id="snippet3"::: Next, instrument the definition of each query with a log message: -```csharp -// Program.cs -public static void Main(string[] args) -{ - var startingDeck = (from s in Suits().LogQuery("Suit Generation") - from r in Ranks().LogQuery("Rank Generation") - select new { Suit = s, Rank = r }).LogQuery("Starting Deck"); - - foreach (var c in startingDeck) - { - Console.WriteLine(c); - } - - Console.WriteLine(); - var times = 0; - var shuffle = startingDeck; - - do - { - // Out shuffle - /* - shuffle = shuffle.Take(26) - .LogQuery("Top Half") - .InterleaveSequenceWith(shuffle.Skip(26) - .LogQuery("Bottom Half")) - .LogQuery("Shuffle"); - */ - - // In shuffle - shuffle = shuffle.Skip(26).LogQuery("Bottom Half") - .InterleaveSequenceWith(shuffle.Take(26).LogQuery("Top Half")) - .LogQuery("Shuffle"); - - foreach (var c in shuffle) - { - Console.WriteLine(c); - } - - times++; - Console.WriteLine(times); - } while (!startingDeck.SequenceEquals(shuffle)); - - Console.WriteLine(times); -} -``` +:::code source="snippets/console-linq/InterimSteps.cs" id="StepSeven"::: -Notice that you don't log every time you access a query. You log only when you create the original query. The program still takes a long time to run, but now you can see why. If you run out of patience running the in shuffle with logging turned on, switch back to the out shuffle. You'll still see the lazy evaluation effects. In one run, it executes 2592 queries, including all the value and suit generation. +Notice that you don't log every time you access a query. You log only when you create the original query. The program still takes a long time to run, but now you can see why. If you run out of patience running the in shuffle with logging turned on, switch back to the out shuffle. You still see the lazy evaluation effects. In one run, it executes 2,592 queries, including the value and suit generation. -You can improve the performance of the code here to reduce the number of executions you make. A simple fix you can make is to *cache* the results of the original LINQ query that constructs the deck of cards. Currently, you're executing the queries again and again every time the do-while loop goes through an iteration, re-constructing the deck of cards and reshuffling it every time. To cache the deck of cards, you can leverage the LINQ methods and ; when you append them to the queries, they'll perform the same actions you've told them to, but now they'll store the results in an array or a list, depending on which method you choose to call. Append the LINQ method to both queries and run the program again: +You can improve the performance of the code to reduce the number of executions you make. A simple fix is to *cache* the results of the original LINQ query that constructs the deck of cards. Currently, you're executing the queries again and again every time the do-while loop goes through an iteration, reconstructing the deck of cards and reshuffling it every time. To cache the deck of cards, apply the LINQ methods and . When you append them to the queries, they perform the same actions you told them to, but now they store the results in an array or a list, depending on which method you choose to call. Append the LINQ method to both queries and run the program again: -[!CODE-csharp[Main](../../../samples/snippets/csharp/getting-started/console-linq/Program.cs?name=snippet1)] +:::code source="snippets/console-linq/Program.cs" id="snippet1"::: -Now the out shuffle is down to 30 queries. Run again with the in shuffle and you'll see similar improvements: it now executes 162 queries. +Now the out shuffle is down to 30 queries. Run again with the in shuffle and you see similar improvements: it now executes 162 queries. -Please note that this example is **designed** to highlight the use cases where lazy evaluation can cause performance difficulties. While it's important to see where lazy evaluation can impact code performance, it's equally important to understand that not all queries should run eagerly. The performance hit you incur without using is because each new arrangement of the deck of cards is built from the previous arrangement. Using lazy evaluation means each new deck configuration is built from the original deck, even executing the code that built the `startingDeck`. That causes a large amount of extra work. +This example is **designed** to highlight the use cases where lazy evaluation can cause performance difficulties. While it's important to see where lazy evaluation can impact code performance, it's equally important to understand that not all queries should run eagerly. The performance hit you incur without using is because each new arrangement of the deck of cards is built from the previous arrangement. Using lazy evaluation means each new deck configuration is built from the original deck, even executing the code that built the `startingDeck`. That causes a large amount of extra work. -In practice, some algorithms run well using eager evaluation, and others run well using lazy evaluation. For daily usage, lazy evaluation is usually a better choice when the data source is a separate process, like a database engine. For databases, lazy evaluation allows more complex queries to execute only one round trip to the database process and back to the rest of your code. LINQ is flexible whether you choose to utilize lazy or eager evaluation, so measure your processes and pick whichever kind of evaluation gives you the best performance. +In practice, some algorithms run well using eager evaluation, and others run well using lazy evaluation. For daily usage, lazy evaluation is usually a better choice when the data source is a separate process, like a database engine. For databases, lazy evaluation allows more complex queries to execute only one round trip to the database process and back to the rest of your code. LINQ is flexible whether you choose to use lazy or eager evaluation, so measure your processes and pick whichever evaluation gives you the best performance. ## Conclusion In this project, you covered: -- using LINQ queries to aggregate data into a meaningful sequence -- writing Extension methods to add our own custom functionality to LINQ queries -- locating areas in our code where our LINQ queries might run into performance issues like degraded speed -- lazy and eager evaluation in regards to LINQ queries and the implications they might have on query performance +- Using LINQ queries to aggregate data into a meaningful sequence. +- Writing extension methods to add custom functionality to LINQ queries. +- Locating areas in code where LINQ queries might run into performance issues like degraded speed. +- Lazy and eager evaluation in LINQ queries and the implications they might have on query performance. -Aside from LINQ, you learned a bit about a technique magicians use for card tricks. Magicians use the Faro shuffle because they can control where every card moves in the deck. Now that you know, don't spoil it for everyone else! +Aside from LINQ, you learned about a technique magicians use for card tricks. Magicians use the faro shuffle because they can control where every card moves in the deck. Now that you know, don't spoil it for everyone else! For more information on LINQ, see: - [Introduction to LINQ](../linq/index.md) -- [Basic LINQ Query Operations (C#)](../linq/standard-query-operators/index.md) -- [Data Transformations With LINQ (C#)](../linq/standard-query-operators/index.md) -- [Query Syntax and Method Syntax in LINQ (C#)](../linq/get-started/write-linq-queries.md) -- [C# Features That Support LINQ](../linq/get-started/features-that-support-linq.md) +- [Basic LINQ query operations (C#)](../linq/standard-query-operators/index.md) +- [Data transformations with LINQ (C#)](../linq/standard-query-operators/index.md) +- [Query syntax and method syntax in LINQ (C#)](../linq/get-started/write-linq-queries.md) +- [C# features that support LINQ](../linq/get-started/features-that-support-linq.md) diff --git a/docs/framework/64-bit-apps.md b/docs/framework/64-bit-apps.md index 2fec1250af545..d7a4396209b40 100644 --- a/docs/framework/64-bit-apps.md +++ b/docs/framework/64-bit-apps.md @@ -18,7 +18,7 @@ When you compile an application, you can specify that it should run on a Windows > [!NOTE] > Because of the design of x86 emulation and the WOW64 subsystem for the Itanium processor family, applications are restricted to execution on one processor. These factors reduce the performance and scalability of 32-bit .NET applications that run on Itanium-based systems. We recommend that you use .NET Framework 4 or later, which includes native 64-bit support for Itanium-based systems, for increased performance and scalability. - By default, when you run a 64-bit managed application on a 64-bit Windows operating system, you can create an object of no more than 2 gigabytes (GB). However, in .NET Framework 4.5 and later, you can increase this limit. For more information, see the [\ element](./configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md). + By default, when you run a 64-bit managed application on a 64-bit Windows operating system, you can create an object of no more than 2 gigabytes (GB). However, in .NET Framework 4.5 and later, you can increase this limit. For more information, see the [`` element](./configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md). Many assemblies run identically on both the 32-bit CLR and the 64-bit CLR. However, some programs may behave differently, depending on the CLR, if they contain one or more of the following: diff --git a/docs/framework/additional-apis/pos-for-net/adding-plug-and-play-support.md b/docs/framework/additional-apis/pos-for-net/adding-plug-and-play-support.md index 5a9f66f50bf43..2e54280fbf9a5 100644 --- a/docs/framework/additional-apis/pos-for-net/adding-plug-and-play-support.md +++ b/docs/framework/additional-apis/pos-for-net/adding-plug-and-play-support.md @@ -10,9 +10,9 @@ ms.custom: "pos-restored-from-archive" Microsoft Point of Service for .NET (POS for .NET) includes support for Plug and Play devices. By adding Plug and Play support to your Service Objects, applications can become more simple, reliable, and efficient. Service Objects should support it whenever possible. -Implementing Plug and Play support at the Service Object level is very simple. Once you know the hardware ID of your device, simply add a single attribute to your class, . The **HardwareId** attribute is used by to intelligently filter out Service Objects from the list of available devices depending on the state of the device. If the Service Object has a **HardwareId** attribute that refers to an installed Plug and Play device, but that device is not connected, the Service Object will be excluded from the **PosExplorer** device list. This list is returned when applications call . +Implementing Plug and Play support at the Service Object level is very simple. Once you know the hardware ID of your device, simply add a single attribute to your class, . The `HardwareId` attribute is used by to intelligently filter out Service Objects from the list of available devices depending on the state of the device. If the Service Object has a `HardwareId` attribute that refers to an installed Plug and Play device, but that device is not connected, the Service Object will be excluded from the **PosExplorer** device list. This list is returned when applications call . -Service Objects may also have more than one **HardwareId** attribute, in which case **PosExplorer** associates a union of all specified devices with the Service Object. It is possible to override the **HardwareId** attributes or add to the list of associated hardware on the Service Object without rebuilding the Service Object assembly. For information about overriding or adding the **HardwareId** attribute, see [Plug and Play XML Configuration](plug-and-play-xml-configuration.md). +Service Objects may also have more than one `HardwareId` attribute, in which case **PosExplorer** associates a union of all specified devices with the Service Object. It is possible to override the `HardwareId` attributes or add to the list of associated hardware on the Service Object without rebuilding the Service Object assembly. For information about overriding or adding the `HardwareId` attribute, see [Plug and Play XML Configuration](plug-and-play-xml-configuration.md). Only the application is responsible for catching and events and updating its status as appropriate based on the updated device list returned from **PosExplorer**. The Service Object does not need to detect these events. @@ -20,11 +20,11 @@ Only the application is responsible for catching class provides two methods, **DecodeDataLabel** and **DecodeScanDataType** for decoding incoming date. These methods are called when the properties **ScanDataLabel** and **ScanDataType**, respectively, are accessed. The **ScannerBase** class defers data decoding until the application accesses the data properties and the decoded data will be cached for future reads. -The **ScannerBase** class implements the **ScannerBase.DecodeData** attribute as required by the Unified Point Of Service (UnifiedPOS) specification. If **DecodeData** is not set to **true** when the application reads the **ScanDataLabel** property, an empty byte array will be returned. Similarly, **ScanDataType** returns **BarCodeSymbology.Unknown**. This functionality is implemented in the **ScannerBase** class and is transparent to both the application and the Service Object. +The **ScannerBase** class implements the `ScannerBase.DecodeData` attribute as required by the Unified Point Of Service (UnifiedPOS) specification. If **DecodeData** is not set to **true** when the application reads the **ScanDataLabel** property, an empty byte array will be returned. Similarly, **ScanDataType** returns **BarCodeSymbology.Unknown**. This functionality is implemented in the **ScannerBase** class and is transparent to both the application and the Service Object. ## To implement DecodeScanDataLabel diff --git a/docs/framework/additional-apis/pos-for-net/pinpad-sample.md b/docs/framework/additional-apis/pos-for-net/pinpad-sample.md index f8bb5e9b65c26..55a6aa8778e59 100644 --- a/docs/framework/additional-apis/pos-for-net/pinpad-sample.md +++ b/docs/framework/additional-apis/pos-for-net/pinpad-sample.md @@ -20,7 +20,7 @@ This sample demonstrates which methods must be implemented in a **PinPad** Servi 4. Create a Service Object class derived from . -5. Add the **ServiceObject** attribute to your Service Object class, using the **DeviceType.PinPad** value as your device type. +5. Add the `ServiceObject` attribute to your Service Object class, using the **DeviceType.PinPad** value as your device type. ## Example diff --git a/docs/framework/additional-apis/pos-for-net/plug-and-play-support.md b/docs/framework/additional-apis/pos-for-net/plug-and-play-support.md index 36b9377533ed6..3f7856ebf8c83 100644 --- a/docs/framework/additional-apis/pos-for-net/plug-and-play-support.md +++ b/docs/framework/additional-apis/pos-for-net/plug-and-play-support.md @@ -24,8 +24,8 @@ When an application invokes the method **PosExplorer.GetDevices**, **PosExplorer 1. Searches for all assemblies in the specified POS for .NET directories. 2. If the assembly is not marked with the **PosAssembly** global attribute, discards it. -3. Searches for classes marked with the **ServiceObject** attribute. For each such class: - 1. Looks for a hardware ID associated with this class, as either a **HardwareId** attribute or within the [Plug and Play XML Configuration](plug-and-play-xml-configuration.md) file. If there is no hardware ID, leaves the Service Object in the **PosExplorer** list. +3. Searches for classes marked with the `ServiceObject` attribute. For each such class: + 1. Looks for a hardware ID associated with this class, as either a `HardwareId` attribute or within the [Plug and Play XML Configuration](plug-and-play-xml-configuration.md) file. If there is no hardware ID, leaves the Service Object in the **PosExplorer** list. 2. If there is a hardware ID, then queries Windows to retrieve the device's status. If the device is attached to the computer, leaves it in the **PosExplorer** list. 3. If the device is not attached to the computer, removes it from the **PosExplorer** list. diff --git a/docs/framework/additional-apis/pos-for-net/plug-and-play-xml-configuration.md b/docs/framework/additional-apis/pos-for-net/plug-and-play-xml-configuration.md index c8fd55568f6a9..d20a931cb1827 100644 --- a/docs/framework/additional-apis/pos-for-net/plug-and-play-xml-configuration.md +++ b/docs/framework/additional-apis/pos-for-net/plug-and-play-xml-configuration.md @@ -16,9 +16,9 @@ To support these cases, Microsoft Point of Service for .NET (POS for .NET) speci A Plug and Play configuration file must begin with a top-level node named **PointOfServiceConfig** and have the attribute **Version** to indicate the XML version of the file. -Following that, there may be any number of **ServiceObject** subnodes. Each service object node must include **Type** and **Name** attributes to indicate the POS device type and name of the Service Object. These two fields will be matched against available Service Objects to determine which, if any, should be associated with devices specified in the subnode **HardwareId**. There is also an optional attribute on the **ServiceObject** node, **Override**. If this attribute is set, then the device associations in the XML file overrides those contained in the assembly. +Following that, there may be any number of **ServiceObject** subnodes. Each service object node must include `Type` and `Name` attributes to indicate the POS device type and name of the Service Object. These two fields will be matched against available Service Objects to determine which, if any, should be associated with devices specified in the subnode **HardwareId**. There is also an optional attribute on the **ServiceObject** node, `Override`. If this attribute is set, then the device associations in the XML file overrides those contained in the assembly. -The **ServiceObject** node contains subnodes with the name **HardwareId**, which have **From** and **To** attributes. The contents of these attributes are the same as would be found in the **HardwareId** attribute in a Service Object assembly and specify the range of hardware IDs to associate with the Service Object. +The **ServiceObject** node contains subnodes with the name **HardwareId**, which have `From` and `To` attributes. The contents of these attributes are the same as would be found in the `HardwareId` attribute in a Service Object assembly and specify the range of hardware IDs to associate with the Service Object. ## Example @@ -35,17 +35,17 @@ The example shows a typical XML Plug and Play configuration file. ## Hardware ID Precedence -If the **Override** attribute on the **ServiceObject** node is set, then the device association specified in the XML takes precedence, and any **HardwareId** attribute on the Service Object will be discarded. +If the `Override` attribute on the **ServiceObject** node is set, then the device association specified in the XML takes precedence, and any `HardwareId` attribute on the Service Object will be discarded. -If the **Override** attribute is not set, then neither the XML nor the **HardwareId** has precedence. Instead, **PosExplorer** associates the union of all specified devices with the Service Object. +If the `Override` attribute is not set, then neither the XML nor the **HardwareId** has precedence. Instead, **PosExplorer** associates the union of all specified devices with the Service Object. ## See Also -#### Tasks +### Tasks - [Adding Plug and Play Support](adding-plug-and-play-support.md) -#### Concepts +### Concepts - [Plug and Play Support](plug-and-play-support.md) - [POS for .NET Registry Settings](pos-for-net-registry-settings.md) diff --git a/docs/framework/additional-apis/pos-for-net/poscommon-information-for-service-object-developers.md b/docs/framework/additional-apis/pos-for-net/poscommon-information-for-service-object-developers.md index f7ae52937b135..e5d2bdd73739f 100644 --- a/docs/framework/additional-apis/pos-for-net/poscommon-information-for-service-object-developers.md +++ b/docs/framework/additional-apis/pos-for-net/poscommon-information-for-service-object-developers.md @@ -50,7 +50,7 @@ This property is also used to enable or disable the device by setting the proper POS for .NET verifies that the device has been opened, and then retrieves the current value of the property. -Within **Base** class implementations, this value is set automatically based on the contents of the **ServiceObject** attribute. +Within **Base** class implementations, this value is set automatically based on the contents of the `ServiceObject` attribute. If you are not deriving from a POS for .NET **Base** class, and are instead deriving from an **Interface**-level or **Basic**-level class, then **DeviceName** should be set by the Service Subject during the method. @@ -138,11 +138,11 @@ Setting can cause the following excep ## ServiceObjectDescription Property -POS for .NET verifies that the device has been opened, and then retrieves the current value of the property. The Service Object developer should not have to set this value, since it is set by the POS for .NET **Basic** class using the description information provided in the **ServiceObject** attribute. +POS for .NET verifies that the device has been opened, and then retrieves the current value of the property. The Service Object developer should not have to set this value, since it is set by the POS for .NET **Basic** class using the description information provided in the `ServiceObject` attribute. ## ServiceObjectVersion Property -POS for .NET verifies that the device has been opened, and then retrieves the current value of the property. The Service Object developer should not have to set this value, since it is set by the POS for .NET **Basic** class using the version information provided in the **ServiceObject** attribute. +POS for .NET verifies that the device has been opened, and then retrieves the current value of the property. The Service Object developer should not have to set this value, since it is set by the POS for .NET **Basic** class using the version information provided in the `ServiceObject` attribute. ## State Property diff --git a/docs/framework/additional-apis/pos-for-net/poskeyboard-implementation.md b/docs/framework/additional-apis/pos-for-net/poskeyboard-implementation.md index 8e9ba7c647135..e834115225c87 100644 --- a/docs/framework/additional-apis/pos-for-net/poskeyboard-implementation.md +++ b/docs/framework/additional-apis/pos-for-net/poskeyboard-implementation.md @@ -36,7 +36,7 @@ This section contains a sample **PosKeyboard** Service Object that generates sim 4. Create a Service Object class derived from **PosKeyboardBase**. -5. Add the **ServiceObject** attribute to your Service Object class, using the **DeviceType.PosKeyboard** value as your device type. +5. Add the `ServiceObject` attribute to your Service Object class, using the **DeviceType.PosKeyboard** value as your device type. ## To add features to the sample keyboard Service Object diff --git a/docs/framework/additional-apis/pos-for-net/statistics-sample.md b/docs/framework/additional-apis/pos-for-net/statistics-sample.md index 95d35e97be9cb..8dce48fd1f8a7 100644 --- a/docs/framework/additional-apis/pos-for-net/statistics-sample.md +++ b/docs/framework/additional-apis/pos-for-net/statistics-sample.md @@ -70,7 +70,7 @@ The key members of the **DeviceStatistics** class are detailed below: ``` - When an application requests all statistics from the device, the device returns a `` entry for every defined statistic in the device category. The device category is defined by the version of the XML schema specified by the **version** attribute in the `` tag. If the device does not record any statistics, the `` tag will be empty. + When an application requests all statistics from the device, the device returns a `` entry for every defined statistic in the device category. The device category is defined by the version of the XML schema specified by the `version` attribute in the `` tag. If the device does not record any statistics, the `` tag will be empty. POS for .NET uses handlers to perform the reading and writing of statistics in a manner similar to the way events are handled. When one of these statistic handlers is created, it is assigned to a particular device statistic. When this statistic is read or updated, the handler calls a delegate that is able to read from or write to the device as necessary. diff --git a/docs/framework/app-domains/assembly-placement.md b/docs/framework/app-domains/assembly-placement.md index bbfa9316e7238..730fb145d1328 100644 --- a/docs/framework/app-domains/assembly-placement.md +++ b/docs/framework/app-domains/assembly-placement.md @@ -13,7 +13,7 @@ ms.assetid: ff8d48bc-f606-484f-9fe1-d0af264269fb [!INCLUDE [net-framework-specific](../includes/net-framework-specific.md)] -For most .NET Framework applications, you locate assemblies that make up an application in the application's directory, in a subdirectory of the application's directory, or in the global assembly cache (if the assembly is shared). You can override where the common language runtime looks for an assembly by using the [\ Element](../configure-apps/file-schema/runtime/codebase-element.md) in a configuration file. If the assembly does not have a strong name, the location specified using the [\ Element](../configure-apps/file-schema/runtime/codebase-element.md) is restricted to the application directory or a subdirectory. If the assembly has a strong name, the [\ Element](../configure-apps/file-schema/runtime/codebase-element.md) can specify any location on the computer or on a network. +For most .NET Framework applications, you locate assemblies that make up an application in the application's directory, in a subdirectory of the application's directory, or in the global assembly cache (if the assembly is shared). You can override where the common language runtime looks for an assembly by using the [`` Element](../configure-apps/file-schema/runtime/codebase-element.md) in a configuration file. If the assembly does not have a strong name, the location specified using the [`` Element](../configure-apps/file-schema/runtime/codebase-element.md) is restricted to the application directory or a subdirectory. If the assembly has a strong name, the [`` Element](../configure-apps/file-schema/runtime/codebase-element.md) can specify any location on the computer or on a network. Similar rules apply to locating assemblies when working with unmanaged code or COM interop applications: if the assembly will be shared by multiple applications, it should be installed into the global assembly cache. Assemblies used with unmanaged code must be exported as a type library and registered. Assemblies used by COM interop must be registered in the catalog, although in some cases this registration occurs automatically. diff --git a/docs/framework/app-domains/build-multifile-assembly.md b/docs/framework/app-domains/build-multifile-assembly.md index c09ed12a1fd55..9f70421ed5391 100644 --- a/docs/framework/app-domains/build-multifile-assembly.md +++ b/docs/framework/app-domains/build-multifile-assembly.md @@ -93,9 +93,9 @@ This article explains how to create a multifile assembly and provides code that vbc /t:module Stringer.vb ``` - Specifying the *module* parameter with the **/t:** compiler option indicates that the file should be compiled as a module rather than as an assembly. The compiler produces a module called *Stringer.netmodule*, which can be added to an assembly. + Specifying the *module* parameter with the `/t:` compiler option indicates that the file should be compiled as a module rather than as an assembly. The compiler produces a module called *Stringer.netmodule*, which can be added to an assembly. -3. Compile all other modules, using the necessary compiler options to indicate the other modules that are referenced in the code. This step uses the **/addmodule** compiler option. +3. Compile all other modules, using the necessary compiler options to indicate the other modules that are referenced in the code. This step uses the `/addmodule` compiler option. In the following example, a code module called *Client* has an entry point `Main` method that references a method in the *Stringer.netmodule* module created in step 1. @@ -166,7 +166,7 @@ This article explains how to create a multifile assembly and provides code that vbc /addmodule:Stringer.netmodule /t:module Client.vb ``` - Specify the **/t:module** option because this module will be added to an assembly in a future step. Specify the **/addmodule** option because the code in *Client* references a namespace created by the code in *Stringer.netmodule*. The compiler produces a module called *Client.netmodule* that contains a reference to another module, *Stringer.netmodule*. + Specify the `/t:module` option because this module will be added to an assembly in a future step. Specify the `/addmodule` option because the code in *Client* references a namespace created by the code in *Stringer.netmodule*. The compiler produces a module called *Client.netmodule* that contains a reference to another module, *Stringer.netmodule*. > [!NOTE] > The C# and Visual Basic compilers support directly creating multifile assemblies using the following two different syntaxes. @@ -207,9 +207,9 @@ This article explains how to create a multifile assembly and provides code that At the command prompt, type the following command: - **al** \<*module name*> \<*module name*> … **/main:**\<*method name*> **/out:**\<*file name*> **/target:**\<*assembly file type*> + `al` \<*module name*> \<*module name*> … `/main:`\<*method name*> `/out:`\<*file name*> `/target:`\<*assembly file type*> - In this command, the *module name* arguments specify the name of each module to include in the assembly. The **/main:** option specifies the method name that is the assembly's entry point. The **/out:** option specifies the name of the output file, which contains assembly metadata. The **/target:** option specifies that the assembly is a console application executable (*.exe*) file, a Windows executable (*.win*) file, or a library (*.lib*) file. + In this command, the *module name* arguments specify the name of each module to include in the assembly. The `/main:` option specifies the method name that is the assembly's entry point. The `/out:` option specifies the name of the output file, which contains assembly metadata. The `/target:` option specifies that the assembly is a console application executable (*.exe*) file, a Windows executable (*.win*) file, or a library (*.lib*) file. In the following example, *Al.exe* creates an assembly that is a console application executable called *myAssembly.exe*. The application consists of two modules called *Client.netmodule* and *Stringer.netmodule*, and the executable file called *myAssembly.exe*, which contains only assembly metadata. The entry point of the assembly is the `Main` method in the class `MainClientApp`, which is located in *Client.dll*. diff --git a/docs/framework/app-domains/build-single-file-assembly.md b/docs/framework/app-domains/build-single-file-assembly.md index 97adabada1349..7440048ef0f1e 100644 --- a/docs/framework/app-domains/build-single-file-assembly.md +++ b/docs/framework/app-domains/build-single-file-assembly.md @@ -69,9 +69,9 @@ vbc -out:myAssembly.exe myCode.vb To create a library assembly, at the command prompt, type the following command: -\<*compiler command*> **-t:library** \<*module name*> +\<*compiler command*> `-t:library` \<*module name*> -In this command, *compiler command* is the compiler command for the language used in your code module, and *module name* is the name of the code module to compile into the assembly. You can also use other compiler options, such as the **-out:** option. +In this command, *compiler command* is the compiler command for the language used in your code module, and *module name* is the name of the code module to compile into the assembly. You can also use other compiler options, such as the `-out:` option. The following example creates a library assembly named *myCodeAssembly.dll* from a code module called `myCode`. diff --git a/docs/framework/app-domains/gac.md b/docs/framework/app-domains/gac.md index 0428b4d9fd2b7..8eb3813da8b49 100644 --- a/docs/framework/app-domains/gac.md +++ b/docs/framework/app-domains/gac.md @@ -21,7 +21,7 @@ Each computer where the Common Language Runtime is installed has a machine-wide You should share assemblies by installing them into the Global Assembly Cache only when you need to. As a general guideline, keep assembly dependencies private, and locate assemblies in the application directory unless sharing an assembly is explicitly required. In addition, it is not necessary to install assemblies into the Global Assembly Cache to make them accessible to COM interop or unmanaged code. > [!NOTE] -> There are scenarios where you explicitly do not want to install an assembly into the Global Assembly Cache. If you place one of the assemblies that make up an application in the Global Assembly Cache, you can no longer replicate or install the application by using the **xcopy** command to copy the application directory. You must move the assembly in the Global Assembly Cache as well. +> There are scenarios where you explicitly do not want to install an assembly into the Global Assembly Cache. If you place one of the assemblies that make up an application in the Global Assembly Cache, you can no longer replicate or install the application by using the `xcopy` command to copy the application directory. You must move the assembly in the Global Assembly Cache as well. There are two ways to deploy an assembly into the Global Assembly Cache: diff --git a/docs/framework/app-domains/how-to-configure-an-application-domain.md b/docs/framework/app-domains/how-to-configure-an-application-domain.md index c2d31e361ca86..f51a3ce32a875 100644 --- a/docs/framework/app-domains/how-to-configure-an-application-domain.md +++ b/docs/framework/app-domains/how-to-configure-an-application-domain.md @@ -15,14 +15,14 @@ ms.assetid: 07ea8438-7a34-49f0-a7e8-3d6ff7e4a482 [!INCLUDE [net-framework-specific](../includes/net-framework-specific.md)] -You can provide the common language runtime with configuration information for a new application domain using the class. When creating your own application domains, the most important property is . The other **AppDomainSetup** properties are used mainly by runtime hosts to configure a particular application domain. +You can provide the common language runtime with configuration information for a new application domain using the class. When creating your own application domains, the most important property is . The other `AppDomainSetup` properties are used mainly by runtime hosts to configure a particular application domain. - The **ApplicationBase** property defines the root directory of the application. When the runtime needs to satisfy a type request, it probes for the assembly containing the type in the directory specified by the **ApplicationBase** property. + The `ApplicationBase` property defines the root directory of the application. When the runtime needs to satisfy a type request, it probes for the assembly containing the type in the directory specified by the `ApplicationBase` property. > [!NOTE] -> A new application domain inherits only the **ApplicationBase** property of the creator. +> A new application domain inherits only the `ApplicationBase` property of the creator. - The following example creates an instance of the **AppDomainSetup** class, uses this class to create a new application domain, writes the information to console, and then unloads the application domain. + The following example creates an instance of the `AppDomainSetup` class, uses this class to create a new application domain, writes the information to console, and then unloads the application domain. ## Example diff --git a/docs/framework/app-domains/how-to-create-an-application-domain.md b/docs/framework/app-domains/how-to-create-an-application-domain.md index 4da638cc41773..599c424860af1 100644 --- a/docs/framework/app-domains/how-to-create-an-application-domain.md +++ b/docs/framework/app-domains/how-to-create-an-application-domain.md @@ -16,7 +16,7 @@ ms.assetid: ba1fa43e-49f5-47d9-bd7f-3024af16f4ba A common language runtime host creates application domains automatically when they are needed. However, you can create your own application domains and load into them those assemblies that you want to manage personally. You can also create application domains from which you execute code. - You create a new application domain using one of the overloaded **CreateDomain** methods in the class. You can give the application domain a name and reference it by that name. + You create a new application domain using one of the overloaded `CreateDomain` methods in the class. You can give the application domain a name and reference it by that name. The following example creates a new application domain, assigns it the name `MyDomain`, and then prints the name of the host domain and the newly created child application domain to the console. diff --git a/docs/framework/app-domains/how-to-unload-an-application-domain.md b/docs/framework/app-domains/how-to-unload-an-application-domain.md index 6fcf215f22cab..3244dd3b222e3 100644 --- a/docs/framework/app-domains/how-to-unload-an-application-domain.md +++ b/docs/framework/app-domains/how-to-unload-an-application-domain.md @@ -16,7 +16,7 @@ ms.assetid: f356116d-e415-4f7c-a332-6e6a60227192 [!INCLUDE [net-framework-specific](../includes/net-framework-specific.md)] -When you have finished using an application domain, unload it using the method. The **Unload** method gracefully shuts down the specified application domain. During the unloading process, no new threads can access the application domain, and all application domain–specific data structures are freed. +When you have finished using an application domain, unload it using the method. The `Unload` method gracefully shuts down the specified application domain. During the unloading process, no new threads can access the application domain, and all application domain–specific data structures are freed. Assemblies loaded into the application domain are removed and are no longer available. If an assembly in the application domain is domain-neutral, data for the assembly remains in memory until the entire process is shut down. There is no mechanism to unload a domain-neutral assembly other than shutting down the entire process. There are situations where the request to unload an application domain does not work and results in a . diff --git a/docs/framework/app-domains/index.md b/docs/framework/app-domains/index.md index d201ee7dda12e..0d8cf21391689 100644 --- a/docs/framework/app-domains/index.md +++ b/docs/framework/app-domains/index.md @@ -37,4 +37,4 @@ Provides a conceptual overview of assemblies. Provides a conceptual overview of application domains. [Reflection Overview](../../fundamentals/reflection/reflection.md)\ -Describes how to use the **Reflection** class to obtain information about an assembly. +Describes how to use the `Reflection` class to obtain information about an assembly. diff --git a/docs/framework/app-domains/retrieve-setup-information.md b/docs/framework/app-domains/retrieve-setup-information.md index 7a7e3a7a90b30..cc35064d8a51e 100644 --- a/docs/framework/app-domains/retrieve-setup-information.md +++ b/docs/framework/app-domains/retrieve-setup-information.md @@ -18,7 +18,7 @@ ms.assetid: 5cdb12ae-1e37-4a62-8ec7-93d6dcc6e8d9 Each instance of an application domain consists of both properties and information. You can retrieve setup information from an application domain using the class. This class provides several members that retrieve configuration information about an application domain. - You can also query the **AppDomainSetup** object for the application domain to obtain setup information that was passed to the domain when it was created. + You can also query the `AppDomainSetup` object for the application domain to obtain setup information that was passed to the domain when it was created. The following example creates a new application domain and then prints several member values to the console. diff --git a/docs/framework/app-domains/shadow-copy-assemblies.md b/docs/framework/app-domains/shadow-copy-assemblies.md index 0f45e6fc34492..7dd105293d0f3 100644 --- a/docs/framework/app-domains/shadow-copy-assemblies.md +++ b/docs/framework/app-domains/shadow-copy-assemblies.md @@ -71,7 +71,7 @@ When an application domain that uses shadow copying starts, there is a delay whi Beginning with the .NET Framework 4, the default startup behavior is to directly compare the file date and time of each assembly in the application directory with the file date and time of the copy in the shadow copy directory. If the assembly has been updated, it is copied by using the same procedure as in earlier versions of the .NET Framework; otherwise, the copy in the shadow copy directory is loaded. -The resulting performance improvement is largest for applications in which assemblies do not change frequently and changes usually occur in a small subset of assemblies. If a majority of assemblies in an application change frequently, the new default behavior might cause a performance regression. You can restore the startup behavior of previous versions of the .NET Framework by adding the [\ element](../configure-apps/file-schema/runtime/shadowcopyverifybytimestamp-element.md) to the configuration file, with `enabled="false"`. +The resulting performance improvement is largest for applications in which assemblies do not change frequently and changes usually occur in a small subset of assemblies. If a majority of assemblies in an application change frequently, the new default behavior might cause a performance regression. You can restore the startup behavior of previous versions of the .NET Framework by adding the [`` element](../configure-apps/file-schema/runtime/shadowcopyverifybytimestamp-element.md) to the configuration file, with `enabled="false"`. @@ -85,4 +85,4 @@ The class has several methods, such as - - -- [\ Element](../configure-apps/file-schema/runtime/shadowcopyverifybytimestamp-element.md) +- [`` Element](../configure-apps/file-schema/runtime/shadowcopyverifybytimestamp-element.md) diff --git a/docs/framework/app-domains/use.md b/docs/framework/app-domains/use.md index 3ad7740e18083..41ee28a5d6792 100644 --- a/docs/framework/app-domains/use.md +++ b/docs/framework/app-domains/use.md @@ -65,4 +65,4 @@ Describes how to create dynamic assemblies. Provides a conceptual overview of application domains. [Reflection Overview](../../fundamentals/reflection/reflection.md) -Describes how to use the **Reflection** class to obtain information about an assembly. +Describes how to use the `Reflection` class to obtain information about an assembly. diff --git a/docs/framework/configure-apps/assembly-binding-redirection-security-permission.md b/docs/framework/configure-apps/assembly-binding-redirection-security-permission.md index cd7c6a32a60eb..1200671aa5835 100644 --- a/docs/framework/configure-apps/assembly-binding-redirection-security-permission.md +++ b/docs/framework/configure-apps/assembly-binding-redirection-security-permission.md @@ -17,16 +17,16 @@ Explicit assembly binding redirection in an application configuration file requi The permission is not required if assembly redirection is performed in a publisher policy file that is controlled by the component publisher, or in the machine configuration file that is controlled by the administrator. However, the permission is required for an application to explicitly ignore publisher policy using the [\](./file-schema/runtime/publisherpolicy-element.md) element in the application configuration file. - The following table shows the default security settings for the **BindingRedirects** flag. + The following table shows the default security settings for the `BindingRedirects` flag. | Zone | BindingRedirects flag setting | |------------------------------|-------------------------------| -| Trusted Zone (local machine) | **ON** | -| Intranet Zone | **ON** | -| Internet Zone | **OFF** | -| Untrusted zones | **OFF** | +| Trusted Zone (local machine) | `ON` | +| Intranet Zone | `ON` | +| Internet Zone | `OFF` | +| Untrusted zones | `OFF` | - An administrator can change these security settings to support or restrict specific scenarios on a given computer. There are no tools for changing the **BindingRedirects** flag setting from the default; an administrator must manually edit the Security.config file on a user's computer. + An administrator can change these security settings to support or restrict specific scenarios on a given computer. There are no tools for changing the `BindingRedirects` flag setting from the default; an administrator must manually edit the Security.config file on a user's computer. ## See also diff --git a/docs/framework/configure-apps/file-schema/add-element-for-custom-2.md b/docs/framework/configure-apps/file-schema/add-element-for-custom-2.md index da54dd666ac7b..3e31d5f16198b 100644 --- a/docs/framework/configure-apps/file-schema/add-element-for-custom-2.md +++ b/docs/framework/configure-apps/file-schema/add-element-for-custom-2.md @@ -2,16 +2,16 @@ description: "Learn more about: element for NameValueSectionHandler and DictionarySectionHandler" title: " element for NameValueSectionHandler and DictionarySectionHandler" ms.date: "05/01/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/sectionName/add" -helpviewer_keywords: +helpviewer_keywords: - "add Element" - " Element" ms.assetid: 0d4ddb53-eb2b-49c0-9c33-a8dec5c39b46 --- -# \ element for NameValueSectionHandler and DictionarySectionHandler +# `` element for NameValueSectionHandler and DictionarySectionHandler -Adds custom application settings. Each **\** tag contains a key/value pair. +Adds custom application settings. Each `` tag contains a key/value pair. [**\**](configuration-element.md)\   [**\**](custom-element-2.md)\ @@ -27,14 +27,14 @@ Adds custom application settings. Each **\** tag contains a key/value pair. | Attribute | Description | | --------- | ----------- | -| **key** | Required attribute.

Specifies the name of the setting. | -| **value** | Required attribute.

Specifies the value of the setting. | +| `key` | Required attribute.

Specifies the name of the setting. | +| `value` | Required attribute.

Specifies the value of the setting. | ## Parent element | Element | Description | | ------- | ------------| -| [**\** Element](custom-element-2.md) | Defines settings for custom configuration sections that use the and classes. | +| [`` Element](custom-element-2.md) | Defines settings for custom configuration sections that use the and classes. | ## Child elements @@ -42,7 +42,7 @@ None ## Example -The following example shows how to define a custom configuration section and use the **\** element to put settings into the section: +The following example shows how to define a custom configuration section and use the `` element to put settings into the section: ```xml diff --git a/docs/framework/configure-apps/file-schema/application-settings-schema.md b/docs/framework/configure-apps/file-schema/application-settings-schema.md index 4ae4bf07540ac..ffb83d2cb1aef 100644 --- a/docs/framework/configure-apps/file-schema/application-settings-schema.md +++ b/docs/framework/configure-apps/file-schema/application-settings-schema.md @@ -2,7 +2,7 @@ description: "Learn more about: Application Settings schema" title: "Application Settings schema" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "schema application settings" - "application settings, schema [Windows Forms]" - "Windows Forms, application settings schema" @@ -25,29 +25,29 @@ Application settings defines the following elements as part of the configuration | Element | Description | | -------------------------- | ------------------------------------------------------------------------------------- | -| **\** | Contains all **\** tags specific to the application. | -| **\** | Contains all **\** tags specific to the current user. | -| **\** | Defines a setting. Child of either **\** or **\**. | -| **\** | Defines a setting's value. Child of **\**. | +| `` | Contains all `` tags specific to the application. | +| `` | Contains all `` tags specific to the current user. | +| `` | Defines a setting. Child of either `` or ``. | +| `` | Defines a setting's value. Child of ``. | -## \ element +## `` element -This element contains all **\** tags that are specific to an instance of the application on a client computer. It defines no attributes. +This element contains all `` tags that are specific to an instance of the application on a client computer. It defines no attributes. -## \ element +## `` element -This element contains all **\** tags that are specific to the user who is currently using the application. It defines no attributes. +This element contains all `` tags that are specific to the user who is currently using the application. It defines no attributes. -## \ element +## `` element This element defines a setting. It has the following attributes. | Attribute | Description | | ---------------- | ----------- | -| **name** | Required. The unique ID of the setting. Settings created through Visual Studio are saved with the name `ProjectName.Properties.Settings`. | -| **serializeAs** | Required. The format to use for serializing the value to text. Valid values are:

- `string`. The value is serialized as a string using a .
- `xml`. The value is serialized using XML serialization.
- `binary`. The value is serialized as text-encoded binary using binary serialization.
- `custom`. The settings provider has inherent knowledge of this setting and serializes and de-serializes it. | +| `name` | Required. The unique ID of the setting. Settings created through Visual Studio are saved with the name `ProjectName.Properties.Settings`. | +| `serializeAs` | Required. The format to use for serializing the value to text. Valid values are:

- `string`. The value is serialized as a string using a .
- `xml`. The value is serialized using XML serialization.
- `binary`. The value is serialized as text-encoded binary using binary serialization.
- `custom`. The settings provider has inherent knowledge of this setting and serializes and de-serializes it. | -Add the names for settings that you create in **\** as entries under the **\** element at the top of the file. For example: +Add the names for settings that you create in `` as entries under the `` element at the top of the file. For example: ```xml @@ -61,7 +61,7 @@ Add the names for settings that you create in **\** as entr ``` -## \ element +## `` element This element contains the value of a setting. diff --git a/docs/framework/configure-apps/file-schema/appsettings/add-element-for-appsettings.md b/docs/framework/configure-apps/file-schema/appsettings/add-element-for-appsettings.md index ac48607c925c9..567d5dc5ac878 100644 --- a/docs/framework/configure-apps/file-schema/appsettings/add-element-for-appsettings.md +++ b/docs/framework/configure-apps/file-schema/appsettings/add-element-for-appsettings.md @@ -2,14 +2,14 @@ description: "Learn more about: element for " title: " element for " ms.date: "05/01/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/appSettings/add" -helpviewer_keywords: +helpviewer_keywords: - "add Element" - " Element" ms.assetid: 8734efdc-00f6-4a65-bba6-084c5bc65246 --- -# \ element for \ +# `` element for \ Adds a custom application setting. @@ -29,8 +29,8 @@ Adds a custom application setting. | | Description | | --------- | ----------- | -| **key** | Required attribute.

Specifies the name of the key to add. | -| **value** | Required attribute.

Specifies the value of the key to add. | +| `key` | Required attribute.

Specifies the name of the key to add. | +| `value` | Required attribute.

Specifies the value of the key to add. | ## Parent element diff --git a/docs/framework/configure-apps/file-schema/appsettings/appsettings-element-for-configuration.md b/docs/framework/configure-apps/file-schema/appsettings/appsettings-element-for-configuration.md index 3b9d8df0ede22..4f69e3b78abd8 100644 --- a/docs/framework/configure-apps/file-schema/appsettings/appsettings-element-for-configuration.md +++ b/docs/framework/configure-apps/file-schema/appsettings/appsettings-element-for-configuration.md @@ -9,7 +9,7 @@ helpviewer_keywords: - " Element" ms.assetid: 39694cc4-6b84-45a6-9329-385a0d8b48fe --- -# \ element for \ +# `` element for \ Contains custom application settings. This is a predefined configuration section provided by the .NET Framework. @@ -28,13 +28,13 @@ Contains custom application settings. This is a predefined configuration section | | Description | | --------- | ----------- | -| **file** | Optional attribute.

Specifies a relative path to an external file containing custom application configuration settings. The specified file contains the same kind of settings that are specified in the **\**, **\**, and **\** elements and uses the same key/value pair format as those elements.

The path specified is relative to the main configuration file. For a Windows Forms application, this is the binary folder (such as */bin/debug*), not the location of the application configuration file. For Web Forms applications, the path is relative to the application root, where the *web.config* file is located.

The runtime ignores the attribute if the specified file can't be found. | +| `file` | Optional attribute.

Specifies a relative path to an external file containing custom application configuration settings. The specified file contains the same kind of settings that are specified in the ``, ``, and `` elements and uses the same key/value pair format as those elements.

The path specified is relative to the main configuration file. For a Windows Forms application, this is the binary folder (such as */bin/debug*), not the location of the application configuration file. For Web Forms applications, the path is relative to the application root, where the *web.config* file is located.

The runtime ignores the attribute if the specified file can't be found. | ## Parent element | | Description | | --- | ----------- | -| [**\** Element](../configuration-element.md) | The root element in every configuration file used by the common language runtime and .NET Framework applications. | +| [`` Element](../configuration-element.md) | The root element in every configuration file used by the common language runtime and .NET Framework applications. | ## Child elements @@ -46,11 +46,11 @@ Contains custom application settings. This is a predefined configuration section ## Remarks -The **\** element stores custom application configuration information, such as database connection strings, file paths, XML Web service URLs, or any other custom configuration information for an application. The key/value pairs specified in the **\** element are accessed in code using the class. +The `` element stores custom application configuration information, such as database connection strings, file paths, XML Web service URLs, or any other custom configuration information for an application. The key/value pairs specified in the `` element are accessed in code using the class. -You can use the **file** attribute in the **\** element of the *Web.config* and application configuration files. This attribute specifies a configuration file that provides additional settings or overrides the settings specified in the **\** element. The **file** attribute can be used in source control team development scenarios, such as when a user wants to override the project settings specified in an application configuration file. +You can use the `file` attribute in the `` element of the *Web.config* and application configuration files. This attribute specifies a configuration file that provides additional settings or overrides the settings specified in the `` element. The `file` attribute can be used in source control team development scenarios, such as when a user wants to override the project settings specified in an application configuration file. -Configuration files specified by the **file** attribute must have a root node of **\** rather than **\**. +Configuration files specified by the `file` attribute must have a root node of `` rather than ``. ## Example diff --git a/docs/framework/configure-apps/file-schema/appsettings/clear-element-for-appsettings.md b/docs/framework/configure-apps/file-schema/appsettings/clear-element-for-appsettings.md index b2f951e16a6af..1dc4dd2d21122 100644 --- a/docs/framework/configure-apps/file-schema/appsettings/clear-element-for-appsettings.md +++ b/docs/framework/configure-apps/file-schema/appsettings/clear-element-for-appsettings.md @@ -2,14 +2,14 @@ description: "Learn more about: element for " title: " element for " ms.date: "05/01/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/appSettings/clear" -helpviewer_keywords: +helpviewer_keywords: - "clear Element" - " Element" ms.assetid: 6d18c7be-27db-438b-8fb5-765d396b0b7b --- -# \ element for \ +# `` element for \ Clears custom application settings. diff --git a/docs/framework/configure-apps/file-schema/appsettings/index.md b/docs/framework/configure-apps/file-schema/appsettings/index.md index a5f4221f902f6..d7c359a3b4f9c 100644 --- a/docs/framework/configure-apps/file-schema/appsettings/index.md +++ b/docs/framework/configure-apps/file-schema/appsettings/index.md @@ -2,7 +2,7 @@ description: "Learn more about: App Settings schema" title: "App Settings schema" ms.date: "05/01/2017" -helpviewer_keywords: +helpviewer_keywords: - "schema app settings" - "app settings, schema [Windows Forms]" - "Windows Forms, app settings schema" @@ -21,24 +21,24 @@ Contains custom application settings, such as file paths, XML Web service URLs, | Element | Description | | ------- | ----------- | -| [**\**](appsettings-element-for-configuration.md) | Contains **\**, **\**, and **\** tags to control application settings. Has an optional **file** attribute. | -| [**\**](add-element-for-appsettings.md) | Defines a setting. Child of **\**. Requires **key** and **value** attributes. | -| [**\**](clear-element-for-appsettings.md) | Clears all settings. Child of **\**. Has no attributes. | -| [**\**](remove-element-for-appsettings.md) | Removes a setting. Child of **\**. Requires a **key** attribute. | +| [**\**](appsettings-element-for-configuration.md) | Contains ``, ``, and `` tags to control application settings. Has an optional `file` attribute. | +| [**\**](add-element-for-appsettings.md) | Defines a setting. Child of ``. Requires `key` and `value` attributes. | +| [**\**](clear-element-for-appsettings.md) | Clears all settings. Child of ``. Has no attributes. | +| [**\**](remove-element-for-appsettings.md) | Removes a setting. Child of ``. Requires a `key` attribute. | -## \ element +## `` element -This element contains **\**, **\**, and **\** tags to control application settings. It defines an optional attribute for **file**. +This element contains ``, ``, and `` tags to control application settings. It defines an optional attribute for **file**. -## \ element +## `` element -Adds a custom application setting as a name/value pair to the application settings collection. It defines attributes for **key** and **value**. +Adds a custom application setting as a name/value pair to the application settings collection. It defines attributes for `key` and **value**. -## \ element +## `` element -Removes all references to inherited custom application settings and allows only the references that are added by **\** elements following the **\** element. It defines no attributes. +Removes all references to inherited custom application settings and allows only the references that are added by `` elements following the `` element. It defines no attributes. -## \ element +## `` element Removes a reference to an inherited custom application setting from the application settings collection. It defines an attribute for **key**. diff --git a/docs/framework/configure-apps/file-schema/appsettings/remove-element-for-appsettings.md b/docs/framework/configure-apps/file-schema/appsettings/remove-element-for-appsettings.md index c85c8c22c07d7..8c6f8de351461 100644 --- a/docs/framework/configure-apps/file-schema/appsettings/remove-element-for-appsettings.md +++ b/docs/framework/configure-apps/file-schema/appsettings/remove-element-for-appsettings.md @@ -2,14 +2,14 @@ description: "Learn more about: element for " title: " element for " ms.date: "05/01/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/appSettings/remove" -helpviewer_keywords: +helpviewer_keywords: - "remove Element" - " Element" ms.assetid: 218c4464-e007-4539-803f-7c8b0a909fd8 --- -# \ element for \ +# `` element for `` Removes custom application settings. @@ -29,7 +29,7 @@ Removes custom application settings. | | Description | | ------- | ----------- | -| **key** | Required attribute.

Specifies the name of the key to remove. | +| `key` | Required attribute.

Specifies the name of the key to remove. | ### Parent element diff --git a/docs/framework/configure-apps/file-schema/assemblybinding-element-for-configuration.md b/docs/framework/configure-apps/file-schema/assemblybinding-element-for-configuration.md index e20a6c75b046a..d620473a1f936 100644 --- a/docs/framework/configure-apps/file-schema/assemblybinding-element-for-configuration.md +++ b/docs/framework/configure-apps/file-schema/assemblybinding-element-for-configuration.md @@ -2,15 +2,15 @@ description: "Learn more about: element for " title: " element for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/assemblyBinding" -helpviewer_keywords: +helpviewer_keywords: - "assemblyBinding Element" - " Element" ms.assetid: 6cc55983-b894-449b-8e26-b258e53939cd --- -# \ element for \ +# `` element for \ Specifies assembly binding policy at the configuration level. @@ -29,7 +29,7 @@ Specifies assembly binding policy at the configuration level. | | Description | | --------- | ----------- | -| **xmlns** | Required attribute.

Specifies the XML namespace required for assembly binding. Use the string "urn:schemas-microsoft-com:asm.v1" as the value. | +| `xmlns` | Required attribute.

Specifies the XML namespace required for assembly binding. Use the string "urn:schemas-microsoft-com:asm.v1" as the value. | ## Parent element @@ -48,7 +48,7 @@ Specifies assembly binding policy at the configuration level. The [**\**](linkedconfiguration-element.md) element simplifies the management of component assemblies by allowing application configuration files to include assembly configuration files in well-known locations, rather than duplicating assembly configuration settings. > [!NOTE] -> The **\** element is not supported for applications with Windows side-by-side manifests. +> The `` element is not supported for applications with Windows side-by-side manifests. ## Example diff --git a/docs/framework/configure-apps/file-schema/clear-element-for-custom-2.md b/docs/framework/configure-apps/file-schema/clear-element-for-custom-2.md index 5fa930ddd7692..ebe69e619842d 100644 --- a/docs/framework/configure-apps/file-schema/clear-element-for-custom-2.md +++ b/docs/framework/configure-apps/file-schema/clear-element-for-custom-2.md @@ -2,14 +2,14 @@ description: "Learn more about: element for NameValueSectionHandler and DictionarySectionHandler" title: " element for NameValueSectionHandler and DictionarySectionHandler" ms.date: "05/01/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/sectionName/clear" -helpviewer_keywords: +helpviewer_keywords: - "clear Element" - " Element" ms.assetid: ff2294ec-fb82-4b0c-933e-ae185433fc7b --- -# \ element for NameValueSectionHandler and DictionarySectionHandler +# `` element for NameValueSectionHandler and DictionarySectionHandler Clears all previously defined settings in a section. @@ -31,7 +31,7 @@ None | | Description | | --- | ------------| -| [**\** Element](custom-element-2.md) | Defines settings for custom configuration sections that use the and classes. | +| [`` Element](custom-element-2.md) | Defines settings for custom configuration sections that use the and classes. | ## Child elements @@ -39,13 +39,13 @@ None ## Remarks -You can use the **\** element to remove all settings from your application that were defined at a higher level in the configuration file hierarchy. +You can use the `` element to remove all settings from your application that were defined at a higher level in the configuration file hierarchy. ## Example -This example defines a machine configuration file and an application configuration file and shows how to use the **\** element in an application configuration file to clear sections previously defined in the machine configuration file. +This example defines a machine configuration file and an application configuration file and shows how to use the `` element in an application configuration file to clear sections previously defined in the machine configuration file. -The following machine configuration file code declares the section **\**: +The following machine configuration file code declares the section ``: ```xml @@ -60,7 +60,7 @@ The following machine configuration file code declares the section **\ ``` -The following application configuration file code removes all settings from **\**. The application cannot retrieve any of the settings that were declared in the in the **\** section of the machine configuration file. +The following application configuration file code removes all settings from ``. The application cannot retrieve any of the settings that were declared in the in the `` section of the machine configuration file. ```xml diff --git a/docs/framework/configure-apps/file-schema/compiler/compiler-element.md b/docs/framework/configure-apps/file-schema/compiler/compiler-element.md index 4f2afc034af48..9934c43d7f753 100644 --- a/docs/framework/configure-apps/file-schema/compiler/compiler-element.md +++ b/docs/framework/configure-apps/file-schema/compiler/compiler-element.md @@ -12,7 +12,7 @@ helpviewer_keywords: - "compiler element" ms.assetid: 7a151659-b803-4c27-b5ce-1c4aa0d5a823 --- -# \ Element +# `` Element Specifies the compiler configuration attributes for a language provider. @@ -100,6 +100,6 @@ The following example illustrates a typical compiler configuration element: - - - [Configuration File Schema](../index.md) -- [\ Element](compilers-element.md) +- [`` Element](compilers-element.md) - [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md) - [compiler Element for compilers for compilation (ASP.NET Settings Schema)](/previous-versions/dotnet/netframework-4.0/a15ebt6c(v=vs.100)) diff --git a/docs/framework/configure-apps/file-schema/compiler/compilers-element.md b/docs/framework/configure-apps/file-schema/compiler/compilers-element.md index fc69627834b92..9be5fdfc0a881 100644 --- a/docs/framework/configure-apps/file-schema/compiler/compilers-element.md +++ b/docs/framework/configure-apps/file-schema/compiler/compilers-element.md @@ -2,86 +2,86 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#compilers" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.codedom/compilers" -helpviewer_keywords: +helpviewer_keywords: - "compiler configuration elements, element" - " element" - "compilers element" ms.assetid: d40fba59-98f9-4783-ae0c-2ebea27ce77b --- -# \ Element +# `` Element -Container for compiler configuration elements; contains zero or more [\](compiler-element.md) elements. +Container for compiler configuration elements; contains zero or more [\](compiler-element.md) elements. [**\**](../configuration-element.md)\   [**\**](system-codedom-element.md)\     **\** -## Syntax - -```xml - - - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\ Element](compiler-element.md)|Specifies the compiler configuration attributes for a language provider.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\ Element](../configuration-element.md)|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|[\ Element](system-codedom-element.md)|Specifies compiler configuration settings for available language providers.| - -## Remarks - - The [\](compilers-element.md) element contains the compiler configuration settings for language providers on a computer. Each [\](compiler-element.md) element specifies the compiler configuration attributes for a specific language provider. - - The .NET Framework defines the initial compiler and language provider settings in the machine configuration file (Machine.config). Developers and compiler vendors can add configuration settings for a new implementation. Use the method to programmatically enumerate language provider and compiler configuration settings on a computer. - -## Configuration File - - This element can be used in the machine configuration file and the application configuration file. - -## Example - - The following example illustrates a typical compiler configuration element. - -```xml - - - - +## Syntax + +```xml + + + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\ Element](compiler-element.md)|Specifies the compiler configuration attributes for a language provider.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\ Element](../configuration-element.md)|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|[\ Element](system-codedom-element.md)|Specifies compiler configuration settings for available language providers.| + +## Remarks + + The [\](compilers-element.md) element contains the compiler configuration settings for language providers on a computer. Each [\](compiler-element.md) element specifies the compiler configuration attributes for a specific language provider. + + The .NET Framework defines the initial compiler and language provider settings in the machine configuration file (Machine.config). Developers and compiler vendors can add configuration settings for a new implementation. Use the method to programmatically enumerate language provider and compiler configuration settings on a computer. + +## Configuration File + + This element can be used in the machine configuration file and the application configuration file. + +## Example + + The following example illustrates a typical compiler configuration element. + +```xml + + + + - - - -``` - + warningLevel="1" /> + + + +``` + ## See also - - - [Configuration File Schema](../index.md) - [Compiler and Language Provider Settings Schema](index.md) -- [\ Element](compiler-element.md) +- [`` Element](compiler-element.md) diff --git a/docs/framework/configure-apps/file-schema/compiler/index.md b/docs/framework/configure-apps/file-schema/compiler/index.md index 998a915777bfa..e0157d43270ba 100644 --- a/docs/framework/configure-apps/file-schema/compiler/index.md +++ b/docs/framework/configure-apps/file-schema/compiler/index.md @@ -2,7 +2,7 @@ description: "Learn more about: Compiler and Language Provider Settings Schema" title: "Compiler and Language Provider Settings Schema" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "configuration settings [.NET Framework], compilers" - "compiler configuration elements, schema" - "compiler configuration elements" @@ -15,44 +15,44 @@ ms.assetid: c020b139-8699-4f0d-9ac9-70d0c5b2a8c8 --- # Compiler and Language Provider Settings Schema -Compiler and language provider settings specify compiler configuration elements for available language providers. Each compiler configuration element specifies the code provider type name, compiler parameters, supported language names, and supported file extensions. - -The .NET Framework defines the initial compiler settings in the machine configuration file (Machine.config). Developers and compiler vendors can add configuration settings for a new implementation. Use the method to programmatically enumerate language provider and compiler configuration settings on a computer. - +Compiler and language provider settings specify compiler configuration elements for available language providers. Each compiler configuration element specifies the code provider type name, compiler parameters, supported language names, and supported file extensions. + +The .NET Framework defines the initial compiler settings in the machine configuration file (Machine.config). Developers and compiler vendors can add configuration settings for a new implementation. Use the method to programmatically enumerate language provider and compiler configuration settings on a computer. + [**\**](../configuration-element.md)\   [**\**](system-codedom-element.md)\     [**\**](compilers-element.md)\       [**\**](compiler-element.md) - -|Element|Description| -|-------------|-----------------| -|[\](system-codedom-element.md)|Specifies compiler configuration settings for available language providers.| -|[\](compilers-element.md)|Container for compiler configuration elements; contains zero or more [\](compiler-element.md) elements.| -|[\](compiler-element.md)|Specifies the compiler configuration attributes for a language provider.| - -## Example - - The following example illustrates a typical compiler configuration element. - -```xml - - - - - - - - -``` - + +|Element|Description| +|-------------|-----------------| +|[\](system-codedom-element.md)|Specifies compiler configuration settings for available language providers.| +|[\](compilers-element.md)|Container for compiler configuration elements; contains zero or more [\](compiler-element.md) elements.| +|[\](compiler-element.md)|Specifies the compiler configuration attributes for a language provider.| + +## Example + + The following example illustrates a typical compiler configuration element. + +```xml + + + + + + + + +``` + ## See also - - - [Configuration File Schema](../index.md) -- [\ Element](compiler-element.md) +- [`` Element](compiler-element.md) diff --git a/docs/framework/configure-apps/file-schema/compiler/provideroption-element.md b/docs/framework/configure-apps/file-schema/compiler/provideroption-element.md index 02fc301ae2989..49e1a95d11797 100644 --- a/docs/framework/configure-apps/file-schema/compiler/provideroption-element.md +++ b/docs/framework/configure-apps/file-schema/compiler/provideroption-element.md @@ -2,17 +2,17 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "provideroption" -helpviewer_keywords: +helpviewer_keywords: - " element" - "providerOptions" - "provideroption element" ms.assetid: 014f2e0b-c0b5-4fc4-92d3-73f02978b2a1 --- -# \ Element +# `` Element -Specifies the compiler version attributes for a language provider. +Specifies the compiler version attributes for a language provider. [**\**](../configuration-element.md)\   [**\**](system-codedom-element.md)\ @@ -20,80 +20,80 @@ Specifies the compiler version attributes for a language provider.       [**\**](compiler-element.md)\         **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`name`|Required attribute.

Specifies the name of the option; for example, "CompilerVersion".| -|`value`|Required attribute.

Specifies the value for the option; for example, "v3.5".| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\ Element](../configuration-element.md)|The root element in every configuration file that is used by the common language runtime and .NET Framework applications.| -|[\ Element](system-codedom-element.md)|Specifies compiler configuration settings for available language providers.| -|[\ Element](compilers-element.md)|Container for compiler configuration elements; contains zero or more `` elements.| -|[\ Element](compiler-element.md)|Specifies the compiler configuration attributes for a language provider.| - -## Remarks - - In .NET Framework version 3.5, Code Document Object Model (CodeDOM) code providers can support provider-specific options by using the `` element. - - The .NET Framework 3.5 includes updated .NET Framework 2.0 assemblies and provides new version 3.5 assemblies that contain new types. The Microsoft C# and Visual Basic code providers are contained in .NET Framework 2.0 assemblies but have been updated to support version 3.5 compilers. By default, the updated code providers generate code for version 2.0 compilers. You can use the `` element to change the target compiler version to 3.5. To do this, specify "CompilerVersion" for the `name` attribute and "v3.5" for the `value` attribute. You must precede the version number with a lower-case "v". - - You can make the version specification global by adding the `` element to the .NET Framework 2.0 Machine.config or root Web.config file. If you update the default compiler version to 3.5 in the Machine.config file, you can change it back to 2.0 on a per-application basis by using the `` element in the application configuration file. - - CodeDOM code provider implementers can process custom options by providing a constructor that takes a `providerOptions` parameter of type . - -## Example - - The following example demonstrates how to specify that version 3.5 of the C# code provider should be used. - -```xml - - - - - +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`name`|Required attribute.

Specifies the name of the option; for example, "CompilerVersion".| +|`value`|Required attribute.

Specifies the value for the option; for example, "v3.5".| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\ Element](../configuration-element.md)|The root element in every configuration file that is used by the common language runtime and .NET Framework applications.| +|[\ Element](system-codedom-element.md)|Specifies compiler configuration settings for available language providers.| +|[\ Element](compilers-element.md)|Container for compiler configuration elements; contains zero or more `` elements.| +|[\ Element](compiler-element.md)|Specifies the compiler configuration attributes for a language provider.| + +## Remarks + + In .NET Framework version 3.5, Code Document Object Model (CodeDOM) code providers can support provider-specific options by using the `` element. + + The .NET Framework 3.5 includes updated .NET Framework 2.0 assemblies and provides new version 3.5 assemblies that contain new types. The Microsoft C# and Visual Basic code providers are contained in .NET Framework 2.0 assemblies but have been updated to support version 3.5 compilers. By default, the updated code providers generate code for version 2.0 compilers. You can use the `` element to change the target compiler version to 3.5. To do this, specify "CompilerVersion" for the `name` attribute and "v3.5" for the `value` attribute. You must precede the version number with a lower-case "v". + + You can make the version specification global by adding the `` element to the .NET Framework 2.0 Machine.config or root Web.config file. If you update the default compiler version to 3.5 in the Machine.config file, you can change it back to 2.0 on a per-application basis by using the `` element in the application configuration file. + + CodeDOM code provider implementers can process custom options by providing a constructor that takes a `providerOptions` parameter of type . + +## Example + + The following example demonstrates how to specify that version 3.5 of the C# code provider should be used. + +```xml + + + + + - - - - - -``` - + PublicKeyToken=b77a5c561934e089" + compilerOptions="/optimize" + warningLevel="1" > + + + + + +``` + ## See also - - - [Configuration File Schema](../index.md) -- [\ Element](compilers-element.md) +- [`` Element](compilers-element.md) - [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md) - [compiler Element for compilers for compilation (ASP.NET Settings Schema)](/previous-versions/dotnet/netframework-4.0/a15ebt6c(v=vs.100)) diff --git a/docs/framework/configure-apps/file-schema/compiler/system-codedom-element.md b/docs/framework/configure-apps/file-schema/compiler/system-codedom-element.md index 4190d12a10421..7de088b65eee5 100644 --- a/docs/framework/configure-apps/file-schema/compiler/system-codedom-element.md +++ b/docs/framework/configure-apps/file-schema/compiler/system-codedom-element.md @@ -2,97 +2,97 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.codedom" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#system.codedom" -helpviewer_keywords: +helpviewer_keywords: - "compiler configuration elements, element" - "system.codedom element" - " element" ms.assetid: 672a68f7-e69f-4479-ac30-e980085ec4fe --- -# \ Element - -Specifies compiler configuration settings for available language providers. - -[**\**](../configuration-element.md) -  **\** - -## Syntax - -```xml - - ... - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](compilers-element.md)|Container for compiler configuration elements; contains zero or more [\](compiler-element.md) elements.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](../configuration-element.md)|The root element in every configuration file used by the common language runtime and .NET Framework applications.| - -## Remarks - -## .NET Framework Version 2.0 - - The [\](system-codedom-element.md) element contains compiler configuration settings for language providers installed on a computer in addition to the default providers that are installed with the .NET Framework, such as the and the . The [\](compilers-element.md) element contains zero or more [\](compiler-element.md) elements. Each [\](compiler-element.md) element specifies the compiler configuration attributes for a specific language provider. - - Developers and compiler vendors can add configuration settings to the machine configuration file (Machine.config) for a new implementation. Use the method to programmatically enumerate both the default language providers and language providers identified by the compiler configuration settings on a computer. - +# `` Element + +Specifies compiler configuration settings for available language providers. + +[**\**](../configuration-element.md) +  **\** + +## Syntax + +```xml + + ... + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](compilers-element.md)|Container for compiler configuration elements; contains zero or more [\](compiler-element.md) elements.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](../configuration-element.md)|The root element in every configuration file used by the common language runtime and .NET Framework applications.| + +## Remarks + +## .NET Framework Version 2.0 + + The [\](system-codedom-element.md) element contains compiler configuration settings for language providers installed on a computer in addition to the default providers that are installed with the .NET Framework, such as the and the . The [\](compilers-element.md) element contains zero or more [\](compiler-element.md) elements. Each [\](compiler-element.md) element specifies the compiler configuration attributes for a specific language provider. + + Developers and compiler vendors can add configuration settings to the machine configuration file (Machine.config) for a new implementation. Use the method to programmatically enumerate both the default language providers and language providers identified by the compiler configuration settings on a computer. + > [!NOTE] -> In the .NET Framework versions 1.0 and 1.1, the default language providers supplied by the .NET Framework are identified in the [\](compilers-element.md) element. In .NET Framework version 2.0, the default language providers are not identified in the [\](compilers-element.md) element, but can be enumerated using the method. - -## .NET Framework Versions 1.0 and 1.1 - - The [\](system-codedom-element.md) element contains the compiler configuration settings for language providers on a computer. The [\](compilers-element.md) element contains zero or more [\](compiler-element.md) elements. Each [\](compiler-element.md) element specifies the compiler configuration attributes for a specific language provider. - - The .NET Framework defines the initial compiler settings in the machine configuration file (Machine.config). Developers and compiler vendors can add configuration settings for a new implementation. Use the method to programmatically enumerate language provider and compiler configuration settings on a computer. - -## Configuration File - - This element can be used in the machine configuration file and the application configuration file. - -## Example - - The following example illustrates a typical compiler configuration. - -```xml - - - - +> In the .NET Framework versions 1.0 and 1.1, the default language providers supplied by the .NET Framework are identified in the [\](compilers-element.md) element. In .NET Framework version 2.0, the default language providers are not identified in the [\](compilers-element.md) element, but can be enumerated using the method. + +## .NET Framework Versions 1.0 and 1.1 + + The [\](system-codedom-element.md) element contains the compiler configuration settings for language providers on a computer. The [\](compilers-element.md) element contains zero or more [\](compiler-element.md) elements. Each [\](compiler-element.md) element specifies the compiler configuration attributes for a specific language provider. + + The .NET Framework defines the initial compiler settings in the machine configuration file (Machine.config). Developers and compiler vendors can add configuration settings for a new implementation. Use the method to programmatically enumerate language provider and compiler configuration settings on a computer. + +## Configuration File + + This element can be used in the machine configuration file and the application configuration file. + +## Example + + The following example illustrates a typical compiler configuration. + +```xml + + + + - - - -``` - + PublicKeyToken=b77a5c561934e089" + compilerOptions="" + warningLevel="1" /> + + + +``` + ## See also - - - [Configuration File Schema](../index.md) - [Compiler and Language Provider Settings Schema](index.md) -- [\ Element](compiler-element.md) +- [`` Element](compiler-element.md) diff --git a/docs/framework/configure-apps/file-schema/configsections-element-for-configuration.md b/docs/framework/configure-apps/file-schema/configsections-element-for-configuration.md index 01ccbf457c0b4..0eaff26de8861 100644 --- a/docs/framework/configure-apps/file-schema/configsections-element-for-configuration.md +++ b/docs/framework/configure-apps/file-schema/configsections-element-for-configuration.md @@ -2,14 +2,14 @@ description: "Learn more about: element for " title: " element for " ms.date: "05/01/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/configSections" -helpviewer_keywords: +helpviewer_keywords: - "configSections Element" - " Element" ms.assetid: 9f963c1b-dc3f-4220-a8b6-2dd7a5a8e039 --- -# \ element for \ +# `` element for `` Contains configuration section and namespace declarations. @@ -35,7 +35,7 @@ None ## Remarks -If this element is in a configuration file, it must be the first child element of the **\** element. +If this element is in a configuration file, it must be the first child element of the `` element. ## Example diff --git a/docs/framework/configure-apps/file-schema/configuration-element.md b/docs/framework/configure-apps/file-schema/configuration-element.md index fcb8121a9d40a..eea6f30ca77a8 100644 --- a/docs/framework/configure-apps/file-schema/configuration-element.md +++ b/docs/framework/configure-apps/file-schema/configuration-element.md @@ -2,16 +2,16 @@ description: "Learn more about: element" title: " element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration" -helpviewer_keywords: +helpviewer_keywords: - " element" - "configuration element" - "container tags, element" ms.assetid: 2ec1c9dc-2e5c-4ef0-9958-81670ab88449 --- -# \ element +# `` element The root element in every configuration file used by the common language runtime and .NET Framework applications. @@ -38,20 +38,20 @@ None | Element | Description | | --- | ----------- | | [**\**](assemblybinding-element-for-configuration.md) | Specifies assembly binding policy at the configuration level.| -| [**\** Settings Schema](./startup/index.md) | All elements in the startup settings schema. | -| [**\** Settings Schema](./runtime/index.md) | All elements in the runtime settings schema. | -| [**\** Settings Schema](/previous-versions/dotnet/netframework-4.0/z415cf9a(v=vs.100)) | All elements in the remoting settings schema. | -| [**\** Settings Schema](./network/index.md) | All elements in the network settings schema. | -| [**\** Settings Schema](./cryptography/index.md) | All elements in the crypto settings schema. | -| [**\** Sections Schema](configuration-sections-schema.md) | All elements in the configuration section settings schema. | +| [`` Settings Schema](./startup/index.md) | All elements in the startup settings schema. | +| [`` Settings Schema](./runtime/index.md) | All elements in the runtime settings schema. | +| [`` Settings Schema](/previous-versions/dotnet/netframework-4.0/z415cf9a(v=vs.100)) | All elements in the remoting settings schema. | +| [`` Settings Schema](./network/index.md) | All elements in the network settings schema. | +| [`` Settings Schema](./cryptography/index.md) | All elements in the crypto settings schema. | +| [`` Sections Schema](configuration-sections-schema.md) | All elements in the configuration section settings schema. | | [Trace and Debug Settings Schema](./trace-debug/index.md) | All elements in the trace and debug settings schema. | | [ASP.NET Configuration Settings Schema](/previous-versions/dotnet/netframework-4.0/b5ysx397(v=vs.100)) | All elements in the ASP.NET configuration schema, which includes elements for configuring ASP.NET Web sites and applications. Used in *Web.config* files. | -| [**\** Settings Schema](/previous-versions/dotnet/netframework-4.0/cctwteet(v=vs.100)) | All elements in the Web services settings schema. | +| [`` Settings Schema](/previous-versions/dotnet/netframework-4.0/cctwteet(v=vs.100)) | All elements in the Web services settings schema. | | [Web Settings Schema](./web/index.md) | All elements in the Web settings schema, which includes elements for configuring how ASP.NET works with a host application such as IIS. Used in *aspnet.config* files. | ## Remarks -Each configuration file must contain exactly one **\** element. +Each configuration file must contain exactly one `` element. ## See also diff --git a/docs/framework/configure-apps/file-schema/configuration-sections-schema.md b/docs/framework/configure-apps/file-schema/configuration-sections-schema.md index 510b7eaf1091f..d3973fee0340a 100644 --- a/docs/framework/configure-apps/file-schema/configuration-sections-schema.md +++ b/docs/framework/configure-apps/file-schema/configuration-sections-schema.md @@ -2,7 +2,7 @@ description: "Learn more about: Configuration sections schema" title: "Configuration sections schema" ms.date: "05/02/2017" -helpviewer_keywords: +helpviewer_keywords: - "configuration settings [.NET Framework], custom" - "schema configuration settings" - "configuration sections [.NET Framework]" @@ -23,8 +23,8 @@ The configuration sections schema contains elements that define custom settings | | Description | | --- | ----------- | | [**\**](configsections-element-for-configuration.md) | Contains configuration section and namespace declarations. | -| [**\
** for **\** and **\**](section-element.md) | Contains a configuration section declaration. | -| [**\** for **\**](sectiongroup-element-for-configsections.md) | Defines a namespace for configuration sections. | +| [`
` for `` and ``](section-element.md) | Contains a configuration section declaration. | +| [`` for ``](sectiongroup-element-for-configsections.md) | Defines a namespace for configuration sections. | diff --git a/docs/framework/configure-apps/file-schema/cryptography/cryptoclass-element.md b/docs/framework/configure-apps/file-schema/cryptography/cryptoclass-element.md index 157ee1936f1a1..1ff74090509ab 100644 --- a/docs/framework/configure-apps/file-schema/cryptography/cryptoclass-element.md +++ b/docs/framework/configure-apps/file-schema/cryptography/cryptoclass-element.md @@ -2,17 +2,17 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/mscorlib/cryptographySettings/cryptoNameMapping/cryptoClasses/cryptoClass" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#cryptoClass" -helpviewer_keywords: +helpviewer_keywords: - "cryptoClass element" - " element" ms.assetid: 03db52ef-010e-44ea-b6fd-b9c900ecad50 --- -# \ Element +# `` Element -Contains a cryptography class that has a mapping to a friendly name in the [\](nameentry-element.md) element. +Contains a cryptography class that has a mapping to a friendly name in the [\](nameentry-element.md) element. [**\**](../configuration-element.md)\   [**\**](mscorlib-element-for-cryptography-settings.md)\ @@ -21,59 +21,59 @@ Contains a cryptography class that has a mapping to a friendly name in the [\**](cryptoclasses-element.md)\           **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`customClassName`|Required attribute.

Contains the information for the cryptography class. Use this attribute to provide a short name for your class. You must specify a string that meets the requirements specified in [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`cryptoClasses`|Contains a list of cryptography classes that have a mapping to a friendly name in the [\](nameentry-element.md) element.| -|`cryptographySettings`|Contains cryptography settings.| -|`cryptoNameMapping`|Contains mappings of classes to friendly names.| -|`mscorlib`|Contains the [\](cryptographysettings-element.md) element.| - -## Example - - The following example shows how use the **\** element to reference a cryptography class and to configure the runtime. You can then pass the string "RSA" to the method and use the method to return a `MyCryptoRSAClass` object. - -```xml - - - - - - - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`customClassName`|Required attribute.

Contains the information for the cryptography class. Use this attribute to provide a short name for your class. You must specify a string that meets the requirements specified in [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`cryptoClasses`|Contains a list of cryptography classes that have a mapping to a friendly name in the [\](nameentry-element.md) element.| +|`cryptographySettings`|Contains cryptography settings.| +|`cryptoNameMapping`|Contains mappings of classes to friendly names.| +|`mscorlib`|Contains the [\](cryptographysettings-element.md) element.| + +## Example + + The following example shows how use the `` element to reference a cryptography class and to configure the runtime. You can then pass the string "RSA" to the method and use the method to return a `MyCryptoRSAClass` object. + +```xml + + + + + + + + + + + + + +``` + ## See also - [Configuration File Schema](../index.md) diff --git a/docs/framework/configure-apps/file-schema/cryptography/cryptoclasses-element.md b/docs/framework/configure-apps/file-schema/cryptography/cryptoclasses-element.md index 2f1a36972bba8..014c3167d6d55 100644 --- a/docs/framework/configure-apps/file-schema/cryptography/cryptoclasses-element.md +++ b/docs/framework/configure-apps/file-schema/cryptography/cryptoclasses-element.md @@ -2,79 +2,79 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/mscorlib/cryptographySettings/cryptoNameMapping/cryptoClasses" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#cryptoClasses" -helpviewer_keywords: +helpviewer_keywords: - " element" - "cryptoClasses element" ms.assetid: 290d5f96-946d-4f02-babb-1d31ec0b8295 --- -# \ Element - -Contains a list of cryptography classes that have a mapping to a friendly name in the [\](nameentry-element.md) element. - -[**\**](../configuration-element.md) -  [**\**](mscorlib-element-for-cryptography-settings.md) -    [**\**](cryptographysettings-element.md) -      [**\**](cryptonamemapping-element.md) -        **\** - -## Syntax - -```xml +# `` Element + +Contains a list of cryptography classes that have a mapping to a friendly name in the [\](nameentry-element.md) element. + +[**\**](../configuration-element.md) +  [**\**](mscorlib-element-for-cryptography-settings.md) +    [**\**](cryptographysettings-element.md) +      [**\**](cryptonamemapping-element.md) +        **\** + +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](cryptoclass-element.md)|Contains a cryptography class that has a mapping to a friendly name in the **\** element.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`cryptographySettings`|Contains cryptography settings.| -|`cryptoNameMapping`|Contains mappings of classes to friendly names.| -|`mscorlib`|Contains the `cryptographySettings` element.| - -## Example - - The following example shows how use the **\** element to reference a cryptography class and to configure the runtime. You can then pass the string "RSA" to the method and use the method to return a `MyCryptoRSAClass` object. - -```xml - - - - - - - - - - - - - - - -``` - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](cryptoclass-element.md)|Contains a cryptography class that has a mapping to a friendly name in the `` element.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`cryptographySettings`|Contains cryptography settings.| +|`cryptoNameMapping`|Contains mappings of classes to friendly names.| +|`mscorlib`|Contains the `cryptographySettings` element.| + +## Example + + The following example shows how use the `` element to reference a cryptography class and to configure the runtime. You can then pass the string "RSA" to the method and use the method to return a `MyCryptoRSAClass` object. + +```xml + + + + + + + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/cryptography/cryptographysettings-element.md b/docs/framework/configure-apps/file-schema/cryptography/cryptographysettings-element.md index fc7fdfc95a8b2..c82bd46a05212 100644 --- a/docs/framework/configure-apps/file-schema/cryptography/cryptographysettings-element.md +++ b/docs/framework/configure-apps/file-schema/cryptography/cryptographysettings-element.md @@ -2,79 +2,79 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/mscorlib/cryptographySettings" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#cryptographySettings" -helpviewer_keywords: +helpviewer_keywords: - "cryptographySettings element" - " element" ms.assetid: 6201b7da-bcb7-49f7-b9f5-ba1fe05573b9 --- -# \ Element +# `` Element -Contains cryptography settings. +Contains cryptography settings. [**\**](../configuration-element.md)\   [**\**](mscorlib-element-for-cryptography-settings.md)\     **\** -## Syntax - -```xml +## Syntax + +```xml + + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](cryptonamemapping-element.md)|Contains mappings of classes to friendly names.| +|[\](oidmap-element.md)|Contains ASN.1 object identifier (OID) mappings to classes.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`mscorlib`|Contains the `cryptographySettings` element.| + +## Example + + The following example shows how use the `` element to contain cryptography name mappings and OID mappings. This example configures the runtime so that returns a `MyHashClass` object and the `MyCryptoClass` class maps to the object identifier 1.3.36.2.1. + +```xml + + - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](cryptonamemapping-element.md)|Contains mappings of classes to friendly names.| -|[\](oidmap-element.md)|Contains ASN.1 object identifier (OID) mappings to classes.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`mscorlib`|Contains the `cryptographySettings` element.| - -## Example - - The following example shows how use the **\** element to contain cryptography name mappings and OID mappings. This example configures the runtime so that returns a `MyHashClass` object and the `MyCryptoClass` class maps to the object identifier 1.3.36.2.1. - -```xml - - - - - - - - - - - - - - - - -``` - + + + + + + + + + + + + + +``` + ## See also - [Configuration File Schema](../index.md) diff --git a/docs/framework/configure-apps/file-schema/cryptography/cryptonamemapping-element.md b/docs/framework/configure-apps/file-schema/cryptography/cryptonamemapping-element.md index 3eb23c8aabad4..c359d3eea65f0 100644 --- a/docs/framework/configure-apps/file-schema/cryptography/cryptonamemapping-element.md +++ b/docs/framework/configure-apps/file-schema/cryptography/cryptonamemapping-element.md @@ -2,77 +2,77 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#cryptoNameMapping" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/mscorlib/cryptographySettings/cryptoNameMapping" -helpviewer_keywords: +helpviewer_keywords: - " element" - "cryptoNameMapping element" ms.assetid: c59c9494-149b-4ce6-b38d-371f896ae85c --- -# \ Element +# `` Element -Contains mappings of classes to friendly names. +Contains mappings of classes to friendly names. [**\**](../configuration-element.md)\   [**\**](mscorlib-element-for-cryptography-settings.md)\     [**\**](cryptographysettings-element.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|`cryptoClasses`|Contains a list of cryptography classes that have a mapping to a friendly name in the **\** element.| -|`nameEntry`|Maps a class name to a friendly algorithm name, which allows one class to have many friendly names.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`cryptographySettings`|Contains cryptography settings.| -|`cryptoNameMapping`|Contains mappings of classes to friendly names.| -|`mscorlib`|Contains the \ element.| - -## Example - - The following example shows how to use the **\** element to reference a cryptography class and to configure the runtime. You can then pass the string "RSA" to the method and use the method to return a `MyCryptoRSAClass` object. - -```xml - - - - - - - - - - - - - -``` - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|`cryptoClasses`|Contains a list of cryptography classes that have a mapping to a friendly name in the `` element.| +|`nameEntry`|Maps a class name to a friendly algorithm name, which allows one class to have many friendly names.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`cryptographySettings`|Contains cryptography settings.| +|`cryptoNameMapping`|Contains mappings of classes to friendly names.| +|`mscorlib`|Contains the `` element.| + +## Example + + The following example shows how to use the `` element to reference a cryptography class and to configure the runtime. You can then pass the string "RSA" to the method and use the method to return a `MyCryptoRSAClass` object. + +```xml + + + + + + + + + + + + + +``` + ## See also - [Configuration File Schema](../index.md) diff --git a/docs/framework/configure-apps/file-schema/cryptography/index.md b/docs/framework/configure-apps/file-schema/cryptography/index.md index 7a125eac3d22a..7730fc8667b7d 100644 --- a/docs/framework/configure-apps/file-schema/cryptography/index.md +++ b/docs/framework/configure-apps/file-schema/cryptography/index.md @@ -2,7 +2,7 @@ description: "Learn more about: Cryptography Settings Schema" title: "Cryptography Settings Schema" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "configuration schema [.NET Framework], cryptography" - "elements [.NET Framework], cryptography" - "schema configuration settings" @@ -14,8 +14,8 @@ ms.assetid: 1f55050a-b2a3-4868-a3c0-da20826150f3 --- # Cryptography Settings Schema -The cryptography settings schema contains elements that specify how to map friendly algorithm names to classes that implement cryptography algorithms. - +The cryptography settings schema contains elements that specify how to map friendly algorithm names to classes that implement cryptography algorithms. + [**\**](../configuration-element.md)\   [**\**](mscorlib-element-for-cryptography-settings.md)\     [**\**](cryptographysettings-element.md)\ @@ -26,17 +26,17 @@ The cryptography settings schema contains elements that specify how to map frien       [**\**](oidmap-element.md)\        [**\**](oidentry-element.md) -|Element|Description| -|-------------|-----------------| -|[**\](cryptoclasses-element.md)|Contains a list of cryptography classes that have a mapping to a friendly name in the **\** element.| -|[**\](cryptoclass-element.md)|Contains a cryptography class that has a mapping to a friendly name in the **\** element.| -|[**\](cryptographysettings-element.md)|Contains cryptography settings.| -|[**\](cryptonamemapping-element.md)|Contains mappings of classes to friendly names.| -|[**\** element for cryptography settings](mscorlib-element-for-cryptography-settings.md)|Contains the **\** element.| -|[**\**](nameentry-element.md)|Maps a class name to a friendly algorithm name, which allows one class to have many friendly names.| -|[**\**](oidentry-element.md)|Maps an ASN.1 object identifier (OID) to a friendly name.| -|[**\**](oidmap-element.md)|Contains ASN.1 OID mappings to classes.| - +|Element|Description| +|-------------|-----------------| +|[**\](cryptoclasses-element.md)|Contains a list of cryptography classes that have a mapping to a friendly name in the `` element.| +|[**\](cryptoclass-element.md)|Contains a cryptography class that has a mapping to a friendly name in the `` element.| +|[**\](cryptographysettings-element.md)|Contains cryptography settings.| +|[**\](cryptonamemapping-element.md)|Contains mappings of classes to friendly names.| +|[**\** element for cryptography settings](mscorlib-element-for-cryptography-settings.md)|Contains the `` element.| +|[**\**](nameentry-element.md)|Maps a class name to a friendly algorithm name, which allows one class to have many friendly names.| +|[**\**](oidentry-element.md)|Maps an ASN.1 object identifier (OID) to a friendly name.| +|[**\**](oidmap-element.md)|Contains ASN.1 OID mappings to classes.| + ## See also - [Configuration File Schema](../index.md) diff --git a/docs/framework/configure-apps/file-schema/cryptography/mscorlib-element-for-cryptography-settings.md b/docs/framework/configure-apps/file-schema/cryptography/mscorlib-element-for-cryptography-settings.md index 5a15a6e48544c..4263450605859 100644 --- a/docs/framework/configure-apps/file-schema/cryptography/mscorlib-element-for-cryptography-settings.md +++ b/docs/framework/configure-apps/file-schema/cryptography/mscorlib-element-for-cryptography-settings.md @@ -2,71 +2,71 @@ description: "Learn more about: Element for Cryptography Settings" title: " Element for Cryptography Settings" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#mscorlib" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/mscorlib" -helpviewer_keywords: +helpviewer_keywords: - "mscorlib element" - " element" ms.assetid: d549668f-31f1-4b92-8021-a9135c09ca3c --- -# \ Element for Cryptography Settings - -Contains the [\ element](cryptographysettings-element.md). - -[**\**](../configuration-element.md) -  **\** - -## Syntax - -```xml +# `` Element for Cryptography Settings + +Contains the [`` element](cryptographysettings-element.md). + +[**\**](../configuration-element.md) +  **\** + +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|`cryptographySettings`|Contains cryptography settings.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| - -## Example - - The following example shows how to use the **\** element to reference a cryptography class and to configure the runtime. You can then pass the string "RSA" to the method and use the method to return a `MyCryptoRSAClass` object. - -```xml - - - - - - - - - - - - - -``` - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|`cryptographySettings`|Contains cryptography settings.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| + +## Example + + The following example shows how to use the `` element to reference a cryptography class and to configure the runtime. You can then pass the string "RSA" to the method and use the method to return a `MyCryptoRSAClass` object. + +```xml + + + + + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/cryptography/nameentry-element.md b/docs/framework/configure-apps/file-schema/cryptography/nameentry-element.md index d55790338fdc5..e7a9049805138 100644 --- a/docs/framework/configure-apps/file-schema/cryptography/nameentry-element.md +++ b/docs/framework/configure-apps/file-schema/cryptography/nameentry-element.md @@ -2,79 +2,79 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#nameEntry" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/mscorlib/cryptographySettings/cryptoNameMapping/nameEntry" -helpviewer_keywords: +helpviewer_keywords: - " element" - "nameEntry element" ms.assetid: 7d7535e9-4b4a-4b8c-82e2-e40dff5a7821 --- -# \ Element - -Maps a class name to a friendly algorithm name, which allows one class to have many friendly names. - -[**\**](../configuration-element.md) -  [**\**](mscorlib-element-for-cryptography-settings.md) -    [**\**](cryptographysettings-element.md) -      [**\**](cryptonamemapping-element.md) -        **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**name**|Required attribute.

Specifies the friendly name of the algorithm that the cryptography class implements.| -|**class**|Required attribute.

Specifies the value for the **name** attribute in the [\](cryptoclass-element.md) element.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.web`|Specifies the root element for the ASP.NET configuration section.| - -## Remarks - - The **name** attribute can be the name of one of the abstract classes found in the namespace. When you call the **Create** method on an abstract cryptography class, the abstract class name is passed to the method. **CreateFromName** returns an instance of the type indicated by the **class** attribute. If the **name** attribute is a short name, such as RSA, you can use that name when calling the **CreateFromName** method. - -## Example - - The following example shows how to use the **\** element to reference a cryptography class and to configure the runtime. You can then pass the string "RSA" to the method and use the method to return a `MyCryptoRSAClass` object. - -```xml - - - - - - - - - - - - - -``` - +# `` Element + +Maps a class name to a friendly algorithm name, which allows one class to have many friendly names. + +[**\**](../configuration-element.md) +  [**\**](mscorlib-element-for-cryptography-settings.md) +    [**\**](cryptographysettings-element.md) +      [**\**](cryptonamemapping-element.md) +        **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|**name**|Required attribute.

Specifies the friendly name of the algorithm that the cryptography class implements.| +|`class`|Required attribute.

Specifies the value for the `name` attribute in the [\](cryptoclass-element.md) element.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.web`|Specifies the root element for the ASP.NET configuration section.| + +## Remarks + + The `name` attribute can be the name of one of the abstract classes found in the namespace. When you call the `Create` method on an abstract cryptography class, the abstract class name is passed to the method. `CreateFromName` returns an instance of the type indicated by the `class` attribute. If the `name` attribute is a short name, such as RSA, you can use that name when calling the `CreateFromName` method. + +## Example + + The following example shows how to use the `` element to reference a cryptography class and to configure the runtime. You can then pass the string "RSA" to the method and use the method to return a `MyCryptoRSAClass` object. + +```xml + + + + + + + + + + + + + +``` + ## See also - [Configuration File Schema](../index.md) diff --git a/docs/framework/configure-apps/file-schema/cryptography/oidentry-element.md b/docs/framework/configure-apps/file-schema/cryptography/oidentry-element.md index a4e9be9bc49a3..3ecb6d492d91e 100644 --- a/docs/framework/configure-apps/file-schema/cryptography/oidentry-element.md +++ b/docs/framework/configure-apps/file-schema/cryptography/oidentry-element.md @@ -2,17 +2,17 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/mscorlib/cryptographySettings/oidMap/oidEntry" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#oidEntry" -helpviewer_keywords: +helpviewer_keywords: - " element" - "oidEntry element" ms.assetid: 22fb88b0-bf27-489c-9ca0-e65950ac136c --- -# \ Element +# `` Element -Maps an ASN.1 object identifier (OID) to a friendly name. +Maps an ASN.1 object identifier (OID) to a friendly name. [**\**](../configuration-element.md)\   [**\**](mscorlib-element-for-cryptography-settings.md)\ @@ -20,64 +20,64 @@ Maps an ASN.1 object identifier (OID) to a friendly name.       [**\**](oidmap-element.md)\        **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**OID**|Required attribute.

Specifies the ASN.1 OID corresponding to the algorithm implemented by your class.| -|**name**|Required attribute.

Specifies the value for the **name** attribute in the [\](nameentry-element.md) tag.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`cryptographySettings`|Contains cryptography settings.| -|`mscorlib`|Contains the `cryptographySettings` element.| -|`oidMap`|Contains ASN.1 object identifier (OID) mappings to classes.| - -## Remarks - - ASN.1 object identifiers identify algorithms in some cryptographic formats. Map object identifiers to friendly names for the algorithms you want to identify. - -## Example - - The following example shows how to use the **\** element to map an object identifier for the RIPEMD-160 hash algorithm to an implementation of that hash algorithm. - -```xml - - - - - - - - - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`OID`|Required attribute.

Specifies the ASN.1 OID corresponding to the algorithm implemented by your class.| +|`name`|Required attribute.

Specifies the value for the `name` attribute in the [\](nameentry-element.md) tag.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`cryptographySettings`|Contains cryptography settings.| +|`mscorlib`|Contains the `cryptographySettings` element.| +|`oidMap`|Contains ASN.1 object identifier (OID) mappings to classes.| + +## Remarks + + ASN.1 object identifiers identify algorithms in some cryptographic formats. Map object identifiers to friendly names for the algorithms you want to identify. + +## Example + + The following example shows how to use the `` element to map an object identifier for the RIPEMD-160 hash algorithm to an implementation of that hash algorithm. + +```xml + + + + + + + + + + + + + + + +``` + ## See also - [Configuration File Schema](../index.md) diff --git a/docs/framework/configure-apps/file-schema/cryptography/oidmap-element.md b/docs/framework/configure-apps/file-schema/cryptography/oidmap-element.md index 257f5ab1413b7..62621d83a1ab9 100644 --- a/docs/framework/configure-apps/file-schema/cryptography/oidmap-element.md +++ b/docs/framework/configure-apps/file-schema/cryptography/oidmap-element.md @@ -2,76 +2,76 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#oidMap" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/mscorlib/cryptographySettings/oidMap" -helpviewer_keywords: +helpviewer_keywords: - " element" - "oidMap element" ms.assetid: 7f0c2246-c070-4748-b96a-2f66a296c539 --- -# \ Element +# `` Element -Contains ASN.1 object identifier (OID) mappings to classes. +Contains ASN.1 object identifier (OID) mappings to classes. [**\**](../configuration-element.md)\   [**\**](mscorlib-element-for-cryptography-settings.md)\     [**\**](cryptographysettings-element.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](oidentry-element.md)|Maps an ASN.1 OID to a friendly name.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`cryptographySettings`|Contains cryptography settings.| -|`mscorlib`|Contains the `cryptographySettings` element.| - -## Example - - The following example shows how to use the **\** element to contain a mapping of an OID for the RIPEMD-160 hash algorithm to an implementation of that hash algorithm. - -```xml - - - - - - - - - - - - - - - -``` - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](oidentry-element.md)|Maps an ASN.1 OID to a friendly name.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`cryptographySettings`|Contains cryptography settings.| +|`mscorlib`|Contains the `cryptographySettings` element.| + +## Example + + The following example shows how to use the `` element to contain a mapping of an OID for the RIPEMD-160 hash algorithm to an implementation of that hash algorithm. + +```xml + + + + + + + + + + + + + + + +``` + ## See also - [Configuration File Schema](../index.md) diff --git a/docs/framework/configure-apps/file-schema/custom-element-1.md b/docs/framework/configure-apps/file-schema/custom-element-1.md index 936653bec044e..5f394788e0bca 100644 --- a/docs/framework/configure-apps/file-schema/custom-element-1.md +++ b/docs/framework/configure-apps/file-schema/custom-element-1.md @@ -2,15 +2,15 @@ description: "Learn more about: Custom element for SingleTagSectionHandler" title: "Custom element for SingleTagSectionHandler" ms.date: "05/01/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/sectionName" -helpviewer_keywords: +helpviewer_keywords: - "custom element" ms.assetid: e62056c6-b351-40eb-afc0-cc13fc44e45e --- # Custom element for SingleTagSectionHandler -Defines settings in a custom configuration section that is defined by a \
element and uses the class. +Defines settings in a custom configuration section that is defined by a `
` element and uses the class. [**\**](configuration-element.md)\   *\* @@ -37,11 +37,11 @@ None ## Remarks -The **\** element is a custom element defined by a [**\
**](section-element.md) tag in the [**\**](configsections-element-for-configuration.md) element. The configuration system returns a object when you call . +The `` element is a custom element defined by a [`
`](section-element.md) tag in the [``](configsections-element-for-configuration.md) element. The configuration system returns a object when you call . ## Example -The following example declares a custom element called **\** that contains settings read by the class: +The following example declares a custom element called `` that contains settings read by the class: ```xml diff --git a/docs/framework/configure-apps/file-schema/custom-element-2.md b/docs/framework/configure-apps/file-schema/custom-element-2.md index 3a9294532b772..b6905cb8c8487 100644 --- a/docs/framework/configure-apps/file-schema/custom-element-2.md +++ b/docs/framework/configure-apps/file-schema/custom-element-2.md @@ -35,7 +35,7 @@ None ## Remarks -The **\** element is a custom element defined by a **\
** tag in the **\** element. +The `` element is a custom element defined by a `
` tag in the `` element. The following table shows the type of object the ConfigurationSettings.GetConfig method returns for each configuration section handler: @@ -48,7 +48,7 @@ The following table shows the type of object the ConfigurationSettings.GetConfig The following example shows how to declare sections that use the and classes. -The first custom element is **\**, which contains settings read by the class in the `System.dll` assembly. The second custom element is **\**, which contains settings read by the class in the `System.dll` assembly. +The first custom element is ``, which contains settings read by the class in the `System.dll` assembly. The second custom element is ``, which contains settings read by the class in the `System.dll` assembly. ```xml diff --git a/docs/framework/configure-apps/file-schema/linkedconfiguration-element.md b/docs/framework/configure-apps/file-schema/linkedconfiguration-element.md index 3acacf9ffbceb..3fd8e1bf0f921 100644 --- a/docs/framework/configure-apps/file-schema/linkedconfiguration-element.md +++ b/docs/framework/configure-apps/file-schema/linkedconfiguration-element.md @@ -2,10 +2,10 @@ description: "Learn more about: element" title: " element" ms.date: "10/23/2023" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/assemblyBinding/linkedConfiguration" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#linkedConfiguration" -helpviewer_keywords: +helpviewer_keywords: - "configuration files [.NET Framework],linked configuration files" - " element" - "including configuration files" @@ -14,7 +14,7 @@ helpviewer_keywords: ms.assetid: 8eb34f3b-427e-4288-a7ff-c73f489deb45 --- -# \ element +# `` element Specifies a configuration file to include. @@ -32,13 +32,13 @@ Specifies a configuration file to include. | Attribute | Description | | --------- | ----------- | -| **href** | Required attribute.

The URL of the configuration file to include. The only format supported for the **href** attribute is `file://`. Local files and UNC files are supported. | +| `href` | Required attribute.

The URL of the configuration file to include. The only format supported for the `href` attribute is `file://`. Local files and UNC files are supported. | ## Parent element | Element | Description | | --- | ----------- | -| [\ Element](assemblybinding-element-for-configuration.md) | Specifies assembly binding policy at the configuration level. | +| [`` Element](assemblybinding-element-for-configuration.md) | Specifies assembly binding policy at the configuration level. | ## Child elements @@ -46,10 +46,10 @@ None ## Remarks -The **\** element simplifies servicing for component assemblies. If one or more applications use an assembly that has a configuration file residing in a well-known location, their configuration files can use the \ element to include the assembly configuration file, rather than duplicating configuration information. When the component assembly is serviced, updating the common configuration file provides updated configuration information to all applications that use the assembly. +The `` element simplifies servicing for component assemblies. If one or more applications use an assembly that has a configuration file residing in a well-known location, their configuration files can use the `` element to include the assembly configuration file, rather than duplicating configuration information. When the component assembly is serviced, updating the common configuration file provides updated configuration information to all applications that use the assembly. > [!NOTE] -> The \ element isn't supported for applications with Windows side-by-side manifests. +> The `` element isn't supported for applications with Windows side-by-side manifests. The following rules govern the use of linked configuration files: @@ -61,11 +61,11 @@ The following rules govern the use of linked configuration files: - All linked configuration files are merged to form one assembly configuration file, similar to the behavior of the `#include` directive in C/C++. -- The \ element is allowed only in application configuration files. If the element appears in a *Machine.config* file, it's ignored. +- The `` element is allowed only in application configuration files. If the element appears in a *Machine.config* file, it's ignored. -- There's no restriction on the content of the included configuration files, as long as they conform to the schema of the parent \ element. +- There's no restriction on the content of the included configuration files, as long as they conform to the schema of the parent `` element. -- Circular references are detected and terminated. That is, if the \ elements of a series of configuration files form a loop, the loop is detected and stopped. +- Circular references are detected and terminated. That is, if the `` elements of a series of configuration files form a loop, the loop is detected and stopped. ## Example @@ -81,5 +81,5 @@ The following example shows how to include configuration file from a local hard ## See also -- [\ Element](assemblybinding-element-for-configuration.md) +- [`` Element](assemblybinding-element-for-configuration.md) - [Configuration file schema for the .NET Framework](index.md) diff --git a/docs/framework/configure-apps/file-schema/network/add-element-for-authenticationmodules-network-settings.md b/docs/framework/configure-apps/file-schema/network/add-element-for-authenticationmodules-network-settings.md index 91e27ad421a80..f7080c6052d94 100644 --- a/docs/framework/configure-apps/file-schema/network/add-element-for-authenticationmodules-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/add-element-for-authenticationmodules-network-settings.md @@ -2,86 +2,86 @@ title: " Element for authenticationModules (Network Settings)" description: The network settings element for connectionManagement adds an IP address or DNS name to the connection management list in the .NET Framework. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#add" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/authenticationModules/add" -helpviewer_keywords: +helpviewer_keywords: - "authenticationModules, add element" - "add element, authenticationModules" - ", add element" - " element, authenticationModules" ms.assetid: 333c5fb0-a2ab-4db8-8531-a7fe37bb9b5b --- -# \ Element for authenticationModules (Network Settings) +# `` Element for authenticationModules (Network Settings) -Adds an authentication module to the application. +Adds an authentication module to the application. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](authenticationmodules-element-network-settings.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`type`|The fully qualified type name (indicated by the property) and the assembly name (indicated by the property), separated by a comma.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[authenticationModules](authenticationmodules-element-network-settings.md)|Specifies modules used to authenticate network requests.| - -## Remarks - - The `add` element adds an authentication module to the end of the list of registered authentication modules. Authentication modules are called in the order in which they were added to the list. - - The value for the `type` attribute should be a valid type name and corresponding assembly name, separated by a comma. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example enables the default authentication modules. You should replace the values for Version and PublicKeyToken with the correct values for the specified module. - -```xml - - - - - - - - - - - -``` - +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`type`|The fully qualified type name (indicated by the property) and the assembly name (indicated by the property), separated by a comma.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[authenticationModules](authenticationmodules-element-network-settings.md)|Specifies modules used to authenticate network requests.| + +## Remarks + + The `add` element adds an authentication module to the end of the list of registered authentication modules. Authentication modules are called in the order in which they were added to the list. + + The value for the `type` attribute should be a valid type name and corresponding assembly name, separated by a comma. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example enables the default authentication modules. You should replace the values for Version and PublicKeyToken with the correct values for the specified module. + +```xml + + + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/add-element-for-bypasslist-network-settings.md b/docs/framework/configure-apps/file-schema/network/add-element-for-bypasslist-network-settings.md index 89c89883b3b2d..757865e1798ed 100644 --- a/docs/framework/configure-apps/file-schema/network/add-element-for-bypasslist-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/add-element-for-bypasslist-network-settings.md @@ -2,85 +2,85 @@ description: "Learn more about: Element for bypasslist (Network Settings)" title: " Element for bypasslist (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/defaultProxy/bypasslist/add" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#add" -helpviewer_keywords: +helpviewer_keywords: - ", add element" - "bypasslist, add element" - " element, bypasslist" - "add element, bypasslist" ms.assetid: a0b86e28-86b4-4497-abe8-d5fd614c7926 --- -# \ Element for bypasslist (Network Settings) - -Adds an IP address or DNS name to the proxy bypass list. - -[**\**](../configuration-element.md) -  [**\**](system-net-element-network-settings.md) -    [**\**](defaultproxy-element-network-settings.md) -      [**\**](bypasslist-element-network-settings.md) -        **\** - -## Syntax - -```xml +# `` Element for bypasslist (Network Settings) + +Adds an IP address or DNS name to the proxy bypass list. + +[**\**](../configuration-element.md) +  [**\**](system-net-element-network-settings.md) +    [**\**](defaultproxy-element-network-settings.md) +      [**\**](bypasslist-element-network-settings.md) +        **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|**address**|A regular expression describing an IP address or DNS name.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[bypasslist](bypasslist-element-network-settings.md)|Provides a set of regular expressions that describe addresses that do not use a proxy.| - -## Remarks - - The `add` element inserts regular expressions describing IP addresses or DNS server names to the list of addresses that bypass a proxy server. - - The value of the `address` attribute should be a regular expression that describes a set of IP addresses or host names. - +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|**address**|A regular expression describing an IP address or DNS name.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[bypasslist](bypasslist-element-network-settings.md)|Provides a set of regular expressions that describe addresses that do not use a proxy.| + +## Remarks + + The `add` element inserts regular expressions describing IP addresses or DNS server names to the list of addresses that bypass a proxy server. + + The value of the `address` attribute should be a regular expression that describes a set of IP addresses or host names. + You should use caution when specifying a regular expression for this element. The regular expression `[a-z]+\\.contoso\\.com` matches any host in the contoso.com domain, but it also matches any host in the contoso.com.cpandl.com domain. To match only a host in the contoso.com domain, use an anchor (`$`): `[a-z]+\\.contoso\\.com$`. - - For more information about regular expressions, see .[.NET Framework Regular Expressions](../../../../standard/base-types/regular-expressions.md). - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example adds two addresses to the bypass list. The first bypasses the proxy for all servers in the contoso.com domain; the second bypasses the proxy for all servers whose IP address begins with 192.168. - -```xml - - - - - - - - - - -``` - + + For more information about regular expressions, see .[.NET Framework Regular Expressions](../../../../standard/base-types/regular-expressions.md). + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example adds two addresses to the bypass list. The first bypasses the proxy for all servers in the contoso.com domain; the second bypasses the proxy for all servers whose IP address begins with 192.168. + +```xml + + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/add-element-for-connectionmanagement-network-settings.md b/docs/framework/configure-apps/file-schema/network/add-element-for-connectionmanagement-network-settings.md index ead750290530b..8e0d6dc4b396f 100644 --- a/docs/framework/configure-apps/file-schema/network/add-element-for-connectionmanagement-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/add-element-for-connectionmanagement-network-settings.md @@ -2,80 +2,80 @@ description: "Learn more about: Element for connectionManagement (Network Settings)" title: " Element for connectionManagement (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#add" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/connectionManagement/add" -helpviewer_keywords: +helpviewer_keywords: - " element, connectionManagement" - ", add element" - "add element, connectionManagement" - "connectionManagement, add element" ms.assetid: 856bf57d-1c63-46c7-a178-03d97b0a4149 --- -# \ Element for connectionManagement (Network Settings) +# `` Element for connectionManagement (Network Settings) -Adds an IP address or DNS name to the connection management list. +Adds an IP address or DNS name to the connection management list. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](connectionmanagement-element-network-settings.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`address`|A string describing an IP address or DNS name.| -|`maxconnection`|The maximum number of connections allowed to a server. If not supplied, the default is 2.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[connectionManagement](connectionmanagement-element-network-settings.md)|Specifies the maximum number of connections to a network host.| - -## Remarks - - The value of the `address` attribute should be either an asterisk to indicate all connections, or a string of the form `://[:]`. - - If the URI passed to any HTTP APIs contains Unicode, the name will be converted internally using which might return a punicode string (behavior dependent on the current IDN configuration). - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example configures an application to use four connections to the server `www.contoso.com` and two connections to all other servers. - -```xml - - - - - - - - -``` - +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`address`|A string describing an IP address or DNS name.| +|`maxconnection`|The maximum number of connections allowed to a server. If not supplied, the default is 2.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[connectionManagement](connectionmanagement-element-network-settings.md)|Specifies the maximum number of connections to a network host.| + +## Remarks + + The value of the `address` attribute should be either an asterisk to indicate all connections, or a string of the form `://[:]`. + + If the URI passed to any HTTP APIs contains Unicode, the name will be converted internally using which might return a punicode string (behavior dependent on the current IDN configuration). + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example configures an application to use four connections to the server `www.contoso.com` and two connections to all other servers. + +```xml + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/add-element-for-schemesettings-uri-settings.md b/docs/framework/configure-apps/file-schema/network/add-element-for-schemesettings-uri-settings.md index e43bc0508f009..8845b7c09da0b 100644 --- a/docs/framework/configure-apps/file-schema/network/add-element-for-schemesettings-uri-settings.md +++ b/docs/framework/configure-apps/file-schema/network/add-element-for-schemesettings-uri-settings.md @@ -4,84 +4,84 @@ title: " Element for schemeSettings (Uri Settings)" ms.date: "03/30/2017" ms.assetid: 594a7b3b-af23-4cfa-b616-0b2dddb1a705 --- -# \ Element for schemeSettings (Uri Settings) +# `` Element for schemeSettings (Uri Settings) -Adds a scheme setting for a scheme name. +Adds a scheme setting for a scheme name. [**\**](../configuration-element.md)\   [**\**](uri-element-uri-settings.md)\     [**\**](schemesettings-element-uri-settings.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|name|The scheme name for which this setting applies. The only supported values are name="http" and name="https".| - -## {Attribute name} Attribute - -|Value|Description| -|-----------|-----------------| -|genericUriParserOptions|The parser options for this scheme. The only supported value is genericUriParserOptions= "DontUnescapePathDotsAndSlashes".| - -### Child Elements - - None - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\ Element (Uri Settings)](schemesettings-element-uri-settings.md)|Specifies how a will be parsed for specific schemes.| - -## Remarks - - By default, the class un-escapes percent encoded path delimiters before executing path compression. This was implemented as a security mechanism against attacks like the following: - - `http://www.contoso.com/..%2F..%2F/Windows/System32/cmd.exe?/c+dir+c:\` - - If this URI gets passed down to modules not handling percent encoded characters correctly, it could result in the following command being executed by the server: - - `c:\Windows\System32\cmd.exe /c dir c:\` - - For this reason, class first un-escapes path delimiters and then applies path compression. The result of passing the malicious URL above to class constructor results in the following URI: - - `http://www.microsoft.com/Windows/System32/cmd.exe?/c+dir+c:\` - - This default behavior can be modified to not un-escape percent encoded path delimiters using the schemeSettings configuration option for a specific scheme. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example shows a configuration used by the class to support not escaping percent-encoded path delimiters for the http scheme. - -```xml - - - - - - - -``` - +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|name|The scheme name for which this setting applies. The only supported values are name="http" and name="https".| + +## {Attribute name} Attribute + +|Value|Description| +|-----------|-----------------| +|genericUriParserOptions|The parser options for this scheme. The only supported value is genericUriParserOptions= "DontUnescapePathDotsAndSlashes".| + +### Child Elements + + None + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\ Element (Uri Settings)](schemesettings-element-uri-settings.md)|Specifies how a will be parsed for specific schemes.| + +## Remarks + + By default, the class un-escapes percent encoded path delimiters before executing path compression. This was implemented as a security mechanism against attacks like the following: + + `http://www.contoso.com/..%2F..%2F/Windows/System32/cmd.exe?/c+dir+c:\` + + If this URI gets passed down to modules not handling percent encoded characters correctly, it could result in the following command being executed by the server: + + `c:\Windows\System32\cmd.exe /c dir c:\` + + For this reason, class first un-escapes path delimiters and then applies path compression. The result of passing the malicious URL above to class constructor results in the following URI: + + `http://www.microsoft.com/Windows/System32/cmd.exe?/c+dir+c:\` + + This default behavior can be modified to not un-escape percent encoded path delimiters using the schemeSettings configuration option for a specific scheme. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example shows a configuration used by the class to support not escaping percent-encoded path delimiters for the http scheme. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/add-element-for-webrequestmodules-network-settings.md b/docs/framework/configure-apps/file-schema/network/add-element-for-webrequestmodules-network-settings.md index 11536962b9c95..3d612e87e23e2 100644 --- a/docs/framework/configure-apps/file-schema/network/add-element-for-webrequestmodules-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/add-element-for-webrequestmodules-network-settings.md @@ -2,86 +2,86 @@ description: "Learn more about: Element for webRequestModules (Network Settings)" title: " Element for webRequestModules (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/webRequestModules/add" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#add" -helpviewer_keywords: +helpviewer_keywords: - ", add element" - "webRequestModules, add element" - "add element, webRequestModules" - " element, webRequestModules" ms.assetid: 47ec4adc-f39f-4bcd-8680-1ec21fd26890 --- -# \ Element for webRequestModules (Network Settings) +# `` Element for webRequestModules (Network Settings) -Adds a custom Web request module to the application. +Adds a custom Web request module to the application. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](webrequestmodules-element-network-settings.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`prefix`|The URI prefix for requests handled by this Web request module.| -|`type`|The fully qualified type name (indicated by the property) and the assembly name (indicated by the property), separated by a comma, that implements this Web request module.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[webRequestModules](webrequestmodules-element-network-settings.md)|Specifies modules to use to request information from network hosts.| - -## Remarks - - The `prefix` attribute defines the URI prefix that uses the specified Web request module. Web request modules are typically registered to handle a specific protocol, such as HTTP or FTP, but can be registered to handle a request to a specific server or path on a server. - - The Web request module is created when a URI matching prefix is passed to the method. - +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`prefix`|The URI prefix for requests handled by this Web request module.| +|`type`|The fully qualified type name (indicated by the property) and the assembly name (indicated by the property), separated by a comma, that implements this Web request module.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[webRequestModules](webrequestmodules-element-network-settings.md)|Specifies modules to use to request information from network hosts.| + +## Remarks + + The `prefix` attribute defines the URI prefix that uses the specified Web request module. Web request modules are typically registered to handle a specific protocol, such as HTTP or FTP, but can be registered to handle a request to a specific server or path on a server. + + The Web request module is created when a URI matching prefix is passed to the method. + The value for the `prefix` attribute should be the leading characters of a valid URI. For example, `http` or `http://www.contoso.com`. - + The value for the `type` attribute should be a valid type name and corresponding assembly name, separated by a comma. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example registers a custom Web request module for HTTP. You should replace the values for Version and PublicKeyToken with the correct values for the specified module. - -```xml - - - - - - - -``` - + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example registers a custom Web request module for HTTP. You should replace the values for Version and PublicKeyToken with the correct values for the specified module. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/authenticationmodules-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/authenticationmodules-element-network-settings.md index 24fa16c8eed15..1f7c9f35e6612 100644 --- a/docs/framework/configure-apps/file-schema/network/authenticationmodules-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/authenticationmodules-element-network-settings.md @@ -2,74 +2,74 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#authenticationModules" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/authenticationModules" -helpviewer_keywords: +helpviewer_keywords: - "authenticationModules element" - " element" ms.assetid: 10fcfaad-82ef-4692-871a-0aec9dfbe75e --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Specifies modules used to authenticate network requests. +Specifies modules used to authenticate network requests. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     **\** -## Syntax - -```xml +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[add](add-element-for-authenticationmodules-network-settings.md)|Adds an authentication module to the application.| -|[clear](clear-element-for-authenticationmodules-network-settings.md)|Clears all authentication modules from the application.| -|[remove](remove-element-for-authenticationmodules-network-settings.md)|Removes an authentication module from the application.| - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[system.net](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| - -## Remarks - - The `authenticationModule` element specifies the authentication modules that conduct the authentication process with a server. An authentication module must implement the interface. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example enables an authentication module. You should replace the values for Version and PublicKeyToken with the correct values for the specified module. - -```xml - - - - - - - -``` - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[add](add-element-for-authenticationmodules-network-settings.md)|Adds an authentication module to the application.| +|[clear](clear-element-for-authenticationmodules-network-settings.md)|Clears all authentication modules from the application.| +|[remove](remove-element-for-authenticationmodules-network-settings.md)|Removes an authentication module from the application.| + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[system.net](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| + +## Remarks + + The `authenticationModule` element specifies the authentication modules that conduct the authentication process with a server. An authentication module must implement the interface. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example enables an authentication module. You should replace the values for Version and PublicKeyToken with the correct values for the specified module. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/bypasslist-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/bypasslist-element-network-settings.md index 21f3fcc629b79..ec4ebb58b451e 100644 --- a/docs/framework/configure-apps/file-schema/network/bypasslist-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/bypasslist-element-network-settings.md @@ -2,81 +2,81 @@ title: " Element (Network Settings)" description: The network settings element provides a set of regular expressions that describe addresses that do not use a proxy in the .NET Framework. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#bypasslist" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/defaultProxy/bypasslist" -helpviewer_keywords: +helpviewer_keywords: - "bypasslist element" - " element" ms.assetid: 124446b7-abb1-4e5e-a492-b64398f268f1 --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Provides a set of regular expressions that describe addresses that do not use a proxy. +Provides a set of regular expressions that describe addresses that do not use a proxy. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](defaultproxy-element-network-settings.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[add](add-element-for-bypasslist-network-settings.md)|Adds an IP address or DNS name to the proxy bypass list.| -|[clear](clear-element-for-bypasslist-network-settings.md)|Clears the bypass list.| -|[remove](remove-element-for-bypasslist-network-settings.md)|Removes an IP address or DNS name from the proxy bypass list.| - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[defaultProxy](defaultproxy-element-network-settings.md)|Configures the Hypertext Transfer Protocol (HTTP) proxy server.| - -## Remarks - - The bypass list contains regular expressions that describe URIs that instances access directly instead of through the proxy server. - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[add](add-element-for-bypasslist-network-settings.md)|Adds an IP address or DNS name to the proxy bypass list.| +|[clear](clear-element-for-bypasslist-network-settings.md)|Clears the bypass list.| +|[remove](remove-element-for-bypasslist-network-settings.md)|Removes an IP address or DNS name from the proxy bypass list.| + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[defaultProxy](defaultproxy-element-network-settings.md)|Configures the Hypertext Transfer Protocol (HTTP) proxy server.| + +## Remarks + + The bypass list contains regular expressions that describe URIs that instances access directly instead of through the proxy server. + You should use caution when specifying a regular expression for this element. The regular expression `[a-z]+\\.contoso\\.com` matches any host in the contoso.com domain, but it also matches any host in the contoso.com.cpandl.com domain. To match only a host in the contoso.com domain, use an anchor (`$`): `[a-z]+\\.contoso\\.com$`. - - For more information about regular expressions, see .[.NET Framework Regular Expressions](../../../../standard/base-types/regular-expressions.md). - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example adds two addresses to the bypass list. The first bypasses the proxy for all servers in the contoso.com domain; the second bypasses the proxy for all servers whose IP addresses begin with 192.168. - -```xml - - - - - - - - - - -``` - + + For more information about regular expressions, see .[.NET Framework Regular Expressions](../../../../standard/base-types/regular-expressions.md). + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example adds two addresses to the bypass list. The first bypasses the proxy for all servers in the contoso.com domain; the second bypasses the proxy for all servers whose IP addresses begin with 192.168. + +```xml + + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/clear-element-for-authenticationmodules-network-settings.md b/docs/framework/configure-apps/file-schema/network/clear-element-for-authenticationmodules-network-settings.md index 4b513837c6140..e0c6b24992a69 100644 --- a/docs/framework/configure-apps/file-schema/network/clear-element-for-authenticationmodules-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/clear-element-for-authenticationmodules-network-settings.md @@ -2,71 +2,71 @@ description: "Learn more about: Element for authenticationModules (Network Settings)" title: " Element for authenticationModules (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/authenticationModules/clear" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#clear" -helpviewer_keywords: +helpviewer_keywords: - "clear element, authenticationModules" - ", clear element" - " element, authenticationModules" - "authenticationModules, clear element" ms.assetid: dc522c45-4a80-4831-8955-f7b68a47edfd --- -# \ Element for authenticationModules (Network Settings) +# `` Element for authenticationModules (Network Settings) -Clears all authentication modules from the application. +Clears all authentication modules from the application. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](authenticationmodules-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[authenticationModules](authenticationmodules-element-network-settings.md)|Specifies modules used to authenticate network requests.| - -## Remarks - - The `clear` element removes all authentication modules that were defined earlier in the configuration file or at a higher level in the configuration hierarchy. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example removes all configured authentication modules. - -```xml - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[authenticationModules](authenticationmodules-element-network-settings.md)|Specifies modules used to authenticate network requests.| + +## Remarks + + The `clear` element removes all authentication modules that were defined earlier in the configuration file or at a higher level in the configuration hierarchy. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example removes all configured authentication modules. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/clear-element-for-bypasslist-network-settings.md b/docs/framework/configure-apps/file-schema/network/clear-element-for-bypasslist-network-settings.md index f8cac29421cb6..90baa55d83a36 100644 --- a/docs/framework/configure-apps/file-schema/network/clear-element-for-bypasslist-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/clear-element-for-bypasslist-network-settings.md @@ -2,76 +2,76 @@ description: "Learn more about: Element for bypasslist (Network Settings)" title: " Element for bypasslist (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/defaultProxy/bypasslist/clear" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#clear" -helpviewer_keywords: +helpviewer_keywords: - "clear element, bypasslist" - " element, bypasslist" - ", clear element" - "bypasslist, clear element" ms.assetid: 301584ca-a914-4100-b180-3b288d3b099e --- -# \ Element for bypasslist (Network Settings) +# `` Element for bypasslist (Network Settings) + +Clears the proxy bypass list. -Clears the proxy bypass list. - [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](defaultproxy-element-network-settings.md)\       [**\**](bypasslist-element-network-settings.md)\         **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[bypasslist](bypasslist-element-network-settings.md)|Provides a set of regular expressions that describe addresses that do not use a proxy.| - -## Remarks - - The `clear` element clears all entries from the bypass list. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example clears the bypass list and then adds two addresses to the bypass list. The first bypasses the proxy for all servers in the contoso.com domain; the second bypasses the proxy for all servers whose IP address begins with 192.168. - -```xml - - - - - - - - - - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[bypasslist](bypasslist-element-network-settings.md)|Provides a set of regular expressions that describe addresses that do not use a proxy.| + +## Remarks + + The `clear` element clears all entries from the bypass list. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example clears the bypass list and then adds two addresses to the bypass list. The first bypasses the proxy for all servers in the contoso.com domain; the second bypasses the proxy for all servers whose IP address begins with 192.168. + +```xml + + + + + + + + + + -``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/clear-element-for-connectionmanagement-network-settings.md b/docs/framework/configure-apps/file-schema/network/clear-element-for-connectionmanagement-network-settings.md index 812e522a8c753..22dae8fa1df1b 100644 --- a/docs/framework/configure-apps/file-schema/network/clear-element-for-connectionmanagement-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/clear-element-for-connectionmanagement-network-settings.md @@ -2,73 +2,73 @@ description: "Learn more about: Element for connectionManagement (Network Settings)" title: " Element for connectionManagement (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/connectionManagement/clear" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#clear" -helpviewer_keywords: +helpviewer_keywords: - " element, connectionManagement" - "connectionManagement, clear element" - "clear element, connectionManagement" - ", clear element" ms.assetid: fb259282-84c4-4dc4-a226-78d904a6edc3 --- -# \ Element for connectionManagement (Network Settings) +# `` Element for connectionManagement (Network Settings) -Clears the connection management list. +Clears the connection management list. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](connectionmanagement-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[connectionManagement](connectionmanagement-element-network-settings.md)|Specifies the maximum number of connections to a network host.| - -## Remarks - - The `clear` element clears all entries from the connection management list. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example clears the connection management list and then adds new connection management entries for the server `www.contoso.com` and all other network hosts. - -```xml - - - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[connectionManagement](connectionmanagement-element-network-settings.md)|Specifies the maximum number of connections to a network host.| + +## Remarks + + The `clear` element clears all entries from the connection management list. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example clears the connection management list and then adds new connection management entries for the server `www.contoso.com` and all other network hosts. + +```xml + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/clear-element-for-schemesettings-uri-settings.md b/docs/framework/configure-apps/file-schema/network/clear-element-for-schemesettings-uri-settings.md index bf8c9afd82ba8..1ceb4972d1161 100644 --- a/docs/framework/configure-apps/file-schema/network/clear-element-for-schemesettings-uri-settings.md +++ b/docs/framework/configure-apps/file-schema/network/clear-element-for-schemesettings-uri-settings.md @@ -4,74 +4,74 @@ title: " Element for schemeSettings (Uri Settings)" ms.date: "03/30/2017" ms.assetid: 65098332-ce61-4542-ab8d-e7dc0257d31f --- -# \ Element for schemeSettings (Uri Settings) +# `` Element for schemeSettings (Uri Settings) -Clears all existing scheme settings. +Clears all existing scheme settings. [**\**](../configuration-element.md)\   [**\**](uri-element-uri-settings.md)\     [**\**](schemesettings-element-uri-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\ Element (Uri Settings)](schemesettings-element-uri-settings.md)|Specifies how a will be parsed for specific schemes.| - -## Remarks - - By default, the class un-escapes percent encoded path delimiters before executing path compression. This was implemented as a security mechanism against attacks like the following: - - `http://www.contoso.com/..%2F..%2F/Windows/System32/cmd.exe?/c+dir+c:\` - - If this URI gets passed down to modules not handling percent encoded characters correctly, it could result in the following command being executed by the server: - - `c:\Windows\System32\cmd.exe /c dir c:\` - - For this reason, class first un-escapes path delimiters and then applies path compression. The result of passing the malicious URL above to class constructor results in the following URI: - - `http://www.microsoft.com/Windows/System32/cmd.exe?/c+dir+c:\` - - This default behavior can be modified to not un-escape percent encoded path delimiters using the schemeSettings configuration option for a specific scheme. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example shows a configuration used by the class that clears all scheme settings and then adds support for not escaping percent-encoded path delimiters for the http scheme. - -```xml - - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\ Element (Uri Settings)](schemesettings-element-uri-settings.md)|Specifies how a will be parsed for specific schemes.| + +## Remarks + + By default, the class un-escapes percent encoded path delimiters before executing path compression. This was implemented as a security mechanism against attacks like the following: + + `http://www.contoso.com/..%2F..%2F/Windows/System32/cmd.exe?/c+dir+c:\` + + If this URI gets passed down to modules not handling percent encoded characters correctly, it could result in the following command being executed by the server: + + `c:\Windows\System32\cmd.exe /c dir c:\` + + For this reason, class first un-escapes path delimiters and then applies path compression. The result of passing the malicious URL above to class constructor results in the following URI: + + `http://www.microsoft.com/Windows/System32/cmd.exe?/c+dir+c:\` + + This default behavior can be modified to not un-escape percent encoded path delimiters using the schemeSettings configuration option for a specific scheme. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example shows a configuration used by the class that clears all scheme settings and then adds support for not escaping percent-encoded path delimiters for the http scheme. + +```xml + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/clear-element-for-webrequestmodules-network-settings.md b/docs/framework/configure-apps/file-schema/network/clear-element-for-webrequestmodules-network-settings.md index ac013994d650c..7219d92735a2d 100644 --- a/docs/framework/configure-apps/file-schema/network/clear-element-for-webrequestmodules-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/clear-element-for-webrequestmodules-network-settings.md @@ -2,75 +2,75 @@ description: "Learn more about: Element for webRequestModules (Network Settings)" title: " Element for webRequestModules (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/webRequestModules/clear" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#clear" -helpviewer_keywords: +helpviewer_keywords: - " element, webRequestModules" - ", clear element" - "webRequestModules, clear element" - "clear element, webRequestModules" ms.assetid: 48f38bcb-f30c-4b74-a8f0-1a3caf1aa96f --- -# \ Element for webRequestModules (Network Settings) +# `` Element for webRequestModules (Network Settings) -Removes all registered Web request modules from the application. +Removes all registered Web request modules from the application. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](webrequestmodules-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[webRequestModules](webrequestmodules-element-network-settings.md)|Specifies modules to use to request information from network hosts.| - -## Remarks - - The `clear` element removes all registered Web request modules that were defined earlier in the configuration file or at a higher level in the configuration hierarchy. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example clears all Web request modules and then registers a Web request module for HTTP. - -```xml - - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[webRequestModules](webrequestmodules-element-network-settings.md)|Specifies modules to use to request information from network hosts.| + +## Remarks + + The `clear` element removes all registered Web request modules that were defined earlier in the configuration file or at a higher level in the configuration hierarchy. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example clears all Web request modules and then registers a Web request module for HTTP. + +```xml + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/connectionmanagement-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/connectionmanagement-element-network-settings.md index 0257a12b68b85..65634a32ffd9b 100644 --- a/docs/framework/configure-apps/file-schema/network/connectionmanagement-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/connectionmanagement-element-network-settings.md @@ -2,74 +2,74 @@ title: " Element (Network Settings)" description: The network settings element specifies the maximum number of connections to a network host in the .NET Framework. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/connectionManagement" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#connectionManagement" -helpviewer_keywords: +helpviewer_keywords: - " element" - "connectionManagement element" ms.assetid: bedccaab-12a2-4511-8f67-e961f249aec6 --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Specifies the maximum number of connections to a network host. +Specifies the maximum number of connections to a network host. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     **\** -## Syntax - -```xml +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[add](add-element-for-connectionmanagement-network-settings.md)|Adds an IP address or DNS name to the connection management list.| -|[clear](clear-element-for-connectionmanagement-network-settings.md)|Clears the connection management list.| -|[remove](remove-element-for-connectionmanagement-network-settings.md)|Removes an IP address or DNS name from the connection management list.| - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[system.net](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| - -## Remarks - - The `connectionManagement` element defines the maximum number of connections to a server or group of servers. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example configures an application to use four connections to the server `www.contoso.com` and two connections to all other servers. - -```xml - - - - - - - - -``` - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[add](add-element-for-connectionmanagement-network-settings.md)|Adds an IP address or DNS name to the connection management list.| +|[clear](clear-element-for-connectionmanagement-network-settings.md)|Clears the connection management list.| +|[remove](remove-element-for-connectionmanagement-network-settings.md)|Removes an IP address or DNS name from the connection management list.| + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[system.net](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| + +## Remarks + + The `connectionManagement` element defines the maximum number of connections to a server or group of servers. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example configures an application to use four connections to the server `www.contoso.com` and two connections to all other servers. + +```xml + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/defaultftpcachepolicy-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/defaultftpcachepolicy-element-network-settings.md index e1b28d88717f1..8a7ed07ed85ad 100644 --- a/docs/framework/configure-apps/file-schema/network/defaultftpcachepolicy-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/defaultftpcachepolicy-element-network-settings.md @@ -2,82 +2,82 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#defaultFtpCachePolicy" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/requestCaching/defaultFtpCachePolicy" -helpviewer_keywords: +helpviewer_keywords: - " element" - "defaultFtpCachePolicy element" ms.assetid: 0eb0c5cb-dd97-484d-8614-785e88877abb --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Describes whether FTP caching is active and describes the default caching policy. +Describes whether FTP caching is active and describes the default caching policy. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](requestcaching-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`policyLevel`|Specifies the FTP caching policy. The default value is `Default`.| - -## policyLevel Attribute - -|Value|Description| -|-----------|-----------------| -|`Default`|Returns the cached resource if the resource is fresh, the content length is accurate, and the expiration, modification, and content length attributes are present.| -|`BypassCache`|Returns the resource from the server.| -|`CacheOnly`|Returns the cached resource if the content length is present and matches the entry size.| -|`CacheIfAvailable`|Returns the cached resource if the content length is provided and matches the entry size; otherwise, the resource is downloaded from the server and is returned to the caller.| -|`Revalidate`|Returns the cached resource if the timestamp of the cached resource is the same as the timestamp of the resource on the server; otherwise, the resource is downloaded from the server, stored in the cache, and returned to the caller.| -|`Reload`|Downloads the resource from the server, stores it in the cache, and returns the resource to the caller.| -|`NoCacheNoStore`|If a cached resource exists, it is deleted. The resource is downloaded from the server and is returned to the caller.| -|`Revalidate`|Satisfies a request by using the cached copy of the resource if the timestamp is the same as the timestamp of the resource on the server; otherwise, the resource is downloaded from the server, presented to the caller, and stored in the cache.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[requestCaching](requestcaching-element-network-settings.md)|Controls the caching mechanism for network requests.| - -## Remarks - -## Example - - The following example shows how to specify an FTP caching policy of `NoCacheNoStore`. - -```xml - - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`policyLevel`|Specifies the FTP caching policy. The default value is `Default`.| + +## policyLevel Attribute + +|Value|Description| +|-----------|-----------------| +|`Default`|Returns the cached resource if the resource is fresh, the content length is accurate, and the expiration, modification, and content length attributes are present.| +|`BypassCache`|Returns the resource from the server.| +|`CacheOnly`|Returns the cached resource if the content length is present and matches the entry size.| +|`CacheIfAvailable`|Returns the cached resource if the content length is provided and matches the entry size; otherwise, the resource is downloaded from the server and is returned to the caller.| +|`Revalidate`|Returns the cached resource if the timestamp of the cached resource is the same as the timestamp of the resource on the server; otherwise, the resource is downloaded from the server, stored in the cache, and returned to the caller.| +|`Reload`|Downloads the resource from the server, stores it in the cache, and returns the resource to the caller.| +|`NoCacheNoStore`|If a cached resource exists, it is deleted. The resource is downloaded from the server and is returned to the caller.| +|`Revalidate`|Satisfies a request by using the cached copy of the resource if the timestamp is the same as the timestamp of the resource on the server; otherwise, the resource is downloaded from the server, presented to the caller, and stored in the cache.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[requestCaching](requestcaching-element-network-settings.md)|Controls the caching mechanism for network requests.| + +## Remarks + +## Example + + The following example shows how to specify an FTP caching policy of `NoCacheNoStore`. + +```xml + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/defaulthttpcachepolicy-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/defaulthttpcachepolicy-element-network-settings.md index 9be9bf949024d..06bd5ba623575 100644 --- a/docs/framework/configure-apps/file-schema/network/defaulthttpcachepolicy-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/defaulthttpcachepolicy-element-network-settings.md @@ -2,85 +2,85 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/requestCaching/defaultHttpCachePolicy" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#defaultHttpCachePolicy" -helpviewer_keywords: +helpviewer_keywords: - "defaultHttpCachePolicy element" - " element" ms.assetid: 2c1247d0-39b0-4c12-919a-a925ce075c79 --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Describes whether HTTP caching is active and describes the default caching policy. +Describes whether HTTP caching is active and describes the default caching policy. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](requestcaching-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`maximumAge`|Specifies the maximum time interval before a cached object is marked as expired.| -|`maximumStale`|Specifies the maximum time past the computed freshness time before a cached object is marked as expired.| -|`minimumFresh`|Specifies the minimum time for a cached object to be considered fresh.| -|`policyLevel`|Specifies whether the caching policy is automatic, or whether the cache is bypassed. The default value is `BypassCache`.| - -### Child Elements - - None - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[requestCaching](requestcaching-element-network-settings.md)|Controls the caching mechanism for network requests.| - -## Remarks - - The value for the `policyLevel` attribute is either `BypassCache` or `Default`. - - Values for the `maximumAge`, `maximumStale`, and `minimumFresh` elements are either an explicit time interval with a format of *d*.*hh*:*mm*:*ss* (days, hours, minutes, and seconds), or the constants `minValue` or `maxValue`, as appropriate. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example shows how to specify a minimum fresh time of six hours, a maximum age time of two days, and a maximum stale time of four hours. - -```xml - - - - +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`maximumAge`|Specifies the maximum time interval before a cached object is marked as expired.| +|`maximumStale`|Specifies the maximum time past the computed freshness time before a cached object is marked as expired.| +|`minimumFresh`|Specifies the minimum time for a cached object to be considered fresh.| +|`policyLevel`|Specifies whether the caching policy is automatic, or whether the cache is bypassed. The default value is `BypassCache`.| + +### Child Elements + + None + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[requestCaching](requestcaching-element-network-settings.md)|Controls the caching mechanism for network requests.| + +## Remarks + + The value for the `policyLevel` attribute is either `BypassCache` or `Default`. + + Values for the `maximumAge`, `maximumStale`, and `minimumFresh` elements are either an explicit time interval with a format of *d*.*hh*:*mm*:*ss* (days, hours, minutes, and seconds), or the constants `minValue` or `maxValue`, as appropriate. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example shows how to specify a minimum fresh time of six hours, a maximum age time of two days, and a maximum stale time of four hours. + +```xml + + + + - - - -``` - + /> + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/defaultproxy-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/defaultproxy-element-network-settings.md index 4e1323c869b24..52fd470ceedb5 100644 --- a/docs/framework/configure-apps/file-schema/network/defaultproxy-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/defaultproxy-element-network-settings.md @@ -9,7 +9,7 @@ helpviewer_keywords: - "defaultProxy element" - " element" --- -# \ element (network settings) +# `` element (network settings) Configures the Hypertext Transfer Protocol (HTTP) proxy server. diff --git a/docs/framework/configure-apps/file-schema/network/httplistener-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/httplistener-element-network-settings.md index 1ad15984a3f14..ad52ba765f34d 100644 --- a/docs/framework/configure-apps/file-schema/network/httplistener-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/httplistener-element-network-settings.md @@ -4,130 +4,130 @@ title: " Element (Network Settings)" ms.date: "03/30/2017" ms.assetid: 62f121fd-3f2e-4033-bb39-48ae996bfbd9 --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Customizes parameters used by the class. +Customizes parameters used by the class. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](settings-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Type - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|unescapeRequestUrl|A Boolean value that indicates if a instance uses the raw unescaped URI instead of the converted URI.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| - -## Remarks - - The **unescapeRequestUrl** attribute indicates if uses the raw unescaped URI instead of the converted URI where any percent-encoded values are converted and other normalization steps are taken. - - When a instance receives a request through the `http.sys` service, it creates an instance of the URI string provided by `http.sys`, and exposes it as the property. - - The `http.sys` service exposes two request URI strings: - -- Raw URI - -- Converted URI - - The raw URI is the provided in the request line of a HTTP request: - - `GET /path/` - - `Host: www.contoso.com` - - The raw URI provided by `http.sys` for the request mentioned above, is "/path/". This represents the string following the HTTP verb as it was sent over the network. - - The `http.sys` service creates a converted URI from the information provided in the request by using the URI provided in the HTTP request line and the Host header to determine the origin server the request should be forwarded to. This is done by comparing the information from the request with a set of registered URI prefixes. The HTTP Server SDK documentation refers to this converted URI as the HTTP_COOKED_URL structure. - - In order to be able to compare the request with registered URI prefixes, some normalization to the request needs to be done. For the sample above the converted URI would be as follows: - - `http://www.contoso.com/path/` - - The `http.sys` service combines the property value and the string in the request line to create a converted URI. In addition, `http.sys` and the class also does the following: - -- Un-escapes all percent encoded values. - -- Converts percent-encoded non-ASCII characters into a UTF-16 character representation. Note that UTF-8 and ANSI/DBCS characters are supported as well as Unicode characters (Unicode encoding using the %uXXXX format). - -- Executes other normalization steps, like path compression. - - Since the request doesn't contain any information about the encoding used for percent-encoded values, it may not be possible to determine the correct encoding just by parsing the percent-encoded values. - - Therefore `http.sys` provides two registry keys for modifying the process: - -|Registry Key|Default Value|Description| -|------------------|-------------------|-----------------| -|EnableNonUTF8|1|If zero, `http.sys` accepts only UTF-8-encoded URLs.

If non-zero, `http.sys` also accepts ANSI-encoded or DBCS-encoded URLs in requests.| -|FavorUTF8|1|If non-zero, `http.sys` always tries to decode a URL as UTF-8 first; if that conversion fails and EnableNonUTF8 is non-zero, Http.sys then tries to decode it as ANSI or DBCS.

If zero (and EnableNonUTF8 is non-zero), `http.sys` tries to decode it as ANSI or DBCS; if that is not successful, it tries a UTF-8 conversion.| - - When receives a request, it uses the converted URI from `http.sys` as input to the property. - - There is a need for supporting characters besides characters and numbers in URIs. An example is the following URI, which is used to retrieve customer information for customer number "1/3812": - - `http://www.contoso.com/Customer('1%2F3812')/` - - Note the percent-encoded slash in the Uri (%2F). This is necessary, since in this case the slash character represents data and not a path delimiter. - - Passing the string to Uri constructor will lead to the following URI: - - `http://www.contoso.com/Customer('1/3812')/` - - Splitting the path into its segments would result in the following elements: - - `Customer('1` - - `3812')` - - This is not the intent of the sender of the request. - - If the **unescapeRequestUrl** attribute is set to **false**, then when the receives a request, it uses the raw URI instead of the converted URI from `http.sys` as input to the property. - - The default value for the **unescapeRequestUrl** attribute is **true**. - - The property can be used to get the current value of the **unescapeRequestUrl** attribute from applicable configuration files. - -## Example - - The following example shows how to configure the class when it receives a request to use the raw URI instead of the converted URI from `http.sys` as input to the property. - -```xml - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Type + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|unescapeRequestUrl|A Boolean value that indicates if a instance uses the raw unescaped URI instead of the converted URI.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| + +## Remarks + + The `unescapeRequestUrl` attribute indicates if uses the raw unescaped URI instead of the converted URI where any percent-encoded values are converted and other normalization steps are taken. + + When a instance receives a request through the `http.sys` service, it creates an instance of the URI string provided by `http.sys`, and exposes it as the property. + + The `http.sys` service exposes two request URI strings: + +- Raw URI + +- Converted URI + + The raw URI is the provided in the request line of a HTTP request: + + `GET /path/` + + `Host: www.contoso.com` + + The raw URI provided by `http.sys` for the request mentioned above, is "/path/". This represents the string following the HTTP verb as it was sent over the network. + + The `http.sys` service creates a converted URI from the information provided in the request by using the URI provided in the HTTP request line and the Host header to determine the origin server the request should be forwarded to. This is done by comparing the information from the request with a set of registered URI prefixes. The HTTP Server SDK documentation refers to this converted URI as the HTTP_COOKED_URL structure. + + In order to be able to compare the request with registered URI prefixes, some normalization to the request needs to be done. For the sample above the converted URI would be as follows: + + `http://www.contoso.com/path/` + + The `http.sys` service combines the property value and the string in the request line to create a converted URI. In addition, `http.sys` and the class also does the following: + +- Un-escapes all percent encoded values. + +- Converts percent-encoded non-ASCII characters into a UTF-16 character representation. Note that UTF-8 and ANSI/DBCS characters are supported as well as Unicode characters (Unicode encoding using the %uXXXX format). + +- Executes other normalization steps, like path compression. + + Since the request doesn't contain any information about the encoding used for percent-encoded values, it may not be possible to determine the correct encoding just by parsing the percent-encoded values. + + Therefore `http.sys` provides two registry keys for modifying the process: + +|Registry Key|Default Value|Description| +|------------------|-------------------|-----------------| +|EnableNonUTF8|1|If zero, `http.sys` accepts only UTF-8-encoded URLs.

If non-zero, `http.sys` also accepts ANSI-encoded or DBCS-encoded URLs in requests.| +|FavorUTF8|1|If non-zero, `http.sys` always tries to decode a URL as UTF-8 first; if that conversion fails and EnableNonUTF8 is non-zero, Http.sys then tries to decode it as ANSI or DBCS.

If zero (and EnableNonUTF8 is non-zero), `http.sys` tries to decode it as ANSI or DBCS; if that is not successful, it tries a UTF-8 conversion.| + + When receives a request, it uses the converted URI from `http.sys` as input to the property. + + There is a need for supporting characters besides characters and numbers in URIs. An example is the following URI, which is used to retrieve customer information for customer number "1/3812": + + `http://www.contoso.com/Customer('1%2F3812')/` + + Note the percent-encoded slash in the Uri (%2F). This is necessary, since in this case the slash character represents data and not a path delimiter. + + Passing the string to Uri constructor will lead to the following URI: + + `http://www.contoso.com/Customer('1/3812')/` + + Splitting the path into its segments would result in the following elements: + + `Customer('1` + + `3812')` + + This is not the intent of the sender of the request. + + If the `unescapeRequestUrl` attribute is set to **false**, then when the receives a request, it uses the raw URI instead of the converted URI from `http.sys` as input to the property. + + The default value for the `unescapeRequestUrl` attribute is **true**. + + The property can be used to get the current value of the `unescapeRequestUrl` attribute from applicable configuration files. + +## Example + + The following example shows how to configure the class when it receives a request to use the raw URI instead of the converted URI from `http.sys` as input to the property. + +```xml + + + + + + + +``` + ## Element Information **Namespace**: System.Net diff --git a/docs/framework/configure-apps/file-schema/network/httpwebrequest-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/httpwebrequest-element-network-settings.md index b41a2b94d8e30..0e4024c644371 100644 --- a/docs/framework/configure-apps/file-schema/network/httpwebrequest-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/httpwebrequest-element-network-settings.md @@ -2,81 +2,81 @@ title: " Element (Network Settings)" description: The network settings element customizes Web request parameters in the .NET Framework. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/settings/httpWebRequest" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#httpWebRequest" -helpviewer_keywords: +helpviewer_keywords: - " element" - "httpWebRequest element" ms.assetid: 52acd9d2-5bdc-4dc4-9c2a-f0a476ccbb31 --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Customizes Web request parameters. +Customizes Web request parameters. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](settings-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`maximumResponseHeadersLength`|Specifies the maximum length of a response header, in kilobytes. The default is 64. A value of -1 indicates that no size limit will be imposed on the response headers.| -|`maximumErrorResponseLength`|Specifies the maximum length of an error response, in kilobytes. The default is 64. A value of -1 indicates that no size limit will be imposed on the error response.| -|`maximumUnauthorizedUploadLength`|Specifies the maximum length of an upload in response to an unauthorized error code, in bytes. The default is -1. A value of -1 indicates that no size limit will be imposed on the upload.| -|`useUnsafeHeaderParsing`|Specifies whether unsafe header parsing is enabled. The default value is `false`.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| - -## Remarks - - By default, the .NET Framework strictly enforces RFC 2616 for URI parsing. Some server responses may include control characters in prohibited fields, which will cause the method to throw a . If **useUnsafeHeaderParsing** is set to **true**, will not throw in this case; however, your application will be vulnerable to several forms of URI parsing attacks. The best solution is to change the server so that the response does not include control characters. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example shows how to specify a larger than normal maximum header length. - -```xml - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`maximumResponseHeadersLength`|Specifies the maximum length of a response header, in kilobytes. The default is 64. A value of -1 indicates that no size limit will be imposed on the response headers.| +|`maximumErrorResponseLength`|Specifies the maximum length of an error response, in kilobytes. The default is 64. A value of -1 indicates that no size limit will be imposed on the error response.| +|`maximumUnauthorizedUploadLength`|Specifies the maximum length of an upload in response to an unauthorized error code, in bytes. The default is -1. A value of -1 indicates that no size limit will be imposed on the upload.| +|`useUnsafeHeaderParsing`|Specifies whether unsafe header parsing is enabled. The default value is `false`.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| + +## Remarks + + By default, the .NET Framework strictly enforces RFC 2616 for URI parsing. Some server responses may include control characters in prohibited fields, which will cause the method to throw a . If `useUnsafeHeaderParsing` is set to **true**, will not throw in this case; however, your application will be vulnerable to several forms of URI parsing attacks. The best solution is to change the server so that the response does not include control characters. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example shows how to specify a larger than normal maximum header length. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/idn-element-uri-settings.md b/docs/framework/configure-apps/file-schema/network/idn-element-uri-settings.md index d80bd12289483..094f218ecd680 100644 --- a/docs/framework/configure-apps/file-schema/network/idn-element-uri-settings.md +++ b/docs/framework/configure-apps/file-schema/network/idn-element-uri-settings.md @@ -4,41 +4,41 @@ title: " Element (Uri Settings)" ms.date: "03/30/2017" ms.assetid: 16c8e869-1791-4cf5-9244-3d3c738f60ec --- -# \ Element (Uri Settings) +# `` Element (Uri Settings) Specifies if Internationalized Domain Name (IDN) parsing is applied to a domain name. - -[**\**](../configuration-element.md) -  [**\**](uri-element-uri-settings.md) -    **\** - -## Syntax - + +[**\**](../configuration-element.md) +  [**\**](uri-element-uri-settings.md) +    **\** + +## Syntax + ```xml -``` - -## Attributes and Elements +/> +``` + +## Attributes and Elements - The following sections describe attributes, child elements, and parent elements. - -### Attributes + The following sections describe attributes, child elements, and parent elements. -|**Element**|**Description**| -|-----------------|---------------------| -|`enabled`|Specifies if Internationalized Domain Name (IDN) parsing is applied to a domain name The default value is none.| +### Attributes + +|**Element**|**Description**| +|-----------------|---------------------| +|`enabled`|Specifies if Internationalized Domain Name (IDN) parsing is applied to a domain name The default value is none.| ### Child elements None - + ### Parent elements -|**Element**|**Description**| -|-----------------|---------------------| -|[uri](uri-element-uri-settings.md)|Contains settings that specify how the .NET Framework handles web addresses expressed using uniform resource identifiers (URIs).| +|**Element**|**Description**| +|-----------------|---------------------| +|[uri](uri-element-uri-settings.md)|Contains settings that specify how the .NET Framework handles web addresses expressed using uniform resource identifiers (URIs).| ## Remarks @@ -47,16 +47,16 @@ The existing class has been extended in .NET Framework 3.5. 3. To enable support for IRI, the following two changes are required: 1. Add the following line to the machine.config file under the .NET Framework 2.0 directory: - - ```xml -
- ``` - + + ```xml +
+ ``` + 2. Specify whether you want Internationalized Domain Name (IDN) parsing applied to the domain name and whether IRI parsing rules should be applied. This can be done in the machine.config or in the app.config file. There are three possible values for IDN depending on the DNS servers that are used: -- idn enabled = All +- idn enabled = All This value will convert any Unicode domain names to their Punycode equivalents (IDN names). diff --git a/docs/framework/configure-apps/file-schema/network/index.md b/docs/framework/configure-apps/file-schema/network/index.md index a54cecd97594e..26360dfb02995 100644 --- a/docs/framework/configure-apps/file-schema/network/index.md +++ b/docs/framework/configure-apps/file-schema/network/index.md @@ -2,7 +2,7 @@ title: "Network Settings Schema" description: Learn about the schema for the network settings that specify how the .NET Framework connects to the Internet and handles URIs. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "elements [.NET Framework], network configuration elements" - "sending data, network configuration elements" - "receiving data, network configuration elements" @@ -18,25 +18,25 @@ ms.assetid: f1de5a0f-76c5-4833-819f-5222b8146340 Network settings specify how the .NET Framework connects to the Internet. -The \ settings specify how the .NET Framework connects to the network. The following table describes the function of each child configuration element under the [\ Element (Network Settings)](system-net-element-network-settings.md). - -|Element|Description| -|-------------|-----------------| -|[\ Element (Network Settings)](authenticationmodules-element-network-settings.md)|Specifies the modules used to authenticate Internet requests.| -|[\ Element (Network Settings)](connectionmanagement-element-network-settings.md)|Specifies the maximum number of connections to Internet hosts.| -|[\ Element (Network Settings)](defaultproxy-element-network-settings.md)|Specifies the proxy server used for HTTP requests to the Internet.| -|[\ Element (Network Settings)](mailsettings-element-network-settings.md)|Contains settings for mail sending options.| -|[\ Element (Network Settings)](requestcaching-element-network-settings.md)|Controls the caching mechanism for network requests.| -|[\ Element (Network Settings)](webrequestmodules-element-network-settings.md)|Specifies the modules used to request information from Internet hosts.| - -The \ settings specify how the .NET Framework handles web addresses expressed using uniform resource identifiers (URIs). The following table describes the function of each child configuration element under the [\ Element (Uri Settings)](uri-element-uri-settings.md). - -|Element|Description| -|-------------|-----------------| -|[\ Element (Uri Settings)](idn-element-uri-settings.md)|Specifies if Internationalized Domain Name (IDN) parsing is applied to domain names.| -|[\ Element (Uri Settings)](iriparsing-element-uri-settings.md)|Specifies if International Resource Identifier (IRI) parsing is applied to a and whether IRI parsing rules should be applied.| -|[\ Element (Uri Settings)](schemesettings-element-uri-settings.md)|Specifies how a will be parsed for specific schemes.| - +The `` settings specify how the .NET Framework connects to the network. The following table describes the function of each child configuration element under the [`` Element (Network Settings)](system-net-element-network-settings.md). + +|Element|Description| +|-------------|-----------------| +|[\ Element (Network Settings)](authenticationmodules-element-network-settings.md)|Specifies the modules used to authenticate Internet requests.| +|[\ Element (Network Settings)](connectionmanagement-element-network-settings.md)|Specifies the maximum number of connections to Internet hosts.| +|[\ Element (Network Settings)](defaultproxy-element-network-settings.md)|Specifies the proxy server used for HTTP requests to the Internet.| +|[\ Element (Network Settings)](mailsettings-element-network-settings.md)|Contains settings for mail sending options.| +|[\ Element (Network Settings)](requestcaching-element-network-settings.md)|Controls the caching mechanism for network requests.| +|[\ Element (Network Settings)](webrequestmodules-element-network-settings.md)|Specifies the modules used to request information from Internet hosts.| + +The `` settings specify how the .NET Framework handles web addresses expressed using uniform resource identifiers (URIs). The following table describes the function of each child configuration element under the [`` Element (Uri Settings)](uri-element-uri-settings.md). + +|Element|Description| +|-------------|-----------------| +|[\ Element (Uri Settings)](idn-element-uri-settings.md)|Specifies if Internationalized Domain Name (IDN) parsing is applied to domain names.| +|[\ Element (Uri Settings)](iriparsing-element-uri-settings.md)|Specifies if International Resource Identifier (IRI) parsing is applied to a and whether IRI parsing rules should be applied.| +|[\ Element (Uri Settings)](schemesettings-element-uri-settings.md)|Specifies how a will be parsed for specific schemes.| + ## See also - [Configuring Internet Applications](../../../network-programming/configuring-internet-applications.md) diff --git a/docs/framework/configure-apps/file-schema/network/ipv6-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/ipv6-element-network-settings.md index 720396854b400..a3aa385cbf04f 100644 --- a/docs/framework/configure-apps/file-schema/network/ipv6-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/ipv6-element-network-settings.md @@ -2,73 +2,73 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/settings/ipv6" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#ipv6" -helpviewer_keywords: +helpviewer_keywords: - " element" - "ipv6 element" ms.assetid: 10b79aef-327b-4718-a892-e11f55e4d169 --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Enables Internet Protocol version 6 (IPv6) responses from obsolete members of the class. +Enables Internet Protocol version 6 (IPv6) responses from obsolete members of the class. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](settings-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`enabled`|Specifies whether members of the class return Internet Protocol version 6 (IPv6) addresses. The default value is `false`.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| - -## Remarks - - This setting enables IPv6 support for the obsolete members of the class: , , , , , , and . For other members of the namespace, IPv6 addresses may be returned if IPv6 is enabled in the operating system. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example shows how to enable IPv6 support for the class. - -```xml - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`enabled`|Specifies whether members of the class return Internet Protocol version 6 (IPv6) addresses. The default value is `false`.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| + +## Remarks + + This setting enables IPv6 support for the obsolete members of the class: , , , , , , and . For other members of the namespace, IPv6 addresses may be returned if IPv6 is enabled in the operating system. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example shows how to enable IPv6 support for the class. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/iriparsing-element-uri-settings.md b/docs/framework/configure-apps/file-schema/network/iriparsing-element-uri-settings.md index 769cf63bcd11c..893cbd6077d64 100644 --- a/docs/framework/configure-apps/file-schema/network/iriparsing-element-uri-settings.md +++ b/docs/framework/configure-apps/file-schema/network/iriparsing-element-uri-settings.md @@ -4,79 +4,79 @@ title: " Element (Uri Settings)" ms.date: "03/30/2017" ms.assetid: 953d0b53-445e-41f9-b302-77c4030852ce --- -# \ Element (Uri Settings) - -Specifies if International Resource Identifier (IRI) parsing is applied to a and whether IRI parsing rules should be applied. - -[**\**](../configuration-element.md) -  [**\**](uri-element-uri-settings.md) -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Element**|**Description**| -|-----------------|---------------------| -|`enabled`|Specifies whether IRI parsing is enabled. The default value is `false`.| - -### Child Elements - - None - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[uri](uri-element-uri-settings.md)|Contains settings that specify how the .NET Framework handles web addresses expressed using uniform resource identifiers (URIs).| - -## Remarks - - The existing class has been extended in .NET Framework 3.5. 3.0 SP1, and 2.0 SP1 to provide support for International Resource Identifiers (IRI) and Internationalized Domain Names (IDN). Current users will not see any change from the .NET Framework 2.0 behavior unless they specifically enable IRI and IDN support. This ensures application compatibility with prior versions of the .NET Framework. - - To enable support for IRI, the following two changes are required: - -1. Add the following line to the machine.config file under the .NET Framework 2.0 directory - - ```xml -
- ``` - -2. Specify whether IRI parsing rules should be applied. This can be done in the machine.config or in the app.config file. - - Enabling IRI parsing (iriParsing enabled = `true`) will do normalization and character checking according to the latest IRI rules in RFC 3987. The default value is `false` and will do normalization and character checking according to RFC 2396 and RFC 3986 (for IPv6 literals). - -### Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - -### Description - - The following example shows a configuration used by the class to support IRI parsing and IDN names. - -### Code - -```xml - - - - - - -``` - +# `` Element (Uri Settings) + +Specifies if International Resource Identifier (IRI) parsing is applied to a and whether IRI parsing rules should be applied. + +[**\**](../configuration-element.md) +  [**\**](uri-element-uri-settings.md) +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Element**|**Description**| +|-----------------|---------------------| +|`enabled`|Specifies whether IRI parsing is enabled. The default value is `false`.| + +### Child Elements + + None + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[uri](uri-element-uri-settings.md)|Contains settings that specify how the .NET Framework handles web addresses expressed using uniform resource identifiers (URIs).| + +## Remarks + + The existing class has been extended in .NET Framework 3.5. 3.0 SP1, and 2.0 SP1 to provide support for International Resource Identifiers (IRI) and Internationalized Domain Names (IDN). Current users will not see any change from the .NET Framework 2.0 behavior unless they specifically enable IRI and IDN support. This ensures application compatibility with prior versions of the .NET Framework. + + To enable support for IRI, the following two changes are required: + +1. Add the following line to the machine.config file under the .NET Framework 2.0 directory + + ```xml +
+ ``` + +2. Specify whether IRI parsing rules should be applied. This can be done in the machine.config or in the app.config file. + + Enabling IRI parsing (iriParsing enabled = `true`) will do normalization and character checking according to the latest IRI rules in RFC 3987. The default value is `false` and will do normalization and character checking according to RFC 2396 and RFC 3986 (for IPv6 literals). + +### Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + +### Description + + The following example shows a configuration used by the class to support IRI parsing and IDN names. + +### Code + +```xml + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/mailsettings-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/mailsettings-element-network-settings.md index 913fd13c41aca..ccda7d1d3fd9f 100644 --- a/docs/framework/configure-apps/file-schema/network/mailsettings-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/mailsettings-element-network-settings.md @@ -2,70 +2,70 @@ title: " Element (Network Settings)" description: The network settings element configures the mail sending options in the .NET Framework. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#mailSettings" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/mailSettings" -helpviewer_keywords: +helpviewer_keywords: - "mailSettings element" - " element" ms.assetid: 54f0f153-17e5-4f49-afdc-deadb940c9c1 --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Configures mail sending options. +Configures mail sending options. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     **\** -## Syntax - -```xml +## Syntax + +```xml - ... + ... -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Attribute|Description| -|---------------|-----------------| -|[\ Element (Network Settings)](smtp-element-network-settings.md)|Configures Simple Mail Transport Protocol options.| - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[\ Element (Network Settings)](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| - -## Example - - The following example specifies the appropriate SMTP parameters to send email using the default network credentials. - -```xml - - - - - - - - - -``` - +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Attribute|Description| +|---------------|-----------------| +|[\ Element (Network Settings)](smtp-element-network-settings.md)|Configures Simple Mail Transport Protocol options.| + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[\ Element (Network Settings)](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| + +## Example + + The following example specifies the appropriate SMTP parameters to send email using the default network credentials. + +```xml + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/module-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/module-element-network-settings.md index 7059386b82f50..7df3d1c68a4e8 100644 --- a/docs/framework/configure-apps/file-schema/network/module-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/module-element-network-settings.md @@ -2,77 +2,77 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#module" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/defaultProxy/module" -helpviewer_keywords: +helpviewer_keywords: - "module element" - " element" ms.assetid: 10318725-9666-4d65-ab61-b94c64e59f13 --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Adds a new proxy module to the application. +Adds a new proxy module to the application. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](defaultproxy-element-network-settings.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`type`|The fully qualified type name (indicated by the property) and the assembly name (indicated by the property), separated by a comma, that implements the proxy.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[defaultProxy](defaultproxy-element-network-settings.md)|Configures the Hypertext Transfer Protocol (HTTP) proxy server.| - -## Remarks - - The `module` element registers proxy classes that implement the interface. After registering the proxy class, `module` can be used to request information through the supported proxy. - - The value for the `type` attribute should be the class name of the module and the name of its corresponding Dynamic Link Library (DLL). - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example registers a custom proxy class. - -```xml - - - - - - - -``` - +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`type`|The fully qualified type name (indicated by the property) and the assembly name (indicated by the property), separated by a comma, that implements the proxy.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[defaultProxy](defaultproxy-element-network-settings.md)|Configures the Hypertext Transfer Protocol (HTTP) proxy server.| + +## Remarks + + The `module` element registers proxy classes that implement the interface. After registering the proxy class, `module` can be used to request information through the supported proxy. + + The value for the `type` attribute should be the class name of the module and the name of its corresponding Dynamic Link Library (DLL). + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example registers a custom proxy class. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/network-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/network-element-network-settings.md index 0512cd445f989..b16fc6546e5ef 100644 --- a/docs/framework/configure-apps/file-schema/network/network-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/network-element-network-settings.md @@ -2,18 +2,18 @@ title: " Element (Network Settings)" description: The network settings element configures the network options for an external SMTP server options in the .NET Framework. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#network" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/mailSettings/smtp/network" -helpviewer_keywords: +helpviewer_keywords: - " element" - "network element" ms.assetid: 2c2c6ad4-ed11-48ab-b28e-2bc0ba9b42c7 ms.custom: sfi-ropc-nochange --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Configures the network options for an external Simple Mail Transport Protocol (SMTP) server. +Configures the network options for an external Simple Mail Transport Protocol (SMTP) server. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\ @@ -21,95 +21,95 @@ Configures the network options for an external Simple Mail Transport Protocol (S       [**\**](smtp-element-network-settings.md)\         **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`clientDomain`|Specifies the client domain name to use in the initial SMTP protocol request to connect to the SMTP mail server. The default value is the localhost name of the local computer sending the request.| -|`defaultCredentials`|Specifies whether the default user credentials should be used to access the SMTP mail server for SMTP transactions. The default value is `false`.| -|`enableSsl`|Specifies whether SSL is used to access an SMTP mail server. The default value is `false`.| -|`host`|Specifies the hostname of the SMTP mail server to use for SMTP transactions. This attribute has no default value.| -|`password`|Specifies the password to use for authentication to the SMTP mail server. This attribute has no default value.| -|`port`|Specifies the port number to use to connect to the SMTP mail server. The default value is 25.| -|`targetName`|Specifies the Service Provider Name (SPN) to use for authentication when using extended protection for SMTP transactions. This attribute has no default value.| -|`userName`|Specifies the user name to use for authentication to the SMTP mail server. This attribute has no default value.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\ Element (Network Settings)](smtp-element-network-settings.md)|Configures Simple Mail Transport Protocol (SMTP) mail sending options.| - -## Remarks - - Some SMTP servers require that you authenticate yourself to the server before use. If you want to authenticate yourself using the default network credentials on your host, set the `defaultCredentials` attribute to `true`. The property can be used to get the current value of the `defaultCredentials` attribute from applicable configuration files. - - You can also use basic authentication (a user name and password) to authenticate yourself to the SMTP server. To use this option, you must specify a valid user name and password for the specified SMTP server. - + targetName="string" + userName="string" +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`clientDomain`|Specifies the client domain name to use in the initial SMTP protocol request to connect to the SMTP mail server. The default value is the localhost name of the local computer sending the request.| +|`defaultCredentials`|Specifies whether the default user credentials should be used to access the SMTP mail server for SMTP transactions. The default value is `false`.| +|`enableSsl`|Specifies whether SSL is used to access an SMTP mail server. The default value is `false`.| +|`host`|Specifies the hostname of the SMTP mail server to use for SMTP transactions. This attribute has no default value.| +|`password`|Specifies the password to use for authentication to the SMTP mail server. This attribute has no default value.| +|`port`|Specifies the port number to use to connect to the SMTP mail server. The default value is 25.| +|`targetName`|Specifies the Service Provider Name (SPN) to use for authentication when using extended protection for SMTP transactions. This attribute has no default value.| +|`userName`|Specifies the user name to use for authentication to the SMTP mail server. This attribute has no default value.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\ Element (Network Settings)](smtp-element-network-settings.md)|Configures Simple Mail Transport Protocol (SMTP) mail sending options.| + +## Remarks + + Some SMTP servers require that you authenticate yourself to the server before use. If you want to authenticate yourself using the default network credentials on your host, set the `defaultCredentials` attribute to `true`. The property can be used to get the current value of the `defaultCredentials` attribute from applicable configuration files. + + You can also use basic authentication (a user name and password) to authenticate yourself to the SMTP server. To use this option, you must specify a valid user name and password for the specified SMTP server. + > [!NOTE] -> Basic authentication sends the `userName` and `password` values to the server unencrypted. Anyone monitoring network traffic can view your credentials and use them to connect to the server. You should consider using a more secure authentication mechanism, such as Kerberos or NT LAN Manager (NTLM.) If `defaultCredentials` is `true`, Kerberos or NTLM will be used if the server supports these protocols. - - The basic authentication and default network credentials options are mutually exclusive; if you set `defaultCredentials` to `true` and specify a user name and password, the default network credential is used, and the basic authentication data is ignored. - - For basic authentication if you specify a `userName`, you should also specify a `password` to authentication yourself to the mail server. - - The property can be used to get the current value of the `userName` attribute from applicable configuration files. The property can be used to get the current value of the `password` attribute from applicable configuration files. A `password` attribute would not normally be entered in configuration files for security reasons. - - The `clientDomain` attribute changes the client domain name used in the initial SMTP protocol request to an SMTP server. The `clientDomain` attribute can be set to the fully-qualified domain name of the local machine, rather than the localhost name that is used by default. This provides greater compliance with the SMTP protocol standards. The default value is the localhost name of the local computer sending the request. The property can be used to get the current value of the `clientDomain` attribute from applicable configuration files. - - The `targetName` attribute is used for authentication when using extended protection. The default value is of the form "SMTPSVC/\" where \ is the hostname of the SMTP mail server. The property can be used to get the current value of the `targetName` attribute from applicable configuration files. - - The `enableSsl` attribute specifies whether SSL is used to access an SMTP mail server. The class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information. - - An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported. - - The property can be used to get the current value of the `enableSsl` attribute from applicable configuration files. - -## Example - - The following example specifies the appropriate SMTP parameters to send email using the default network credentials. - -```xml - - - - - - - - - -``` - +> Basic authentication sends the `userName` and `password` values to the server unencrypted. Anyone monitoring network traffic can view your credentials and use them to connect to the server. You should consider using a more secure authentication mechanism, such as Kerberos or NT LAN Manager (NTLM.) If `defaultCredentials` is `true`, Kerberos or NTLM will be used if the server supports these protocols. + + The basic authentication and default network credentials options are mutually exclusive; if you set `defaultCredentials` to `true` and specify a user name and password, the default network credential is used, and the basic authentication data is ignored. + + For basic authentication if you specify a `userName`, you should also specify a `password` to authentication yourself to the mail server. + + The property can be used to get the current value of the `userName` attribute from applicable configuration files. The property can be used to get the current value of the `password` attribute from applicable configuration files. A `password` attribute would not normally be entered in configuration files for security reasons. + + The `clientDomain` attribute changes the client domain name used in the initial SMTP protocol request to an SMTP server. The `clientDomain` attribute can be set to the fully-qualified domain name of the local machine, rather than the localhost name that is used by default. This provides greater compliance with the SMTP protocol standards. The default value is the localhost name of the local computer sending the request. The property can be used to get the current value of the `clientDomain` attribute from applicable configuration files. + + The `targetName` attribute is used for authentication when using extended protection. The default value is of the form "SMTPSVC/\" where `` is the hostname of the SMTP mail server. The property can be used to get the current value of the `targetName` attribute from applicable configuration files. + + The `enableSsl` attribute specifies whether SSL is used to access an SMTP mail server. The class only supports the SMTP Service Extension for Secure SMTP over Transport Layer Security as defined in RFC 3207. In this mode, the SMTP session begins on an unencrypted channel, then a STARTTLS command is issued by the client to the server to switch to secure communication using SSL. See RFC 3207 published by the Internet Engineering Task Force (IETF) for more information. + + An alternate connection method is where an SSL session is established up front before any protocol commands are sent. This connection method is sometimes called SMTPS and by default uses port 465. This alternate connection method using SSL is not currently supported. + + The property can be used to get the current value of the `enableSsl` attribute from applicable configuration files. + +## Example + + The following example specifies the appropriate SMTP parameters to send email using the default network credentials. + +```xml + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/performancecounter-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/performancecounter-element-network-settings.md index fc9dd00c35127..d800431143bd6 100644 --- a/docs/framework/configure-apps/file-schema/network/performancecounter-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/performancecounter-element-network-settings.md @@ -2,76 +2,76 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/settings/performanceCounters" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#performanceCounters" -helpviewer_keywords: +helpviewer_keywords: - "performanceCounters element" ms.assetid: 3afa1586-e1b8-473d-8985-c3fc90cf561b --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Enables or disables networking performance counters. +Enables or disables networking performance counters. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](settings-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Specifies whether the networking performance counters are enabled. The default value is `false`.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| - -## Remarks - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - - Networking performance counters need to be enabled in the configuration file to be used. All networking performance counters are enabled or disabled with a single setting in the configuration file. Individual networking performance counters cannot be enabled or disabled. For more information on the specific networking performance counters, see [Networking performance counters](../../../debug-trace-profile/performance-counters.md#networking-performance-counters). - - The default value is that networking performance counters are disabled. - - The property can be used to get the current value of the **enabled** attribute from applicable configuration files. - -## Example - - The following example shows how to configure the and related namespaces to enable networking performance counters. - -```xml - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Specifies whether the networking performance counters are enabled. The default value is `false`.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| + +## Remarks + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + + Networking performance counters need to be enabled in the configuration file to be used. All networking performance counters are enabled or disabled with a single setting in the configuration file. Individual networking performance counters cannot be enabled or disabled. For more information on the specific networking performance counters, see [Networking performance counters](../../../debug-trace-profile/performance-counters.md#networking-performance-counters). + + The default value is that networking performance counters are disabled. + + The property can be used to get the current value of the `enabled` attribute from applicable configuration files. + +## Example + + The following example shows how to configure the and related namespaces to enable networking performance counters. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/proxy-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/proxy-element-network-settings.md index e9d36e3d0afb1..0cd2aabec3f0e 100644 --- a/docs/framework/configure-apps/file-schema/network/proxy-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/proxy-element-network-settings.md @@ -2,26 +2,26 @@ title: " Element (Network Settings)" description: The network settings element defines the proxy server options in the .NET Framework. This article includes an example. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/defaultProxy/proxy" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#proxy" -helpviewer_keywords: +helpviewer_keywords: - " element" - "proxy element" ms.assetid: 37a548d8-fade-4ac5-82ec-b49b6c6cb22a --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Defines a proxy server. +Defines a proxy server. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](defaultproxy-element-network-settings.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`autoDetect`|Specifies whether the proxy is automatically detected. The default value is `Unspecified`.| -|`bypassonlocal`|Specifies whether the proxy is bypassed for local resources. Local resources include the local server (`http://localhost`, `http://loopback`, or `http://127.0.0.1`) and a URI without a period (`http://webserver`). The default value is `Unspecified`.| -|`proxyaddress`|Specifies the proxy URI to use.| -|`scriptLocation`|Specifies the location of the configuration script. Do not use the `bypassonlocal` attribute with this attribute. | -|`usesystemdefault`|Specifies whether to use system proxy settings. If set to `True`, subsequent attributes will override system proxy settings. The default value is `Unspecified`.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[defaultProxy](defaultproxy-element-network-settings.md)|Configures the Hypertext Transfer Protocol (HTTP) proxy server.| - -## Text Value - -## Remarks - - The `proxy` element defines a proxy server for an application. If this element is missing from the configuration file, then .NET Framework will use the system proxy settings. - - The value for the `proxyaddress` attribute should be a well-formed Uniform Resource Indicator (URI). - +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`autoDetect`|Specifies whether the proxy is automatically detected. The default value is `Unspecified`.| +|`bypassonlocal`|Specifies whether the proxy is bypassed for local resources. Local resources include the local server (`http://localhost`, `http://loopback`, or `http://127.0.0.1`) and a URI without a period (`http://webserver`). The default value is `Unspecified`.| +|`proxyaddress`|Specifies the proxy URI to use.| +|`scriptLocation`|Specifies the location of the configuration script. Do not use the `bypassonlocal` attribute with this attribute. | +|`usesystemdefault`|Specifies whether to use system proxy settings. If set to `True`, subsequent attributes will override system proxy settings. The default value is `Unspecified`.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[defaultProxy](defaultproxy-element-network-settings.md)|Configures the Hypertext Transfer Protocol (HTTP) proxy server.| + +## Text Value + +## Remarks + + The `proxy` element defines a proxy server for an application. If this element is missing from the configuration file, then .NET Framework will use the system proxy settings. + + The value for the `proxyaddress` attribute should be a well-formed Uniform Resource Indicator (URI). + The `scriptLocation` attribute refers to the automatic detection of proxy configuration scripts. The class will attempt to locate a configuration script (usually named Wpad.dat) when the **Use automatic configuration script** option is selected for the connection in Internet properties. If `bypassonlocal` is set to any value, `scriptLocation` is ignored. - - An exception is thrown if the `proxyaddress` attribute specifies an invalid default proxy. The property on the exception should have more information about the root cause of the error. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example uses the defaults from the system proxy, specifies the proxy address, and bypasses the proxy for local access. - -```xml - - - - - - - -``` - + + An exception is thrown if the `proxyaddress` attribute specifies an invalid default proxy. The property on the exception should have more information about the root cause of the error. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example uses the defaults from the system proxy, specifies the proxy address, and bypasses the proxy for local access. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/remove-element-for-authenticationmodules-network-settings.md b/docs/framework/configure-apps/file-schema/network/remove-element-for-authenticationmodules-network-settings.md index 41f3939c1ef40..d41f3aa506cbe 100644 --- a/docs/framework/configure-apps/file-schema/network/remove-element-for-authenticationmodules-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/remove-element-for-authenticationmodules-network-settings.md @@ -2,77 +2,77 @@ description: "Learn more about: Element for authenticationModules (Network Settings)" title: " Element for authenticationModules (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/authenticationModules/remove" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#remove" -helpviewer_keywords: +helpviewer_keywords: - "remove element, authenticationModules" - ", remove element" - " element, authenticationModules" - "authenticationModules, remove element" ms.assetid: abf79949-b05c-465a-b51c-bbeda9a74173 --- -# \ Element for authenticationModules (Network Settings) +# `` Element for authenticationModules (Network Settings) -Removes an authentication module from the application. +Removes an authentication module from the application. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](authenticationmodules-element-network-settings.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|**type**|The name of the authentication module to remove.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[authenticationModules](authenticationmodules-element-network-settings.md)|Specifies modules used to authenticate network requests.| - -## Remarks - - The `remove` element removes authentication modules that were defined earlier in the configuration file or at a higher level in the configuration hierarchy. - - The value for the `type` attribute should be a valid class name. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example removes an authentication module. - -```xml - - - - - - - -``` - +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|**type**|The name of the authentication module to remove.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[authenticationModules](authenticationmodules-element-network-settings.md)|Specifies modules used to authenticate network requests.| + +## Remarks + + The `remove` element removes authentication modules that were defined earlier in the configuration file or at a higher level in the configuration hierarchy. + + The value for the `type` attribute should be a valid class name. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example removes an authentication module. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/remove-element-for-bypasslist-network-settings.md b/docs/framework/configure-apps/file-schema/network/remove-element-for-bypasslist-network-settings.md index fded5c966b26e..368f90fe82909 100644 --- a/docs/framework/configure-apps/file-schema/network/remove-element-for-bypasslist-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/remove-element-for-bypasslist-network-settings.md @@ -13,15 +13,15 @@ helpviewer_keywords: ms.assetid: 61dcfb4a-e3d9-4abf-a2cd-7d685fe2f64b --- -# \ Element for bypasslist (Network Settings) +# `` Element for bypasslist (Network Settings) Removes an IP address or DNS name from the proxy bypass list. -[**\**](../configuration-element.md) -  [**\**](system-net-element-network-settings.md) -    [**\**](defaultproxy-element-network-settings.md) -      [**\**](bypasslist-element-network-settings.md) -        **\** +[**\**](../configuration-element.md) +  [**\**](system-net-element-network-settings.md) +    [**\**](defaultproxy-element-network-settings.md) +      [**\**](bypasslist-element-network-settings.md) +        **\** ## Syntax diff --git a/docs/framework/configure-apps/file-schema/network/remove-element-for-connectionmanagement-network-settings.md b/docs/framework/configure-apps/file-schema/network/remove-element-for-connectionmanagement-network-settings.md index f4c278382ac8d..6e4e9820bce4e 100644 --- a/docs/framework/configure-apps/file-schema/network/remove-element-for-connectionmanagement-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/remove-element-for-connectionmanagement-network-settings.md @@ -2,79 +2,79 @@ description: "Learn more about: Element for connectionManagement (Network Settings)" title: " Element for connectionManagement (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/connectionManagement/remove" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#remove" -helpviewer_keywords: +helpviewer_keywords: - "connectionManagement, remove element" - " element, connectionManagement" - ", remove element" - "remove element, connectionManagement" ms.assetid: 94b81775-5a22-4975-8c47-8620c40c3f35 --- -# \ Element for connectionManagement (Network Settings) +# `` Element for connectionManagement (Network Settings) -Removes an IP address or DNS name from the connection management list. +Removes an IP address or DNS name from the connection management list. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](connectionmanagement-element-network-settings.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`address`|An IP address or DNS name.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[connectionManagement](connectionmanagement-element-network-settings.md)|Specifies the maximum number of connections to a network host.| - -## Remarks - - The `remove` element removes the connection management list entry for the specified server. - - The value of the `address` attribute should be a valid IP address or host name. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example removes any connection management list entries for the server `www.adventure-works.com` and then configures an application to use four connections to the server `www.contoso.com` and two connections to all other servers. - -```xml - - - - - - - - - -``` - +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`address`|An IP address or DNS name.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[connectionManagement](connectionmanagement-element-network-settings.md)|Specifies the maximum number of connections to a network host.| + +## Remarks + + The `remove` element removes the connection management list entry for the specified server. + + The value of the `address` attribute should be a valid IP address or host name. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example removes any connection management list entries for the server `www.adventure-works.com` and then configures an application to use four connections to the server `www.contoso.com` and two connections to all other servers. + +```xml + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/remove-element-for-schemesettings-uri-settings.md b/docs/framework/configure-apps/file-schema/network/remove-element-for-schemesettings-uri-settings.md index bef0cafefc0dc..8fa2bbf74e54c 100644 --- a/docs/framework/configure-apps/file-schema/network/remove-element-for-schemesettings-uri-settings.md +++ b/docs/framework/configure-apps/file-schema/network/remove-element-for-schemesettings-uri-settings.md @@ -4,77 +4,77 @@ title: " Element for schemeSettings (Uri Settings)" ms.date: "03/30/2017" ms.assetid: 4095ba51-de20-4f87-b562-018abe422c91 --- -# \ Element for schemeSettings (Uri Settings) +# `` Element for schemeSettings (Uri Settings) -Removes a scheme setting for a scheme name. +Removes a scheme setting for a scheme name. [**\**](../configuration-element.md)\   [**\**](uri-element-uri-settings.md)\     [**\**](schemesettings-element-uri-settings.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|name|The scheme name for which this setting applies. The only supported values are name="http" and name="https".| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\ Element (Uri Settings)](schemesettings-element-uri-settings.md)|Specifies how a will be parsed for specific schemes.| - -## Remarks - - By default, the class un-escapes percent encoded path delimiters before executing path compression. This was implemented as a security mechanism against attacks like the following: - - `http://www.contoso.com/..%2F..%2F/Windows/System32/cmd.exe?/c+dir+c:\` - - If this URI gets passed down to modules not handling percent encoded characters correctly, it could result in the following command being executed by the server: - - `c:\Windows\System32\cmd.exe /c dir c:\` - - For this reason, class first un-escapes path delimiters and then applies path compression. The result of passing the malicious URL above to class constructor results in the following URI: - - `http://www.microsoft.com/Windows/System32/cmd.exe?/c+dir+c:\` - - This default behavior can be modified to not un-escape percent encoded path delimiters using the schemeSettings configuration option for a specific scheme. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example shows a configuration used by the class that removes any scheme settings for the http scheme. - -```xml - - - - - - - -``` - +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|name|The scheme name for which this setting applies. The only supported values are name="http" and name="https".| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\ Element (Uri Settings)](schemesettings-element-uri-settings.md)|Specifies how a will be parsed for specific schemes.| + +## Remarks + + By default, the class un-escapes percent encoded path delimiters before executing path compression. This was implemented as a security mechanism against attacks like the following: + + `http://www.contoso.com/..%2F..%2F/Windows/System32/cmd.exe?/c+dir+c:\` + + If this URI gets passed down to modules not handling percent encoded characters correctly, it could result in the following command being executed by the server: + + `c:\Windows\System32\cmd.exe /c dir c:\` + + For this reason, class first un-escapes path delimiters and then applies path compression. The result of passing the malicious URL above to class constructor results in the following URI: + + `http://www.microsoft.com/Windows/System32/cmd.exe?/c+dir+c:\` + + This default behavior can be modified to not un-escape percent encoded path delimiters using the schemeSettings configuration option for a specific scheme. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example shows a configuration used by the class that removes any scheme settings for the http scheme. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/remove-element-for-webrequestmodules-network-settings.md b/docs/framework/configure-apps/file-schema/network/remove-element-for-webrequestmodules-network-settings.md index 519d9af1b6201..efa09d01a10fe 100644 --- a/docs/framework/configure-apps/file-schema/network/remove-element-for-webrequestmodules-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/remove-element-for-webrequestmodules-network-settings.md @@ -2,81 +2,81 @@ description: "Learn more about: Element for webRequestModules (Network Settings)" title: " Element for webRequestModules (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/webRequestModules/remove" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#remove" -helpviewer_keywords: +helpviewer_keywords: - "remove element, webRequestModules" - "webRequestModules, remove element" - " element, webRequestModules" - ", remove element" ms.assetid: dd84d2fe-2f4f-457a-9d3c-441d0d21cc10 --- -# \ Element for webRequestModules (Network Settings) +# `` Element for webRequestModules (Network Settings) + +Removes a custom Web request module from the application. -Removes a custom Web request module from the application. - [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](webrequestmodules-element-network-settings.md)\       **\** - -## Syntax - -```xml + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`prefix`|The URI prefix for requests handled by this Web request module.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[webRequestModules](webrequestmodules-element-network-settings.md)|Specifies modules to use to request information from network hosts.| - -## Remarks - - The `remove` element removes the registered Web request module for the specified URI prefix. - - The value for the `prefix` attribute should be the leading characters of a valid URI -- for example, "`http`", or "`http://www.contoso.com`". - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`prefix`|The URI prefix for requests handled by this Web request module.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[webRequestModules](webrequestmodules-element-network-settings.md)|Specifies modules to use to request information from network hosts.| + +## Remarks + + The `remove` element removes the registered Web request module for the specified URI prefix. + + The value for the `prefix` attribute should be the leading characters of a valid URI -- for example, "`http`", or "`http://www.contoso.com`". + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example The following example removes the existing Web request module for HTTP and then registers a new custom Web request module for HTTP requests to `www.contoso.com`. - -```xml - - - - - - - - -``` - + +```xml + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/requestcaching-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/requestcaching-element-network-settings.md index a8b04411ccc34..e72d512c8c954 100644 --- a/docs/framework/configure-apps/file-schema/network/requestcaching-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/requestcaching-element-network-settings.md @@ -2,88 +2,88 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#requestCaching" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/requestCaching" -helpviewer_keywords: +helpviewer_keywords: - "requestCaching element" - " element" ms.assetid: 9962a2fe-cbda-41a6-9377-571811eaea84 --- -# \ Element (Network Settings) - -Controls the caching mechanism for network requests. - -[**\**](../configuration-element.md) -  [**\**](system-net-element-network-settings.md) -    **\** - -## Syntax - -```xml - - ... - ... +# `` Element (Network Settings) + +Controls the caching mechanism for network requests. + +[**\**](../configuration-element.md) +  [**\**](system-net-element-network-settings.md) +    **\** + +## Syntax + +```xml + + ... + ... -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`isPrivateCache`|Specifies whether the cache provides isolation between the information of different users. The default value is `true`. This value should be `false` for middle tier applications.| -|`disableAllCaching`|Specifies that caching is disabled for all Web responses, and cannot be overridden programmatically.| -|`defaultPolicyLevel`|One of the values in the enumeration. The default value is `BypassCache`.| -|`unspecifiedMaximumAge`|Specifies the default time after which content is marked as expired.| - -## policyLevel Attribute - -|Value|Description| -|-----------|-----------------| -|`Default`|Returns the cached resource if the resource is fresh, the content length is accurate, and the expiration, modification, and content length attributes are present.| -|`BypassCache`|Returns the resource from the server.| -|`CacheOnly`|Returns the cached resource if the content length is present and matches the entry size.| -|`CacheIfAvailable`|Returns the cached resource if the content length is provided and matches the entry size; otherwise, the resource is downloaded from the server and is returned to the caller.| -|`Revalidate`|Returns the cached resource if the timestamp of the cached resource is the same as the timestamp of the resource on the server; otherwise, the resource is downloaded from the server, stored in the cache, and is returned to the caller.| -|`Reload`|Downloads the resource from the server, stores it in the cache, and returns the resource to the caller.| -|`NoCacheNoStore`|If a cached resource exists, it is deleted. The resource is downloaded from the server and is returned to the caller.| -|`Revalidate`|Satisfies a request by using the cached copy of the resource if the timestamp is the same as the timestamp of the resource on the server; otherwise, the resource is downloaded from the server, presented to the caller, and is stored in the cache,| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[defaultHttpCachePolicy](defaulthttpcachepolicy-element-network-settings.md)|Optional element.

Describes whether HTTP caching is active and describes the default caching policy.| -|[\ Element (Network Settings)](defaultftpcachepolicy-element-network-settings.md)|Optional element.

Describes whether FTP caching is active and describes the default caching policy.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[system.net](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| - -## Example - - The following example shows how to disable all caching. - -```xml - - - - - -``` - +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`isPrivateCache`|Specifies whether the cache provides isolation between the information of different users. The default value is `true`. This value should be `false` for middle tier applications.| +|`disableAllCaching`|Specifies that caching is disabled for all Web responses, and cannot be overridden programmatically.| +|`defaultPolicyLevel`|One of the values in the enumeration. The default value is `BypassCache`.| +|`unspecifiedMaximumAge`|Specifies the default time after which content is marked as expired.| + +## policyLevel Attribute + +|Value|Description| +|-----------|-----------------| +|`Default`|Returns the cached resource if the resource is fresh, the content length is accurate, and the expiration, modification, and content length attributes are present.| +|`BypassCache`|Returns the resource from the server.| +|`CacheOnly`|Returns the cached resource if the content length is present and matches the entry size.| +|`CacheIfAvailable`|Returns the cached resource if the content length is provided and matches the entry size; otherwise, the resource is downloaded from the server and is returned to the caller.| +|`Revalidate`|Returns the cached resource if the timestamp of the cached resource is the same as the timestamp of the resource on the server; otherwise, the resource is downloaded from the server, stored in the cache, and is returned to the caller.| +|`Reload`|Downloads the resource from the server, stores it in the cache, and returns the resource to the caller.| +|`NoCacheNoStore`|If a cached resource exists, it is deleted. The resource is downloaded from the server and is returned to the caller.| +|`Revalidate`|Satisfies a request by using the cached copy of the resource if the timestamp is the same as the timestamp of the resource on the server; otherwise, the resource is downloaded from the server, presented to the caller, and is stored in the cache,| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[defaultHttpCachePolicy](defaulthttpcachepolicy-element-network-settings.md)|Optional element.

Describes whether HTTP caching is active and describes the default caching policy.| +|[\ Element (Network Settings)](defaultftpcachepolicy-element-network-settings.md)|Optional element.

Describes whether FTP caching is active and describes the default caching policy.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[system.net](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| + +## Example + + The following example shows how to disable all caching. + +```xml + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/schemesettings-element-uri-settings.md b/docs/framework/configure-apps/file-schema/network/schemesettings-element-uri-settings.md index f66fae81ddcf9..8fe69a0ff14c2 100644 --- a/docs/framework/configure-apps/file-schema/network/schemesettings-element-uri-settings.md +++ b/docs/framework/configure-apps/file-schema/network/schemesettings-element-uri-settings.md @@ -4,77 +4,77 @@ title: " Element (Uri Settings)" ms.date: "03/30/2017" ms.assetid: 0ae45c6e-8c4c-4c0d-8b9f-a93824648890 --- -# \ Element (Uri Settings) - -Specifies how a will be parsed for specific schemes. - -[**\**](../configuration-element.md) -  [**\**](uri-element-uri-settings.md) -    **\** - -## Syntax - -```xml +# `` Element (Uri Settings) + +Specifies how a will be parsed for specific schemes. + +[**\**](../configuration-element.md) +  [**\**](uri-element-uri-settings.md) +    **\** + +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None - -### Child Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[add](add-element-for-schemesettings-uri-settings.md)|Adds a scheme setting for a scheme name.| -|[clear](clear-element-for-schemesettings-uri-settings.md)|Clears all existing scheme settings.| -|[remove](remove-element-for-schemesettings-uri-settings.md)|Removes a scheme setting for a scheme name.| - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[uri](uri-element-uri-settings.md)|Contains settings that specify how the .NET Framework handles web addresses expressed using uniform resource identifiers (URIs).| - -## Remarks - - By default, the class un-escapes percent encoded path delimiters before executing path compression. This was implemented as a security mechanism against attacks like the following: - - `http://www.contoso.com/..%2F..%2F/Windows/System32/cmd.exe?/c+dir+c:\` - - If this URI gets passed down to modules not handling percent encoded characters correctly, it could result in the following command being executed by the server: - - `c:\Windows\System32\cmd.exe /c dir c:\` - - For this reason, class first un-escapes path delimiters and then applies path compression. The result of passing the malicious URL above to class constructor results in the following URI: - - `http://www.contoso.com/Windows/System32/cmd.exe?/c+dir+c:\` - - This default behavior can be modified to not un-escape percent encoded path delimiters using the schemeSettings configuration option for a specific scheme. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example shows a configuration used by the class to support not escaping percent-encoded path delimiters for the http scheme. - -```xml - - - - - - - -``` - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None + +### Child Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[add](add-element-for-schemesettings-uri-settings.md)|Adds a scheme setting for a scheme name.| +|[clear](clear-element-for-schemesettings-uri-settings.md)|Clears all existing scheme settings.| +|[remove](remove-element-for-schemesettings-uri-settings.md)|Removes a scheme setting for a scheme name.| + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[uri](uri-element-uri-settings.md)|Contains settings that specify how the .NET Framework handles web addresses expressed using uniform resource identifiers (URIs).| + +## Remarks + + By default, the class un-escapes percent encoded path delimiters before executing path compression. This was implemented as a security mechanism against attacks like the following: + + `http://www.contoso.com/..%2F..%2F/Windows/System32/cmd.exe?/c+dir+c:\` + + If this URI gets passed down to modules not handling percent encoded characters correctly, it could result in the following command being executed by the server: + + `c:\Windows\System32\cmd.exe /c dir c:\` + + For this reason, class first un-escapes path delimiters and then applies path compression. The result of passing the malicious URL above to class constructor results in the following URI: + + `http://www.contoso.com/Windows/System32/cmd.exe?/c+dir+c:\` + + This default behavior can be modified to not un-escape percent encoded path delimiters using the schemeSettings configuration option for a specific scheme. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example shows a configuration used by the class to support not escaping percent-encoded path delimiters for the http scheme. + +```xml + + + + + + + +``` + ## Element Information **Namespace**: System diff --git a/docs/framework/configure-apps/file-schema/network/servicepointmanager-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/servicepointmanager-element-network-settings.md index 412ea1e0ef3ae..ef1e550cfc05b 100644 --- a/docs/framework/configure-apps/file-schema/network/servicepointmanager-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/servicepointmanager-element-network-settings.md @@ -2,69 +2,69 @@ title: " Element (Network Settings)" description: The network settings element configures connections to network resources options in the .NET Framework. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#servicePointManager" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/settings/servicePointManager" -helpviewer_keywords: +helpviewer_keywords: - "servicePointManager element" - " element" ms.assetid: 6e5def51-3646-4ef6-a7bd-c69151321bec --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Configures connections to network resources. +Configures connections to network resources. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](settings-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`checkCertificateName`|Specifies whether the system should verify that the name on the certificate matches the server host name before using the certificate. The default value is `true`.| -|`checkCertificateRevocationList`|Specifies whether the system should check whether the certificate has been revoked before using the certificate. The default value is `false`.| -|`dnsRefreshTimeout`|Specifies how long Domain Name Service (DNS) resolutions are cached in conjunction with the DNS Round Robin option, in milliseconds. The default value is 120,000 milliseconds (two minutes).| -|`enableDnsRoundRobin`|Specifies whether DNS resolutions of host names with multiple Internet Protocol (IP) addresses return all the addresses, or just the first one. The default value is `false`.| -|`encryptionPolicy`|Specifies the encryption policy applied to an SSL/TLS session on a instance. The possible values are equivalent to the values for the enumeration. The use of is required when the encryption policy is set to `NoEncryption`. The default value is `RequireEncryption`.| -|`expect100Continue`|Specifies whether POST methods should expect to receive a `100-continue` response from the server. The default value is `true`.| -|`useNagleAlgorithm`|Specifies whether connections controlled by the service point manager use the Nagle algorithm. The default value is `true`.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[Settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| - -## Remarks - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`checkCertificateName`|Specifies whether the system should verify that the name on the certificate matches the server host name before using the certificate. The default value is `true`.| +|`checkCertificateRevocationList`|Specifies whether the system should check whether the certificate has been revoked before using the certificate. The default value is `false`.| +|`dnsRefreshTimeout`|Specifies how long Domain Name Service (DNS) resolutions are cached in conjunction with the DNS Round Robin option, in milliseconds. The default value is 120,000 milliseconds (two minutes).| +|`enableDnsRoundRobin`|Specifies whether DNS resolutions of host names with multiple Internet Protocol (IP) addresses return all the addresses, or just the first one. The default value is `false`.| +|`encryptionPolicy`|Specifies the encryption policy applied to an SSL/TLS session on a instance. The possible values are equivalent to the values for the enumeration. The use of is required when the encryption policy is set to `NoEncryption`. The default value is `RequireEncryption`.| +|`expect100Continue`|Specifies whether POST methods should expect to receive a `100-continue` response from the server. The default value is `true`.| +|`useNagleAlgorithm`|Specifies whether connections controlled by the service point manager use the Nagle algorithm. The default value is `true`.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[Settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| + +## Remarks + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/settings-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/settings-element-network-settings.md index 63e57b34b83ac..0e4380c565bd5 100644 --- a/docs/framework/configure-apps/file-schema/network/settings-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/settings-element-network-settings.md @@ -2,68 +2,68 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#settings" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/settings" -helpviewer_keywords: +helpviewer_keywords: - "settings element" - " element" ms.assetid: 189ce989-c39b-427d-b004-6b82a668b931 --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Configures basic network options for the namespace. +Configures basic network options for the namespace. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     **\** -## Syntax - -```xml - - ... - ... - ... - ... - ... - ... - ... - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[httpListener](httplistener-element-network-settings.md)|Customizes parameters used by the class.| -|[httpWebRequest](httpwebrequest-element-network-settings.md)|Customizes Web request parameters.| -|[ipv6](ipv6-element-network-settings.md)|Enables Internet Protocol version 6 (IPv6) support.| -|[\ Element (Network Settings)](performancecounter-element-network-settings.md)|Enables network performance counters.| -|[servicePointManager](servicepointmanager-element-network-settings.md)|Configures connections to network resources.| -|[socket](socket-element-network-settings.md)|Specifies whether socket operations use completion ports.| -|[\ Element (Network Settings)](webproxyscript-element-network-settings.md)|Configures the characteristics of the script used to discover Web proxies.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[system.net](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| - -## Remarks - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - +## Syntax + +```xml + + ... + ... + ... + ... + ... + ... + ... + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[httpListener](httplistener-element-network-settings.md)|Customizes parameters used by the class.| +|[httpWebRequest](httpwebrequest-element-network-settings.md)|Customizes Web request parameters.| +|[ipv6](ipv6-element-network-settings.md)|Enables Internet Protocol version 6 (IPv6) support.| +|[\ Element (Network Settings)](performancecounter-element-network-settings.md)|Enables network performance counters.| +|[servicePointManager](servicepointmanager-element-network-settings.md)|Configures connections to network resources.| +|[socket](socket-element-network-settings.md)|Specifies whether socket operations use completion ports.| +|[\ Element (Network Settings)](webproxyscript-element-network-settings.md)|Configures the characteristics of the script used to discover Web proxies.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[system.net](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| + +## Remarks + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/smtp-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/smtp-element-network-settings.md index fea2513505f7f..92f9113e98a8a 100644 --- a/docs/framework/configure-apps/file-schema/network/smtp-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/smtp-element-network-settings.md @@ -2,80 +2,80 @@ title: " Element (Network Settings)" description: The network settings element configures the delivery format, delivery method, and from address for sending emails options in the .NET Framework. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/mailSettings/smtp" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#smtp" -helpviewer_keywords: +helpviewer_keywords: - " element" - "smtp element" ms.assetid: 220b0329-e384-4e0c-86b4-0945ad17efd9 --- -# \ Element (Network Settings) +# `` Element (Network Settings) + +Configures the delivery format, delivery method, and from address for sending emails. -Configures the delivery format, delivery method, and from address for sending emails. - [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](mailsettings-element-network-settings.md)\       **\** - -## Syntax - -```xml - - ... - ... - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`deliveryFormat`|Specifies the delivery format for outgoing emails. Acceptable values are SevenBit and International.| -|`deliveryMethod`|Specifies the delivery method for emails. Acceptable values are Network, PickupDirectoryFromIis, and SpecifiedPickupDirectory.| -|`from`|Specifies the from address for outgoing emails.| - -### Child Elements - -|Attribute|Description| -|---------------|-----------------| -|`specifiedPickupDirectory`|Configures the local directory for a Simple Mail Transport Protocol (SMTP) server.| -|`network`|Configures the network options for an external SMTP server.| - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[\ Element (Network Settings)](mailsettings-element-network-settings.md)|Configures mail sending options.| - -## Example - - The following example specifies the appropriate SMTP parameters to send email using the default network credentials. - -```xml - - - - - - - - - -``` - + ... + ... + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`deliveryFormat`|Specifies the delivery format for outgoing emails. Acceptable values are SevenBit and International.| +|`deliveryMethod`|Specifies the delivery method for emails. Acceptable values are Network, PickupDirectoryFromIis, and SpecifiedPickupDirectory.| +|`from`|Specifies the from address for outgoing emails.| + +### Child Elements + +|Attribute|Description| +|---------------|-----------------| +|`specifiedPickupDirectory`|Configures the local directory for a Simple Mail Transport Protocol (SMTP) server.| +|`network`|Configures the network options for an external SMTP server.| + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[\ Element (Network Settings)](mailsettings-element-network-settings.md)|Configures mail sending options.| + +## Example + + The following example specifies the appropriate SMTP parameters to send email using the default network credentials. + +```xml + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/socket-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/socket-element-network-settings.md index d3a7f7971f53d..6ecd5f0badd03 100644 --- a/docs/framework/configure-apps/file-schema/network/socket-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/socket-element-network-settings.md @@ -2,108 +2,108 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/settings/socket" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#socket" -helpviewer_keywords: +helpviewer_keywords: - " element" - "socket element" ms.assetid: 366c634c-7d16-478f-aedf-053eda94a1a0 --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Specifies whether socket operations use completion ports. +Specifies whether socket operations use completion ports. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](settings-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|**Attribute**|**Description**| -|-------------------|---------------------| -|`alwaysUseCompletionPortsForAccept`|Indicates whether the socket should always use completion ports for Accept method calls. The default value is `false`.| -|`alwaysUseCompletionPortsForConnect`|Indicates whether the socket should always use completion ports for Connect method calls. The default value is `false`.| -|`ipProtectionLevel`|Specifies the default to use for a socket. The default value depends on the version of Windows.| - -### Child Elements - - None. - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| - -## Remarks - - The `alwaysUseCompletionPortsForAccept` and `alwaysUseCompletionPortsForConnect` attributes are used to specify the default behavior regarding the use of completion ports by the classes in the .namespace. Completion ports are recommended for high performance server applications. - - The default value for the `alwaysUseCompletionPortsForAccept` and `alwaysUseCompletionPortsForConnect` attributes is **false**. - - The can be used to get the current value of the `alwaysUseCompletionPortsForAccept` attribute from applicable configuration files. The can be used to get the current value of the `alwaysUseCompletionPortsForConnect` attribute from applicable configuration files. - - The `ipProtectionLevel` attribute specifies the default to use for a socket. The property enables configuration of a restriction for an IPv6 socket to a specified scope, such as addresses with the same link local or site local prefix. This option enables applications to place access restrictions on IPv6 sockets. Such restrictions enable an application running on a private LAN to simply and robustly harden itself against external attacks. This option widens or narrows the scope of a listening socket, enabling unrestricted access from public and private users when appropriate, or restricting access only to the same site, as required. - - This `ipProtectionLevel` attribute setting affects only initial incoming traffic: - -- A TCP server listening for incoming connections on a socket. - -- A UDP application receiving a packet on a socket. - - This configuration setting does not affect already established TCP connections (traffic is unrestricted in both directions) and does not affect an application sending UDP packets. - - The possible values for the `ipProtectionLevel` attribute setting correspond with the defined protection levels specified in the enumeration as follows: - -|**Attribute Value**|**Description**| -|-|-| -|EdgeRestricted|The IP protection level is edge restricted. This value would be used by applications designed to operate across the Internet. This setting does not allow Network Address Translation (NAT) traversal using the Windows Teredo implementation. These applications may bypass IPv4 firewalls, so applications must be hardened against Internet attacks directed at the opened port. On Windows Server 2003 and Windows XP, the default value for the IP Protection level on a socket is edge restricted.| -|Restricted|The IP protection level is restricted. This value would be used by intranet applications that do not implement Internet scenarios. These applications are generally not tested or hardened against Internet-style attacks. This setting will limit the received traffic to link-local only.| -|Unrestricted|The IP protection level is unrestricted. This value would be used by applications designed to operate across the Internet, including applications taking advantage of IPv6 NAT traversal capabilities built into Windows (Teredo, for example). These applications may bypass IPv4 firewalls, so applications must be hardened against Internet attacks directed at the opened port. On Windows Server 2008 R2 and Windows Vista, the default value for the IP Protection level on a socket is unrestricted.| -|Unspecified|The IP protection level is unspecified. On Windows 7 and Windows Server 2008 R2, the default value for the IP Protection level on a socket is unspecified.| - - The default value for the `ipProtectionLevel` attribute is **Unspecified**. - - The property can be used to get the current value of the `ipProtectionLevel` attribute from applicable configuration files. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example shows how to specify that completion ports should be used and that the default should be unrestricted. - -```xml - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|**Attribute**|**Description**| +|-------------------|---------------------| +|`alwaysUseCompletionPortsForAccept`|Indicates whether the socket should always use completion ports for Accept method calls. The default value is `false`.| +|`alwaysUseCompletionPortsForConnect`|Indicates whether the socket should always use completion ports for Connect method calls. The default value is `false`.| +|`ipProtectionLevel`|Specifies the default to use for a socket. The default value depends on the version of Windows.| + +### Child Elements + + None. + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| + +## Remarks + + The `alwaysUseCompletionPortsForAccept` and `alwaysUseCompletionPortsForConnect` attributes are used to specify the default behavior regarding the use of completion ports by the classes in the .namespace. Completion ports are recommended for high performance server applications. + + The default value for the `alwaysUseCompletionPortsForAccept` and `alwaysUseCompletionPortsForConnect` attributes is **false**. + + The can be used to get the current value of the `alwaysUseCompletionPortsForAccept` attribute from applicable configuration files. The can be used to get the current value of the `alwaysUseCompletionPortsForConnect` attribute from applicable configuration files. + + The `ipProtectionLevel` attribute specifies the default to use for a socket. The property enables configuration of a restriction for an IPv6 socket to a specified scope, such as addresses with the same link local or site local prefix. This option enables applications to place access restrictions on IPv6 sockets. Such restrictions enable an application running on a private LAN to simply and robustly harden itself against external attacks. This option widens or narrows the scope of a listening socket, enabling unrestricted access from public and private users when appropriate, or restricting access only to the same site, as required. + + This `ipProtectionLevel` attribute setting affects only initial incoming traffic: + +- A TCP server listening for incoming connections on a socket. + +- A UDP application receiving a packet on a socket. + + This configuration setting does not affect already established TCP connections (traffic is unrestricted in both directions) and does not affect an application sending UDP packets. + + The possible values for the `ipProtectionLevel` attribute setting correspond with the defined protection levels specified in the enumeration as follows: + +|**Attribute Value**|**Description**| +|-|-| +|EdgeRestricted|The IP protection level is edge restricted. This value would be used by applications designed to operate across the Internet. This setting does not allow Network Address Translation (NAT) traversal using the Windows Teredo implementation. These applications may bypass IPv4 firewalls, so applications must be hardened against Internet attacks directed at the opened port. On Windows Server 2003 and Windows XP, the default value for the IP Protection level on a socket is edge restricted.| +|Restricted|The IP protection level is restricted. This value would be used by intranet applications that do not implement Internet scenarios. These applications are generally not tested or hardened against Internet-style attacks. This setting will limit the received traffic to link-local only.| +|Unrestricted|The IP protection level is unrestricted. This value would be used by applications designed to operate across the Internet, including applications taking advantage of IPv6 NAT traversal capabilities built into Windows (Teredo, for example). These applications may bypass IPv4 firewalls, so applications must be hardened against Internet attacks directed at the opened port. On Windows Server 2008 R2 and Windows Vista, the default value for the IP Protection level on a socket is unrestricted.| +|Unspecified|The IP protection level is unspecified. On Windows 7 and Windows Server 2008 R2, the default value for the IP Protection level on a socket is unspecified.| + + The default value for the `ipProtectionLevel` attribute is **Unspecified**. + + The property can be used to get the current value of the `ipProtectionLevel` attribute from applicable configuration files. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example shows how to specify that completion ports should be used and that the default should be unrestricted. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/specifiedpickupdirectory-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/specifiedpickupdirectory-element-network-settings.md index e75fad9fc9b1e..735181a44931e 100644 --- a/docs/framework/configure-apps/file-schema/network/specifiedpickupdirectory-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/specifiedpickupdirectory-element-network-settings.md @@ -2,74 +2,74 @@ title: " Element (Network Settings)" description: The network settings element configures the local directory for an SMTP server options in the .NET Framework. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#specifiedPickupDirectory" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/mailSettings/smtp/specifiedPickupDirectory" -helpviewer_keywords: +helpviewer_keywords: - "specifiedPickupDirectory element" - " element" ms.assetid: 0121f49d-bff2-4bc6-af06-f1628dcd61f1 --- -# \ Element (Network Settings) +# `` Element (Network Settings) + +Configures the local directory for a Simple Mail Transport Protocol (SMTP) server. -Configures the local directory for a Simple Mail Transport Protocol (SMTP) server. - [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](mailsettings-element-network-settings.md)\       [**\**](smtp-element-network-settings.md)\ -        **\** - -## Syntax - -```xml -** + +## Syntax + +```xml + -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`pickupDirectoryLocation`|The directory where applications save email for later processing by the SMTP server.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\ Element (Network Settings)](smtp-element-network-settings.md)|Configures Simple Mail Transport Protocol (SMTP) mail sending options.| - -## Remarks - - The `specifiedPickupDirectory` attribute sets the directory where applications save mail messages to be processed by the SMTP server. - -## Example - - The following example specifies c:\maildrop as the mail pickup directory. - -```xml - - - - - - - - - -``` - +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`pickupDirectoryLocation`|The directory where applications save email for later processing by the SMTP server.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\ Element (Network Settings)](smtp-element-network-settings.md)|Configures Simple Mail Transport Protocol (SMTP) mail sending options.| + +## Remarks + + The `specifiedPickupDirectory` attribute sets the directory where applications save mail messages to be processed by the SMTP server. + +## Example + + The following example specifies c:\maildrop as the mail pickup directory. + +```xml + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/network/system-net-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/system-net-element-network-settings.md index c569591951aaa..95e646d584543 100644 --- a/docs/framework/configure-apps/file-schema/network/system-net-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/system-net-element-network-settings.md @@ -2,96 +2,96 @@ title: " Element (Network Settings)" description: The network settings element contains settings that specify how the .NET Framework connects to the network options in the .NET Framework. ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#system.Net" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.Net" -helpviewer_keywords: +helpviewer_keywords: - "system.Net element" - " element" ms.assetid: 52de4d6c-b24d-44aa-ba7d-6b5061f1357e --- -# \ Element (Network Settings) - -Contains settings that specify how the .NET Framework connects to the network. - -[**\**](../configuration-element.md) -  **\** - -## Syntax - -```xml +# `` Element (Network Settings) + +Contains settings that specify how the .NET Framework connects to the network. + +[**\**](../configuration-element.md) +  **\** + +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[authenticationModules](authenticationmodules-element-network-settings.md)|Specifies modules used to authenticate Internet requests.| -|[connectionManagement](connectionmanagement-element-network-settings.md)|Specifies the maximum number of connections to an Internet host.| -|[defaultProxy](defaultproxy-element-network-settings.md)|Configures the Hypertext Transfer Protocol (HTTP) proxy server.| -|[mailSettings](mailsettings-element-network-settings.md)|Configures Simple Mail Transport Protocol (SMTP) mail sending options.| -|[requestCaching](requestcaching-element-network-settings.md)|Controls the caching mechanism for network requests.| -|[settings](settings-element-network-settings.md)|Configures basic network options for classes in the and related child namespaces.| -|[webRequestModules](webrequestmodules-element-network-settings.md)|Specifies modules to use to request information from Internet hosts.| - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[configuration](../configuration-element.md)|Contains settings for all namespaces.| - -## Remarks - - The [\](system-net-element-network-settings.md) element contains settings for classes in the and related child namespaces. The settings configure authentication modules, connection management, mail settings, the proxy server, and Internet request modules for receiving information from Internet hosts. - -## Example - - The following example shows a typical configuration used by classes. - -```xml - - - - - - - - - - - - - - - - - - - - - - -``` - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[authenticationModules](authenticationmodules-element-network-settings.md)|Specifies modules used to authenticate Internet requests.| +|[connectionManagement](connectionmanagement-element-network-settings.md)|Specifies the maximum number of connections to an Internet host.| +|[defaultProxy](defaultproxy-element-network-settings.md)|Configures the Hypertext Transfer Protocol (HTTP) proxy server.| +|[mailSettings](mailsettings-element-network-settings.md)|Configures Simple Mail Transport Protocol (SMTP) mail sending options.| +|[requestCaching](requestcaching-element-network-settings.md)|Controls the caching mechanism for network requests.| +|[settings](settings-element-network-settings.md)|Configures basic network options for classes in the and related child namespaces.| +|[webRequestModules](webrequestmodules-element-network-settings.md)|Specifies modules to use to request information from Internet hosts.| + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[configuration](../configuration-element.md)|Contains settings for all namespaces.| + +## Remarks + + The [\](system-net-element-network-settings.md) element contains settings for classes in the and related child namespaces. The settings configure authentication modules, connection management, mail settings, the proxy server, and Internet request modules for receiving information from Internet hosts. + +## Example + + The following example shows a typical configuration used by classes. + +```xml + + + + + + + + + + + + + + + + + + + + + + +``` + ## See also - [Network Settings Schema](index.md) diff --git a/docs/framework/configure-apps/file-schema/network/uri-element-uri-settings.md b/docs/framework/configure-apps/file-schema/network/uri-element-uri-settings.md index fe388a2bbd384..e3002661e5d94 100644 --- a/docs/framework/configure-apps/file-schema/network/uri-element-uri-settings.md +++ b/docs/framework/configure-apps/file-schema/network/uri-element-uri-settings.md @@ -4,67 +4,67 @@ title: " Element (Uri Settings)" ms.date: "03/30/2017" ms.assetid: c22bab8b-477c-4ae4-8498-65ad409e0847 --- -# \ Element (Uri Settings) - -Contains settings that specify how the .NET Framework handles web addresses expressed using uniform resource identifiers (URIs). - -[**\**](../configuration-element.md) -  **\** - -## Syntax - -```xml - - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[idn](idn-element-uri-settings.md)|Specifies if Internationalized Domain Name (IDN) parsing is applied to domain names.| -|[iriParsing](iriparsing-element-uri-settings.md)|Specifies if International Resource Identifier (IRI) parsing is applied to and whether IRI parsing rules should be applied.| -|[schemeSettings](schemesettings-element-uri-settings.md)|Specifies how a will be parsed for specific schemes.| - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[configuration](../configuration-element.md)|Contains settings for all namespaces.| - -## Remarks - - The `uri` element contains settings for members of the class used by classes in the namespace. The settings configure support for IRI and IDN. - -## Example - -### Description - - The following example shows a configuration used by the class to support IRI parsing and IDN names. The example also clears all scheme settings and then adds support for not escaping percent-encoded path delimiters for the http scheme. - -### Code - -```xml - - - - - - - - - - -``` - +# `` Element (Uri Settings) + +Contains settings that specify how the .NET Framework handles web addresses expressed using uniform resource identifiers (URIs). + +[**\**](../configuration-element.md) +  **\** + +## Syntax + +```xml + + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[idn](idn-element-uri-settings.md)|Specifies if Internationalized Domain Name (IDN) parsing is applied to domain names.| +|[iriParsing](iriparsing-element-uri-settings.md)|Specifies if International Resource Identifier (IRI) parsing is applied to and whether IRI parsing rules should be applied.| +|[schemeSettings](schemesettings-element-uri-settings.md)|Specifies how a will be parsed for specific schemes.| + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[configuration](../configuration-element.md)|Contains settings for all namespaces.| + +## Remarks + + The `uri` element contains settings for members of the class used by classes in the namespace. The settings configure support for IRI and IDN. + +## Example + +### Description + + The following example shows a configuration used by the class to support IRI parsing and IDN names. The example also clears all scheme settings and then adds support for not escaping percent-encoded path delimiters for the http scheme. + +### Code + +```xml + + + + + + + + + + +``` + ## See also - [Network Settings Schema](index.md) diff --git a/docs/framework/configure-apps/file-schema/network/webproxyscript-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/webproxyscript-element-network-settings.md index fbdc438ab277b..903b2f0ac5b48 100644 --- a/docs/framework/configure-apps/file-schema/network/webproxyscript-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/webproxyscript-element-network-settings.md @@ -2,57 +2,57 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#webProxyScript" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/settings/webProxyScript" -helpviewer_keywords: +helpviewer_keywords: - " element" - "webProxyScript element" ms.assetid: a13c26db-6218-4af3-9696-38f24b23bfac --- -# \ Element (Network Settings) +# `` Element (Network Settings) -Configures the characteristics of the script used to discover Web proxies. +Configures the characteristics of the script used to discover Web proxies. [**\**](../configuration-element.md)\   [**\**](system-net-element-network-settings.md)\     [**\**](settings-element-network-settings.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`downloadTimeout`|Specifies the maximum time to download the script in hours, minutes, and seconds. The default value is one minute.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| - -## Remarks - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`downloadTimeout`|Specifies the maximum time to download the script in hours, minutes, and seconds. The default value is one minute.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[settings](settings-element-network-settings.md)|Configures basic network options for the namespace.| + +## Remarks + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + ## See also - [Network Settings Schema](index.md) diff --git a/docs/framework/configure-apps/file-schema/network/webrequestmodules-element-network-settings.md b/docs/framework/configure-apps/file-schema/network/webrequestmodules-element-network-settings.md index f790d56329a45..8c75261e8d40e 100644 --- a/docs/framework/configure-apps/file-schema/network/webrequestmodules-element-network-settings.md +++ b/docs/framework/configure-apps/file-schema/network/webrequestmodules-element-network-settings.md @@ -2,78 +2,78 @@ description: "Learn more about: Element (Network Settings)" title: " Element (Network Settings)" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.net/webRequestModules" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#webRequestModules" -helpviewer_keywords: +helpviewer_keywords: - "webRequestModules element" - " element" ms.assetid: 1263de11-3e0a-4f94-97c9-710b2ae53817 --- -# \ Element (Network Settings) - -Specifies modules to use to request information from network hosts. - -[**\**](../configuration-element.md) -  [**\**](system-net-element-network-settings.md) -    \ - -## Syntax - -```xml +# `` Element (Network Settings) + +Specifies modules to use to request information from network hosts. + +[**\**](../configuration-element.md) +  [**\**](system-net-element-network-settings.md) +    \ + +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[add](add-element-for-webrequestmodules-network-settings.md)|Adds a custom Web request module to the application.| -|[clear](clear-element-for-webrequestmodules-network-settings.md)|Removes all registered Web request modules from the application.| -|[remove](remove-element-for-webrequestmodules-network-settings.md)|Removes a custom Web request module from the application.| - -### Parent Elements - -|**Element**|**Description**| -|-----------------|---------------------| -|[system.net](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| - -## Remarks - - The `webRequestModules` element registers descendants of the class to handle information requests to network hosts. Web request modules must implement the interface. - - The .NET Framework includes Web request modules for URIs that begin with `http://`, `https://`, and `file://`. You can override the default modules only by registering a custom module in the configuration file. - -## Configuration Files - - This element can be used in the application configuration file or the machine configuration file (Machine.config). - -## Example - - The following example registers the default HTTP module. You should replace the values for Version and PublicKeyToken with the correct values for the specified module. - -```xml - - - - - - - -``` - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[add](add-element-for-webrequestmodules-network-settings.md)|Adds a custom Web request module to the application.| +|[clear](clear-element-for-webrequestmodules-network-settings.md)|Removes all registered Web request modules from the application.| +|[remove](remove-element-for-webrequestmodules-network-settings.md)|Removes a custom Web request module from the application.| + +### Parent Elements + +|**Element**|**Description**| +|-----------------|---------------------| +|[system.net](system-net-element-network-settings.md)|Contains settings that specify how the .NET Framework connects to the network.| + +## Remarks + + The `webRequestModules` element registers descendants of the class to handle information requests to network hosts. Web request modules must implement the interface. + + The .NET Framework includes Web request modules for URIs that begin with `http://`, `https://`, and `file://`. You can override the default modules only by registering a custom module in the configuration file. + +## Configuration Files + + This element can be used in the application configuration file or the machine configuration file (Machine.config). + +## Example + + The following example registers the default HTTP module. You should replace the values for Version and PublicKeyToken with the correct values for the specified module. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/remove-element-for-custom-2.md b/docs/framework/configure-apps/file-schema/remove-element-for-custom-2.md index a85be6dbb1da2..89ca2255a1819 100644 --- a/docs/framework/configure-apps/file-schema/remove-element-for-custom-2.md +++ b/docs/framework/configure-apps/file-schema/remove-element-for-custom-2.md @@ -2,14 +2,14 @@ description: "Learn more about: element for NameValueSectionHandler and DictionarySectionHandler" title: " element for NameValueSectionHandler and DictionarySectionHandler" ms.date: "05/01/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/sectionName/remove" -helpviewer_keywords: +helpviewer_keywords: - "remove Element" - " Element" ms.assetid: 8d8af7f5-26c9-4db9-bbe4-b2a4e6949568 --- -# \ element for NameValueSectionHandler and DictionarySectionHandler +# `` element for NameValueSectionHandler and DictionarySectionHandler Removes a previously defined setting. @@ -27,13 +27,13 @@ Removes a previously defined setting. | | Description | | --------- | ----------- | -| **key** | Required attribute.

Specifies the name of the setting to remove. | +| `key` | Required attribute.

Specifies the name of the setting to remove. | ## Parent element | Element | Description | | ------- | ------------| -| [**\** Element](custom-element-2.md) | Defines settings for custom configuration sections that use the and classes. | +| [`` Element](custom-element-2.md) | Defines settings for custom configuration sections that use the and classes. | ## Child elements @@ -41,13 +41,13 @@ None ## Remarks -You can use the **\** element to remove settings from your application that were defined at a higher level in the configuration file hierarchy. +You can use the `` element to remove settings from your application that were defined at a higher level in the configuration file hierarchy. ## Example -The following example shows how to use the **\** element in an application configuration file to remove settings previously defined in the machine configuration file. +The following example shows how to use the `` element in an application configuration file to remove settings previously defined in the machine configuration file. -The following machine configuration file code declares the section **\** and adds two settings, `key1` and `key2`, to it: +The following machine configuration file code declares the section `` and adds two settings, `key1` and `key2`, to it: ```xml diff --git a/docs/framework/configure-apps/file-schema/runtime/add-element-for-namedcaches.md b/docs/framework/configure-apps/file-schema/runtime/add-element-for-namedcaches.md index 8ed72e12f166f..bf041c9f788ab 100644 --- a/docs/framework/configure-apps/file-schema/runtime/add-element-for-namedcaches.md +++ b/docs/framework/configure-apps/file-schema/runtime/add-element-for-namedcaches.md @@ -2,83 +2,83 @@ description: "Learn more about: Element for " title: " Element for " ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "add element for " - " element for " ms.assetid: ce2a63a8-c829-4742-a6ea-72ee5d89f169 --- -# \ Element for \ +# `` Element for \ + +Adds a `namedCache` entry to the `namedCaches` collection for a memory cache. -Adds a `namedCache` entry to the `namedCaches` collection for a memory cache. - [**\**](../configuration-element.md)\   [**\**](system-runtime-caching-element-cache-settings.md)\     [**\**](memorycache-element-cache-settings.md)\       [**\**](namedcaches-element-cache-settings.md)\ -        **\** - -## Syntax - -```xml - - - - -``` - -## Type - - `None` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|-|-| -|`CacheMemoryLimitMegabytes`|An integer value that specifies the maximum allowed size (in megabytes) that an instance of a can grow to. The default value is 0, which means that the class's autosizing heuristics are used by default.| -|`Name`|The name of the cache.| -|`PhysicalMemoryLimitPercentage`|An integer value between 0 and 100 that specifies the maximum percentage of physically installed computer memory that can be consumed by the cache. The default value is 0, which means that the class's autosizing heuristics are used by default.| -|`PollingInterval`|A value that indicates the time interval after which the cache implementation compares the current memory load against the absolute and percentage-based memory limits that are set for the cache instance. This value is entered in "HH:MM:SS" format.| - -### Child Elements - - `None` - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](namedcaches-element-cache-settings.md)|Contains a collection of configuration settings for the named instances.| - -## Remarks - - The `add` element adds an entry to the `namedCaches` collection for a memory cache. You can use the [clear](clear-element-for-namedcaches.md) element before you use the `add` element to be certain that there are no other named caches in the collection. This element can be used in the machine.config file and in the Web.config file. - -## Example - - The following example shows how to define settings for the default `namedCache` entry to the `namedCaches` collection for a memory cache. - -```xml - - - - - +        **\** + +## Syntax + +```xml + + + + +``` + +## Type + + `None` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|-|-| +|`CacheMemoryLimitMegabytes`|An integer value that specifies the maximum allowed size (in megabytes) that an instance of a can grow to. The default value is 0, which means that the class's autosizing heuristics are used by default.| +|`Name`|The name of the cache.| +|`PhysicalMemoryLimitPercentage`|An integer value between 0 and 100 that specifies the maximum percentage of physically installed computer memory that can be consumed by the cache. The default value is 0, which means that the class's autosizing heuristics are used by default.| +|`PollingInterval`|A value that indicates the time interval after which the cache implementation compares the current memory load against the absolute and percentage-based memory limits that are set for the cache instance. This value is entered in "HH:MM:SS" format.| + +### Child Elements + + `None` + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](namedcaches-element-cache-settings.md)|Contains a collection of configuration settings for the named instances.| + +## Remarks + + The `add` element adds an entry to the `namedCaches` collection for a memory cache. You can use the [clear](clear-element-for-namedcaches.md) element before you use the `add` element to be certain that there are no other named caches in the collection. This element can be used in the machine.config file and in the Web.config file. + +## Example + + The following example shows how to define settings for the default `namedCache` entry to the `namedCaches` collection for a memory cache. + +```xml + + + + + - - - - - -``` - + physicalMemoryPercentage="0" + pollingInterval="00:02:00" /> + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) -- [\ Element (Cache Settings)](namedcaches-element-cache-settings.md) +- [`` Element (Cache Settings)](namedcaches-element-cache-settings.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/alwaysflowimpersonationpolicy-element.md b/docs/framework/configure-apps/file-schema/runtime/alwaysflowimpersonationpolicy-element.md index 711af4e018fa0..9a09b18443dca 100644 --- a/docs/framework/configure-apps/file-schema/runtime/alwaysflowimpersonationpolicy-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/alwaysflowimpersonationpolicy-element.md @@ -2,114 +2,114 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/alwaysFlowImpersonationPolicy" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#alwaysFlowImpersonationPolicy" -helpviewer_keywords: +helpviewer_keywords: - "alwaysFlowImpersonationPolicy element" - " element" ms.assetid: ee622801-9e46-470b-85ab-88c4b1dd2ee1 --- -# \ Element +# `` Element + +Specifies that the Windows identity always flows across asynchronous points, regardless of how impersonation was performed. -Specifies that the Windows identity always flows across asynchronous points, regardless of how impersonation was performed. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\     **\** - -## Syntax - -```xml + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Indicates whether the Windows identity flows across asynchronous points.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|`false`|The Windows identity does not flow across asynchronous points, unless the impersonation is performed through managed methods such as . This is the default.| -|`true`|The Windows identity always flows across asynchronous points, regardless of how impersonation was performed.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - In the .NET Framework versions 1.0 and 1.1, the Windows identity does not flow across asynchronous points. In .NET Framework version 2.0, there is an object that contains information about the currently executing thread, and flows it across asynchronous points within an application domain. The also flows as part of the information that flows across the asynchronous points, provided the impersonation was achieved using managed methods such as and not through other means such as platform invoke to native methods. This element is used to specify that the Windows identity does flow across asynchronous points, regardless of how the impersonation was achieved. - - You can alter this default behavior in two other ways: - -1. In managed code on a per-thread basis. - - You can suppress the flow on a per-thread basis by modifying the and settings by using the , , or method. - -2. In the call to the unmanaged hosting interface to load the common language runtime (CLR). - - If an unmanaged hosting interface (instead of a simple managed executable) is used to load the CLR, you can specify a special flag in the call to the [CorBindToRuntimeEx Function](../../../unmanaged-api/hosting/corbindtoruntimeex-function.md) function. To enable the compatibility mode for the entire process, set the `flags` parameter for [CorBindToRuntimeEx Function](../../../unmanaged-api/hosting/corbindtoruntimeex-function.md) to `STARTUP_ALWAYSFLOW_IMPERSONATION`. - -## Configuration File - - In a .NET Framework application, this element can be used only in the application configuration file. - - For an ASP.NET application, the impersonation flow can be configured in the aspnet.config file found in the \\Microsoft.NET\Framework\vx.x.xxxx directory. - - ASP.NET by default disables the impersonation flow in the aspnet.config file by using the following configuration settings: - + enabled="true|false"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Indicates whether the Windows identity flows across asynchronous points.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|`false`|The Windows identity does not flow across asynchronous points, unless the impersonation is performed through managed methods such as . This is the default.| +|`true`|The Windows identity always flows across asynchronous points, regardless of how impersonation was performed.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + In the .NET Framework versions 1.0 and 1.1, the Windows identity does not flow across asynchronous points. In .NET Framework version 2.0, there is an object that contains information about the currently executing thread, and flows it across asynchronous points within an application domain. The also flows as part of the information that flows across the asynchronous points, provided the impersonation was achieved using managed methods such as and not through other means such as platform invoke to native methods. This element is used to specify that the Windows identity does flow across asynchronous points, regardless of how the impersonation was achieved. + + You can alter this default behavior in two other ways: + +1. In managed code on a per-thread basis. + + You can suppress the flow on a per-thread basis by modifying the and settings by using the , , or method. + +2. In the call to the unmanaged hosting interface to load the common language runtime (CLR). + + If an unmanaged hosting interface (instead of a simple managed executable) is used to load the CLR, you can specify a special flag in the call to the [CorBindToRuntimeEx Function](../../../unmanaged-api/hosting/corbindtoruntimeex-function.md) function. To enable the compatibility mode for the entire process, set the `flags` parameter for [CorBindToRuntimeEx Function](../../../unmanaged-api/hosting/corbindtoruntimeex-function.md) to `STARTUP_ALWAYSFLOW_IMPERSONATION`. + +## Configuration File + + In a .NET Framework application, this element can be used only in the application configuration file. + + For an ASP.NET application, the impersonation flow can be configured in the aspnet.config file found in the \\Microsoft.NET\Framework\vx.x.xxxx directory. + + ASP.NET by default disables the impersonation flow in the aspnet.config file by using the following configuration settings: + ```xml - - - - - - -``` - - In ASP.NET, if you want to allow the flow of impersonation instead, you must explicitly use the following configuration settings: - -```xml - - - - - - -``` - -## Example - - The following example shows how to specify that the Windows identity flows across asynchronous points, even when the impersonation is achieved through means other than managed methods. - -```xml - - - - - -``` - + + + + + + +``` + + In ASP.NET, if you want to allow the flow of impersonation instead, you must explicitly use the following configuration settings: + +```xml + + + + + + +``` + +## Example + + The following example shows how to specify that the Windows identity flows across asynchronous points, even when the impersonation is achieved through means other than managed methods. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) - [Runtime Settings Schema](index.md) - [Configuration File Schema](../index.md) -- [\ Element](legacyimpersonationpolicy-element.md) +- [`` Element](legacyimpersonationpolicy-element.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md b/docs/framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md index 25658365fbae8..88788e1b06c94 100644 --- a/docs/framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md @@ -9,7 +9,7 @@ helpviewer_keywords: - "configuration" ms.assetid: 4ce07f47-7ddb-4d91-b067-501bd8b88752 --- -# \ element +# `` element Defines one or more switches used by the class to provide an opt-out mechanism for new functionality. @@ -182,5 +182,5 @@ The following example uses the `` element to add two settings to the ` -- [\ Element](runtime-element.md) -- [\ Element](../configuration-element.md) +- [`` Element](runtime-element.md) +- [`` Element](../configuration-element.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/appdomainmanagerassembly-element.md b/docs/framework/configure-apps/file-schema/runtime/appdomainmanagerassembly-element.md index 249c4d3f2bd26..c5c8f224ce537 100644 --- a/docs/framework/configure-apps/file-schema/runtime/appdomainmanagerassembly-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/appdomainmanagerassembly-element.md @@ -2,81 +2,81 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - " element" - "appDomainManagerAssembly element" ms.assetid: c7c56e39-a700-44f5-b94e-411bfce339d9 --- -# \ Element +# `` Element + +Specifies the assembly that provides the application domain manager for the default application domain in the process. -Specifies the assembly that provides the application domain manager for the default application domain in the process. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`value`|Required attribute. Specifies the display name of the assembly that provides the application domain manager for the default application domain in the process.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - To specify the type of the application domain manager, you must specify both this element and the [\](appdomainmanagertype-element.md) element. If either of these elements is not specified, the other is ignored. - - When the default application domain is loaded, is thrown if the specified assembly does not exist or if the assembly does not contain the type specified by the [\](appdomainmanagertype-element.md) element; and the process fails to start. If the assembly is found but the version information does not match, a is thrown. - - When you specify the application domain manager type for the default application domain, other application domains created from the default application domain inherit the application domain manager type. Use the and properties to specify a different application domain manager type for a new application domain. - - Specifying the application domain manager type requires the application to have full trust. (For example, an application running on the desktop has full trust.) If the application does not have full trust, a is thrown. - - For the format of the assembly display name, see the property. - - This configuration element is available only in the .NET Framework 4 and later. - -## Example - - The following example shows how to specify that the application domain manager for the default application domain of a process is the `MyMgr` type in the `AdMgrExample` assembly. - -```xml - - - + value="assembly display name" /> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`value`|Required attribute. Specifies the display name of the assembly that provides the application domain manager for the default application domain in the process.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + To specify the type of the application domain manager, you must specify both this element and the [\](appdomainmanagertype-element.md) element. If either of these elements is not specified, the other is ignored. + + When the default application domain is loaded, is thrown if the specified assembly does not exist or if the assembly does not contain the type specified by the [\](appdomainmanagertype-element.md) element; and the process fails to start. If the assembly is found but the version information does not match, a is thrown. + + When you specify the application domain manager type for the default application domain, other application domains created from the default application domain inherit the application domain manager type. Use the and properties to specify a different application domain manager type for a new application domain. + + Specifying the application domain manager type requires the application to have full trust. (For example, an application running on the desktop has full trust.) If the application does not have full trust, a is thrown. + + For the format of the assembly display name, see the property. + + This configuration element is available only in the .NET Framework 4 and later. + +## Example + + The following example shows how to specify that the application domain manager for the default application domain of a process is the `MyMgr` type in the `AdMgrExample` assembly. + +```xml + + + - - -``` - + value="AdMgrExample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6856bccf150f00b3" /> + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) - - -- [\ Element](appdomainmanagertype-element.md) +- [`` Element](appdomainmanagertype-element.md) - [Runtime Settings Schema](index.md) - [Configuration File Schema](../index.md) - [SetAppDomainManagerType Method](../../../unmanaged-api/hosting/iclrcontrol-setappdomainmanagertype-method.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/appdomainmanagertype-element.md b/docs/framework/configure-apps/file-schema/runtime/appdomainmanagertype-element.md index bcf5f8c97823c..7029183b0c885 100644 --- a/docs/framework/configure-apps/file-schema/runtime/appdomainmanagertype-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/appdomainmanagertype-element.md @@ -2,81 +2,81 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "appDomainManagerType element" - " element" ms.assetid: ae8d5a7e-e7f7-47f7-98d9-455cc243a322 --- -# \ Element +# `` Element + +Specifies the type that serves as the application domain manager for the default application domain. -Specifies the type that serves as the application domain manager for the default application domain. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`value`|Required attribute. Specifies the name of the type, including the namespace, that serves as the application domain manager for the default application domain in the process.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - To specify the type of the application domain manager, you must specify both this element and the [\](appdomainmanagerassembly-element.md) element. If either of these elements is not specified, the other is ignored. - - When the default application domain is loaded, is thrown if the specified type does not exist in the assembly that is specified by the [\](appdomainmanagerassembly-element.md) element; and the process fails to start. - - When you specify the application domain manager type for the default application domain, other application domains created from the default application domain inherit the application domain manager type. Use the and properties to specify a different application domain manager type for a new application domain. - - Specifying the application domain manager type requires the application to have full trust. (For example, an application running on the desktop has full trust.) If the application does not have full trust, a is thrown. - - The format of the type and namespace is the same format that is used for the property. - - This configuration element is available only in the .NET Framework 4 and later. - -## Example - - The following example shows how to specify that the application domain manager for the default application domain of a process is the `MyMgr` type in the `AdMgrExample` assembly. - -```xml - - - + value="type name" /> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`value`|Required attribute. Specifies the name of the type, including the namespace, that serves as the application domain manager for the default application domain in the process.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + To specify the type of the application domain manager, you must specify both this element and the [\](appdomainmanagerassembly-element.md) element. If either of these elements is not specified, the other is ignored. + + When the default application domain is loaded, is thrown if the specified type does not exist in the assembly that is specified by the [\](appdomainmanagerassembly-element.md) element; and the process fails to start. + + When you specify the application domain manager type for the default application domain, other application domains created from the default application domain inherit the application domain manager type. Use the and properties to specify a different application domain manager type for a new application domain. + + Specifying the application domain manager type requires the application to have full trust. (For example, an application running on the desktop has full trust.) If the application does not have full trust, a is thrown. + + The format of the type and namespace is the same format that is used for the property. + + This configuration element is available only in the .NET Framework 4 and later. + +## Example + + The following example shows how to specify that the application domain manager for the default application domain of a process is the `MyMgr` type in the `AdMgrExample` assembly. + +```xml + + + - - -``` - + value="AdMgrExample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6856bccf150f00b3" /> + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) - - -- [\ Element](appdomainmanagerassembly-element.md) +- [`` Element](appdomainmanagerassembly-element.md) - [Runtime Settings Schema](index.md) - [Configuration File Schema](../index.md) - [SetAppDomainManagerType Method](../../../unmanaged-api/hosting/iclrcontrol-setappdomainmanagertype-method.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md b/docs/framework/configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md index 4c811bca4251b..5199d32afb123 100644 --- a/docs/framework/configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md @@ -2,74 +2,74 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "appDomainResourceMonitoring element" - " element" ms.assetid: 02119ab6-1e91-448e-97ad-e7b2e5c4bbbd --- -# \ Element +# `` Element + +Instructs the runtime to collect statistics on all application domains in the process for the life of the process. -Instructs the runtime to collect statistics on all application domains in the process for the life of the process. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Specifies whether the runtime collects statistics for application domain resource monitoring.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|`true`|Statistics for application domain resource monitoring are collected.| -|`false`|Statistics for application domain resource monitoring are not collected.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - Application domain resource monitoring is available through the managed application domain class, the hosting [ICLRAppDomainResourceMonitor](../../../unmanaged-api/hosting/iclrappdomainresourcemonitor-interface.md) interface, and event tracing for Windows (ETW). When monitoring is enabled, statistics are collected for all application domains in the process for the life of the process. - - To enable monitoring from managed code, use the property. - - This configuration element is available only in the .NET Framework 4 and later. - -## Example - - The following example shows how to enable application domain resource monitoring. - -```xml - - - - - -``` - + enabled="true|false"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Specifies whether the runtime collects statistics for application domain resource monitoring.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|`true`|Statistics for application domain resource monitoring are collected.| +|`false`|Statistics for application domain resource monitoring are not collected.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + Application domain resource monitoring is available through the managed application domain class, the hosting [ICLRAppDomainResourceMonitor](../../../unmanaged-api/hosting/iclrappdomainresourcemonitor-interface.md) interface, and event tracing for Windows (ETW). When monitoring is enabled, statistics are collected for all application domains in the process for the life of the process. + + To enable monitoring from managed code, use the property. + + This configuration element is available only in the .NET Framework 4 and later. + +## Example + + The following example shows how to enable application domain resource monitoring. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/assemblybinding-element-for-runtime.md b/docs/framework/configure-apps/file-schema/runtime/assemblybinding-element-for-runtime.md index 2d14b0a9bd287..e3170b36f1e1a 100644 --- a/docs/framework/configure-apps/file-schema/runtime/assemblybinding-element-for-runtime.md +++ b/docs/framework/configure-apps/file-schema/runtime/assemblybinding-element-for-runtime.md @@ -2,92 +2,92 @@ description: "Learn more about: Element for " title: " Element for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/assemblyBinding" -helpviewer_keywords: +helpviewer_keywords: - " element" - "assemblyBinding element" - "container tags, element" ms.assetid: 964cbb35-ab49-4498-8471-209689e5dada --- -# \ Element for \ +# `` Element for \ + +Contains information about assembly version redirection and the locations of assemblies. -Contains information about assembly version redirection and the locations of assemblies. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**xmlns**|Required attribute.

Specifies the XML namespace required for assembly binding. Use the string "urn:schemas-microsoft-com:asm.v1" as the value.| -|**appliesTo**|Specifies the runtime version the .NET Framework assembly redirection applies to. This optional attribute uses a .NET Framework version number to indicate what version it applies to. If no **appliesTo** attribute is specified, the **\** element applies to all versions of the .NET Framework. The **appliesTo** attribute was introduced in .NET Framework version 1.1; it is ignored by .NET Framework version 1.0. This means that all **\** elements are applied when using .NET Framework version 1.0, even if an **appliesTo** attribute is specified.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](dependentassembly-element.md)|Encapsulates binding policy and assembly location for an assembly. Use one **\** tag for each assembly.| -|[\](probing-element.md)|Specifies subdirectories the common language runtime searches when loading assemblies.| -|[\](publisherpolicy-element.md)|Specifies whether the runtime applies publisher policy.| -|[\](qualifyassembly-element.md)|Specifies the full name of the assembly that should be dynamically loaded when a partial name is used.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Example - - The following example shows how to redirect one assembly version to another and provide a codebase. - -```xml - - - - - - - - - - - -``` - - The following example shows how to use the **appliesTo** attribute to redirect binding of a .NET Framework assembly. - -```xml - - + xmlns="urn:schemas-microsoft-com:asm.v1" appliesTo="v1.0.3705"> + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|**xmlns**|Required attribute.

Specifies the XML namespace required for assembly binding. Use the string "urn:schemas-microsoft-com:asm.v1" as the value.| +|**appliesTo**|Specifies the runtime version the .NET Framework assembly redirection applies to. This optional attribute uses a .NET Framework version number to indicate what version it applies to. If no `appliesTo` attribute is specified, the `` element applies to all versions of the .NET Framework. The `appliesTo` attribute was introduced in .NET Framework version 1.1; it is ignored by .NET Framework version 1.0. This means that all `` elements are applied when using .NET Framework version 1.0, even if an `appliesTo` attribute is specified.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](dependentassembly-element.md)|Encapsulates binding policy and assembly location for an assembly. Use one `` tag for each assembly.| +|[\](probing-element.md)|Specifies subdirectories the common language runtime searches when loading assemblies.| +|[\](publisherpolicy-element.md)|Specifies whether the runtime applies publisher policy.| +|[\](qualifyassembly-element.md)|Specifies the full name of the assembly that should be dynamically loaded when a partial name is used.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Example + + The following example shows how to redirect one assembly version to another and provide a codebase. + +```xml + + + + + + + + + + + +``` + + The following example shows how to use the `appliesTo` attribute to redirect binding of a .NET Framework assembly. + +```xml + + - - - - - -``` - + + + + +
+``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/assemblyidentity-element-for-runtime.md b/docs/framework/configure-apps/file-schema/runtime/assemblyidentity-element-for-runtime.md index 5462ac1c8a741..9834ce62d4b77 100644 --- a/docs/framework/configure-apps/file-schema/runtime/assemblyidentity-element-for-runtime.md +++ b/docs/framework/configure-apps/file-schema/runtime/assemblyidentity-element-for-runtime.md @@ -2,123 +2,123 @@ description: "Learn more about: Element for " title: " Element for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/assemblyBinding/dependentAssembly/assemblyIdentity" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#assemblyIdentity" -helpviewer_keywords: +helpviewer_keywords: - " element" - "container tags, element" - "assemblyIdentity element" ms.assetid: cea4d187-6398-4da4-af09-c1abc6a349c1 --- -# \ Element for \ +# `` Element for \ + +Contains identifying information about the assembly. -Contains identifying information about the assembly. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\     [**\**](assemblybinding-element-for-runtime.md)\       [**\**](dependentassembly-element.md)\ -        **\** - -## Syntax - -```xml +        **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`name`|Required attribute.

The name of the assembly| -|`culture`|Optional attribute.

A string that specifies the language and country/region of the assembly.| -|`publicKeyToken`|Optional attribute.

A hexadecimal value that specifies the strong name of the assembly.| -|`processorArchitecture`|Optional attribute.

One of the values "x86", "amd64", "msil", or "ia64", specifying the processor architecture for an assembly that contains processor-specific code. The values are not case-sensitive. If the attribute is assigned any other value, the entire `` element is ignored. See .| - -## processorArchitecture Attribute - -|Value|Description| -|-----------|-----------------| -|`amd64`|AMD x86-64 architecture only.| -|`ia64`|Intel Itanium architecture only.| -|`msil`|Neutral with respect to processor and bits-per-word.| -|`x86`|A 32-bit x86 processor, either native or in the Windows on Windows (WOW) environment on a 64-bit platform.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`dependentAssembly`|Encapsulates binding policy and assembly location for each assembly. Use one `` element for each assembly.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - Every **\** element must have one **\** child element. - - If the `processorArchitecture` attribute is present, the `` element applies only to the assembly with the corresponding processor architecture. If the `processorArchitecture` attribute is not present, the `` element can apply to an assembly with any processor architecture. - - The following example shows a configuration file for two assemblies with the same name that target two different processor architectures, and whose versions have not been maintained in synch. When the application executes on the x86 platform, the first `` element applies and the other is ignored. If the application executes on a platform other than x86 or ia64, both are ignored. - -```xml - - - - - +name="assembly name" +publicKeyToken="public key token" +culture="assembly culture"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`name`|Required attribute.

The name of the assembly| +|`culture`|Optional attribute.

A string that specifies the language and country/region of the assembly.| +|`publicKeyToken`|Optional attribute.

A hexadecimal value that specifies the strong name of the assembly.| +|`processorArchitecture`|Optional attribute.

One of the values "x86", "amd64", "msil", or "ia64", specifying the processor architecture for an assembly that contains processor-specific code. The values are not case-sensitive. If the attribute is assigned any other value, the entire `` element is ignored. See .| + +## processorArchitecture Attribute + +|Value|Description| +|-----------|-----------------| +|`amd64`|AMD x86-64 architecture only.| +|`ia64`|Intel Itanium architecture only.| +|`msil`|Neutral with respect to processor and bits-per-word.| +|`x86`|A 32-bit x86 processor, either native or in the Windows on Windows (WOW) environment on a 64-bit platform.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`dependentAssembly`|Encapsulates binding policy and assembly location for each assembly. Use one `` element for each assembly.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + Every `` element must have one `` child element. + + If the `processorArchitecture` attribute is present, the `` element applies only to the assembly with the corresponding processor architecture. If the `processorArchitecture` attribute is not present, the `` element can apply to an assembly with any processor architecture. + + The following example shows a configuration file for two assemblies with the same name that target two different processor architectures, and whose versions have not been maintained in synch. When the application executes on the x86 platform, the first `` element applies and the other is ignored. If the application executes on a platform other than x86 or ia64, both are ignored. + +```xml + + + + + - - - + + + + processorArchitecture="ia64" /> - - - - -``` - - If a configuration file contains an `` element with no `processorArchitecture` attribute, and does not contain an element that matches the platform, the element without the `processorArchitecture` attribute is used. - -## Example - - The following example shows how to provide information about an assembly. - -```xml - - - - - - - - - - -``` - + newVersion="2.0.0.0" /> + +
+
+
+``` + + If a configuration file contains an `` element with no `processorArchitecture` attribute, and does not contain an element that matches the platform, the element without the `processorArchitecture` attribute is used. + +## Example + + The following example shows how to provide information about an assembly. + +```xml + + + + + + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/bindingredirect-element.md b/docs/framework/configure-apps/file-schema/runtime/bindingredirect-element.md index a750ddbcf4978..c7dc795d95738 100644 --- a/docs/framework/configure-apps/file-schema/runtime/bindingredirect-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/bindingredirect-element.md @@ -2,87 +2,87 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/assemblyBinding/dependentAssembly/bindingRedirect" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#bindingRedirect" -helpviewer_keywords: +helpviewer_keywords: - " element" - "container tags, element" - "bindingRedirect element" ms.assetid: 67784ecd-9663-434e-bd6a-26975e447ac0 --- -# \ Element +# `` Element + +Redirects one assembly version to another. -Redirects one assembly version to another. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\     [**\**](assemblybinding-element-for-runtime.md)\       [**\**](dependentassembly-element.md)\ -        **\** - -## Syntax - -```xml +        **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`oldVersion`|Required attribute.

Specifies the version of the assembly that was originally requested. The format of an assembly version number is *major.minor.build.revision*. Valid values for each part of this version number are 0 to 65535.

You can also specify a range of versions in the following format:

*n.n.n.n - n.n.n.n*| -|`newVersion`|Required attribute.

Specifies the version of the assembly to use instead of the originally requested version in the format: *n.n.n.n*

This value can specify an earlier version than `oldVersion`.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|None|| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`dependentAssembly`|Encapsulates binding policy and assembly location for each assembly. Use one dependentAssembly element for each assembly.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - When you build a .NET Framework application against a strong-named assembly, the application uses that version of the assembly at run time by default, even if a new version is available. However, you can configure the application to run against a newer version of the assembly. For details on how the runtime uses these files to determine which assembly version to use, see [How the Runtime Locates Assemblies](../../../deployment/how-the-runtime-locates-assemblies.md). - - You can redirect more than one assembly version by including multiple `bindingRedirect` elements in a `dependentAssembly` element. You can also redirect from a newer version to an older version of the assembly. - - Explicit assembly binding redirection in an application configuration file requires a security permission. This applies to redirection of .NET Framework assemblies and assemblies from third parties. The permission is granted by setting the flag on the . For more information, see [Assembly Binding Redirection Security Permission](../../assembly-binding-redirection-security-permission.md). - -## Example - - The following example shows how to redirect one assembly version to another. - -```xml - - - - - - - - - - -``` - +oldVersion="existing assembly version" +newVersion="new assembly version"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`oldVersion`|Required attribute.

Specifies the version of the assembly that was originally requested. The format of an assembly version number is *major.minor.build.revision*. Valid values for each part of this version number are 0 to 65535.

You can also specify a range of versions in the following format:

*n.n.n.n - n.n.n.n*| +|`newVersion`|Required attribute.

Specifies the version of the assembly to use instead of the originally requested version in the format: *n.n.n.n*

This value can specify an earlier version than `oldVersion`.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|None|| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`dependentAssembly`|Encapsulates binding policy and assembly location for each assembly. Use one dependentAssembly element for each assembly.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + When you build a .NET Framework application against a strong-named assembly, the application uses that version of the assembly at run time by default, even if a new version is available. However, you can configure the application to run against a newer version of the assembly. For details on how the runtime uses these files to determine which assembly version to use, see [How the Runtime Locates Assemblies](../../../deployment/how-the-runtime-locates-assemblies.md). + + You can redirect more than one assembly version by including multiple `bindingRedirect` elements in a `dependentAssembly` element. You can also redirect from a newer version to an older version of the assembly. + + Explicit assembly binding redirection in an application configuration file requires a security permission. This applies to redirection of .NET Framework assemblies and assemblies from third parties. The permission is granted by setting the flag on the . For more information, see [Assembly Binding Redirection Security Permission](../../assembly-binding-redirection-security-permission.md). + +## Example + + The following example shows how to redirect one assembly version to another. + +```xml + + + + + + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/bypasstrustedappstrongnames-element.md b/docs/framework/configure-apps/file-schema/runtime/bypasstrustedappstrongnames-element.md index d0a30158d9f54..802587fdd271a 100644 --- a/docs/framework/configure-apps/file-schema/runtime/bypasstrustedappstrongnames-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/bypasstrustedappstrongnames-element.md @@ -9,7 +9,7 @@ helpviewer_keywords: - " element" ms.assetid: 71b2ebf6-3843-41e2-ad52-ffa5cd083a40 --- -# \ Element +# `` Element Specifies whether to bypass the validation of strong names on full-trust assemblies that are loaded into a full-trust . diff --git a/docs/framework/configure-apps/file-schema/runtime/clear-element-for-namedcaches.md b/docs/framework/configure-apps/file-schema/runtime/clear-element-for-namedcaches.md index 1481f214833dd..72869b941455d 100644 --- a/docs/framework/configure-apps/file-schema/runtime/clear-element-for-namedcaches.md +++ b/docs/framework/configure-apps/file-schema/runtime/clear-element-for-namedcaches.md @@ -2,57 +2,57 @@ description: "Learn more about: Element for " title: " Element for " ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - " element for " - "clear element for " ms.assetid: ea01a858-65da-4348-800f-5e3df59d4d79 --- -# \ Element for \ +# `` Element for \ + +Clears all `namedCache` entries in the `namedCaches` collection for a memory cache. -Clears all `namedCache` entries in the `namedCaches` collection for a memory cache. - [**\**](../configuration-element.md)\   [**\**](system-runtime-caching-element-cache-settings.md)\     [**\**](memorycache-element-cache-settings.md)\       [**\**](namedcaches-element-cache-settings.md)\ -        **\** - -## Syntax - -```xml - - - - -``` - -## Type - - `Type` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - `None` - -### Child Elements - - `None` - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](namedcaches-element-cache-settings.md)|Contains a collection of configuration settings for the named instances.| - -## Remarks - - The `clear` element clears all `namedCache` entries in the named cache collection for a memory cache. You can use the `clear` element before you use the `add` element to add a new named cache entry in order to be certain there are no other named caches in the collection. - +        **\** + +## Syntax + +```xml + + + + +``` + +## Type + + `Type` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + `None` + +### Child Elements + + `None` + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](namedcaches-element-cache-settings.md)|Contains a collection of configuration settings for the named instances.| + +## Remarks + + The `clear` element clears all `namedCache` entries in the named cache collection for a memory cache. You can use the `clear` element before you use the `add` element to add a new named cache entry in order to be certain there are no other named caches in the collection. + ## See also - [Configure apps by using configuration files](../../index.md) -- [\ Element (Cache Settings)](namedcaches-element-cache-settings.md) +- [`` Element (Cache Settings)](namedcaches-element-cache-settings.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/codebase-element.md b/docs/framework/configure-apps/file-schema/runtime/codebase-element.md index 873770abdd510..e2fd79208c71e 100644 --- a/docs/framework/configure-apps/file-schema/runtime/codebase-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/codebase-element.md @@ -12,7 +12,7 @@ helpviewer_keywords: ms.assetid: d48a3983-2297-43ff-a14d-1f29d3995822 --- -# \ Element +# `` Element Specifies where the common language runtime can find an assembly. @@ -62,11 +62,11 @@ None. ## Remarks -For the runtime to use the **\** setting in a machine configuration file or publisher policy file, the file must also redirect the assembly version. Application configuration files can have a codebase setting without redirecting the assembly version. After determining which assembly version to use, the runtime applies the codebase setting from the file that determines the version. If no codebase is indicated, the runtime probes for the assembly in the usual way. +For the runtime to use the `` setting in a machine configuration file or publisher policy file, the file must also redirect the assembly version. Application configuration files can have a codebase setting without redirecting the assembly version. After determining which assembly version to use, the runtime applies the codebase setting from the file that determines the version. If no codebase is indicated, the runtime probes for the assembly in the usual way. If the assembly has a strong name, the codebase setting can be anywhere on the local intranet or the Internet. If the assembly is a private assembly, the codebase setting must be a path relative to the application's directory. -For assemblies without a strong name, version is ignored and the loader uses the first appearance of \ inside \. If there is an entry in the application configuration file that redirects binding to another assembly, the redirection will take precedence even if the assembly version doesn't match the binding request. +For assemblies without a strong name, version is ignored and the loader uses the first appearance of `` inside ``. If there is an entry in the application configuration file that redirects binding to another assembly, the redirection will take precedence even if the assembly version doesn't match the binding request. ## Example diff --git a/docs/framework/configure-apps/file-schema/runtime/compatsortnlsversion-element.md b/docs/framework/configure-apps/file-schema/runtime/compatsortnlsversion-element.md index 138b4a86038d3..3e454fef88a64 100644 --- a/docs/framework/configure-apps/file-schema/runtime/compatsortnlsversion-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/compatsortnlsversion-element.md @@ -2,95 +2,95 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - " element" - "CompatSortNLSVersion element" ms.assetid: 782cc82e-83f7-404a-80b7-6d3061a8b6e3 --- -# \ Element +# `` Element + +Specifies that the runtime should use legacy sort orders when performing string comparisons. -Specifies that the runtime should use legacy sort orders when performing string comparisons. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Specifies the locale ID whose sort order is to be used.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|4096|The locale ID that represents an alternate sort order. In this case, 4096 represents the sort order of the .NET Framework 3.5 and earlier versions.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about runtime initialization options.| - -## Remarks - - Because string comparison, sorting, and casing operations performed by the class in the .NET Framework 4 conform to the Unicode 5.1 standard, the results of string comparison methods such as and may differ from previous versions of the .NET Framework. If your application depends on legacy behavior, you can restore the string comparison and sorting rules used in the .NET Framework 3.5 and earlier versions by including the `` element in your application's configuration file. - + enabled="4096"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Specifies the locale ID whose sort order is to be used.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|4096|The locale ID that represents an alternate sort order. In this case, 4096 represents the sort order of the .NET Framework 3.5 and earlier versions.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about runtime initialization options.| + +## Remarks + + Because string comparison, sorting, and casing operations performed by the class in the .NET Framework 4 conform to the Unicode 5.1 standard, the results of string comparison methods such as and may differ from previous versions of the .NET Framework. If your application depends on legacy behavior, you can restore the string comparison and sorting rules used in the .NET Framework 3.5 and earlier versions by including the `` element in your application's configuration file. + > [!IMPORTANT] -> Restoring legacy string comparison and sorting rules also requires the sort00001000.dll dynamic link library to be available on the local system. - - You can also use legacy string sorting and comparison rules in a specific application domain by passing the string "NetFx40_Legacy20SortingBehavior" to the method when you create the application domain. - -## Example - - The following example instantiates two objects and calls the method to compare them by using the conventions of the current culture. - +> Restoring legacy string comparison and sorting rules also requires the sort00001000.dll dynamic link library to be available on the local system. + + You can also use legacy string sorting and comparison rules in a specific application domain by passing the string "NetFx40_Legacy20SortingBehavior" to the method when you create the application domain. + +## Example + + The following example instantiates two objects and calls the method to compare them by using the conventions of the current culture. + [!code-csharp[String.BreakingChanges#1](../../../../../samples/snippets/csharp/VS_Snippets_CLR/string.breakingchanges/cs/example1.cs#1)] - [!code-vb[String.BreakingChanges#1](../../../../../samples/snippets/visualbasic/VS_Snippets_CLR/string.breakingchanges/vb/example1.vb#1)] - + [!code-vb[String.BreakingChanges#1](../../../../../samples/snippets/visualbasic/VS_Snippets_CLR/string.breakingchanges/vb/example1.vb#1)] + When you run the example on the .NET Framework 4, it displays the following output: - + ```console -sta follows a in the sort order. -``` - +sta follows a in the sort order. +``` + This is completely different from the output that is displayed when you run the example on the .NET Framework 3.5: - + ```console -sta equals a in the sort order. -``` - - However, if you add the following configuration file to the example's directory and then run the example on the .NET Framework 4, the output is identical to that produced by the example when it is run on .NET Framework 3.5. - -```xml - - - - - - -``` - +sta equals a in the sort order. +``` + + However, if you add the following configuration file to the example's directory and then run the example on the .NET Framework 4, the output is identical to that produced by the example when it is run on .NET Framework 3.5. + +```xml + + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/crst-disablespinwait-element.md b/docs/framework/configure-apps/file-schema/runtime/crst-disablespinwait-element.md index b3043c57729ad..cf8093c847761 100644 --- a/docs/framework/configure-apps/file-schema/runtime/crst-disablespinwait-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/crst-disablespinwait-element.md @@ -2,65 +2,65 @@ description: "Learn more about: element" title: " element" ms.date: "04/18/2019" -f1_keywords: +f1_keywords: - "Crst_DisableSpinWait" -helpviewer_keywords: +helpviewer_keywords: - "Crst_DisableSpinWait element" --- -# \ element +# `` element + +Specifies whether to disable spin-waiting for a critical section when contended. -Specifies whether to disable spin-waiting for a critical section when contended. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - +    **\** + +## Syntax + +```xml + +``` + ## Attributes and Elements -The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**enabled**|Specifies whether spin-waiting for critical sections when they are contended is disabled.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|1|Disable spin-waiting when a critical section cannot be acquired.| -|0|Do not disable spin-waiting when a critical section cannot be acquired. This is the default value.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about various runtime configuration settings.| - -## Example - -The following example disables spin-waiting in critical sections when contended. - -```xml - - - - - -``` - +The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|**enabled**|Specifies whether spin-waiting for critical sections when they are contended is disabled.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|1|Disable spin-waiting when a critical section cannot be acquired.| +|0|Do not disable spin-waiting when a critical section cannot be acquired. This is the default value.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about various runtime configuration settings.| + +## Example + +The following example disables spin-waiting in critical sections when contended. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/dependentassembly-element.md b/docs/framework/configure-apps/file-schema/runtime/dependentassembly-element.md index 2e854fba34c9f..5172d8abdbc5c 100644 --- a/docs/framework/configure-apps/file-schema/runtime/dependentassembly-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/dependentassembly-element.md @@ -2,81 +2,81 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/assemblyBinding/dependentAssembly" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#dependentAssembly" -helpviewer_keywords: +helpviewer_keywords: - "container tags, element" - "dependentAssembly element" - " element" ms.assetid: 14e95627-dd79-4b82-ac85-e682aa3a31d8 --- -# \ Element +# `` Element + +Encapsulates binding policy and assembly location for each assembly. Use one `dependentAssembly` element for each assembly. -Encapsulates binding policy and assembly location for each assembly. Use one `dependentAssembly` element for each assembly. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\     [**\**](assemblybinding-element-for-runtime.md)\ -      **\** - -## Syntax - -```xml +      **\** + +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|`assemblyIdentity`|Contains identifying information about the assembly. This element must be included in each `dependentAssembly` element.| -|`codeBase`|Specifies where the runtime can find a shared assembly if it is not installed on the computer.| -|`bindingRedirect`|Redirects one assembly version to another.| -|`publisherPolicy`|Specifies whether the runtime applies publisher policy for this assembly.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Example - - The following example shows how to encapsulate assembly information for two assemblies. - -```xml - - - - - - - - - - - - - - -``` - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|`assemblyIdentity`|Contains identifying information about the assembly. This element must be included in each `dependentAssembly` element.| +|`codeBase`|Specifies where the runtime can find a shared assembly if it is not installed on the computer.| +|`bindingRedirect`|Redirects one assembly version to another.| +|`publisherPolicy`|Specifies whether the runtime applies publisher policy for this assembly.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Example + + The following example shows how to encapsulate assembly information for two assemblies. + +```xml + + + + + + + + + + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/developmentmode-element.md b/docs/framework/configure-apps/file-schema/runtime/developmentmode-element.md index 80e8272e38c06..e3ef5ecf250b3 100644 --- a/docs/framework/configure-apps/file-schema/runtime/developmentmode-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/developmentmode-element.md @@ -2,73 +2,73 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/developmentMode" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#developmentMode" -helpviewer_keywords: +helpviewer_keywords: - "developmentMode element" - "container tags, element" - " element" ms.assetid: 60e79a8c-415a-497d-be29-b9d0fd9bdee3 --- -# \ Element +# `` Element + +Specifies whether the runtime searches for assemblies in directories specified by the DEVPATH environment variable. -Specifies whether the runtime searches for assemblies in directories specified by the DEVPATH environment variable. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**developerInstallation**|Specifies whether the runtime searches for assemblies in directories specified by the DEVPATH environment variable.| - -## developerInstallation Attribute - -|Value|Description| -|-----------|-----------------| -|**true**|Searches for assemblies in directories specified by the DEVPATH environment variable.| -|**false**|Does not search for assemblies in directories specified by the DEVPATH environment variable. This is the default| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - Use this setting only at development time. The runtime does not check the versions on strong-named assemblies found in the DEVPATH. It simply uses the first assembly it finds. - -## Example - - The following example shows how to cause the runtime to search for assemblies in directories specified by the DEVPATH environment variable. - -```xml - - - - - -``` - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|**developerInstallation**|Specifies whether the runtime searches for assemblies in directories specified by the DEVPATH environment variable.| + +## developerInstallation Attribute + +|Value|Description| +|-----------|-----------------| +|**true**|Searches for assemblies in directories specified by the DEVPATH environment variable.| +|**false**|Does not search for assemblies in directories specified by the DEVPATH environment variable. This is the default| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + Use this setting only at development time. The runtime does not check the versions on strong-named assemblies found in the DEVPATH. It simply uses the first assembly it finds. + +## Example + + The following example shows how to cause the runtime to search for assemblies in directories specified by the DEVPATH environment variable. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/disablecachingbindingfailures-element.md b/docs/framework/configure-apps/file-schema/runtime/disablecachingbindingfailures-element.md index 8ba66968c8a37..de1f87fe0dec2 100644 --- a/docs/framework/configure-apps/file-schema/runtime/disablecachingbindingfailures-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/disablecachingbindingfailures-element.md @@ -2,82 +2,82 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#disableCachingBindingFailures" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/disableCachingBindingFailures" -helpviewer_keywords: +helpviewer_keywords: - "assemblies [.NET Framework],caching binding failures" - "caching assembly binding failures" - " element" - "disableCachingBindingFailures element" ms.assetid: bf598873-83b7-48de-8955-00b0504fbad0 --- -# \ Element +# `` Element + +Specifies whether to disable the caching of binding failures that occur because the assembly was not found by probing. -Specifies whether to disable the caching of binding failures that occur because the assembly was not found by probing. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|enabled|Required attribute.

Specifies whether to disable the caching of binding failures that occur because the assembly was not found by probing.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|0|Do not disable the caching of binding failures that occur because the assembly was not found by probing. This is the default binding behavior starting with .NET Framework version 2.0.| -|1|Disable the caching of binding failures that occur because the assembly was not found by probing. This setting reverts to the binding behavior of .NET Framework version 1.1.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - Starting with .NET Framework version 2.0, the default behavior for loading assemblies is to cache all binding and loading failures. That is, if an attempt to load an assembly fails, subsequent requests to load the same assembly fail immediately, without any attempt to locate the assembly. This element disables that default behavior for binding failures that occur because the assembly could not be found in the probing path. These failures throw . - - Some binding and loading failures are not affected by this element, and are always cached. These failures occur because the assembly was found but could not be loaded. They throw or . The following list includes some examples of such failures. - -- If you attempt to load a file is not a valid assembly, subsequent attempts to load the assembly will fail even if the bad file is replaced with the correct assembly. - -- If you attempt to load an assembly that is locked by the file system, subsequent attempts to load the assembly will fail even after the assembly is released by the file system. - -- If one or more versions of the assembly that you are attempting to load is in the probing path, but the specific version you are requesting is not among them, subsequent attempts to load that version will fail even if the correct version is moved into the probing path. - -## Example - - The following example shows how to disable the caching of assembly binding failures that occur because the assembly was not found by probing. - -```xml - - - - - -``` - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|enabled|Required attribute.

Specifies whether to disable the caching of binding failures that occur because the assembly was not found by probing.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|0|Do not disable the caching of binding failures that occur because the assembly was not found by probing. This is the default binding behavior starting with .NET Framework version 2.0.| +|1|Disable the caching of binding failures that occur because the assembly was not found by probing. This setting reverts to the binding behavior of .NET Framework version 1.1.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + Starting with .NET Framework version 2.0, the default behavior for loading assemblies is to cache all binding and loading failures. That is, if an attempt to load an assembly fails, subsequent requests to load the same assembly fail immediately, without any attempt to locate the assembly. This element disables that default behavior for binding failures that occur because the assembly could not be found in the probing path. These failures throw . + + Some binding and loading failures are not affected by this element, and are always cached. These failures occur because the assembly was found but could not be loaded. They throw or . The following list includes some examples of such failures. + +- If you attempt to load a file is not a valid assembly, subsequent attempts to load the assembly will fail even if the bad file is replaced with the correct assembly. + +- If you attempt to load an assembly that is locked by the file system, subsequent attempts to load the assembly will fail even after the assembly is released by the file system. + +- If one or more versions of the assembly that you are attempting to load is in the probing path, but the specific version you are requesting is not among them, subsequent attempts to load that version will fail even if the correct version is moved into the probing path. + +## Example + + The following example shows how to disable the caching of assembly binding failures that occur because the assembly was not found by probing. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/disablecommitthreadstack-element.md b/docs/framework/configure-apps/file-schema/runtime/disablecommitthreadstack-element.md index 452cdadcb39b1..458ccf590940e 100644 --- a/docs/framework/configure-apps/file-schema/runtime/disablecommitthreadstack-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/disablecommitthreadstack-element.md @@ -2,75 +2,75 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/disableCommitThreadStack" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#disableCommitThreadStack" -helpviewer_keywords: +helpviewer_keywords: - " element" - "disableCommitThreadStack element" ms.assetid: 3559d46a-7640-4c72-9a11-7e980768929e --- -# \ Element +# `` Element + +Specifies whether the full thread stack is committed when a thread is started. -Specifies whether the full thread stack is committed when a thread is started. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|enabled|Required attribute.

Specifies whether committing the full thread stack on thread startup (the default behavior) is disabled.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|0|Do not disable the default behavior of the common language runtime, which is to commit the full thread stack when a thread is started.| -|1|Disable the default behavior of the common language runtime, which is to commit the full thread stack when a thread is started.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - The default behavior of the common language runtime is to commit the full thread stack when a thread is started. If a large number of threads must be created on a server that has limited memory, and most of those threads will use very little stack space, the server might perform better if the common language runtime does not commit the full thread stack immediately when a thread is started. - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|enabled|Required attribute.

Specifies whether committing the full thread stack on thread startup (the default behavior) is disabled.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|0|Do not disable the default behavior of the common language runtime, which is to commit the full thread stack when a thread is started.| +|1|Disable the default behavior of the common language runtime, which is to commit the full thread stack when a thread is started.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + The default behavior of the common language runtime is to commit the full thread stack when a thread is started. If a large number of threads must be created on a server that has limited memory, and most of those threads will use very little stack space, the server might perform better if the common language runtime does not commit the full thread stack immediately when a thread is started. + > [!NOTE] -> Unmanaged hosts can use the `STARTUP_DISABLE_COMMITTHREADSTACK` startup flag in the [STARTUP_FLAGS](../../../unmanaged-api/hosting/startup-flags-enumeration.md) enumeration to accomplish the same result. - -## Example - - The following example shows how to disable the default behavior of the common language runtime, which is to commit the full thread stack on thread startup. - -```xml - - - - - -``` - +> Unmanaged hosts can use the `STARTUP_DISABLE_COMMITTHREADSTACK` startup flag in the [STARTUP_FLAGS](../../../unmanaged-api/hosting/startup-flags-enumeration.md) enumeration to accomplish the same result. + +## Example + + The following example shows how to disable the default behavior of the common language runtime, which is to commit the full thread stack on thread startup. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/disablefusionupdatesfromadmanager-element.md b/docs/framework/configure-apps/file-schema/runtime/disablefusionupdatesfromadmanager-element.md index af9f9518fc97b..a91ca05d79e4a 100644 --- a/docs/framework/configure-apps/file-schema/runtime/disablefusionupdatesfromadmanager-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/disablefusionupdatesfromadmanager-element.md @@ -2,77 +2,77 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "disableFusionUpdatesFromADManager element" - " element" ms.assetid: 58d2866c-37bd-4ffa-abaf-ff35926a2939 --- -# \ Element +# `` Element + +Specifies whether the default behavior, which is to allow the runtime host to override configuration settings for an application domain, is disabled. -Specifies whether the default behavior, which is to allow the runtime host to override configuration settings for an application domain, is disabled. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|enabled|Required attribute.

Specifies whether the default ability to override Fusion settings is disabled.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|0|Do not disable the ability to override Fusion settings. This is the default behavior, starting with the .NET Framework 4.| -|1|Disable the ability to override Fusion settings. This reverts to the behavior of earlier versions of the .NET Framework.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - Starting with the .NET Framework 4, the default behavior is to allow the object to override configuration settings by using the property or the method of the object that is passed to your implementation of the method, in your subclass of . For the default application domain, the settings you change override the settings that were specified by the application configuration file. For other application domains, they override the configuration settings that were passed to the or method. - - You can either pass new configuration information, or pass null (`Nothing` in Visual Basic) to eliminate configuration information that was passed in. - - Do not pass configuration information to both the property and the method. If you pass configuration information to both, the information you pass to the property is ignored, because the method overrides configuration information from the application configuration file. If you use the property, you can pass null (`Nothing` in Visual Basic) to the method to eliminate any configuration bytes that were specified in the call to the or method. - - In addition to configuration information, you can change the following settings on the object that is passed to your implementation of the method: , , , , , , , , , , , , and . - - As an alternative to using the `` element, you can disable the default behavior by creating a registry setting or by setting an environment variable. In the registry, create a DWORD value named `COMPLUS_disableFusionUpdatesFromADManager` under `HKCU\Software\Microsoft\.NETFramework` or `HKLM\Software\Microsoft\.NETFramework`, and set the value to 1. At the command line, set the environment variable `COMPLUS_disableFusionUpdatesFromADManager` to 1. - -## Example - - The following example shows how to disable the ability to override Fusion settings by using the `` element. - -```xml - - - - - -``` - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|enabled|Required attribute.

Specifies whether the default ability to override Fusion settings is disabled.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|0|Do not disable the ability to override Fusion settings. This is the default behavior, starting with the .NET Framework 4.| +|1|Disable the ability to override Fusion settings. This reverts to the behavior of earlier versions of the .NET Framework.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + Starting with the .NET Framework 4, the default behavior is to allow the object to override configuration settings by using the property or the method of the object that is passed to your implementation of the method, in your subclass of . For the default application domain, the settings you change override the settings that were specified by the application configuration file. For other application domains, they override the configuration settings that were passed to the or method. + + You can either pass new configuration information, or pass null (`Nothing` in Visual Basic) to eliminate configuration information that was passed in. + + Do not pass configuration information to both the property and the method. If you pass configuration information to both, the information you pass to the property is ignored, because the method overrides configuration information from the application configuration file. If you use the property, you can pass null (`Nothing` in Visual Basic) to the method to eliminate any configuration bytes that were specified in the call to the or method. + + In addition to configuration information, you can change the following settings on the object that is passed to your implementation of the method: , , , , , , , , , , , , and . + + As an alternative to using the `` element, you can disable the default behavior by creating a registry setting or by setting an environment variable. In the registry, create a DWORD value named `COMPLUS_disableFusionUpdatesFromADManager` under `HKCU\Software\Microsoft\.NETFramework` or `HKLM\Software\Microsoft\.NETFramework`, and set the value to 1. At the command line, set the environment variable `COMPLUS_disableFusionUpdatesFromADManager` to 1. + +## Example + + The following example shows how to disable the ability to override Fusion settings by using the `` element. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/disablestackoverflowprobing-element.md b/docs/framework/configure-apps/file-schema/runtime/disablestackoverflowprobing-element.md index 79e31380824fc..f07c2ce15fe57 100644 --- a/docs/framework/configure-apps/file-schema/runtime/disablestackoverflowprobing-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/disablestackoverflowprobing-element.md @@ -3,7 +3,7 @@ description: "Learn more about the element" title: " Element" ms.date: 04/20/2022 --- -# \ Element +# `` Element Specifies whether stack-overflow probing is disabled. @@ -44,5 +44,5 @@ The `` specifies whether stack-overflow probing is ## See also - [Configure apps by using configuration files](../../index.md) -- [\ Element](runtime-element.md) -- [\ Element](../configuration-element.md) +- [`` Element](runtime-element.md) +- [`` Element](../configuration-element.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/enableampmparseadjustment-element.md b/docs/framework/configure-apps/file-schema/runtime/enableampmparseadjustment-element.md index 2c87a847f0ed5..00f0e496a943f 100644 --- a/docs/framework/configure-apps/file-schema/runtime/enableampmparseadjustment-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/enableampmparseadjustment-element.md @@ -4,82 +4,82 @@ title: " Element" ms.date: "03/30/2017" ms.assetid: fda998a5-f538-4f8b-a18c-ee7f35e16938 --- -# \ Element +# `` Element + +Determines whether date and time parsing methods use an adjusted set of rules to parse date strings that contain a day, month, hour, and AM/PM designator. -Determines whether date and time parsing methods use an adjusted set of rules to parse date strings that contain a day, month, hour, and AM/PM designator. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Specifies whether date and time parsing methods use an adjusted set of rules to parse date strings that contain only a day, month, hour, and AM/PM designator.| - -### enabled Attribute - -|Value|Description| -|-----------|-----------------| -|0|Date and time parsing methods do not use adjusted rules for parsing date strings that contain only a day, month, hour, and AM/PM designator.| -|1|Date and time parsing methods use adjusted rules for parsing date strings that contain only a day, month, hour, and AM/PM designator.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about runtime initialization options.| - -## Remarks - - The `` element controls how the following methods parse a date string that contains a numeric day and month followed by an hour and an AM/PM designator (such as "4/10 6 AM"): - -- - -- - -- - -- - -- - - No other patterns are affected. - - The `` element has no effect on the , , , and methods. - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Specifies whether date and time parsing methods use an adjusted set of rules to parse date strings that contain only a day, month, hour, and AM/PM designator.| + +### enabled Attribute + +|Value|Description| +|-----------|-----------------| +|0|Date and time parsing methods do not use adjusted rules for parsing date strings that contain only a day, month, hour, and AM/PM designator.| +|1|Date and time parsing methods use adjusted rules for parsing date strings that contain only a day, month, hour, and AM/PM designator.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about runtime initialization options.| + +## Remarks + + The `` element controls how the following methods parse a date string that contains a numeric day and month followed by an hour and an AM/PM designator (such as "4/10 6 AM"): + +- + +- + +- + +- + +- + + No other patterns are affected. + + The `` element has no effect on the , , , and methods. + > [!IMPORTANT] -> In .NET Core and .NET Native, the adjusted AM/PM parsing rules are enabled by default. - - If the parsing adjustment rule is not enabled, the first digit of the string is interpreted as the hour of the 12-hour clock, and the remainder of the string except for the AM/PM designator is ignored. The date and time returned by the parsing method consists of the current date and the hour of the day extracted from the date string. - - If the parsing adjustment rule is enabled, parsing method interpret the day and month as belonging to the current year, and interpret the time as the hour of the 12-hour clock. - - The following table illustrates the difference in the value when the method is used to parse the string ""4/10 6 AM" with the `` element's `enabled` property set to "0" or "1". It assumes that today's date is January 5, 2017, and displays the date as if it is formatted using the specified culture's "G" format string. - -|Culture name|enabled="0"|enabled="1"| -|------------------|------------------|------------------| -|en-US|1/5/2017 4:00:00 AM|4/10/2017 6:00:00 AM| -|en-GB|5/1/2017 6:00:00|10/4/2017 6:00:00| - +> In .NET Core and .NET Native, the adjusted AM/PM parsing rules are enabled by default. + + If the parsing adjustment rule is not enabled, the first digit of the string is interpreted as the hour of the 12-hour clock, and the remainder of the string except for the AM/PM designator is ignored. The date and time returned by the parsing method consists of the current date and the hour of the day extracted from the date string. + + If the parsing adjustment rule is enabled, parsing method interpret the day and month as belonging to the current year, and interpret the time as the hour of the 12-hour clock. + + The following table illustrates the difference in the value when the method is used to parse the string ""4/10 6 AM" with the `` element's `enabled` property set to "0" or "1". It assumes that today's date is January 5, 2017, and displays the date as if it is formatted using the specified culture's "G" format string. + +|Culture name|enabled="0"|enabled="1"| +|------------------|------------------|------------------| +|en-US|1/5/2017 4:00:00 AM|4/10/2017 6:00:00 AM| +|en-GB|5/1/2017 6:00:00|10/4/2017 6:00:00| + ## See also - [Configure apps by using configuration files](../../index.md) -- [\ Element](runtime-element.md) -- [\ Element](../configuration-element.md) +- [`` Element](runtime-element.md) +- [`` Element](../configuration-element.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/enforcefipspolicy-element.md b/docs/framework/configure-apps/file-schema/runtime/enforcefipspolicy-element.md index a5001e4812f26..ad6c211087505 100644 --- a/docs/framework/configure-apps/file-schema/runtime/enforcefipspolicy-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/enforcefipspolicy-element.md @@ -2,73 +2,73 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "enforceFIPSPolicy element" - "FIPS" - " element" - "Federal Information Processing Standards (FIPS)" ms.assetid: c35509c4-35cf-43c0-bb47-75e4208aa24e --- -# \ Element +# `` Element + +Specifies whether to enforce a computer configuration requirement that cryptographic algorithms must comply with the Federal Information Processing Standards (FIPS). -Specifies whether to enforce a computer configuration requirement that cryptographic algorithms must comply with the Federal Information Processing Standards (FIPS). - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|enabled|Required attribute.

Specifies whether to enable the enforcement of a computer configuration requirement that cryptographic algorithms must be compliant with FIPS.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|`true`|If your computer is configured to require cryptographic algorithms to be FIPS compliant, that requirement is enforced. If a class implements an algorithm that is not compliant with FIPS, the constructors or `Create` methods for that class throw exceptions when they are run on that computer. This is the default.| -|`false`|Cryptographic algorithms that are used by the application are not required to be compliant with FIPS, regardless of computer configuration.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - Starting with .NET Framework 2.0, the creation of classes that implement cryptographic algorithms is controlled by the configuration of the computer. If the computer is configured to require algorithms to be compliant with FIPS, and a class implements an algorithm that is not compliant with FIPS, any attempt to create an instance of that class throws an exception. Constructors throw an exception, and `Create` methods throw a exception with an inner exception. - - If your application runs on computers whose configurations require compliance with FIPS, and your application uses an algorithm that is not compliant with FIPS, you can use this element in your configuration file to prevent the common language runtime (CLR) from enforcing FIPS compliance. This element was introduced in the .NET Framework 2.0 Service Pack 1. - -## Example - - The following example shows how to prevent the CLR from enforcing FIPS compliance. - -```xml - - - - - -``` - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|enabled|Required attribute.

Specifies whether to enable the enforcement of a computer configuration requirement that cryptographic algorithms must be compliant with FIPS.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|`true`|If your computer is configured to require cryptographic algorithms to be FIPS compliant, that requirement is enforced. If a class implements an algorithm that is not compliant with FIPS, the constructors or `Create` methods for that class throw exceptions when they are run on that computer. This is the default.| +|`false`|Cryptographic algorithms that are used by the application are not required to be compliant with FIPS, regardless of computer configuration.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + Starting with .NET Framework 2.0, the creation of classes that implement cryptographic algorithms is controlled by the configuration of the computer. If the computer is configured to require algorithms to be compliant with FIPS, and a class implements an algorithm that is not compliant with FIPS, any attempt to create an instance of that class throws an exception. Constructors throw an exception, and `Create` methods throw a exception with an inner exception. + + If your application runs on computers whose configurations require compliance with FIPS, and your application uses an algorithm that is not compliant with FIPS, you can use this element in your configuration file to prevent the common language runtime (CLR) from enforcing FIPS compliance. This element was introduced in the .NET Framework 2.0 Service Pack 1. + +## Example + + The following example shows how to prevent the CLR from enforcing FIPS compliance. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/etwenable-element.md b/docs/framework/configure-apps/file-schema/runtime/etwenable-element.md index 7be7c687937a5..79beb5f7f8e77 100644 --- a/docs/framework/configure-apps/file-schema/runtime/etwenable-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/etwenable-element.md @@ -2,72 +2,72 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "etwEnable element" - " element" ms.assetid: 29dde982-6d8b-4099-8867-ad0d7733f6dc --- -# \ Element +# `` Element + +Specifies whether to enable event tracing for Windows (ETW) for common language runtime events. -Specifies whether to enable event tracing for Windows (ETW) for common language runtime events. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|enabled|Required attribute.

Specifies whether ETW should be enabled.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|true|Enable ETW. This is the default for versions of Windows beginning with the Windows Vista and Windows Server 2008 operating systems.| -|false|Disable ETW. This is the default for earlier versions of Windows.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - Beginning with Windows Vista, ETW is enabled by default. Use this element to disable ETW for an application. In earlier versions of Windows, use this element to enable ETW for an application. - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|enabled|Required attribute.

Specifies whether ETW should be enabled.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|true|Enable ETW. This is the default for versions of Windows beginning with the Windows Vista and Windows Server 2008 operating systems.| +|false|Disable ETW. This is the default for earlier versions of Windows.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + Beginning with Windows Vista, ETW is enabled by default. Use this element to disable ETW for an application. In earlier versions of Windows, use this element to enable ETW for an application. + > [!NOTE] -> ETW can be enabled or disabled globally on a server by using a registry setting. See [Controlling .NET Framework Logging](../../../performance/controlling-logging.md). - -## Example - - The following example shows how to enable ETW tracing for an application. - -```xml - - - - - -``` - +> ETW can be enabled or disabled globally on a server by using a registry setting. See [Controlling .NET Framework Logging](../../../performance/controlling-logging.md). + +## Example + + The following example shows how to enable ETW tracing for an application. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/forceperformancecounteruniquesharedmemoryreads-element.md b/docs/framework/configure-apps/file-schema/runtime/forceperformancecounteruniquesharedmemoryreads-element.md index bfee73d57e241..54ecf602b725c 100644 --- a/docs/framework/configure-apps/file-schema/runtime/forceperformancecounteruniquesharedmemoryreads-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/forceperformancecounteruniquesharedmemoryreads-element.md @@ -2,81 +2,81 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "forcePerformanceCounterUniqueSharedMemoryReads element" - " element" ms.assetid: 91149858-4810-4f65-9b48-468488172c9b --- -# \ Element +# `` Element + +Specifies whether PerfCounter.dll uses the CategoryOptions registry setting in a .NET Framework version 1.1 application to determine whether to load performance counter data from category-specific shared memory or global memory. -Specifies whether PerfCounter.dll uses the CategoryOptions registry setting in a .NET Framework version 1.1 application to determine whether to load performance counter data from category-specific shared memory or global memory. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Indicates whether PerfCounter.dll uses the CategoryOptions registry setting to determine whether to load performance counter data from category-specific shared memory or global memory.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|`false`|PerfCounter.dll does not use the CategoryOptions registry setting This is the default.| -|`true`|PerfCounter.dll does use the CategoryOptions registry setting.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - In versions of the .NET Framework before the .NET Framework 4, the version of PerfCounter.dll that was loaded corresponded to the runtime that was loaded in the process. If a computer had both the .NET Framework version 1.1 and the .NET Framework 2.0 installed, a .NET Framework 1.1 application would load the .NET Framework 1.1 version of PerfCounter.dll. Starting with the .NET Framework 4, the newest installed version of PerfCounter.dll is loaded. This means that a .NET Framework 1.1 application will load the .NET Framework 4 version of PerfCounter.dll if the .NET Framework 4 is installed on the computer. - - Starting with the .NET Framework 4, when consuming performance counters, PerfCounter.dll checks the CategoryOptions registry entry for each provider to determine whether it should read from category-specific shared memory or global shared memory. The .NET Framework 1.1 PerfCounter.dll does not read that registry entry, because it is not aware of category-specific shared memory; it always reads from global shared memory. - - For backward compatibility, the .NET Framework 4 PerfCounter.dll does not check the CategoryOptions registry entry when running in a .NET Framework 1.1 application. It simply uses global shared memory, just like the .NET Framework 1.1 PerfCounter.dll. However, you can instruct the .NET Framework 4 PerfCounter.dll to check the registry setting by enabling the `` element. - +enabled="true|false"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Indicates whether PerfCounter.dll uses the CategoryOptions registry setting to determine whether to load performance counter data from category-specific shared memory or global memory.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|`false`|PerfCounter.dll does not use the CategoryOptions registry setting This is the default.| +|`true`|PerfCounter.dll does use the CategoryOptions registry setting.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + In versions of the .NET Framework before the .NET Framework 4, the version of PerfCounter.dll that was loaded corresponded to the runtime that was loaded in the process. If a computer had both the .NET Framework version 1.1 and the .NET Framework 2.0 installed, a .NET Framework 1.1 application would load the .NET Framework 1.1 version of PerfCounter.dll. Starting with the .NET Framework 4, the newest installed version of PerfCounter.dll is loaded. This means that a .NET Framework 1.1 application will load the .NET Framework 4 version of PerfCounter.dll if the .NET Framework 4 is installed on the computer. + + Starting with the .NET Framework 4, when consuming performance counters, PerfCounter.dll checks the CategoryOptions registry entry for each provider to determine whether it should read from category-specific shared memory or global shared memory. The .NET Framework 1.1 PerfCounter.dll does not read that registry entry, because it is not aware of category-specific shared memory; it always reads from global shared memory. + + For backward compatibility, the .NET Framework 4 PerfCounter.dll does not check the CategoryOptions registry entry when running in a .NET Framework 1.1 application. It simply uses global shared memory, just like the .NET Framework 1.1 PerfCounter.dll. However, you can instruct the .NET Framework 4 PerfCounter.dll to check the registry setting by enabling the `` element. + > [!NOTE] -> Enabling the `` element does not guarantee that category-specific shared memory will be used. Setting enabled to `true` only causes PerfCounter.dll to reference the CategoryOptions registry setting. The default setting for CategoryOptions is to use category-specific shared memory; however, you can change CategoryOptions to indicate that global shared memory should be used. - - The registry key that contains the CategoryOptions setting is HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\\\Performance. By default, CategoryOptions is set to 3, which instructs PerfCounter.dll to use category-specific shared memory. If CategoryOptions is set to 0, PerfCounter.dll uses global shared memory. Instance data will be reused only if the name of the instance being created is identical to the instance being reused. All versions will be able to write to the category. If CategoryOptions is set to 1, global shared memory is used, but instance data can be reused if the category name is the same length as the category being reused. - - The settings 0 and 1 can lead to memory leaks and the filling up of performance counter memory. - -## Example - - The following example shows how to specify that PerfCounter.dll should reference the CategoryOptions registry entry to determine whether it should use category-specific shared memory. - -```xml - - - - - -``` - +> Enabling the `` element does not guarantee that category-specific shared memory will be used. Setting enabled to `true` only causes PerfCounter.dll to reference the CategoryOptions registry setting. The default setting for CategoryOptions is to use category-specific shared memory; however, you can change CategoryOptions to indicate that global shared memory should be used. + + The registry key that contains the CategoryOptions setting is HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\\\Performance. By default, CategoryOptions is set to 3, which instructs PerfCounter.dll to use category-specific shared memory. If CategoryOptions is set to 0, PerfCounter.dll uses global shared memory. Instance data will be reused only if the name of the instance being created is identical to the instance being reused. All versions will be able to write to the category. If CategoryOptions is set to 1, global shared memory is used, but instance data can be reused if the category name is the same length as the category being reused. + + The settings 0 and 1 can lead to memory leaks and the filling up of performance counter memory. + +## Example + + The following example shows how to specify that PerfCounter.dll should reference the CategoryOptions registry entry to determine whether it should use category-specific shared memory. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md b/docs/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md index f28332ea7f021..05c04228edd29 100644 --- a/docs/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md @@ -2,74 +2,74 @@ description: "Learn more about: element" title: "gcAllowVeryLargeObjects element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "gcAllowVeryLargeObjects element" - " element" ms.assetid: 5c7ea24a-39ac-4e5f-83b7-b9f9a1b556ab --- -# \ element +# `` element + +On 64-bit platforms, enables arrays that are greater than 2 gigabytes (GB) in total size. -On 64-bit platforms, enables arrays that are greater than 2 gigabytes (GB) in total size. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - +    **\** + +## Syntax + +```xml + +``` + ## Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Specifies whether arrays that are greater than 2 GB in total size are enabled on 64-bit platforms.| - -### enabled attribute - -|Value|Description| -|-----------|-----------------| -|`false`|Arrays greater than 2 GB in total size are not enabled. This is the default.| -|`true`|Arrays greater than 2 GB in total size are enabled on 64-bit platforms.| - -## Child elements - -None. - + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Specifies whether arrays that are greater than 2 GB in total size are enabled on 64-bit platforms.| + +### enabled attribute + +|Value|Description| +|-----------|-----------------| +|`false`|Arrays greater than 2 GB in total size are not enabled. This is the default.| +|`true`|Arrays greater than 2 GB in total size are enabled on 64-bit platforms.| + +## Child elements + +None. + ## Parent elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about runtime initialization options.| - -## Remarks - - Using this element in your [application configuration file](../../index.md) enables arrays that are larger than 2 GB in size, but does not change other limits on object size or array size: - -- The maximum number of elements in an array is . - -- The maximum size in any single dimension is 2,147,483,591 (0x7FFFFFC7) for byte arrays and arrays of single-byte structures, and 2,146,435,071 (0X7FEFFFFF) for arrays containing other types. - -- The maximum size for strings and other non-array objects is unchanged. - + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about runtime initialization options.| + +## Remarks + + Using this element in your [application configuration file](../../index.md) enables arrays that are larger than 2 GB in size, but does not change other limits on object size or array size: + +- The maximum number of elements in an array is . + +- The maximum size in any single dimension is 2,147,483,591 (0x7FFFFFC7) for byte arrays and arrays of single-byte structures, and 2,146,435,071 (0X7FEFFFFF) for arrays containing other types. + +- The maximum size for strings and other non-array objects is unchanged. + > [!CAUTION] -> Before enabling this feature, ensure that your application does not include unsafe code that assumes that all arrays are smaller than 2 GB in size. For example, unsafe code that uses arrays as buffers might be susceptible to buffer overruns if it's written on the assumption that arrays will not exceed 2 GB. - -## Example - - The following *app.config* file snippet shows how to enable this feature for a .NET Framework application. - -```xml - - - - - -``` - +> Before enabling this feature, ensure that your application does not include unsafe code that assumes that all arrays are smaller than 2 GB in size. For example, unsafe code that uses arrays as buffers might be susceptible to buffer overruns if it's written on the assumption that arrays will not exceed 2 GB. + +## Example + + The following *app.config* file snippet shows how to enable this feature for a .NET Framework application. + +```xml + + + + + +``` + ## Supported in .NET Framework 4.5 and later versions diff --git a/docs/framework/configure-apps/file-schema/runtime/gcconcurrent-element.md b/docs/framework/configure-apps/file-schema/runtime/gcconcurrent-element.md index 36458d2ac9964..7c6386c5da3ff 100644 --- a/docs/framework/configure-apps/file-schema/runtime/gcconcurrent-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/gcconcurrent-element.md @@ -11,7 +11,7 @@ helpviewer_keywords: - " element" ms.assetid: 503f55ba-26ed-45ac-a2ea-caf994da04cd --- -# \ element +# `` element Specifies whether the common language runtime runs garbage collection on a separate thread. @@ -56,14 +56,14 @@ None. ## Remarks -Prior to .NET Framework 4, workstation garbage collection supported concurrent garbage collection, which performed garbage collection in the background on a separate thread. In .NET Framework 4, concurrent garbage collection was replaced by background GC, which also performs garbage collection in the background on a separate thread. Starting with .NET Framework 4.5, background collection became available in server garbage collection. The **gcConcurrent** element controls whether the runtime performs either concurrent or background garbage collection, if it's available, or whether it performs garbage collection in the foreground. +Prior to .NET Framework 4, workstation garbage collection supported concurrent garbage collection, which performed garbage collection in the background on a separate thread. In .NET Framework 4, concurrent garbage collection was replaced by background GC, which also performs garbage collection in the background on a separate thread. Starting with .NET Framework 4.5, background collection became available in server garbage collection. The `gcConcurrent` element controls whether the runtime performs either concurrent or background garbage collection, if it's available, or whether it performs garbage collection in the foreground. ### To disable background garbage collection > [!WARNING] -> Starting with .NET Framework 4, concurrent garbage collection is replaced by background garbage collection. The terms *concurrent* and *background* are used interchangeably in the .NET Framework documentation. To disable background garbage collection, use the **gcConcurrent** element, as discussed in this article. +> Starting with .NET Framework 4, concurrent garbage collection is replaced by background garbage collection. The terms *concurrent* and *background* are used interchangeably in the .NET Framework documentation. To disable background garbage collection, use the `gcConcurrent` element, as discussed in this article. -By default, the runtime uses concurrent or background garbage collection, which is optimized for latency. If your application involves heavy user interaction, leave concurrent garbage collection enabled to minimize the application's pause time to perform garbage collection. If you set the `enabled` attribute of the **gcConcurrent** element to `false`, the runtime uses non-concurrent garbage collection, which is optimized for throughput. +By default, the runtime uses concurrent or background garbage collection, which is optimized for latency. If your application involves heavy user interaction, leave concurrent garbage collection enabled to minimize the application's pause time to perform garbage collection. If you set the `enabled` attribute of the `gcConcurrent` element to `false`, the runtime uses non-concurrent garbage collection, which is optimized for throughput. The following configuration file disables background garbage collection: @@ -75,7 +75,7 @@ The following configuration file disables background garbage collection:
``` -If there's a **gcConcurrentSetting** setting in the machine configuration file, it defines the default value for all .NET Framework applications. The machine configuration file setting overrides the application configuration file setting. +If there's a `gcConcurrentSetting` setting in the machine configuration file, it defines the default value for all .NET Framework applications. The machine configuration file setting overrides the application configuration file setting. For more information on concurrent and background garbage collection, see [Background garbage collection](../../../../standard/garbage-collection/background-gc.md). diff --git a/docs/framework/configure-apps/file-schema/runtime/gccpugroup-element.md b/docs/framework/configure-apps/file-schema/runtime/gccpugroup-element.md index 27d190bd95534..a21d8e33062e4 100644 --- a/docs/framework/configure-apps/file-schema/runtime/gccpugroup-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/gccpugroup-element.md @@ -7,7 +7,7 @@ helpviewer_keywords: - " element" ms.assetid: c1fc7d6c-7220-475c-a312-5b8b201f66e0 --- -# \ Element +# `` Element Specifies whether garbage collection supports multiple CPU groups. diff --git a/docs/framework/configure-apps/file-schema/runtime/gcheapaffinitizemask-element.md b/docs/framework/configure-apps/file-schema/runtime/gcheapaffinitizemask-element.md index 5f6053246f995..35867a2aa2394 100644 --- a/docs/framework/configure-apps/file-schema/runtime/gcheapaffinitizemask-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/gcheapaffinitizemask-element.md @@ -6,7 +6,7 @@ helpviewer_keywords: - "gcHeapCount element" - " element" --- -# \ element +# `` element Defines the affinity between GC heaps and individual processors. @@ -50,11 +50,11 @@ None. ## Remarks -By default, server GC threads are hard-affinitized with their respective CPU so that there is one GC heap, one server GC thread, and one background server GC thread for each processor. Starting with .NET Framework 4.6.2, you can use the **GCHeapAffinitizeMask** element to control the affinity between server GC heaps and processors when the number of heaps is limited by the **GCHeapCount** element. +By default, server GC threads are hard-affinitized with their respective CPU so that there is one GC heap, one server GC thread, and one background server GC thread for each processor. Starting with .NET Framework 4.6.2, you can use the `GCHeapAffinitizeMask` element to control the affinity between server GC heaps and processors when the number of heaps is limited by the `GCHeapCount` element. **GCHeapAffinitizeMask** is typically used along with two other flags: -- [GCNoAffinitize](gcnoaffinitize-element.md), which controls whether server GC threads/heaps are affinitized with CPUs. The `enabled` attribute of the [GCNoAffinitize](gcnoaffinitize-element.md) element must be `false` (its default value) for the **GCHeapAffinitizeMask** setting to be used. +- [GCNoAffinitize](gcnoaffinitize-element.md), which controls whether server GC threads/heaps are affinitized with CPUs. The `enabled` attribute of the [GCNoAffinitize](gcnoaffinitize-element.md) element must be `false` (its default value) for the `GCHeapAffinitizeMask` setting to be used. - [GCHeapCount](gcheapcount-element.md), which limits the number of heaps used by the process for server GC. By default, there is one heap for each processor. @@ -68,7 +68,7 @@ A value of 1023 is 0x3FF or 0011 1111 1111b. The process uses 10 processors, fro ## Example -The following example indicates that an application uses server GC with 10 heaps/threads. Since you don't want those heaps to overlap with heaps from other applications running on the system, use **GCHeapAffinitizeMask** to specify that the process should use CPUs 0 through 9. +The following example indicates that an application uses server GC with 10 heaps/threads. Since you don't want those heaps to overlap with heaps from other applications running on the system, use `GCHeapAffinitizeMask` to specify that the process should use CPUs 0 through 9. ```xml diff --git a/docs/framework/configure-apps/file-schema/runtime/gcheapcount-element.md b/docs/framework/configure-apps/file-schema/runtime/gcheapcount-element.md index 2abf7c6bf0e14..e9e44a417046b 100644 --- a/docs/framework/configure-apps/file-schema/runtime/gcheapcount-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/gcheapcount-element.md @@ -6,7 +6,7 @@ helpviewer_keywords: - "gcHeapCount element" - " element" --- -# \ element +# `` element Specifies the number of heaps/threads to use for server garbage collection. @@ -50,7 +50,7 @@ None. ## Remarks -By default, server GC threads are hard-affinitized with their respective CPU so that there is one GC heap, one server GC thread, and one background server GC thread for each processor. Starting with .NET Framework 4.6.2, you can use the **GCHeapCount** element to limit the number of heaps used by your application for server GC. Limiting the number of heaps used for server GC is particularly useful for systems that run multiple instances of a server application. +By default, server GC threads are hard-affinitized with their respective CPU so that there is one GC heap, one server GC thread, and one background server GC thread for each processor. Starting with .NET Framework 4.6.2, you can use the `GCHeapCount` element to limit the number of heaps used by your application for server GC. Limiting the number of heaps used for server GC is particularly useful for systems that run multiple instances of a server application. **GCHeapCount** is typically used along with two other flags: @@ -58,13 +58,13 @@ By default, server GC threads are hard-affinitized with their respective CPU so - [GCHeapAffinitizeMask](gcheapaffinitizemask-element.md), which controls the affinity of GC threads/heaps with CPUs. -If **GCHeapCount** is set and **GCNoAffinitize** is disabled (its default setting), there is an affinity between the *nn* GC threads/heaps and the first *nn* processors. You can use the **GCHeapAffinitizeMask** element to specify which processors are used by the process's server GC heaps. Otherwise, if multiple server processes are running on a system, their processor usage will overlap. +If `GCHeapCount` is set and `GCNoAffinitize` is disabled (its default setting), there is an affinity between the *nn* GC threads/heaps and the first *nn* processors. You can use the `GCHeapAffinitizeMask` element to specify which processors are used by the process's server GC heaps. Otherwise, if multiple server processes are running on a system, their processor usage will overlap. -If **GCHeapCount** is set and **GCNoAffinitize** is enabled, the garbage collector limits the number of processors used for server GC but does not affinitize GC heaps and processors. +If `GCHeapCount` is set and `GCNoAffinitize` is enabled, the garbage collector limits the number of processors used for server GC but does not affinitize GC heaps and processors. ## Example -The following example indicates that an application uses server GC with 10 heaps/threads. Since you don't want those heaps to overlap with heaps from other applications running on the system, you use the **GCHeapAffinitizeMask** to specify that the process should use CPUs 0 through 9. +The following example indicates that an application uses server GC with 10 heaps/threads. Since you don't want those heaps to overlap with heaps from other applications running on the system, you use the `GCHeapAffinitizeMask` to specify that the process should use CPUs 0 through 9. ```xml diff --git a/docs/framework/configure-apps/file-schema/runtime/gcnoaffinitize-element.md b/docs/framework/configure-apps/file-schema/runtime/gcnoaffinitize-element.md index 0a465461abf1b..baa9b61a256a1 100644 --- a/docs/framework/configure-apps/file-schema/runtime/gcnoaffinitize-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/gcnoaffinitize-element.md @@ -6,7 +6,7 @@ helpviewer_keywords: - "gcNoAffinitize element" - " element" --- -# \ element +# `` element Specifies whether or not to affinitize server GC threads with CPUs. @@ -51,11 +51,11 @@ None. ## Remarks -By default, server GC threads are hard-affinitized with their respective CPUs. Each of the system's available processors has its own GC heap and thread. This is typically the preferred setting since it optimizes cache usage. Starting with .NET Framework 4.6.2, by setting the **GCNoAffinitize** element's `enabled` attribute to `true`, you can specify that server GC threads and CPUs should not be tightly coupled. +By default, server GC threads are hard-affinitized with their respective CPUs. Each of the system's available processors has its own GC heap and thread. This is typically the preferred setting since it optimizes cache usage. Starting with .NET Framework 4.6.2, by setting the `GCNoAffinitize` element's `enabled` attribute to `true`, you can specify that server GC threads and CPUs should not be tightly coupled. -You can specify the **GCNoAffinitize** configuration element alone to not affinitize server GC threads with CPUs. You can also use it along with the [GCHeapCount](gcheapcount-element.md) element to control the number of GC heaps and threads used by an application. +You can specify the `GCNoAffinitize` configuration element alone to not affinitize server GC threads with CPUs. You can also use it along with the [GCHeapCount](gcheapcount-element.md) element to control the number of GC heaps and threads used by an application. -If the `enabled` attribute of the **GCNoAffinitize** element is `false` (its default value), you can also use the [GCHeapCount](gcheapcount-element.md) element to specify the number of GC threads and heaps, along with the [GCHeapAffinitizeMask](gcheapaffinitizemask-element.md) element to specify the processors to which the GC threads and heaps are affinitized. +If the `enabled` attribute of the `GCNoAffinitize` element is `false` (its default value), you can also use the [GCHeapCount](gcheapcount-element.md) element to specify the number of GC threads and heaps, along with the [GCHeapAffinitizeMask](gcheapaffinitizemask-element.md) element to specify the processors to which the GC threads and heaps are affinitized. ## Example diff --git a/docs/framework/configure-apps/file-schema/runtime/gcserver-element.md b/docs/framework/configure-apps/file-schema/runtime/gcserver-element.md index 2b150359b72f4..0db0d3c445aad 100644 --- a/docs/framework/configure-apps/file-schema/runtime/gcserver-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/gcserver-element.md @@ -10,7 +10,7 @@ helpviewer_keywords: - " element" ms.assetid: 8d25b80e-2581-4803-bd87-a59528e3cb03 --- -# \ element +# `` element Specifies whether the common language runtime runs server garbage collection. @@ -55,14 +55,14 @@ None. ## Remarks -The common language runtime (CLR) supports two types of garbage collection: workstation garbage collection, which is available on all systems, and server garbage collection, which is available on multiprocessor systems. Use the **gcServer** element to control the type of garbage collection the CLR performs. Use the property to determine if server garbage collection is enabled. +The common language runtime (CLR) supports two types of garbage collection: workstation garbage collection, which is available on all systems, and server garbage collection, which is available on multiprocessor systems. Use the `gcServer` element to control the type of garbage collection the CLR performs. Use the property to determine if server garbage collection is enabled. For single-processor computers, the default workstation garbage collection should be the fastest option. Either workstation or server can be used for two-processor computers. Server garbage collection should be the fastest option for more than two processors. Most commonly, multiprocessor server systems disable server GC and use workstation GC instead when many instances of a server app run on the same machine. This element can be used only in the application configuration file; it is ignored if it is in the machine configuration file. > [!NOTE] -> In the .NET Framework 4 and earlier versions, concurrent garbage collection is not available when server garbage collection is enabled. Starting with .NET Framework 4.5, server garbage collection is concurrent. To use non-concurrent server garbage collection, set the **gcServer** element to `true` and the [gcConcurrent element](gcconcurrent-element.md) to `false`. +> In the .NET Framework 4 and earlier versions, concurrent garbage collection is not available when server garbage collection is enabled. Starting with .NET Framework 4.5, server garbage collection is concurrent. To use non-concurrent server garbage collection, set the `gcServer` element to `true` and the [gcConcurrent element](gcconcurrent-element.md) to `false`. Starting with .NET Framework 4.6.2, you can also use the following elements to configure server GC: diff --git a/docs/framework/configure-apps/file-schema/runtime/generatepublisherevidence-element.md b/docs/framework/configure-apps/file-schema/runtime/generatepublisherevidence-element.md index 9e6b3295e8670..9c3dd2adc1f27 100644 --- a/docs/framework/configure-apps/file-schema/runtime/generatepublisherevidence-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/generatepublisherevidence-element.md @@ -7,7 +7,7 @@ helpviewer_keywords: - " element" ms.assetid: 7d208f50-e8d5-4a42-bc1a-1cf3590706a8 --- -# \ Element +# `` Element Specifies whether the runtime creates evidence for code access security (CAS). diff --git a/docs/framework/configure-apps/file-schema/runtime/index.md b/docs/framework/configure-apps/file-schema/runtime/index.md index a3e25b96e4506..9f31eaff4555a 100644 --- a/docs/framework/configure-apps/file-schema/runtime/index.md +++ b/docs/framework/configure-apps/file-schema/runtime/index.md @@ -12,7 +12,7 @@ ms.assetid: f04816ab-110d-4e28-9283-845d6d9a4a68 Runtime settings are used by the common language runtime to configure applications that target .NET Framework. This article shows the schema for runtime settings in an [application configuration file](../../index.md). -## The \ section and its parent and child elements +## The `` section and its parent and child elements [\](../configuration-element.md)\   [\](runtime-element.md)\ @@ -72,7 +72,7 @@ Runtime settings are used by the common language runtime to configure applicatio         [\](clear-element-for-namedcaches.md)\         [\](remove-element-for-namedcaches.md) -## Alphabetical list of \ elements +## Alphabetical list of `` elements |Element|Description| |-------------|-----------------| diff --git a/docs/framework/configure-apps/file-schema/runtime/legacycorruptedstateexceptionspolicy-element.md b/docs/framework/configure-apps/file-schema/runtime/legacycorruptedstateexceptionspolicy-element.md index 742183aaeff47..181313fa02ac2 100644 --- a/docs/framework/configure-apps/file-schema/runtime/legacycorruptedstateexceptionspolicy-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/legacycorruptedstateexceptionspolicy-element.md @@ -2,79 +2,79 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - " element" - "legacyCorruptedStateExceptionsPolicy element" ms.assetid: e0a55ddc-bfa8-4f3e-ac14-d1fc3330e4bb --- -# \ Element +# `` Element + +Specifies whether the common language runtime allows managed code to catch access violations and other corrupted state exceptions. -Specifies whether the common language runtime allows managed code to catch access violations and other corrupted state exceptions. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Specifies that the application will catch corrupting state exception failures such as access violations.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|`false`|The application will not catch corrupting state exception failures such as access violations. This is the default.| -|`true`|The application will catch corrupting state exception failures such as access violations.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - In the .NET Framework version 3.5 and earlier, the common language runtime allowed managed code to catch exceptions that were raised by corrupted process states. An access violation is an example of this type of exception. - - Starting with the .NET Framework 4, managed code no longer catches these types of exceptions in `catch` blocks. However, you can override this change and maintain the handling of corrupted state exceptions in two ways: - -- Set the `` element's `enabled` attribute to `true`. This configuration setting is applied processwide and affects all methods. - - -or- - -- Apply the attribute to the method that contains the exceptions `catch` block. - - This configuration element is available only in the .NET Framework 4 and later. - -## Example - - The following example shows how to specify that the application should revert to the behavior before the .NET Framework 4, and catch all corrupting state exception failures. - -```xml - - - - - -``` - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Specifies that the application will catch corrupting state exception failures such as access violations.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|`false`|The application will not catch corrupting state exception failures such as access violations. This is the default.| +|`true`|The application will catch corrupting state exception failures such as access violations.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + In the .NET Framework version 3.5 and earlier, the common language runtime allowed managed code to catch exceptions that were raised by corrupted process states. An access violation is an example of this type of exception. + + Starting with the .NET Framework 4, managed code no longer catches these types of exceptions in `catch` blocks. However, you can override this change and maintain the handling of corrupted state exceptions in two ways: + +- Set the `` element's `enabled` attribute to `true`. This configuration setting is applied processwide and affects all methods. + + -or- + +- Apply the attribute to the method that contains the exceptions `catch` block. + + This configuration element is available only in the .NET Framework 4 and later. + +## Example + + The following example shows how to specify that the application should revert to the behavior before the .NET Framework 4, and catch all corrupting state exception failures. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/legacyimpersonationpolicy-element.md b/docs/framework/configure-apps/file-schema/runtime/legacyimpersonationpolicy-element.md index 6222119c6e0ae..899eefb7ca47a 100644 --- a/docs/framework/configure-apps/file-schema/runtime/legacyimpersonationpolicy-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/legacyimpersonationpolicy-element.md @@ -2,121 +2,121 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#legacyImpersonationPolicy" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/legacyImpersonationPolicy" -helpviewer_keywords: +helpviewer_keywords: - " element" - "legacyImpersonationPolicy element" ms.assetid: 6e00af10-42f3-4235-8415-1bb2db78394e --- -# \ Element +# `` Element + +Specifies that the Windows identity does not flow across asynchronous points, regardless of the flow settings for the execution context on the current thread. -Specifies that the Windows identity does not flow across asynchronous points, regardless of the flow settings for the execution context on the current thread. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Specifies that the does not flow across asynchronous points, regardless of the flow settings on the current thread.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|`false`| flows across asynchronous points depending upon the flow settings for the current thread. This is the default.| -|`true`| does not flow across asynchronous points, regardless of the flow settings on the current thread.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - In the .NET Framework versions 1.0 and 1.1, the does not flow across any user-defined asynchronous points. Starting with .NET Framework version 2.0, there is an object that contains information about the currently executing thread, and it flows across asynchronous points within an application domain. The is included in this execution context and therefore also flows across the asynchronous points, which means that if an impersonation context exists, it will flow as well. - - Starting with .NET Framework 2.0, you can use the `` element to specify that does not flow across asynchronous points. - + enabled="true|false"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Specifies that the does not flow across asynchronous points, regardless of the flow settings on the current thread.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|`false`| flows across asynchronous points depending upon the flow settings for the current thread. This is the default.| +|`true`| does not flow across asynchronous points, regardless of the flow settings on the current thread.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + In the .NET Framework versions 1.0 and 1.1, the does not flow across any user-defined asynchronous points. Starting with .NET Framework version 2.0, there is an object that contains information about the currently executing thread, and it flows across asynchronous points within an application domain. The is included in this execution context and therefore also flows across the asynchronous points, which means that if an impersonation context exists, it will flow as well. + + Starting with .NET Framework 2.0, you can use the `` element to specify that does not flow across asynchronous points. + > [!NOTE] -> The common language runtime (CLR) is aware of impersonation operations performed using only managed code, not of impersonation performed outside of managed code, such as through platform invoke to unmanaged code or through direct calls to Win32 functions. Only managed objects can flow across asynchronous points, unless the `alwaysFlowImpersonationPolicy` element has been set to true (``). Setting the `alwaysFlowImpersonationPolicy` element to true specifies that the Windows identity always flows across asynchronous points, regardless of how impersonation was performed. For more information on flowing unmanaged impersonation across asynchronous points, see [\ Element](alwaysflowimpersonationpolicy-element.md). - - You can alter this default behavior in two other ways: - -1. In managed code on a per-thread basis. - - You can suppress the flow on a per-thread basis by modifying the and settings by using the , or method. - -2. In the call to the unmanaged hosting interface to load the common language runtime (CLR). - - If an unmanaged hosting interface (instead of a simple managed executable) is used to load the CLR, you can specify a special flag in the call to the [CorBindToRuntimeEx Function](../../../unmanaged-api/hosting/corbindtoruntimeex-function.md) function. To enable the compatibility mode for the entire process, set the `flags` parameter for [CorBindToRuntimeEx Function](../../../unmanaged-api/hosting/corbindtoruntimeex-function.md) to STARTUP_LEGACY_IMPERSONATION. - - For more information, see the [\ Element](alwaysflowimpersonationpolicy-element.md). - -## Configuration File - - In a .NET Framework application, this element can be used only in the application configuration file. - - For an ASP.NET application, the impersonation flow can be configured in the aspnet.config file found in the \\Microsoft.NET\Framework\vx.x.xxxx directory. - - ASP.NET by default disables the impersonation flow in the aspnet.config file by using the following configuration settings: - +> The common language runtime (CLR) is aware of impersonation operations performed using only managed code, not of impersonation performed outside of managed code, such as through platform invoke to unmanaged code or through direct calls to Win32 functions. Only managed objects can flow across asynchronous points, unless the `alwaysFlowImpersonationPolicy` element has been set to true (``). Setting the `alwaysFlowImpersonationPolicy` element to true specifies that the Windows identity always flows across asynchronous points, regardless of how impersonation was performed. For more information on flowing unmanaged impersonation across asynchronous points, see [`` Element](alwaysflowimpersonationpolicy-element.md). + + You can alter this default behavior in two other ways: + +1. In managed code on a per-thread basis. + + You can suppress the flow on a per-thread basis by modifying the and settings by using the , or method. + +2. In the call to the unmanaged hosting interface to load the common language runtime (CLR). + + If an unmanaged hosting interface (instead of a simple managed executable) is used to load the CLR, you can specify a special flag in the call to the [CorBindToRuntimeEx Function](../../../unmanaged-api/hosting/corbindtoruntimeex-function.md) function. To enable the compatibility mode for the entire process, set the `flags` parameter for [CorBindToRuntimeEx Function](../../../unmanaged-api/hosting/corbindtoruntimeex-function.md) to STARTUP_LEGACY_IMPERSONATION. + + For more information, see the [`` Element](alwaysflowimpersonationpolicy-element.md). + +## Configuration File + + In a .NET Framework application, this element can be used only in the application configuration file. + + For an ASP.NET application, the impersonation flow can be configured in the aspnet.config file found in the \\Microsoft.NET\Framework\vx.x.xxxx directory. + + ASP.NET by default disables the impersonation flow in the aspnet.config file by using the following configuration settings: + ``` xml - - - - - - -``` - - In ASP.NET, if you want to allow the flow of impersonation instead, you must explicitly use the following configuration settings: - -```xml - - - - - - -``` - -## Example - - The following example shows how to specify the legacy behavior that does not flow the Windows identity across asynchronous points. - -```xml - - - - - -``` - + + + + + + +``` + + In ASP.NET, if you want to allow the flow of impersonation instead, you must explicitly use the following configuration settings: + +```xml + + + + + + +``` + +## Example + + The following example shows how to specify the legacy behavior that does not flow the Windows identity across asynchronous points. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) - [Runtime Settings Schema](index.md) - [Configuration File Schema](../index.md) -- [\ Element](alwaysflowimpersonationpolicy-element.md) +- [`` Element](alwaysflowimpersonationpolicy-element.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/loadfromremotesources-element.md b/docs/framework/configure-apps/file-schema/runtime/loadfromremotesources-element.md index 0076697875551..706751a533782 100644 --- a/docs/framework/configure-apps/file-schema/runtime/loadfromremotesources-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/loadfromremotesources-element.md @@ -7,7 +7,7 @@ helpviewer_keywords: - " element" ms.assetid: 006d1280-2ac3-4db6-a984-a3d4e275046a --- -# \ element +# `` element Specifies whether assemblies loaded from remote sources should be granted full trust in .NET Framework 4 and later. diff --git a/docs/framework/configure-apps/file-schema/runtime/memorycache-element-cache-settings.md b/docs/framework/configure-apps/file-schema/runtime/memorycache-element-cache-settings.md index 4ea2ccdf510dc..5b6aa49d4a532 100644 --- a/docs/framework/configure-apps/file-schema/runtime/memorycache-element-cache-settings.md +++ b/docs/framework/configure-apps/file-schema/runtime/memorycache-element-cache-settings.md @@ -2,98 +2,98 @@ description: "Learn more about: Element (Cache Settings)" title: " Element (Cache Settings)" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - " element" - "caching [.NET Framework], configuration" - "memoryCache element" ms.assetid: 182a622f-f7cf-472d-9d0b-451d2fd94525 --- -# \ Element (Cache Settings) +# `` Element (Cache Settings) + +Defines an element that is used to configure a cache that is based on the class. The class defines a [memoryCache](memorycache-element-cache-settings.md) element that you can use to configure the cache. Multiple instances of the class can be used in a single application. Each `memoryCache` element in the configuration file can contain settings for a named instance. -Defines an element that is used to configure a cache that is based on the class. The class defines a [memoryCache](memorycache-element-cache-settings.md) element that you can use to configure the cache. Multiple instances of the class can be used in a single application. Each `memoryCache` element in the configuration file can contain settings for a named instance. - [**\**](../configuration-element.md)\   [**\**](system-runtime-caching-element-cache-settings.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml - - + + - -``` - -## Type - - class. - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`CacheMemoryLimitMegabytes`|The maximum memory size, in megabytes, that an instance of a object can grow to. The default value is 0, which means that the class's autosize heuristics are used by default. (This setting is only effective on .Net Framework.)| -|`Name`|The name of the cache configuration.| -|`PhysicalMemoryLimitPercentage`|percentage of total physical memory usage on the system (by all processes) at which the cache will begin to evict entries. The default value is 0, which means that the class's autosize heuristics are used by default.| -|`PollingInterval`|A value that indicates the time interval after which the cache implementation compares the current memory load against the absolute and percentage-based memory limits that are set for the cache instance. The value is entered in "HH:MM:SS" format.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](namedcaches-element-cache-settings.md)|Contains a collection of configuration settings for the `namedCache` instance.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](../configuration-element.md)|Specifies the root element in every configuration file that is used by the common language runtime and .NET Framework applications.| -|[\](system-runtime-caching-element-cache-settings.md)|Contains types that let you implement output caching in applications that are built into the .NET Framework.| - -## Remarks - - The class is a concrete implementation of the abstract class. Instances of the class can be supplied with configuration information from application configuration files. The [memoryCache](memorycache-element-cache-settings.md) configuration section contains a `namedCaches` configuration collection. - - When a memory-based cache object is initialized, it first tries to find a `namedCaches` entry that matches the name in the parameter that is passed to the memory cache constructor. If a `namedCaches` entry is found, the polling and memory-management information are retrieved from the configuration file. - - The initialization process then determines whether any configuration entries were overridden, by using the optional collection of name/value pairs of configuration information in the constructor. If you pass any one of the following values in the name/value pair collection, these values override information obtained from the configuration file: - -- - -- - -- - -## Example - - The following example shows how to set the name of the object to the default cache object name by setting the `name` attribute to "Default". - - The `cacheMemoryLimitMegabytes` attribute and the `physicalMemoryLimitPercentage` attribute are set to zero. Setting these attributes to zero means that the autosizing heuristics are used by default. The cache implementation should compare the current memory load against the absolute and percentage-based memory limits every two minutes. - -```xml - - - - + +``` + +## Type + + class. + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`CacheMemoryLimitMegabytes`|The maximum memory size, in megabytes, that an instance of a object can grow to. The default value is 0, which means that the class's autosize heuristics are used by default. (This setting is only effective on .Net Framework.)| +|`Name`|The name of the cache configuration.| +|`PhysicalMemoryLimitPercentage`|percentage of total physical memory usage on the system (by all processes) at which the cache will begin to evict entries. The default value is 0, which means that the class's autosize heuristics are used by default.| +|`PollingInterval`|A value that indicates the time interval after which the cache implementation compares the current memory load against the absolute and percentage-based memory limits that are set for the cache instance. The value is entered in "HH:MM:SS" format.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](namedcaches-element-cache-settings.md)|Contains a collection of configuration settings for the `namedCache` instance.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](../configuration-element.md)|Specifies the root element in every configuration file that is used by the common language runtime and .NET Framework applications.| +|[\](system-runtime-caching-element-cache-settings.md)|Contains types that let you implement output caching in applications that are built into the .NET Framework.| + +## Remarks + + The class is a concrete implementation of the abstract class. Instances of the class can be supplied with configuration information from application configuration files. The [memoryCache](memorycache-element-cache-settings.md) configuration section contains a `namedCaches` configuration collection. + + When a memory-based cache object is initialized, it first tries to find a `namedCaches` entry that matches the name in the parameter that is passed to the memory cache constructor. If a `namedCaches` entry is found, the polling and memory-management information are retrieved from the configuration file. + + The initialization process then determines whether any configuration entries were overridden, by using the optional collection of name/value pairs of configuration information in the constructor. If you pass any one of the following values in the name/value pair collection, these values override information obtained from the configuration file: + +- + +- + +- + +## Example + + The following example shows how to set the name of the object to the default cache object name by setting the `name` attribute to "Default". + + The `cacheMemoryLimitMegabytes` attribute and the `physicalMemoryLimitPercentage` attribute are set to zero. Setting these attributes to zero means that the autosizing heuristics are used by default. The cache implementation should compare the current memory load against the absolute and percentage-based memory limits every two minutes. + +```xml + + + + - - - - -``` - + physicalMemoryLimitPercentage="0" + pollingInterval="00:02:00" /> + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) - -- [\ Element (Cache Settings)](system-runtime-caching-element-cache-settings.md) -- [\ Element (Cache Settings)](namedcaches-element-cache-settings.md) +- [`` Element (Cache Settings)](system-runtime-caching-element-cache-settings.md) +- [`` Element (Cache Settings)](namedcaches-element-cache-settings.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/namedcaches-element-cache-settings.md b/docs/framework/configure-apps/file-schema/runtime/namedcaches-element-cache-settings.md index 4eb767c890134..83c9b03803443 100644 --- a/docs/framework/configure-apps/file-schema/runtime/namedcaches-element-cache-settings.md +++ b/docs/framework/configure-apps/file-schema/runtime/namedcaches-element-cache-settings.md @@ -2,94 +2,94 @@ description: "Learn more about: Element (Cache Settings)" title: " Element (Cache Settings)" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "namedCaches element" - "caching [.NET Framework], configuration" - " element" ms.assetid: 6bd4fbc5-55a6-4dc4-998b-cdcc7e023330 --- -# \ Element (Cache Settings) +# `` Element (Cache Settings) + +Specifies a collection of configuration settings for the named instances. The property references the collection of configuration settings from one or more `namedCaches` elements of the configuration file. -Specifies a collection of configuration settings for the named instances. The property references the collection of configuration settings from one or more `namedCaches` elements of the configuration file. - [**\**](../configuration-element.md)\   [**\**](system-runtime-caching-element-cache-settings.md)\     [**\**](memorycache-element-cache-settings.md)\ -      **\** - -## Syntax - -```xml - +      **\** + +## Syntax + +```xml + - -``` - -## Type - - `None` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`cacheMemoryLimitMegabytes`|An integer value that specifies the maximum allowable size, in megabytes, that an instance of a can grow to. The default value is 0, which means that the autosizing heuristics of the class are used by default.| -|`name`|The name of the cache.| -|`physicalMemoryLimitPercentage`|An integer value between 0 and 100 that specifies the maximum percentage of physically installed computer memory that can be consumed by the cache. The default value is 0, which means that the autosizing heuristics of the class are used by default.| -|`pollingInterval`|A value that indicates the time interval after which the cache implementation compares the current memory load against the absolute and percentage-based memory limits that are set for the cache instance. This value is entered in "HH:MM:SS" format.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](add-element-for-namedcaches.md)|Adds a named cache to the `namedCaches` collection for a memory cache.| -|[\](clear-element-for-namedcaches.md)|Clears the `namedCaches` collection for a memory cache.| -|[\](remove-element-for-namedcaches.md)|Removes a named cache entry from the `namedCaches` collection for a memory cache.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](../configuration-element.md)|Specifies the root element in every configuration file that is used by the common language runtime and .NET Framework applications.| -|[\](memorycache-element-cache-settings.md)|Defines an element that is used to configure a cache that is based on the class.| -|[\](system-runtime-caching-element-cache-settings.md)|Contains types that let you implement output caching in applications that are built into the .NET Framework.| - -## Remarks - - The memory cache configuration section of the Web.config file can contain `add`, `remove`, and `clear` attributes for the `namedCaches` collection. Each `namedCaches` entry is uniquely identified by the `name` attribute. - - You can retrieve instances of memory cache entries by referencing the information in the application configuration files. By default, only the default cache instance has an entry in the configuration file. The default cache instance is the instance that is returned from the property. - - If you set the name attribute to "Default", the element uses the default memory cache instance. - -## Example - - The following example shows how to set the name of the cache to the default cache entry name by setting the `name` attribute to "Default". - - The `cacheMemoryLimitMegabytes` attribute and the `physicalMemoryPercentage` attribute are set to zero. Setting these attributes to zero means that the autosizing heuristics of the class are used. The cache implementation compares the current memory load against the absolute and percentage-based memory limits every two minutes. - -```xml - - - - - + +``` + +## Type + + `None` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`cacheMemoryLimitMegabytes`|An integer value that specifies the maximum allowable size, in megabytes, that an instance of a can grow to. The default value is 0, which means that the autosizing heuristics of the class are used by default.| +|`name`|The name of the cache.| +|`physicalMemoryLimitPercentage`|An integer value between 0 and 100 that specifies the maximum percentage of physically installed computer memory that can be consumed by the cache. The default value is 0, which means that the autosizing heuristics of the class are used by default.| +|`pollingInterval`|A value that indicates the time interval after which the cache implementation compares the current memory load against the absolute and percentage-based memory limits that are set for the cache instance. This value is entered in "HH:MM:SS" format.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](add-element-for-namedcaches.md)|Adds a named cache to the `namedCaches` collection for a memory cache.| +|[\](clear-element-for-namedcaches.md)|Clears the `namedCaches` collection for a memory cache.| +|[\](remove-element-for-namedcaches.md)|Removes a named cache entry from the `namedCaches` collection for a memory cache.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](../configuration-element.md)|Specifies the root element in every configuration file that is used by the common language runtime and .NET Framework applications.| +|[\](memorycache-element-cache-settings.md)|Defines an element that is used to configure a cache that is based on the class.| +|[\](system-runtime-caching-element-cache-settings.md)|Contains types that let you implement output caching in applications that are built into the .NET Framework.| + +## Remarks + + The memory cache configuration section of the Web.config file can contain `add`, `remove`, and `clear` attributes for the `namedCaches` collection. Each `namedCaches` entry is uniquely identified by the `name` attribute. + + You can retrieve instances of memory cache entries by referencing the information in the application configuration files. By default, only the default cache instance has an entry in the configuration file. The default cache instance is the instance that is returned from the property. + + If you set the name attribute to "Default", the element uses the default memory cache instance. + +## Example + + The following example shows how to set the name of the cache to the default cache entry name by setting the `name` attribute to "Default". + + The `cacheMemoryLimitMegabytes` attribute and the `physicalMemoryPercentage` attribute are set to zero. Setting these attributes to zero means that the autosizing heuristics of the class are used. The cache implementation compares the current memory load against the absolute and percentage-based memory limits every two minutes. + +```xml + + + + + - - - - - -``` - + physicalMemoryLimitPercentage="0" + pollingInterval="00:02:00" /> + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) -- [\ Element (Cache Settings)](memorycache-element-cache-settings.md) +- [`` Element (Cache Settings)](memorycache-element-cache-settings.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/netfx40-legacysecuritypolicy-element.md b/docs/framework/configure-apps/file-schema/runtime/netfx40-legacysecuritypolicy-element.md index e541e94682f2b..012ed333c88c0 100644 --- a/docs/framework/configure-apps/file-schema/runtime/netfx40-legacysecuritypolicy-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/netfx40-legacysecuritypolicy-element.md @@ -7,7 +7,7 @@ helpviewer_keywords: - "NetFx40_LegacySecurityPolicy element" ms.assetid: 07132b9c-4a72-4710-99d7-e702405e02d4 --- -# \ Element +# `` Element Specifies whether the runtime uses legacy code access security (CAS) policy. @@ -64,7 +64,7 @@ Applying the `` element to a .NET Framework 4 asse > Applying the `` element can result in significant performance penalties for native image assemblies created by the [Native Image Generator (Ngen.exe)](../../../tools/ngen-exe-native-image-generator.md) that are not installed in the [global assembly cache](../../../app-domains/gac.md). The performance degradation is caused by the inability of the runtime to load the assemblies as native images when the attribute is applied, resulting in their being loaded as just-in-time assemblies. > [!NOTE] -> If you specify a target .NET Framework version that is earlier than the .NET Framework 4 in the project settings for your Visual Studio project, CAS policy will be enabled, including any custom CAS policies you specified for that version. However, you will not be able to use new .NET Framework 4 types and members. You can also specify an earlier version of the .NET Framework by using the [\ element](../startup/supportedruntime-element.md) in the startup settings schema in your [application configuration file](../../index.md). +> If you specify a target .NET Framework version that is earlier than the .NET Framework 4 in the project settings for your Visual Studio project, CAS policy will be enabled, including any custom CAS policies you specified for that version. However, you will not be able to use new .NET Framework 4 types and members. You can also specify an earlier version of the .NET Framework by using the [`` element](../startup/supportedruntime-element.md) in the startup settings schema in your [application configuration file](../../index.md). > [!NOTE] > Configuration file syntax is case-sensitive. You should use the syntax as provided in the Syntax and Example sections. diff --git a/docs/framework/configure-apps/file-schema/runtime/netfx40-pinvokestackresilience-element.md b/docs/framework/configure-apps/file-schema/runtime/netfx40-pinvokestackresilience-element.md index 6a8a5cfa9fd26..20d039b9f6517 100644 --- a/docs/framework/configure-apps/file-schema/runtime/netfx40-pinvokestackresilience-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/netfx40-pinvokestackresilience-element.md @@ -7,7 +7,7 @@ helpviewer_keywords: - "NetFx40_PInvokeStackResilience element" ms.assetid: 39fb1588-72a4-4479-af74-0605233b68bd --- -# \ Element +# `` Element Specifies whether the runtime automatically fixes incorrect platform invoke declarations at run time, at the cost of slower transitions between managed and unmanaged code. diff --git a/docs/framework/configure-apps/file-schema/runtime/netfx45-cultureawarecomparergethashcode-longstrings-element.md b/docs/framework/configure-apps/file-schema/runtime/netfx45-cultureawarecomparergethashcode-longstrings-element.md index 5d39728b2f797..e3cdf4d9e44a4 100644 --- a/docs/framework/configure-apps/file-schema/runtime/netfx45-cultureawarecomparergethashcode-longstrings-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/netfx45-cultureawarecomparergethashcode-longstrings-element.md @@ -9,13 +9,13 @@ helpviewer_keywords: - "hash codes, calculating" ms.assetid: 3a5f38d1-ebc8-44de-aaeb-2929f6e6b48f --- -# \ Element +# `` Element Specifies whether the runtime uses a fixed amount of memory to calculate hash codes for the method. [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** +    **\** ## Syntax diff --git a/docs/framework/configure-apps/file-schema/runtime/prefercominsteadofmanagedremoting-element.md b/docs/framework/configure-apps/file-schema/runtime/prefercominsteadofmanagedremoting-element.md index d0b627421512d..3cd3cfbf423cf 100644 --- a/docs/framework/configure-apps/file-schema/runtime/prefercominsteadofmanagedremoting-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/prefercominsteadofmanagedremoting-element.md @@ -2,75 +2,75 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - " element" - "PreferComInsteadOfManagedRemoting element" ms.assetid: a279a42a-c415-4e79-88cf-64244ebda613 --- -# \ Element +# `` Element + +Specifies whether the runtime will use COM interop instead of remoting for all calls across application domain boundaries. -Specifies whether the runtime will use COM interop instead of remoting for all calls across application domain boundaries. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Indicates whether the runtime will use COM interop instead of remoting across application domain boundaries.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|`false`|The runtime will use remoting across application domain boundaries. This is the default.| -|`true`|The runtime will use COM interop across application domain boundaries.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - When you set the `enabled` attribute to `true`, the runtime behaves as follows: - -- The runtime does not call [IUnknown::QueryInterface](/windows/win32/api/unknwn/nf-unknwn-iunknown-queryinterface(q)) for an [IManagedObject](../../../unmanaged-api/hosting/imanagedobject-interface.md) interface when an [IUnknown](/windows/win32/api/unknwn/nn-unknwn-iunknown) interface enters the domain through a COM interface. Instead, it constructs a [Runtime Callable Wrapper](../../../../standard/native-interop/runtime-callable-wrapper.md) (RCW) around the object. - -- The runtime returns E_NOINTERFACE when it receives a `QueryInterface` call for an [IManagedObject](../../../unmanaged-api/hosting/imanagedobject-interface.md) interface for any [COM Callable Wrapper](../../../../standard/native-interop/com-callable-wrapper.md) (CCW) that has been created in this domain. - - These two behaviors ensure that all calls over COM interfaces between managed objects across application domain boundaries use COM and COM interop instead of remoting. - -## Example - - The following example shows how to specify that the runtime should use COM interop across isolation boundaries: - -```xml - - - - - -``` - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Indicates whether the runtime will use COM interop instead of remoting across application domain boundaries.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|`false`|The runtime will use remoting across application domain boundaries. This is the default.| +|`true`|The runtime will use COM interop across application domain boundaries.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + When you set the `enabled` attribute to `true`, the runtime behaves as follows: + +- The runtime does not call [IUnknown::QueryInterface](/windows/win32/api/unknwn/nf-unknwn-iunknown-queryinterface(q)) for an [IManagedObject](../../../unmanaged-api/hosting/imanagedobject-interface.md) interface when an [IUnknown](/windows/win32/api/unknwn/nn-unknwn-iunknown) interface enters the domain through a COM interface. Instead, it constructs a [Runtime Callable Wrapper](../../../../standard/native-interop/runtime-callable-wrapper.md) (RCW) around the object. + +- The runtime returns E_NOINTERFACE when it receives a `QueryInterface` call for an [IManagedObject](../../../unmanaged-api/hosting/imanagedobject-interface.md) interface for any [COM Callable Wrapper](../../../../standard/native-interop/com-callable-wrapper.md) (CCW) that has been created in this domain. + + These two behaviors ensure that all calls over COM interfaces between managed objects across application domain boundaries use COM and COM interop instead of remoting. + +## Example + + The following example shows how to specify that the runtime should use COM interop across isolation boundaries: + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/probing-element.md b/docs/framework/configure-apps/file-schema/runtime/probing-element.md index 4cb3008f1179d..a319cbe72bb0b 100644 --- a/docs/framework/configure-apps/file-schema/runtime/probing-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/probing-element.md @@ -2,66 +2,66 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/assemblyBinding/probing" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#probing" -helpviewer_keywords: +helpviewer_keywords: - " element" - "container tags, element" - "probing element" ms.assetid: 09c80fc9-1ba5-4192-89f7-3a79b2e4b024 --- -# \ Element +# `` Element + +Specifies application base subdirectories for the common language runtime to search when loading assemblies. -Specifies application base subdirectories for the common language runtime to search when loading assemblies. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\     [**\**](assemblybinding-element-for-runtime.md)\ -      **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`privatePath`|Required attribute.

Specifies subdirectories of the application's base directory that might contain assemblies. Delimit each subdirectory with a semicolon.| - -### Child Elements - -None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Example - - The following example shows how to specify application base subdirectories the runtime should search for assemblies. - -```xml - - - - - - - -``` - +      **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`privatePath`|Required attribute.

Specifies subdirectories of the application's base directory that might contain assemblies. Delimit each subdirectory with a semicolon.| + +### Child Elements + +None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Example + + The following example shows how to specify application base subdirectories the runtime should search for assemblies. + +```xml + + + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/publisherpolicy-element.md b/docs/framework/configure-apps/file-schema/runtime/publisherpolicy-element.md index 43ca25ec3b6fa..ce957a00466b7 100644 --- a/docs/framework/configure-apps/file-schema/runtime/publisherpolicy-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/publisherpolicy-element.md @@ -2,89 +2,89 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/assemblyBinding/publisherPolicy" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/assemblyBinding/dependentAssembly/publisherPolicy" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#publisherPolicy" -helpviewer_keywords: +helpviewer_keywords: - "publisherPolicy element" - "container tags, element" - " element" ms.assetid: 4613407e-d0a8-4ef2-9f81-a6acb9fdc7d4 --- -# \ Element +# `` Element + +Specifies whether the runtime applies publisher policy. -Specifies whether the runtime applies publisher policy. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\     [**\**](assemblybinding-element-for-runtime.md)\       [**\**](dependentassembly-element.md)\ -        **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`apply`|Specifies whether to apply publisher policy.| - -## apply Attribute - -|Value|Description| -|-----------|-----------------| -|`yes`|Applies publisher policy. This is the default setting.| -|`no`|Does not apply publisher policy.| - -### Child Elements - -None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`dependentAssembly`|Encapsulates binding policy and assembly location for each assembly. Use one `` element for each assembly.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - When a component vendor releases a new version of an assembly, the vendor can include a publisher policy so applications that use the old version now use the new version. To specify whether to apply publisher policy for a particular assembly, put the **\** element in the **\** element. - - The default setting for the **apply** attribute is **yes**. Setting the **apply** attribute to **no** overrides any previous **yes** settings for an assembly. - - Permission is required for an application to explicitly ignore publisher policy using the [\](publisherpolicy-element.md) element in the application configuration file. The permission is granted by setting the flag on the . For more information, see [Assembly Binding Redirection Security Permission](../../assembly-binding-redirection-security-permission.md). - -## Example - - The following example turns off publisher policy for the assembly, `myAssembly`. - -```xml - - - - - - - - - - -``` - +        **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`apply`|Specifies whether to apply publisher policy.| + +## apply Attribute + +|Value|Description| +|-----------|-----------------| +|`yes`|Applies publisher policy. This is the default setting.| +|`no`|Does not apply publisher policy.| + +### Child Elements + +None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`dependentAssembly`|Encapsulates binding policy and assembly location for each assembly. Use one `` element for each assembly.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + When a component vendor releases a new version of an assembly, the vendor can include a publisher policy so applications that use the old version now use the new version. To specify whether to apply publisher policy for a particular assembly, put the `` element in the `` element. + + The default setting for the `apply` attribute is **yes**. Setting the `apply` attribute to `no` overrides any previous `yes` settings for an assembly. + + Permission is required for an application to explicitly ignore publisher policy using the [\](publisherpolicy-element.md) element in the application configuration file. The permission is granted by setting the flag on the . For more information, see [Assembly Binding Redirection Security Permission](../../assembly-binding-redirection-security-permission.md). + +## Example + + The following example turns off publisher policy for the assembly, `myAssembly`. + +```xml + + + + + + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/qualifyassembly-element.md b/docs/framework/configure-apps/file-schema/runtime/qualifyassembly-element.md index 6aa83cac437d1..ac1905753a43b 100644 --- a/docs/framework/configure-apps/file-schema/runtime/qualifyassembly-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/qualifyassembly-element.md @@ -2,77 +2,77 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#qualifyAssembly" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/runtime/assemblyBinding/qualifyAssembly" -helpviewer_keywords: +helpviewer_keywords: - "container tags, element" - " element" - "qualifyAssembly element" ms.assetid: ad6442f6-1a9d-43b6-b733-04ac1b7f9b82 --- -# \ Element +# `` Element + +Specifies the full name of the assembly that should be dynamically loaded when a partial name is used. -Specifies the full name of the assembly that should be dynamically loaded when a partial name is used. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\     [**\**](assemblybinding-element-for-runtime.md)\ -      **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`partialName`|Required attribute.

Specifies the partial name of the assembly as it appears in the code.| -|`fullName`|Required attribute.

Specifies the full name of the assembly as it appears in the global assembly cache.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - Calling the method using partial assembly names causes the common language runtime to look for the assembly only in the application base directory. Use the **\** element in your application configuration file to provide the full assembly information (name, version, public key token, and culture) and cause the common language runtime to search for the assembly in the global assembly cache. - - The **fullName** attribute must include the four fields of assembly identity: name, version, public key token, and culture. The **partialName** attribute must partially reference an assembly. You must specify at least the assembly's text name (the most common case), but you can also include version, public key token, or culture (or any combination of the four, but not all four). The **partialName** must match the name specified in your call. For example, you cannot specify `"math"` as the **partialName** attribute in your configuration file and call `Assembly.Load("math, Version=3.3.3.3")` in your code. - -## Example - - The following example logically turns the call `Assembly.Load("math")` into `Assembly.Load("math,version=1.0.0.0,publicKeyToken=a1690a5ea44bab32,culture=neutral")`. - -```xml - - - +      **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`partialName`|Required attribute.

Specifies the partial name of the assembly as it appears in the code.| +|`fullName`|Required attribute.

Specifies the full name of the assembly as it appears in the global assembly cache.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + Calling the method using partial assembly names causes the common language runtime to look for the assembly only in the application base directory. Use the `` element in your application configuration file to provide the full assembly information (name, version, public key token, and culture) and cause the common language runtime to search for the assembly in the global assembly cache. + + The `fullName` attribute must include the four fields of assembly identity: name, version, public key token, and culture. The `partialName` attribute must partially reference an assembly. You must specify at least the assembly's text name (the most common case), but you can also include version, public key token, or culture (or any combination of the four, but not all four). The `partialName` must match the name specified in your call. For example, you cannot specify `"math"` as the `partialName` attribute in your configuration file and call `Assembly.Load("math, Version=3.3.3.3")` in your code. + +## Example + + The following example logically turns the call `Assembly.Load("math")` into `Assembly.Load("math,version=1.0.0.0,publicKeyToken=a1690a5ea44bab32,culture=neutral")`. + +```xml + + + - - - -``` - + fullName= +"math,version=1.0.0.0,publicKeyToken=a1690a5ea44bab32,culture=neutral"/> +
+
+
+``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/relativebindforresources-element.md b/docs/framework/configure-apps/file-schema/runtime/relativebindforresources-element.md index 1a44e78565c26..65b2bcb505e10 100644 --- a/docs/framework/configure-apps/file-schema/runtime/relativebindforresources-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/relativebindforresources-element.md @@ -8,7 +8,7 @@ helpviewer_keywords: ms.assetid: 846ffa47-7257-4ce3-8cac-7ff627e0e34f --- -# \ Element +# `` Element Optimizes the probe for satellite assemblies. diff --git a/docs/framework/configure-apps/file-schema/runtime/remove-element-for-namedcaches.md b/docs/framework/configure-apps/file-schema/runtime/remove-element-for-namedcaches.md index 17742b00a2dd1..264177ef31356 100644 --- a/docs/framework/configure-apps/file-schema/runtime/remove-element-for-namedcaches.md +++ b/docs/framework/configure-apps/file-schema/runtime/remove-element-for-namedcaches.md @@ -2,57 +2,57 @@ description: "Learn more about: Element for " title: " Element for " ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "remove element for namedCaches" - " element for namedCaches" ms.assetid: 24211ea5-163e-4fe5-aed8-004d8499760c --- -# \ Element for \ +# `` Element for \ + +Removes a named cache entry from the `namedCaches` collection for a memory cache. -Removes a named cache entry from the `namedCaches` collection for a memory cache. - [**\**](../configuration-element.md)\   [**\**](system-runtime-caching-element-cache-settings.md)\     [**\**](memorycache-element-cache-settings.md)\       [**\**](namedcaches-element-cache-settings.md)\ -        **\** - -## Syntax - -```xml - - - - -``` - -## Type - - `None` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - `None` - -### Child Elements - - `None` - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](namedcaches-element-cache-settings.md)|Contains a collection of configuration settings for the named instances.| - -## Remarks - - The `remove` element removes a `namedCache` entry from the named cache collection for a memory cache. - +        **\** + +## Syntax + +```xml + + + + +``` + +## Type + + `None` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + `None` + +### Child Elements + + `None` + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](namedcaches-element-cache-settings.md)|Contains a collection of configuration settings for the named instances.| + +## Remarks + + The `remove` element removes a `namedCache` entry from the named cache collection for a memory cache. + ## See also - [Configure apps by using configuration files](../../index.md) -- [\ Element (Cache Settings)](namedcaches-element-cache-settings.md) +- [`` Element (Cache Settings)](namedcaches-element-cache-settings.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/runtime-element.md b/docs/framework/configure-apps/file-schema/runtime/runtime-element.md index 9b2fba1179248..68040ff85ddcb 100644 --- a/docs/framework/configure-apps/file-schema/runtime/runtime-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/runtime-element.md @@ -11,7 +11,7 @@ helpviewer_keywords: - "container tags, element" ms.assetid: 1eb2fae3-de4b-45b6-852f-517c39b751bd --- -# \ Element +# `` Element Provides information used by the common language runtime to configure applications. diff --git a/docs/framework/configure-apps/file-schema/runtime/shadowcopyverifybytimestamp-element.md b/docs/framework/configure-apps/file-schema/runtime/shadowcopyverifybytimestamp-element.md index 9013f32b4a805..e4f7bc42fb067 100644 --- a/docs/framework/configure-apps/file-schema/runtime/shadowcopyverifybytimestamp-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/shadowcopyverifybytimestamp-element.md @@ -2,69 +2,69 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - " element" - "shadowCopyTimeStampVerification element" ms.assetid: 2f1648e5-997b-435e-a4f9-d236c574c66c --- -# \ Element +# `` Element + +Specifies whether shadow copying uses the default startup behavior introduced in the .NET Framework 4, or reverts to the startup behavior of earlier versions of the .NET Framework. -Specifies whether shadow copying uses the default startup behavior introduced in the .NET Framework 4, or reverts to the startup behavior of earlier versions of the .NET Framework. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|enabled|Required attribute.

Specifies whether application domains that use shadow copying compare assembly time stamps when starting up, to determine whether an assembly has been updated before shadow copying the assembly.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|true|At startup, copies only assemblies that have been updated since they were last copied to the shadow copy directory. This is the default for the .NET Framework 4.| -|false|Reverts to the startup behavior of previous versions of the .NET Framework, which was to copy all files at startup.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - Starting with the .NET Framework 4, assemblies are shadow copied only if their time stamps indicate that they have changed since they were last copied to the shadow copy directory. This improves startup times for many applications that use shadow copying, as described in [Shadow Copying Assemblies](../../../app-domains/shadow-copy-assemblies.md). Applications that have a high percentage and frequency of assembly updates might not benefit from this change in behavior. In that case, you can use this element to restore the behavior of previous versions of the .NET Framework. - -## Example - - The following example shows how to disable the default startup behavior of shadow copying in the .NET Framework 4, and revert to the startup behavior of previous versions of the .NET Framework. - -```xml - - - - - -``` - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|enabled|Required attribute.

Specifies whether application domains that use shadow copying compare assembly time stamps when starting up, to determine whether an assembly has been updated before shadow copying the assembly.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|true|At startup, copies only assemblies that have been updated since they were last copied to the shadow copy directory. This is the default for the .NET Framework 4.| +|false|Reverts to the startup behavior of previous versions of the .NET Framework, which was to copy all files at startup.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + Starting with the .NET Framework 4, assemblies are shadow copied only if their time stamps indicate that they have changed since they were last copied to the shadow copy directory. This improves startup times for many applications that use shadow copying, as described in [Shadow Copying Assemblies](../../../app-domains/shadow-copy-assemblies.md). Applications that have a high percentage and frequency of assembly updates might not benefit from this change in behavior. In that case, you can use this element to restore the behavior of previous versions of the .NET Framework. + +## Example + + The following example shows how to disable the default startup behavior of shadow copying in the .NET Framework 4, and revert to the startup behavior of previous versions of the .NET Framework. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/supportportability-element.md b/docs/framework/configure-apps/file-schema/runtime/supportportability-element.md index a8975846e8fea..0b04b788a5333 100644 --- a/docs/framework/configure-apps/file-schema/runtime/supportportability-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/supportportability-element.md @@ -2,80 +2,80 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "supportPortability element" - " element" ms.assetid: 6453ef66-19b4-41f3-b712-52d0c2abc9ca --- -# \ Element +# `` Element + +Specifies that an application can reference the same assembly in two different implementations of the .NET Framework, by disabling the default behavior that treats the assemblies as equivalent for application portability purposes. -Specifies that an application can reference the same assembly in two different implementations of the .NET Framework, by disabling the default behavior that treats the assemblies as equivalent for application portability purposes. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\     [**\**](assemblybinding-element-for-runtime.md)\ -      **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - -The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|PKT|Required attribute.

Specifies the public key token of the affected assembly, as a string.| -|enabled|Optional attribute.

Specifies whether support for portability between implementations of the specified .NET Framework assembly should be enabled.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|true|Enable support for portability between implementations of the specified .NET Framework assembly. This is the default.| -|false|Disable support for portability between implementations of the specified .NET Framework assembly. This enables the application to have references to multiple implementations of the specified assembly.| - -### Child Elements - -None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| -|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| - -## Remarks - -Beginning with the .NET Framework 4, support is automatically provided for applications that can use either of two implementations of the .NET Framework, for example either the .NET Framework implementation or the .NET Framework for Silverlight implementation. The two implementations of a particular .NET Framework assembly are seen as equivalent by the assembly binder. In a few scenarios, this application portability feature causes problems. In those scenarios, the `` element can be used to disable the feature. - -One such scenario is an assembly that has to reference both the .NET Framework implementation and the .NET Framework for Silverlight implementation of a particular reference assembly. For example, a XAML designer written in Windows Presentation Foundation (WPF) might need to reference both the WPF Desktop implementation, for the designer's user interface, and the subset of WPF that is included in the Silverlight implementation. By default, the separate references cause a compiler error, because assembly binding sees the two assemblies as equivalent. This element disables the default behavior, and allows compilation to succeed. - +      **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + +The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|PKT|Required attribute.

Specifies the public key token of the affected assembly, as a string.| +|enabled|Optional attribute.

Specifies whether support for portability between implementations of the specified .NET Framework assembly should be enabled.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|true|Enable support for portability between implementations of the specified .NET Framework assembly. This is the default.| +|false|Disable support for portability between implementations of the specified .NET Framework assembly. This enables the application to have references to multiple implementations of the specified assembly.| + +### Child Elements + +None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| +|`assemblyBinding`|Contains information about assembly version redirection and the locations of assemblies.| + +## Remarks + +Beginning with the .NET Framework 4, support is automatically provided for applications that can use either of two implementations of the .NET Framework, for example either the .NET Framework implementation or the .NET Framework for Silverlight implementation. The two implementations of a particular .NET Framework assembly are seen as equivalent by the assembly binder. In a few scenarios, this application portability feature causes problems. In those scenarios, the `` element can be used to disable the feature. + +One such scenario is an assembly that has to reference both the .NET Framework implementation and the .NET Framework for Silverlight implementation of a particular reference assembly. For example, a XAML designer written in Windows Presentation Foundation (WPF) might need to reference both the WPF Desktop implementation, for the designer's user interface, and the subset of WPF that is included in the Silverlight implementation. By default, the separate references cause a compiler error, because assembly binding sees the two assemblies as equivalent. This element disables the default behavior, and allows compilation to succeed. + > [!IMPORTANT] -> In order for the compiler to pass the information to the common language runtime's assembly-binding logic, you must use the `/appconfig` compiler option to specify the location of the app.config file that contains this element. - -## Example - -The following example enables an application to have references to both the .NET Framework implementation and the .NET Framework for Silverlight implementation of any .NET Framework assembly that exists in both implementations. The `/appconfig` compiler option must be used to specify the location of this app.config file. - -```xml - - - - - - - - -``` - +> In order for the compiler to pass the information to the common language runtime's assembly-binding logic, you must use the `/appconfig` compiler option to specify the location of the app.config file that contains this element. + +## Example + +The following example enables an application to have references to both the .NET Framework implementation and the .NET Framework for Silverlight implementation of any .NET Framework assembly that exists in both implementations. The `/appconfig` compiler option must be used to specify the location of this app.config file. + +```xml + + + + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/system-runtime-caching-element-cache-settings.md b/docs/framework/configure-apps/file-schema/runtime/system-runtime-caching-element-cache-settings.md index d0a931d767b91..4bb8559dd2035 100644 --- a/docs/framework/configure-apps/file-schema/runtime/system-runtime-caching-element-cache-settings.md +++ b/docs/framework/configure-apps/file-schema/runtime/system-runtime-caching-element-cache-settings.md @@ -2,76 +2,76 @@ description: "Learn more about: Element (Cache Settings)" title: " Element (Cache Settings)" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - " element" - "caching [.NET Framework], configuration" - "system.runtime.caching element" ms.assetid: 9b44daee-874a-4bd1-954e-83bf53565590 --- -# \ Element (Cache Settings) +# `` Element (Cache Settings) + +Provides configuration for the default in-memory implementation through the `memoryCache` entry in the configuration file. -Provides configuration for the default in-memory implementation through the `memoryCache` entry in the configuration file. - [**\**](../configuration-element.md)\ -  **\** - -## Syntax - -```xml - - - -``` - +  **\** + +## Syntax + +```xml + + + +``` + ## Attributes and Elements -The following sections describe attributes, child elements, and parent elements. - +The following sections describe attributes, child elements, and parent elements. + ### Attributes -`None` +`None` ### Child Elements -|Element|Description| -|-------------|-----------------| -|[\](memorycache-element-cache-settings.md)|Defines an element that is used to configure a cache that is based on the class.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](../configuration-element.md)|Specifies the root element in every configuration file that is used by the common language runtime and .NET Framework applications.| - +|Element|Description| +|-------------|-----------------| +|[\](memorycache-element-cache-settings.md)|Defines an element that is used to configure a cache that is based on the class.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](../configuration-element.md)|Specifies the root element in every configuration file that is used by the common language runtime and .NET Framework applications.| + ## Remarks -The classes in this namespace provide a way to use caching facilities like those in ASP.NET, but without a dependency on the `System.Web` assembly. For more information, see [Caching in .NET Framework Applications](../../../performance/caching-in-net-framework-applications.md). - +The classes in this namespace provide a way to use caching facilities like those in ASP.NET, but without a dependency on the `System.Web` assembly. For more information, see [Caching in .NET Framework Applications](../../../performance/caching-in-net-framework-applications.md). + > [!NOTE] -> The output caching functionality and types in the namespace are new in .NET Framework 4. - +> The output caching functionality and types in the namespace are new in .NET Framework 4. + ## Example -The following example shows how to configure a cache that is based on the class. The example shows how to configure an instance of the `namedCaches` entry for memory cache. The name of the cache is set to the default cache entry name by setting the `name` attribute to "Default". - -The `cacheMemoryLimitMegabytes` attribute and the `physicalMemoryPercentage` attribute are set to zero. Setting these attributes to zero means that the autosizing heuristics are used by default. The cache implementation should compare the current memory load against the absolute and percentage-based memory limits every two minutes. - -```xml - - - - +The following example shows how to configure a cache that is based on the class. The example shows how to configure an instance of the `namedCaches` entry for memory cache. The name of the cache is set to the default cache entry name by setting the `name` attribute to "Default". + +The `cacheMemoryLimitMegabytes` attribute and the `physicalMemoryPercentage` attribute are set to zero. Setting these attributes to zero means that the autosizing heuristics are used by default. The cache implementation should compare the current memory load against the absolute and percentage-based memory limits every two minutes. + +```xml + + + + - - - - -``` - + physicalMemoryLimitPercentage="0" + pollingInterval="00:02:00" /> + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) -- [\ Element (Cache Settings)](memorycache-element-cache-settings.md) +- [`` Element (Cache Settings)](memorycache-element-cache-settings.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/thread-useallcpugroups-element.md b/docs/framework/configure-apps/file-schema/runtime/thread-useallcpugroups-element.md index 32b75b270bad4..b6256d6e04e93 100644 --- a/docs/framework/configure-apps/file-schema/runtime/thread-useallcpugroups-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/thread-useallcpugroups-element.md @@ -4,13 +4,13 @@ title: " Element" ms.date: "03/30/2017" ms.assetid: d30fe7c5-8469-46e2-b804-e3eec7b24256 --- -# \ Element +# `` Element Specifies whether the runtime distributes managed threads across all CPU groups. [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** +    **\** ## Syntax @@ -70,4 +70,4 @@ The following example shows how to enable support for multiple CPU groups. - [Configure apps by using configuration files](../../index.md) - [Runtime Settings Schema](index.md) - [Configuration File Schema](../index.md) -- [\ Element](gccpugroup-element.md) +- [`` Element](gccpugroup-element.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/throwunobservedtaskexceptions-element.md b/docs/framework/configure-apps/file-schema/runtime/throwunobservedtaskexceptions-element.md index 4bb0dd718ccf7..d5111c82f8107 100644 --- a/docs/framework/configure-apps/file-schema/runtime/throwunobservedtaskexceptions-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/throwunobservedtaskexceptions-element.md @@ -2,92 +2,92 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "ThrowUnobservedTaskExceptions element" - " element" ms.assetid: cea7e588-8b8d-48d2-9ad5-8feaf3642c18 --- -# \ Element +# `` Element + +Specifies whether unhandled task exceptions should terminate a running process. -Specifies whether unhandled task exceptions should terminate a running process. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Specifies whether unhandled task exceptions should terminate the running process.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|`false`|Does not terminate the running process for an unhandled task exception. This is the default.| -|`true`|Terminates the running process for an unhandled task exception.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Specifies whether unhandled task exceptions should terminate the running process.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|`false`|Does not terminate the running process for an unhandled task exception. This is the default.| +|`true`|Terminates the running process for an unhandled task exception.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| |`runtime`|Contains information about runtime initialization options.| - -## Remarks - - If an exception that is associated with a has not been observed, there is no operation, the parent is not attached, and the property was not read the task exception is considered to be unobserved. - - In the .NET Framework 4, by default, if a that has an unobserved exception is garbage collected, the finalizer throws an exception and terminates the process. The termination of the process is determined by the timing of garbage collection and finalization. - - To make it easier for developers to write asynchronous code based on tasks, the .NET Framework 4.5 changes this default behavior for unobserved exceptions. Unobserved exceptions still cause the event to be raised, but by default, the process does not terminate. Instead, the exception is ignored after the event is raised, regardless of whether an event handler observes the exception. - - In .NET Framework 4.5, you can use the [\ element](throwunobservedtaskexceptions-element.md) in an application configuration file to enable the .NET Framework 4 behavior of throwing an exception. - - You can also specify the exception behavior in one of the following ways: - -- By setting the environment variable `COMPlus_ThrowUnobservedTaskExceptions` (`set COMPlus_ThrowUnobservedTaskExceptions=1`). - -- By setting the registry DWORD value ThrowUnobservedTaskExceptions = 1 in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\\.NETFramework key. - + +## Remarks + + If an exception that is associated with a has not been observed, there is no operation, the parent is not attached, and the property was not read the task exception is considered to be unobserved. + + In the .NET Framework 4, by default, if a that has an unobserved exception is garbage collected, the finalizer throws an exception and terminates the process. The termination of the process is determined by the timing of garbage collection and finalization. + + To make it easier for developers to write asynchronous code based on tasks, the .NET Framework 4.5 changes this default behavior for unobserved exceptions. Unobserved exceptions still cause the event to be raised, but by default, the process does not terminate. Instead, the exception is ignored after the event is raised, regardless of whether an event handler observes the exception. + + In .NET Framework 4.5, you can use the [`` element](throwunobservedtaskexceptions-element.md) in an application configuration file to enable the .NET Framework 4 behavior of throwing an exception. + + You can also specify the exception behavior in one of the following ways: + +- By setting the environment variable `COMPlus_ThrowUnobservedTaskExceptions` (`set COMPlus_ThrowUnobservedTaskExceptions=1`). + +- By setting the registry DWORD value ThrowUnobservedTaskExceptions = 1 in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\\.NETFramework key. + ## Example 1 - The following example shows how to enable the throwing of exceptions in tasks by using an application configuration file. - -```xml + The following example shows how to enable the throwing of exceptions in tasks by using an application configuration file. + +```xml - -``` - -## Example 2 +
+``` + +## Example 2 + + The following example demonstrates how an unobserved exception is thrown from a task. The code must be run as a released program to work correctly. - The following example demonstrates how an unobserved exception is thrown from a task. The code must be run as a released program to work correctly. - [!code-csharp[ThrowUnobservedTaskExceptions#1](../../../../../samples/snippets/csharp/VS_Snippets_CLR/throwunobservedtaskexceptions/cs/program.cs#1)] - [!code-vb[ThrowUnobservedTaskExceptions#1](../../../../../samples/snippets/visualbasic/VS_Snippets_CLR/throwunobservedtaskexceptions/vb/program.vb#1)] - + [!code-vb[ThrowUnobservedTaskExceptions#1](../../../../../samples/snippets/visualbasic/VS_Snippets_CLR/throwunobservedtaskexceptions/vb/program.vb#1)] + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/timespan-legacyformatmode-element.md b/docs/framework/configure-apps/file-schema/runtime/timespan-legacyformatmode-element.md index d220bb884168a..33aff2479d3f9 100644 --- a/docs/framework/configure-apps/file-schema/runtime/timespan-legacyformatmode-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/timespan-legacyformatmode-element.md @@ -10,7 +10,7 @@ helpviewer_keywords: - "TimeSpan_LegacyFormatMode element" ms.assetid: 865e7207-d050-4442-b574-57ea29d5e2d6 --- -# \ Element +# `` Element Determines whether the runtime preserves legacy behavior in formatting operations with values. diff --git a/docs/framework/configure-apps/file-schema/runtime/uselegacyjit-element.md b/docs/framework/configure-apps/file-schema/runtime/uselegacyjit-element.md index 5699b81ae60cd..37062572d4a71 100644 --- a/docs/framework/configure-apps/file-schema/runtime/uselegacyjit-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/uselegacyjit-element.md @@ -5,91 +5,91 @@ ms.date: "04/26/2017" ms.assetid: c2cf97f0-9262-4f1f-a754-5568b51110ad --- -# \ Element +# `` Element + +Determines whether the common language runtime uses the legacy 64-bit JIT compiler for just-in-time compilation. -Determines whether the common language runtime uses the legacy 64-bit JIT compiler for just-in-time compilation. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - +    **\** + +## Syntax + ```xml ``` The element name `useLegacyJit` is case-sensitive. - + ## Attributes and elements -The following sections describe attributes, child elements, and parent elements. - -### Attributes - -| Attribute | Description | -| --------- | --------------------------------------------------------------------------------------------- | -| `enabled` | Required attribute.

Specifies whether the runtime uses the legacy 64-bit JIT compiler. | - -### enabled attribute - -| Value | Description | -| ----- | ------------------------------------------------------------------------------------------------------------------- | -| 0 | The common language runtime uses the new 64-bit JIT compiler included in the .NET Framework 4.6 and later versions. | -| 1 | The common language runtime uses the older 64-bit JIT compiler. | - +The following sections describe attributes, child elements, and parent elements. + +### Attributes + +| Attribute | Description | +| --------- | --------------------------------------------------------------------------------------------- | +| `enabled` | Required attribute.

Specifies whether the runtime uses the legacy 64-bit JIT compiler. | + +### enabled attribute + +| Value | Description | +| ----- | ------------------------------------------------------------------------------------------------------------------- | +| 0 | The common language runtime uses the new 64-bit JIT compiler included in the .NET Framework 4.6 and later versions. | +| 1 | The common language runtime uses the older 64-bit JIT compiler. | + ### Child elements None - -### Parent elements - -| Element | Description | -| --------------- | ----------------------------------------------------------------------------------------------------------------- | -| `configuration` | The root element in every configuration file used by the common language runtime and .NET Framework applications. | -| `runtime` | Contains information about runtime initialization options. | - -## Remarks - -Starting with .NET Framework 4.6, the common language runtime uses a new 64-bit compiler for Just-In-Time (JIT) compilation by default. In some cases, this may result in a difference in behavior from application code that was JIT-compiled by the previous version of the 64-bit JIT compiler. By setting the `enabled` attribute of the `` element to `1`, you can disable the new 64-bit JIT compiler and instead compile your app using the legacy 64-bit JIT compiler. - + +### Parent elements + +| Element | Description | +| --------------- | ----------------------------------------------------------------------------------------------------------------- | +| `configuration` | The root element in every configuration file used by the common language runtime and .NET Framework applications. | +| `runtime` | Contains information about runtime initialization options. | + +## Remarks + +Starting with .NET Framework 4.6, the common language runtime uses a new 64-bit compiler for Just-In-Time (JIT) compilation by default. In some cases, this may result in a difference in behavior from application code that was JIT-compiled by the previous version of the 64-bit JIT compiler. By setting the `enabled` attribute of the `` element to `1`, you can disable the new 64-bit JIT compiler and instead compile your app using the legacy 64-bit JIT compiler. + > [!NOTE] -> The `` element affects 64-bit JIT compilation only. Compilation with the 32-bit JIT compiler is unaffected. - -Instead of using a configuration file setting, you can enable the legacy 64-bit JIT compiler in two other ways: - +> The `` element affects 64-bit JIT compilation only. Compilation with the 32-bit JIT compiler is unaffected. + +Instead of using a configuration file setting, you can enable the legacy 64-bit JIT compiler in two other ways: + - Setting an environment variable Set the `COMPLUS_useLegacyJit` environment variable to either `0` (use the new 64-bit JIT compiler) or `1` (use the older 64-bit JIT compiler): - - ```env - COMPLUS_useLegacyJit=0|1 - ``` - + + ```env + COMPLUS_useLegacyJit=0|1 + ``` + The environment variable has *global scope*, which means that it affects all applications run on the machine. If set, it can be overridden by the application configuration file setting. The environment variable name is not case-sensitive. - + - Adding a registry key You can enable the legacy 64-bit JIT compiler by adding a `REG_DWORD` value to either the `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework` or `HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NETFramework` key in the registry. The value is named `useLegacyJit`. If the value is 0, the new compiler is used. If the value is 1, the legacy 64-bit JIT compiler is enabled. The registry value name is not case-sensitive. - - Adding the value to the `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework` key affects all apps running on the machine. Adding the value to the `HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NETFramework` key affects all apps run by the current user. If a machine is configured with multiple user accounts, only apps run by the current user are affected, unless the value is added to the registry keys for other users as well. Adding the `` element to a configuration file overrides the registry settings, if they're present. - -## Example - -The following configuration file disables compilation with the new 64-bit JIT compiler and instead uses the legacy 64-bit JIT compiler. - -```xml - - - - - - -``` - + + Adding the value to the `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework` key affects all apps running on the machine. Adding the value to the `HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NETFramework` key affects all apps run by the current user. If a machine is configured with multiple user accounts, only apps run by the current user are affected, unless the value is added to the registry keys for other users as well. Adding the `` element to a configuration file overrides the registry settings, if they're present. + +## Example + +The following configuration file disables compilation with the new 64-bit JIT compiler and instead uses the legacy 64-bit JIT compiler. + +```xml + + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) -- [\ Element](runtime-element.md) -- [\ Element](../configuration-element.md) +- [`` Element](runtime-element.md) +- [`` Element](../configuration-element.md) - [Mitigation: New 64-bit JIT Compiler](../../../migration-guide/mitigation-new-64-bit-jit-compiler.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/userandomizedstringhashalgorithm-element.md b/docs/framework/configure-apps/file-schema/runtime/userandomizedstringhashalgorithm-element.md index c7efa7834bfd6..16d107678d80f 100644 --- a/docs/framework/configure-apps/file-schema/runtime/userandomizedstringhashalgorithm-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/userandomizedstringhashalgorithm-element.md @@ -2,97 +2,97 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "UseRandomizedStringHashAlgorithm element" - " element" ms.assetid: c08125d6-56cc-4b23-b482-813ff85dc630 --- -# \ Element +# `` Element + +Determines whether the common language runtime calculates hash codes for strings on a per application domain basis. -Determines whether the common language runtime calculates hash codes for strings on a per application domain basis. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`enabled`|Required attribute.

Specifies whether hash codes for strings are calculated on a per application domain basis.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|`0`|The common language runtime does not compute hash codes for strings on a per application domain basis; a single algorithm is used to calculate string hash codes. This is the default.| -|`1`|The common language runtime computes hash codes for strings on a per application domain basis. Identical strings in different application domains and in different processes will have different hash codes.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about runtime initialization options.| - -## Remarks - - By default, the class and the method use a single hashing algorithm that produces a consistent hash code across application domains. This is equivalent to setting the `enabled` attribute of the `` element to `0`. This is the hashing algorithm used in the .NET Framework 4. - - The class and the method can also use a different hashing algorithm that computes hash codes on a per application domain basis. As a result, hash codes for equivalent strings will differ across application domains. This is an opt-in feature; to take advantage of it, you must set the `enabled` attribute of the `` element to `1`. - - The string lookup in a hash table is typically an O(1) operation. However, when a large number of collisions occur, the lookup can become an O(n2) operation. You can use the `` configuration element to generate a random hashing algorithm per application domain, which in turn limits the number of potential collisions, particularly when the keys from which the hash codes are calculated are based on data input by users. - -## Example - - The following example defines a `DisplayString` class that includes a private string constant, `s`, whose value is "This is a string." It also includes a `ShowStringHashCode` method that displays the string value and its hash code along with the name of the application domain in which the method is executing. - + enabled=0|1 /> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`enabled`|Required attribute.

Specifies whether hash codes for strings are calculated on a per application domain basis.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|`0`|The common language runtime does not compute hash codes for strings on a per application domain basis; a single algorithm is used to calculate string hash codes. This is the default.| +|`1`|The common language runtime computes hash codes for strings on a per application domain basis. Identical strings in different application domains and in different processes will have different hash codes.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about runtime initialization options.| + +## Remarks + + By default, the class and the method use a single hashing algorithm that produces a consistent hash code across application domains. This is equivalent to setting the `enabled` attribute of the `` element to `0`. This is the hashing algorithm used in the .NET Framework 4. + + The class and the method can also use a different hashing algorithm that computes hash codes on a per application domain basis. As a result, hash codes for equivalent strings will differ across application domains. This is an opt-in feature; to take advantage of it, you must set the `enabled` attribute of the `` element to `1`. + + The string lookup in a hash table is typically an O(1) operation. However, when a large number of collisions occur, the lookup can become an O(n2) operation. You can use the `` configuration element to generate a random hashing algorithm per application domain, which in turn limits the number of potential collisions, particularly when the keys from which the hash codes are calculated are based on data input by users. + +## Example + + The following example defines a `DisplayString` class that includes a private string constant, `s`, whose value is "This is a string." It also includes a `ShowStringHashCode` method that displays the string value and its hash code along with the name of the application domain in which the method is executing. + [!code-csharp[System.String.GetHashCode#2](../../../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.String.GetHashCode/CS/perdomain.cs#2)] - [!code-vb[System.String.GetHashCode#2](../../../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.String.GetHashCode/VB/perdomain.vb#2)] - - When you run the example without supplying a configuration file, it displays output similar to the following. Note that the hash codes for the string are identical in the two application domains. - + [!code-vb[System.String.GetHashCode#2](../../../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.String.GetHashCode/VB/perdomain.vb#2)] + + When you run the example without supplying a configuration file, it displays output similar to the following. Note that the hash codes for the string are identical in the two application domains. + ```console -String 'This is a string.' in domain 'PerDomain.exe': 941BCEAC -String 'This is a string.' in domain 'NewDomain': 941BCEAC -``` - - However, if you add the following configuration file to the example's directory and then run the example, the hash codes for the same string will differ by application domain. - -```xml - - - - - - -``` - - When the configuration file is present, the example displays the following output: - +String 'This is a string.' in domain 'PerDomain.exe': 941BCEAC +String 'This is a string.' in domain 'NewDomain': 941BCEAC +``` + + However, if you add the following configuration file to the example's directory and then run the example, the hash codes for the same string will differ by application domain. + +```xml + + + + + + +``` + + When the configuration file is present, the example displays the following output: + ```console -String 'This is a string.' in domain 'PerDomain.exe': 5435776D -String 'This is a string.' in domain 'NewDomain': 75CC8236 -``` - +String 'This is a string.' in domain 'PerDomain.exe': 5435776D +String 'This is a string.' in domain 'NewDomain': 75CC8236 +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/runtime/usesmallinternalthreadstacks-element.md b/docs/framework/configure-apps/file-schema/runtime/usesmallinternalthreadstacks-element.md index 9af91b719d9d5..8d830bcb6e18d 100644 --- a/docs/framework/configure-apps/file-schema/runtime/usesmallinternalthreadstacks-element.md +++ b/docs/framework/configure-apps/file-schema/runtime/usesmallinternalthreadstacks-element.md @@ -2,74 +2,74 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "UseSmallInternalThreadStacks element" - " element" ms.assetid: 1e3f6ec0-1cac-4e1c-9c81-17d948ae5874 --- -# \ Element +# `` Element + +Requests that the common language runtime (CLR) reduce memory use by specifying explicit stack sizes when it creates certain threads that it uses internally, instead of using the default stack size for those threads. -Requests that the common language runtime (CLR) reduce memory use by specifying explicit stack sizes when it creates certain threads that it uses internally, instead of using the default stack size for those threads. - [**\**](../configuration-element.md)\   [**\**](runtime-element.md)\ -    **\** - -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|enabled|Required attribute.

Specifies whether to request that the CLR use explicit stack sizes instead of the default stack size when it creates certain threads that it uses internally. The explicit stack sizes are smaller than the default stack size of 1 MB.| - -## enabled Attribute - -|Value|Description| -|-----------|-----------------| -|true|Request explicit stack sizes.| -|false|Use the default stack size. This is the default for the .NET Framework 4.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`runtime`|Contains information about assembly binding and garbage collection.| - -## Remarks - - This configuration element is used to request reduced virtual memory use in a process, because the explicit thread sizes that the CLR uses for its internal threads, if the request is honored, are smaller than the default size. - +    **\** + +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|enabled|Required attribute.

Specifies whether to request that the CLR use explicit stack sizes instead of the default stack size when it creates certain threads that it uses internally. The explicit stack sizes are smaller than the default stack size of 1 MB.| + +## enabled Attribute + +|Value|Description| +|-----------|-----------------| +|true|Request explicit stack sizes.| +|false|Use the default stack size. This is the default for the .NET Framework 4.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`runtime`|Contains information about assembly binding and garbage collection.| + +## Remarks + + This configuration element is used to request reduced virtual memory use in a process, because the explicit thread sizes that the CLR uses for its internal threads, if the request is honored, are smaller than the default size. + > [!IMPORTANT] -> This configuration element is a request to the CLR rather than an absolute requirement. In the .NET Framework 4, the request is honored only for the x86 architecture. This element might be ignored completely in future versions of the CLR, or replaced by explicit stack sizes that are always used for selected internal threads. - - Specifying this configuration element trades reliability for smaller virtual memory use if the CLR honors the request, because smaller stack sizes could potentially make stack overflows more likely. - -## Example - - The following example shows how to request that the CLR use explicit stack sizes for certain threads that it uses internally. - -```xml - - - - - -``` - +> This configuration element is a request to the CLR rather than an absolute requirement. In the .NET Framework 4, the request is honored only for the x86 architecture. This element might be ignored completely in future versions of the CLR, or replaced by explicit stack sizes that are always used for selected internal threads. + + Specifying this configuration element trades reliability for smaller virtual memory use if the CLR honors the request, because smaller stack sizes could potentially make stack overflows more likely. + +## Example + + The following example shows how to request that the CLR use explicit stack sizes for certain threads that it uses internally. + +```xml + + + + + +``` + ## See also - [Configure apps by using configuration files](../../index.md) diff --git a/docs/framework/configure-apps/file-schema/section-element.md b/docs/framework/configure-apps/file-schema/section-element.md index a70cedbad3a3f..c1df5861931c1 100644 --- a/docs/framework/configure-apps/file-schema/section-element.md +++ b/docs/framework/configure-apps/file-schema/section-element.md @@ -2,15 +2,15 @@ description: "Learn more about:
element" title: "
element" ms.date: "05/01/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/configSections/section" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/configSections/sectionGroup/section" -helpviewer_keywords: +helpviewer_keywords: - "section Element" - "
Element" ms.assetid: ec7d4110-2403-47ac-8218-499bfe9d5ddb --- -# \
element +# `
` element Contains a configuration section declaration. @@ -36,8 +36,8 @@ Contains a configuration section declaration. | | Description | | --------- | ----------- | -| **name** | Specifies the name of the configuration section. | -| **type** | Specifies the name of the configuration section handler class that reads the section from the configuration file. The type value has the syntax "fully-qualified-section-handler-class-name, simple-assembly-name". The simple assembly name is the root filename without the *.dll* file extension. | +| `name` | Specifies the name of the configuration section. | +| `type` | Specifies the name of the configuration section handler class that reads the section from the configuration file. The type value has the syntax "fully-qualified-section-handler-class-name, simple-assembly-name". The simple assembly name is the root filename without the *.dll* file extension. | ## Optional attributes @@ -45,18 +45,18 @@ The following attributes are applicable only for ASP.NET applications. The confi | | Description | | ------------------- | ----------- | -| **allowDefinition** | Specifies which configuration file the section can be used in. Use one of the following values:

**Everywhere**
Allows the section to be used in any configuration file. This is the default.
**MachineOnly**
Allows the section to be used only in the machine configuration file (*Machine.config*).
**MachineToApplication**
Allows the section to be used in the machine configuration file or the application configuration file. | -| **allowLocation** | Determines whether the section can be used within the **\** element. Use one of the following values:

**true**
Allows the section to be used within the **\** element. This is the default.
**false**
Does not allow the section to be used within the **\** element. | +| `allowDefinition` | Specifies which configuration file the section can be used in. Use one of the following values:

**Everywhere**
Allows the section to be used in any configuration file. This is the default.
**MachineOnly**
Allows the section to be used only in the machine configuration file (*Machine.config*).
**MachineToApplication**
Allows the section to be used in the machine configuration file or the application configuration file. | +| `allowLocation` | Determines whether the section can be used within the `` element. Use one of the following values:

**true**
Allows the section to be used within the `` element. This is the default.
**false**
Does not allow the section to be used within the `` element. | ## Parent elements | | Description | | --- | ----------- | -| [**\** Element](configsections-element-for-configuration.md) | Contains configuration section and namespace declarations. | -| [**\** Element](sectiongroup-element-for-configsections.md) | Defines a namespace for configuration sections. | +| [`` Element](configsections-element-for-configuration.md) | Contains configuration section and namespace declarations. | +| [`` Element](sectiongroup-element-for-configsections.md) | Defines a namespace for configuration sections. | > [!NOTE] -> A **\
** element is a child element of either **\** or **\** but not both. +> A `
` element is a child element of either `` or `` but not both. ## Child elements @@ -66,7 +66,7 @@ None Declaring a configuration section essentially defines a new element for the configuration file. The new element contains settings that a configuration section handler (that is, a class that implements the interface) reads. The attributes and child elements of a section you define depend on the section handler you use to read your settings. -Declaring a configuration section handler in the *Machine.config* file enables you to use the configuration section in any application configuration file on that computer, unless the **allowDefinition** attribute specifies otherwise. +Declaring a configuration section handler in the *Machine.config* file enables you to use the configuration section in any application configuration file on that computer, unless the `allowDefinition` attribute specifies otherwise. ## Example diff --git a/docs/framework/configure-apps/file-schema/sectiongroup-element-for-configsections.md b/docs/framework/configure-apps/file-schema/sectiongroup-element-for-configsections.md index 3043b30506bae..d522755039ba1 100644 --- a/docs/framework/configure-apps/file-schema/sectiongroup-element-for-configsections.md +++ b/docs/framework/configure-apps/file-schema/sectiongroup-element-for-configsections.md @@ -2,14 +2,14 @@ description: "Learn more about: element for " title: " element for " ms.date: "05/01/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/configSections/sectionGroup" -helpviewer_keywords: +helpviewer_keywords: - "sectionGroup Element" - " Element" ms.assetid: 6c27f9e2-809c-4bc9-aca9-72f90360e7a3 --- -# \ element for \ +# `` element for \ Defines a namespace for configuration sections. @@ -29,13 +29,13 @@ Defines a namespace for configuration sections. | | Description | | --------- | ----------- | -| **name** | Required attribute.

Specifies the name of the section group you are defining. | +| `name` | Required attribute.

Specifies the name of the section group you are defining. | ## Parent element | | Description | | --- | ----------- | -| [**\** Element](configsections-element-for-configuration.md) | Contains configuration section and namespace declarations. | +| [`` Element](configsections-element-for-configuration.md) | Contains configuration section and namespace declarations. | ## Child elements @@ -45,7 +45,7 @@ Defines a namespace for configuration sections. ## Remarks -Declaring a section group creates a container tag for configuration sections and ensures that there are no naming conflicts with configuration sections defined by someone else. You can nest **\** elements within each other. +Declaring a section group creates a container tag for configuration sections and ensures that there are no naming conflicts with configuration sections defined by someone else. You can nest `` elements within each other. ## Example diff --git a/docs/framework/configure-apps/file-schema/startup/index.md b/docs/framework/configure-apps/file-schema/startup/index.md index e6247efd15221..ab76f60ffdb61 100644 --- a/docs/framework/configure-apps/file-schema/startup/index.md +++ b/docs/framework/configure-apps/file-schema/startup/index.md @@ -2,7 +2,7 @@ description: "Learn more about: Startup settings schema" title: "Startup settings schema" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "startup settings schema" - "schema startup settings" - "configuration schema [.NET Framework], startup settings" @@ -10,14 +10,14 @@ ms.assetid: 03de6972-442a-4648-9f3e-efa654e3b949 --- # Startup settings schema -Startup settings specify the version of the common language runtime that should run the application. - -|Element|Description| -|-------------|-----------------| -|[\](requiredruntime-element.md)|Specifies that the application supports only version 1.0 of the common language runtime. Applications built with runtime version 1.1 should use the **\** element.| -|[\](supportedruntime-element.md)|Specifies which versions of the common language runtime the application supports.| -|[\](startup-element.md)|Contains the **\** and **\** elements.| - +Startup settings specify the version of the common language runtime that should run the application. + +|Element|Description| +|-------------|-----------------| +|[\](requiredruntime-element.md)|Specifies that the application supports only version 1.0 of the common language runtime. Applications built with runtime version 1.1 should use the `` element.| +|[\](supportedruntime-element.md)|Specifies which versions of the common language runtime the application supports.| +|[\](startup-element.md)|Contains the `` and `` elements.| + ## See also - [Configuration File Schema](../index.md) diff --git a/docs/framework/configure-apps/file-schema/startup/requiredruntime-element.md b/docs/framework/configure-apps/file-schema/startup/requiredruntime-element.md index e095fca5e626f..50041354bb718 100644 --- a/docs/framework/configure-apps/file-schema/startup/requiredruntime-element.md +++ b/docs/framework/configure-apps/file-schema/startup/requiredruntime-element.md @@ -2,27 +2,27 @@ description: "Learn more about: element" title: " element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#requiredRuntime" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/startup/requiredRuntime" -helpviewer_keywords: +helpviewer_keywords: - "requiredRuntime element" - " element" - "container tags, element" ms.assetid: 9fa1639e-beb8-43be-b7a4-12f7b229c34b --- -# \ element +# `` element Specifies that the application supports only version 1.0 of the common language runtime. This element is deprecated and should no longer be used. The [`supportedRuntime`](supportedruntime-element.md) element should be used instead. -[**\**](../configuration-element.md) -  [**\**](startup-element.md) -    **\** +[**\**](../configuration-element.md) +  [**\**](startup-element.md) +    **\** ## Syntax ```xml - ``` diff --git a/docs/framework/configure-apps/file-schema/startup/startup-element.md b/docs/framework/configure-apps/file-schema/startup/startup-element.md index 96e3a6ba7f122..69f6d05f083ec 100644 --- a/docs/framework/configure-apps/file-schema/startup/startup-element.md +++ b/docs/framework/configure-apps/file-schema/startup/startup-element.md @@ -2,21 +2,21 @@ description: "Learn more about: element" title: " element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/startup" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#startup" -helpviewer_keywords: +helpviewer_keywords: - "container tags, element" - " element" - "startup element" ms.assetid: 536acfd8-f827-452f-838a-e14fa3b87621 --- -# \ element +# `` element Specifies common language runtime startup information. -[**\**](../configuration-element.md) -  **\** +[**\**](../configuration-element.md) +  **\** ## Syntax @@ -46,7 +46,7 @@ Specifies common language runtime startup information. |Element|Description| |-------------|-----------------| -|[\](requiredruntime-element.md)|Specifies that the application supports only version 1.0 of the common language runtime. Applications built with runtime version 1.1 or later should use the **\** element.| +|[\](requiredruntime-element.md)|Specifies that the application supports only version 1.0 of the common language runtime. Applications built with runtime version 1.1 or later should use the `` element.| |[\](supportedruntime-element.md)|Specifies which versions of the common language runtime the application supports.| ### Parent elements @@ -57,7 +57,7 @@ Specifies common language runtime startup information. ## Remarks - The **\** element should be used by all applications built using version 1.1 or later of the runtime. Applications built to support only version 1.0 of the runtime must use the **\** element. + The `` element should be used by all applications built using version 1.1 or later of the runtime. Applications built to support only version 1.0 of the runtime must use the `` element. ## The useLegacyV2RuntimeActivationPolicy attribute diff --git a/docs/framework/configure-apps/file-schema/startup/supportedruntime-element.md b/docs/framework/configure-apps/file-schema/startup/supportedruntime-element.md index 935a06e70e0ec..fffa6fa16ede9 100644 --- a/docs/framework/configure-apps/file-schema/startup/supportedruntime-element.md +++ b/docs/framework/configure-apps/file-schema/startup/supportedruntime-element.md @@ -2,21 +2,21 @@ description: "Learn more about: element" title: " configuration element - .NET" ms.date: "04/02/2019" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#supportedRuntime" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/startup/supportedRuntime" -helpviewer_keywords: +helpviewer_keywords: - "supportedRuntime element" - " element" ms.assetid: 1ae16e23-afbe-4de4-b413-bc457f37b69f --- -# \ element +# `` element -Specifies which common language runtime version and, optionally, .NET Framework version the application supports. +Specifies which common language runtime version and, optionally, .NET Framework version the application supports. -[\](../configuration-element.md) -  [\](startup-element.md) -    **\** +[\](../configuration-element.md) +  [\](startup-element.md) +    **\** ## Syntax @@ -33,19 +33,19 @@ Specifies which common language runtime version and, optionally, .NET Framework ## Remarks -If the **\** element is not present in the application configuration file, the version of the runtime used to build the application is used. +If the `` element is not present in the application configuration file, the version of the runtime used to build the application is used. -The **\** element should be used by all applications built using version 1.1 or later of the runtime. Applications built to support only version 1.0 of the runtime must use the [\](requiredruntime-element.md) element. +The `` element should be used by all applications built using version 1.1 or later of the runtime. Applications built to support only version 1.0 of the runtime must use the [\](requiredruntime-element.md) element. > [!NOTE] -> If you use the [CorBindToRuntimeByCfg](../../../unmanaged-api/hosting/corbindtoruntimebycfg-function.md) function to specify the configuration file, you must use the `` element for all versions of the runtime. The `` element is ignored when you use [CorBindToRuntimeByCfg](../../../unmanaged-api/hosting/corbindtoruntimebycfg-function.md). - +> If you use the [CorBindToRuntimeByCfg](../../../unmanaged-api/hosting/corbindtoruntimebycfg-function.md) function to specify the configuration file, you must use the `` element for all versions of the runtime. The `` element is ignored when you use [CorBindToRuntimeByCfg](../../../unmanaged-api/hosting/corbindtoruntimebycfg-function.md). + For apps that support versions of the runtime from the .NET Framework 1.1 through 3.5, when multiple versions of the runtime are supported, the first element should specify the most preferred version of the runtime, and the last element should specify the least preferred version. For apps that support the .NET Framework 4.0 or later versions, the `version` attribute indicates the CLR version, which is common to the .NET Framework 4 and later versions, and the `sku` attribute indicates the single .NET Framework version that the app targets. -If the **\** element with the `sku` attribute is present in the configuration file and the installed .NET Framework version is lower than the specified supported version, the application fails to run and instead displays a message asking to install the supported version. Otherwise, the application attempts to run on any installed version, but it may behave unexpectedly if it is not fully compatible with that version. (For compatibility differences between versions of .NET Framework, see [Application compatibility in the .NET Framework](../../../migration-guide/application-compatibility.md).) Therefore, we recommend that you include this element in the application configuration file for easier error diagnostics. (The configuration file automatically generated by Visual Studio when creating a new project already contains it.) - +If the `` element with the `sku` attribute is present in the configuration file and the installed .NET Framework version is lower than the specified supported version, the application fails to run and instead displays a message asking to install the supported version. Otherwise, the application attempts to run on any installed version, but it may behave unexpectedly if it is not fully compatible with that version. (For compatibility differences between versions of .NET Framework, see [Application compatibility in the .NET Framework](../../../migration-guide/application-compatibility.md).) Therefore, we recommend that you include this element in the application configuration file for easier error diagnostics. (The configuration file automatically generated by Visual Studio when creating a new project already contains it.) + > [!NOTE] -> If your application uses legacy activation paths, such as the [CorBindToRuntimeEx function](../../../unmanaged-api/hosting/corbindtoruntimeex-function.md), and you want those paths to activate version 4 of the CLR instead of an earlier version, or if your application is built with the .NET Framework 4 but has a dependency on a mixed-mode assembly built with an earlier version of the .NET Framework, it is not sufficient to specify the .NET Framework 4 in the list of supported runtimes. In addition, in the [\ element](startup-element.md) in your configuration file, you must set the `useLegacyV2RuntimeActivationPolicy` attribute to `true`. However, setting this attribute to `true` means that all components built with earlier versions of the .NET Framework are run using the .NET Framework 4 instead of the runtimes they were built with. +> If your application uses legacy activation paths, such as the [CorBindToRuntimeEx function](../../../unmanaged-api/hosting/corbindtoruntimeex-function.md), and you want those paths to activate version 4 of the CLR instead of an earlier version, or if your application is built with the .NET Framework 4 but has a dependency on a mixed-mode assembly built with an earlier version of the .NET Framework, it is not sufficient to specify the .NET Framework 4 in the list of supported runtimes. In addition, in the [`` element](startup-element.md) in your configuration file, you must set the `useLegacyV2RuntimeActivationPolicy` attribute to `true`. However, setting this attribute to `true` means that all components built with earlier versions of the .NET Framework are run using the .NET Framework 4 instead of the runtimes they were built with. We recommend that you test applications with all the .NET Framework versions that they can run on. diff --git a/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-listeners-for-source.md b/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-listeners-for-source.md index b5c12dea9d15c..4c134e94fe214 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-listeners-for-source.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-listeners-for-source.md @@ -2,17 +2,17 @@ description: "Learn more about: Element for for " title: " Element for for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/sources/source/listeners/add" -helpviewer_keywords: +helpviewer_keywords: - "initializeData attribute" - "add element for for " - " element for for " ms.assetid: 4ce36ac1-81ef-48e8-b8b2-b5a5b0e2adcb --- -# \ Element for \ for \ +# `` Element for `` for \ -Adds a listener to the `Listeners` collection for a trace source. +Adds a listener to the `Listeners` collection for a trace source. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\ @@ -21,103 +21,103 @@ Adds a listener to the `Listeners` collection for a trace source.         [**\**](listeners-element-for-source.md)\           **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`type`|Required attribute, unless you're referencing a listener in the `sharedListeners` collection, in which case you only need to refer to it by name (see the [Example](#example)).

Specifies the type of the listener. You must use a string that meets the requirements specified in [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| -|`initializeData`|Optional attribute.

The string passed to the constructor for the specified class. A is thrown if the class does not have a constructor that takes a string.| -|`name`|Optional attribute.

Specifies the name of the listener.| -|`traceOutputOptions`|Optional attribute.

Specifies the property value for the trace listener.| -|[custom attributes]|Optional attributes.

Specifies the value for listener-specific attributes identified by the method for that listener. is an example of an extra attribute unique to the class.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](filter-element-for-add-for-listeners-for-source.md)|Adds a filter to a listener in the `Listeners` collection for a trace source.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`sources`|Contains trace sources that initiate tracing messages.| -|`source`|Specifies a trace source that initiates tracing messages.| -|`listeners`|Specifies listeners that collect, store, and route messages.| - -## Remarks - - The listener classes shipped with the .NET Framework derive from the class. - - If you do not specify the `name` attribute of the trace listener, the property of the trace listener defaults to an empty string (""). If your application has only one listener, you can add it without specifying a name, and you can remove it by specifying an empty string for the name. However, if your application has more than one listener, you should specify a unique name for each trace listener, which allows you to identify and manage individual trace listeners in the collection. - + type="TraceListenerClassName, Version, Culture, PublicKeyToken" + initializeData="data"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`type`|Required attribute, unless you're referencing a listener in the `sharedListeners` collection, in which case you only need to refer to it by name (see the [Example](#example)).

Specifies the type of the listener. You must use a string that meets the requirements specified in [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| +|`initializeData`|Optional attribute.

The string passed to the constructor for the specified class. A is thrown if the class does not have a constructor that takes a string.| +|`name`|Optional attribute.

Specifies the name of the listener.| +|`traceOutputOptions`|Optional attribute.

Specifies the property value for the trace listener.| +|[custom attributes]|Optional attributes.

Specifies the value for listener-specific attributes identified by the method for that listener. is an example of an extra attribute unique to the class.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](filter-element-for-add-for-listeners-for-source.md)|Adds a filter to a listener in the `Listeners` collection for a trace source.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`sources`|Contains trace sources that initiate tracing messages.| +|`source`|Specifies a trace source that initiates tracing messages.| +|`listeners`|Specifies listeners that collect, store, and route messages.| + +## Remarks + + The listener classes shipped with the .NET Framework derive from the class. + + If you do not specify the `name` attribute of the trace listener, the property of the trace listener defaults to an empty string (""). If your application has only one listener, you can add it without specifying a name, and you can remove it by specifying an empty string for the name. However, if your application has more than one listener, you should specify a unique name for each trace listener, which allows you to identify and manage individual trace listeners in the collection. + > [!NOTE] -> Adding more than one trace listener of the same type and with the same name results in only one trace listener of that type and name being added to the `Listeners` collection. However, you can programmatically add multiple identical listeners to the `Listeners` collection. - - The value for the `initializeData` attribute depends on the type of listener you create. Not all trace listeners require that you specify `initializeData`. - +> Adding more than one trace listener of the same type and with the same name results in only one trace listener of that type and name being added to the `Listeners` collection. However, you can programmatically add multiple identical listeners to the `Listeners` collection. + + The value for the `initializeData` attribute depends on the type of listener you create. Not all trace listeners require that you specify `initializeData`. + > [!NOTE] -> When you use the `initializeData` attribute, you may get the compiler warning "The 'initializeData' attribute is not declared." This warning occurs because the configuration settings are validated against the abstract base class , which does not recognize the `initializeData` attribute. Typically, you can ignore this warning for trace listener implementations that have a constructor that takes a parameter. - - The following table shows the trace listeners that are included with the .NET Framework and describes the value of their `initializeData` attributes. - -|Trace listener class|initializeData attribute value| -|--------------------------|------------------------------------| -||The `useErrorStream` value for the constructor. Set the `initializeData` attribute to "`true`" to write trace and debug output to the standard error stream; set it to "`false`" to write to the standard output stream.| -||The name of the file the writes to.| -||The name of an existing event log source.| -||The name of the file that the writes to.| -||The name of the file that the writes to.| -||The name of the file that the writes to.| - -## Configuration File - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use `` elements to add the listeners `console` and `textListener` to the `Listeners` collection for the trace source `TraceSourceApp`. The `textListener` listener writes trace output to the file myListener.log. - -```xml - - - +> When you use the `initializeData` attribute, you may get the compiler warning "The 'initializeData' attribute is not declared." This warning occurs because the configuration settings are validated against the abstract base class , which does not recognize the `initializeData` attribute. Typically, you can ignore this warning for trace listener implementations that have a constructor that takes a parameter. + + The following table shows the trace listeners that are included with the .NET Framework and describes the value of their `initializeData` attributes. + +|Trace listener class|initializeData attribute value| +|--------------------------|------------------------------------| +||The `useErrorStream` value for the constructor. Set the `initializeData` attribute to "`true`" to write trace and debug output to the standard error stream; set it to "`false`" to write to the standard output stream.| +||The name of the file the writes to.| +||The name of an existing event log source.| +||The name of the file that the writes to.| +||The name of the file that the writes to.| +||The name of the file that the writes to.| + +## Configuration File + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use `` elements to add the listeners `console` and `textListener` to the `Listeners` collection for the trace source `TraceSourceApp`. The `textListener` listener writes trace output to the file myListener.log. + +```xml + + + - + switchType="System.Diagnostics.SourceSwitch"> + - - - - - - + type="System.Diagnostics.ConsoleTraceListener"/> + + +
+ + + - - - - -
+ initializeData="myListener.log"/> + + + + +
-``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-listeners-for-trace.md b/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-listeners-for-trace.md index cb57f55251288..6020df572cec3 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-listeners-for-trace.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-listeners-for-trace.md @@ -2,17 +2,17 @@ description: "Learn more about: Element for for " title: " Element for for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/trace/listeners/add" -helpviewer_keywords: +helpviewer_keywords: - "initializeData attribute" - " element for " - "add element for " ms.assetid: 81e804a3-ef11-4d39-bbde-bfa012c179e2 --- -# \ Element for \ for \ +# `` Element for `` for \ -Adds a listener to the **Listeners** collection. +Adds a listener to the `Listeners` collection. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\ @@ -20,86 +20,86 @@ Adds a listener to the **Listeners** collection.       [**\**](listeners-element-for-trace.md)\         **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**type**|Required attribute.

Specifies the type of the listener. You must use a string that meets the requirements specified in [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| -|**initializeData**|Optional attribute.

The string passed to the constructor for the specified class.| -|**name**|Optional attribute.

Specifies the name of the listener.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](filter-element-for-add-for-listeners-for-trace.md)|Adds a filter to a listener in the `Listeners` collection for a trace.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`listeners`|Specifies a listener that collects, stores, and routes messages. Listeners direct the tracing output to an appropriate target.| -|`system.diagnostics`|Specifies the root element for the ASP.NET configuration section.| -|`trace`|Contains listeners that collect, store, and route tracing messages.| - -## Remarks - - The and classes share the same **Listeners** collection. If you add a listener object to the collection in one of these classes, the other class uses the same listener. The listener classes derive from the . - - If you do not specify the `name` attribute of the trace listener, the of the trace listener defaults to an empty string (""). If your application has only one listener, you can add it without specifying a name, and remove it by specifying an empty string for the name. However, if your application has more than one listener, you should specify unique names for each trace listener, which allows you to identify and manage individual trace listeners within the and collections. - + type="trace listener class name, Version, Culture, PublicKeyToken" + initializeData="data"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|**type**|Required attribute.

Specifies the type of the listener. You must use a string that meets the requirements specified in [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| +|**initializeData**|Optional attribute.

The string passed to the constructor for the specified class.| +|**name**|Optional attribute.

Specifies the name of the listener.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](filter-element-for-add-for-listeners-for-trace.md)|Adds a filter to a listener in the `Listeners` collection for a trace.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`listeners`|Specifies a listener that collects, stores, and routes messages. Listeners direct the tracing output to an appropriate target.| +|`system.diagnostics`|Specifies the root element for the ASP.NET configuration section.| +|`trace`|Contains listeners that collect, store, and route tracing messages.| + +## Remarks + + The and classes share the same `Listeners` collection. If you add a listener object to the collection in one of these classes, the other class uses the same listener. The listener classes derive from the . + + If you do not specify the `name` attribute of the trace listener, the of the trace listener defaults to an empty string (""). If your application has only one listener, you can add it without specifying a name, and remove it by specifying an empty string for the name. However, if your application has more than one listener, you should specify unique names for each trace listener, which allows you to identify and manage individual trace listeners within the and collections. + > [!NOTE] -> Adding more than one trace listener of the same type and with the same name results in only one trace listener of that type and name being added to the `Listeners` collection. However, you can programmatically add multiple identical listeners to the `Listeners` collection. - - The value for the **initializeData** attribute depends on the type of listener you create. Not all trace listeners require that you specify **initializeData**. - +> Adding more than one trace listener of the same type and with the same name results in only one trace listener of that type and name being added to the `Listeners` collection. However, you can programmatically add multiple identical listeners to the `Listeners` collection. + + The value for the `initializeData` attribute depends on the type of listener you create. Not all trace listeners require that you specify **initializeData**. + > [!NOTE] -> When you use the `initializeData` attribute, you may get the compiler warning "The 'initializeData' attribute is not declared." This warning occurs because the configuration settings are validated against the abstract base class , which does not recognize the `initializeData` attribute. Typically, you can ignore this warning for trace listener implementations that have a constructor that takes a parameter. - - The following table shows the trace listeners that are included with the .NET Framework and describes the value of their **initializeData** attributes. - -|Trace listener class|initializeData attribute value| -|--------------------------|------------------------------------| -||The `useErrorStream` value for the constructor. Set the `initializeData` attribute to "`true`" to write trace and debug output to ; "`false`" to write to .| -||The name of the file the writes to.| -||The name of the name of an existing event log source.| -||The name of the file that the writes to.| -||The name of the file that the writes to.| -||The name of the file that the writes to.| - -## Example - - The following example shows how to use **\** elements to add the listeners `MyListener` and `MyEventListener` to the **Listeners** collection. `MyListener` creates a file called `MyListener.log` and writes the output to the file. `MyEventListener` creates an entry in the event log. - -```xml - - - - - - - - - - - -``` - +> When you use the `initializeData` attribute, you may get the compiler warning "The 'initializeData' attribute is not declared." This warning occurs because the configuration settings are validated against the abstract base class , which does not recognize the `initializeData` attribute. Typically, you can ignore this warning for trace listener implementations that have a constructor that takes a parameter. + + The following table shows the trace listeners that are included with the .NET Framework and describes the value of their `initializeData` attributes. + +|Trace listener class|initializeData attribute value| +|--------------------------|------------------------------------| +||The `useErrorStream` value for the constructor. Set the `initializeData` attribute to "`true`" to write trace and debug output to ; "`false`" to write to .| +||The name of the file the writes to.| +||The name of the name of an existing event log source.| +||The name of the file that the writes to.| +||The name of the file that the writes to.| +||The name of the file that the writes to.| + +## Example + + The following example shows how to use `` elements to add the listeners `MyListener` and `MyEventListener` to the `Listeners` collection. `MyListener` creates a file called `MyListener.log` and writes the output to the file. `MyEventListener` creates an entry in the event log. + +```xml + + + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-sharedlisteners.md b/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-sharedlisteners.md index 2125a0a7dd2a9..07a6a0ca89d3b 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-sharedlisteners.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-sharedlisteners.md @@ -2,112 +2,112 @@ description: "Learn more about: Element for " title: " Element for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/sharedListeners/add" -helpviewer_keywords: +helpviewer_keywords: - "initializeData attribute" - " element for " - "add element for " ms.assetid: 1595e1bc-2492-421f-8384-7f382eb8eb57 --- -# \ Element for \ +# `` Element for \ -Adds a listener to the `sharedListeners` collection. `sharedListeners` is a collection of listeners that any [\](source-element.md) or [\](trace-element.md) can reference. By default, listeners in the `sharedListeners` collection are not placed in a `Listeners` collection. They must be added by name to the [\](source-element.md) or [\](trace-element.md). It is not possible to get the listeners in the `sharedListeners` collection in code at run time. +Adds a listener to the `sharedListeners` collection. `sharedListeners` is a collection of listeners that any [\](source-element.md) or [\](trace-element.md) can reference. By default, listeners in the `sharedListeners` collection are not placed in a `Listeners` collection. They must be added by name to the [\](source-element.md) or [\](trace-element.md). It is not possible to get the listeners in the `sharedListeners` collection in code at run time. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\     [**\**](sharedlisteners-element.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml +/> ``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`name`|Required attribute.

Specifies the name of the listener that is used to add the shared listener to a `Listeners` collection.| -|`type`|Required attribute.

Specifies the type of the listener. You must use a string that meets the requirements specified in [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| -|`initializeData`|Optional attribute.

The string passed to the constructor for the specified class.| + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`name`|Required attribute.

Specifies the name of the listener that is used to add the shared listener to a `Listeners` collection.| +|`type`|Required attribute.

Specifies the type of the listener. You must use a string that meets the requirements specified in [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| +|`initializeData`|Optional attribute.

The string passed to the constructor for the specified class.| |`traceOutputOptions`|Optional attribute.

The string representation of one or more enumeration members that indicates the data to be written to the trace output. Multiple items are separated by commas. The default value is "None".| -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](filter-element-for-add-for-sharedlisteners.md)|Adds a filter to a listener in the `sharedListeners` collection.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`sharedListeners`|A collection of listeners that any source or trace element can reference.| - -## Remarks - - The listener classes shipped with the .NET Framework derive from the class. The value for the `name` attribute is used to add the shared listener to a `Listeners` collection for either a trace or a trace source. The value for the `initializeData` attribute depends on the type of listener you create. Not all trace listeners require that you specify `initializeData`. - +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](filter-element-for-add-for-sharedlisteners.md)|Adds a filter to a listener in the `sharedListeners` collection.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`sharedListeners`|A collection of listeners that any source or trace element can reference.| + +## Remarks + + The listener classes shipped with the .NET Framework derive from the class. The value for the `name` attribute is used to add the shared listener to a `Listeners` collection for either a trace or a trace source. The value for the `initializeData` attribute depends on the type of listener you create. Not all trace listeners require that you specify `initializeData`. + > [!NOTE] -> When you use the `initializeData` attribute, you may get the compiler warning "The 'initializeData' attribute is not declared." This warning occurs because the configuration settings are validated against the abstract base class , which does not recognize the `initializeData` attribute. Typically, you can ignore this warning for trace listener implementations that have a constructor that takes a parameter. - - The following table shows the trace listeners that are included with the .NET Framework and describes the value of their `initializeData` attributes. - -|Trace listener class|initializeData attribute value| -|--------------------------|------------------------------------| -||The `useErrorStream` value for the constructor. Set the `initializeData` attribute to "`true`" to write trace and debug output to the standard error stream; set it to "`false`" to write to the standard output stream.| -||The name of the file the writes to.| -||The name of an existing event log source.| -||The name of the file that the writes to.| -||The name of the file that the writes to.| -||The name of the file that the writes to.| - -## Configuration File - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use `` elements to add the `textListener` to the `sharedListeners` collection. `textListener` is added by name to the `Listeners` collection for the trace source `TraceSourceApp`. The `textListener` listener writes trace output to the file myListener.log. - -```xml - - - +> When you use the `initializeData` attribute, you may get the compiler warning "The 'initializeData' attribute is not declared." This warning occurs because the configuration settings are validated against the abstract base class , which does not recognize the `initializeData` attribute. Typically, you can ignore this warning for trace listener implementations that have a constructor that takes a parameter. + + The following table shows the trace listeners that are included with the .NET Framework and describes the value of their `initializeData` attributes. + +|Trace listener class|initializeData attribute value| +|--------------------------|------------------------------------| +||The `useErrorStream` value for the constructor. Set the `initializeData` attribute to "`true`" to write trace and debug output to the standard error stream; set it to "`false`" to write to the standard output stream.| +||The name of the file the writes to.| +||The name of an existing event log source.| +||The name of the file that the writes to.| +||The name of the file that the writes to.| +||The name of the file that the writes to.| + +## Configuration File + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use `` elements to add the `textListener` to the `sharedListeners` collection. `textListener` is added by name to the `Listeners` collection for the trace source `TraceSourceApp`. The `textListener` listener writes trace output to the file myListener.log. + +```xml + + + - + switchType="System.Diagnostics.SourceSwitch"> + - - - - - - + type="System.Diagnostics.ConsoleTraceListener"/> + + +
+ + + - - - - -
+ initializeData="myListener.log"/> + + + + +
-``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-switches.md b/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-switches.md index 4ee2c80dec8ab..5a324eb9a362f 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-switches.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/add-element-for-switches.md @@ -2,71 +2,71 @@ description: "Learn more about: Element for " title: " Element for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/switches/add" -helpviewer_keywords: +helpviewer_keywords: - " element for " - "add element for " ms.assetid: 712ac3a7-7abf-4a9e-8db4-acd241c2f369 --- -# \ Element for \ +# `` Element for \ -Specifies the level where a trace switch is set. +Specifies the level where a trace switch is set. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\     [**\**](switches-element.md)\       **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**name**|Required attribute.

Specifies the name of the switch. The value of this attribute corresponds to the *displayName* parameter that is passed to switch constructor.| -|**value**|Required attribute.

Specifies the level of the switch.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`switches`|Contains trace switches and the level where the trace switches are set.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| - -## Remarks - - You can change the level of a trace switch by putting it in a configuration file. If the switch is a , you can turn it on and off. If the switch is a , you can assign different levels to it to specify the types of trace or debug messages the application outputs. - -## Example - - The following example shows how to use the **\** element to set the `General` trace switch to the level, and enable the `Data` Boolean trace switch. - -```xml - - - - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|**name**|Required attribute.

Specifies the name of the switch. The value of this attribute corresponds to the *displayName* parameter that is passed to switch constructor.| +|**value**|Required attribute.

Specifies the level of the switch.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`switches`|Contains trace switches and the level where the trace switches are set.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| + +## Remarks + + You can change the level of a trace switch by putting it in a configuration file. If the switch is a , you can turn it on and off. If the switch is a , you can assign different levels to it to specify the types of trace or debug messages the application outputs. + +## Example + + The following example shows how to use the `` element to set the `General` trace switch to the level, and enable the `Data` Boolean trace switch. + +```xml + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/assert-element.md b/docs/framework/configure-apps/file-schema/trace-debug/assert-element.md index 05ec8b38c6cf8..5293dc6c742ef 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/assert-element.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/assert-element.md @@ -2,73 +2,73 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/assert" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#assert" -helpviewer_keywords: +helpviewer_keywords: - " element" - "assert element" ms.assetid: ef4c3229-b151-4d85-8091-e6456af9b935 --- -# \ Element +# `` Element -Specifies whether to display a message box when you call the method; also specifies the name of the file to write messages to. +Specifies whether to display a message box when you call the method; also specifies the name of the file to write messages to. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\     **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`assertuienabled`|Optional attribute.

Specifies whether to display a message box when the **Debug.Assert** method evaluates to **false**.| -|`logfilename`|Optional attribute.

Specifies the name of the file to write the message to if **Debug.Assert** evaluates to **false**.| - -## assertuienabled Attribute - -|Value|Description| -|-----------|-----------------| -|`true`|Displays the message box. This is the default.| -|`false`|Does not display the message box.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| - -## Remarks - - Both attributes in the **\** element are optional. You can disable message boxes without specifying a file to write the messages to, or you can specify a file to write messages to while leaving message boxes enabled. - -## Example - - The following example shows how to disable displaying message boxes when you call **Debug.Assert** and write the messages to `c:\log.txt`. - -```xml - - - - - -``` - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`assertuienabled`|Optional attribute.

Specifies whether to display a message box when the **Debug.Assert** method evaluates to **false**.| +|`logfilename`|Optional attribute.

Specifies the name of the file to write the message to if **Debug.Assert** evaluates to **false**.| + +## assertuienabled Attribute + +|Value|Description| +|-----------|-----------------| +|`true`|Displays the message box. This is the default.| +|`false`|Does not display the message box.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| + +## Remarks + + Both attributes in the `` element are optional. You can disable message boxes without specifying a file to write the messages to, or you can specify a file to write messages to while leaving message boxes enabled. + +## Example + + The following example shows how to disable displaying message boxes when you call **Debug.Assert** and write the messages to `c:\log.txt`. + +```xml + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/clear-element-for-listeners-for-source.md b/docs/framework/configure-apps/file-schema/trace-debug/clear-element-for-listeners-for-source.md index 992c39ffc92a8..ad5b99ca8bb83 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/clear-element-for-listeners-for-source.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/clear-element-for-listeners-for-source.md @@ -2,16 +2,16 @@ description: "Learn more about: Element for for " title: " Element for for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/sources/source/listeners/clear" -helpviewer_keywords: +helpviewer_keywords: - " element for for " - "clear element for for " ms.assetid: 76796bb2-9c0b-4526-8135-8bf18b16d8d9 --- -# \ Element for \ for \ +# `` Element for `` for \ -Clears the `Listeners` collection for a trace source. +Clears the `Listeners` collection for a trace source. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\ @@ -20,72 +20,72 @@ Clears the `Listeners` collection for a trace source.         [**\**](listeners-element-for-source.md)\           **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`sources`|Contains trace sources that initiate tracing messages.| -|`source`|Specifies a trace source that initiates tracing messages.| -|`listeners`|Specifies listeners that collect, store, and route messages.| - -## Remarks - - The `` element removes all listeners from the `Listeners` collection for a trace source, including the . You can use the `` element before using the `` element to be certain there are no other active listeners in the collection. - -## Configuration File - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use the `` element before using the `` elements to add the listeners `console` and `textListener` to the `Listeners` collection for the trace source `TraceSourceApp`. - -```xml - - - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`sources`|Contains trace sources that initiate tracing messages.| +|`source`|Specifies a trace source that initiates tracing messages.| +|`listeners`|Specifies listeners that collect, store, and route messages.| + +## Remarks + + The `` element removes all listeners from the `Listeners` collection for a trace source, including the . You can use the `` element before using the `` element to be certain there are no other active listeners in the collection. + +## Configuration File + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use the `` element before using the `` elements to add the listeners `console` and `textListener` to the `Listeners` collection for the trace source `TraceSourceApp`. + +```xml + + + - - + switchType="System.Diagnostics.SourceSwitch"> + + - - - - - + type="System.Diagnostics.ConsoleTraceListener"/> + + + + + - - - - - + initializeData="myListener.log"/> + + + + +
-``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/clear-element-for-listeners-for-trace.md b/docs/framework/configure-apps/file-schema/trace-debug/clear-element-for-listeners-for-trace.md index ab0db27e4de81..fbdbc2b18e63f 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/clear-element-for-listeners-for-trace.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/clear-element-for-listeners-for-trace.md @@ -2,16 +2,16 @@ description: "Learn more about: Element for for " title: " Element for for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/trace/listeners/clear" -helpviewer_keywords: +helpviewer_keywords: - "clear element for for " - " element for for " ms.assetid: b44732a8-271f-4a06-ba9e-fe3298d6f192 --- -# \ Element for \ for \ +# `` Element for `` for \ -Clears the `Listeners` collection for trace. +Clears the `Listeners` collection for trace. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\ @@ -19,65 +19,65 @@ Clears the `Listeners` collection for trace.       [**\**](listeners-element-for-trace.md)\         **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`trace`|Contains listeners that collect, store, and route tracing messages.| -|`listeners`|Contains listeners that collect, store, and route messages. Listeners direct the tracing output to an appropriate target.| - -## Remarks - - The `` element removes all listeners from the `Listeners` collection for trace. You can use the `` element before using the `` element to be certain there are no other active listeners in the collection. - - You can clear the `Listeners` collection programmatically by calling the method on the property (`System.Diagnostics.Trace.Listeners.Clear()`). - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`trace`|Contains listeners that collect, store, and route tracing messages.| +|`listeners`|Contains listeners that collect, store, and route messages. Listeners direct the tracing output to an appropriate target.| + +## Remarks + + The `` element removes all listeners from the `Listeners` collection for trace. You can use the `` element before using the `` element to be certain there are no other active listeners in the collection. + + You can clear the `Listeners` collection programmatically by calling the method on the property (`System.Diagnostics.Trace.Listeners.Clear()`). + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + > [!NOTE] -> The `` element removes the from the `Listeners` collection, altering the behavior of the , , , and methods. Calling an `Assert` or `Fail` method normally results in the display of a message box. However, the message box is not displayed if the is not in the `Listeners` collection. - -## Example - - The following example shows how to use the `` element before using the `` element to add the listener `console` to the `Listeners` collection for trace. - -```xml - - - - - +> The `` element removes the from the `Listeners` collection, altering the behavior of the , , , and methods. Calling an `Assert` or `Fail` method normally results in the display of a message box. However, the message box is not displayed if the is not in the `Listeners` collection. + +## Example + + The following example shows how to use the `` element before using the `` element to add the listener `console` to the `Listeners` collection for trace. + +```xml + + + + + + type="System.Diagnostics.ConsoleTraceListener" > - - - - + initializeData="Error" /> + + + + -``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-listeners-for-source.md b/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-listeners-for-source.md index 4c2f24a2b8fd9..adcfb76874e43 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-listeners-for-source.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-listeners-for-source.md @@ -2,18 +2,18 @@ description: "Learn more about: Element for for for " title: " Element for for for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#filter" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/sources/source/listeners/add/filter" -helpviewer_keywords: +helpviewer_keywords: - "initializeData attribute" - " element for for for " - "filter element for for for " ms.assetid: 15808b80-4579-4c25-b385-178cfdf154ba --- -# \ Element for \ for \ for \ +# `` Element for `` for `` for \ -Adds a filter to a listener in the `Listeners` collection for a trace source. +Adds a filter to a listener in the `Listeners` collection for a trace source. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\ @@ -23,73 +23,73 @@ Adds a filter to a listener in the `Listeners` collection for a trace source.           [**\**](add-element-for-listeners-for-source.md)\             **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`type`|Required attribute.

Specifies the type of the filter, which should inherit from the class. You can use the namespace-qualified name of the type, which corresponds to the type's property, or you can use the fully qualified type name including the assembly information, which corresponds to the property. For information about fully qualified type names, see [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| -|`initializeData`|Optional attribute.

The string passed to the constructor for the specified filter class.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`sources`|Contains trace sources that initiate tracing messages.| -|`source`|Specifies a trace source that initiates tracing messages.| -|`listeners`|Contains listeners that collect, store, and route messages. Listeners direct the tracing output to an appropriate target.| -|`add`|Adds a listener to the `Listeners` collection for a trace source.| - -## Remarks - - The `` element must be contained in an `` element for a trace source listener that specifies the type of the listener, not just the name of a listener defined in a [\](sharedlisteners-element.md). If the listener is defined in a [\](sharedlisteners-element.md), the filter for that listener must be defined in that element. - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use the `` element to add a filter to the listener `console` in the `Listeners` collection for the trace source `myTraceSource`, specifying the filter event level as `Error`. - -```xml - - - + initializeData="data" /> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`type`|Required attribute.

Specifies the type of the filter, which should inherit from the class. You can use the namespace-qualified name of the type, which corresponds to the type's property, or you can use the fully qualified type name including the assembly information, which corresponds to the property. For information about fully qualified type names, see [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| +|`initializeData`|Optional attribute.

The string passed to the constructor for the specified filter class.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`sources`|Contains trace sources that initiate tracing messages.| +|`source`|Specifies a trace source that initiates tracing messages.| +|`listeners`|Contains listeners that collect, store, and route messages. Listeners direct the tracing output to an appropriate target.| +|`add`|Adds a listener to the `Listeners` collection for a trace source.| + +## Remarks + + The `` element must be contained in an `` element for a trace source listener that specifies the type of the listener, not just the name of a listener defined in a [\](sharedlisteners-element.md). If the listener is defined in a [\](sharedlisteners-element.md), the filter for that listener must be defined in that element. + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use the `` element to add a filter to the listener `console` in the `Listeners` collection for the trace source `myTraceSource`, specifying the filter event level as `Error`. + +```xml + + + - + switchType="System.Diagnostics.SourceSwitch" > + + type="System.Diagnostics.ConsoleTraceListener" > - - - - - - - - - - -``` - + initializeData="Error" /> + + +
+ + + + + +
+
+``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-listeners-for-trace.md b/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-listeners-for-trace.md index 85119ad167375..8d90e14a4ce40 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-listeners-for-trace.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-listeners-for-trace.md @@ -2,17 +2,17 @@ description: "Learn more about: Element for for for " title: " Element for for for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/trace/listeners/add/filter" -helpviewer_keywords: +helpviewer_keywords: - "initializeData attribute" - "filter element for for for " - " element for for for " ms.assetid: eb9c18f5-dfa8-47c5-b91b-e4b93e76e1cc --- -# \ Element for \ for \ for \ +# `` Element for `` for `` for \ -Adds a filter to a listener in the `Listeners` collection for a trace. +Adds a filter to a listener in the `Listeners` collection for a trace. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\ @@ -21,66 +21,66 @@ Adds a filter to a listener in the `Listeners` collection for a trace.         [**\**](add-element-for-listeners-for-trace.md)\           **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`type`|Required attribute.

Specifies the type of the filter, which should inherit from the class. You can use the namespace-qualified name of the type, which corresponds to the type's property, or you can use the fully qualified type name including the assembly information, which corresponds to the property. For information about fully qualified type names, see [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| -|`initializeData`|Optional attribute.

The string passed to the constructor for the specified filter class.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`trace`|Contains listeners that collect, store, and route tracing messages.| -|`listeners`|Contains listeners that collect, store, and route messages. Listeners direct the tracing output to an appropriate target.| -|`add`|Adds a listener to the `Listeners` collection.| - -## Remarks - - The `` element must be contained in an `` element for a trace listener that specifies the type of the listener, not just the name of a listener defined in a [\](sharedlisteners-element.md). If the listener is defined in a [\](sharedlisteners-element.md), the filter for that listener must be defined in that element. - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use the `` element to add a filter to the listener `console` in the `Listeners` collection for trace, specifying the filter event level as `Error`. - -```xml - - - - + initializeData="data" /> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`type`|Required attribute.

Specifies the type of the filter, which should inherit from the class. You can use the namespace-qualified name of the type, which corresponds to the type's property, or you can use the fully qualified type name including the assembly information, which corresponds to the property. For information about fully qualified type names, see [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| +|`initializeData`|Optional attribute.

The string passed to the constructor for the specified filter class.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`trace`|Contains listeners that collect, store, and route tracing messages.| +|`listeners`|Contains listeners that collect, store, and route messages. Listeners direct the tracing output to an appropriate target.| +|`add`|Adds a listener to the `Listeners` collection.| + +## Remarks + + The `` element must be contained in an `` element for a trace listener that specifies the type of the listener, not just the name of a listener defined in a [\](sharedlisteners-element.md). If the listener is defined in a [\](sharedlisteners-element.md), the filter for that listener must be defined in that element. + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use the `` element to add a filter to the listener `console` in the `Listeners` collection for trace, specifying the filter event level as `Error`. + +```xml + + + + + type="System.Diagnostics.ConsoleTraceListener" > - - - - - - -``` - + initializeData="Error" /> + + +
+
+
+
+``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-sharedlisteners.md b/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-sharedlisteners.md index 1fb983e813e0d..931a517d00701 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-sharedlisteners.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/filter-element-for-add-for-sharedlisteners.md @@ -2,9 +2,9 @@ description: "Learn more about: Element for for " title: " Element for for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/sharedListeners/add/filter" -helpviewer_keywords: +helpviewer_keywords: - "filter element for for " - "initializeData attribute" - " element for for " @@ -12,9 +12,9 @@ helpviewer_keywords: - "trace listeners, filters" ms.assetid: 7d4e7faa-2e4e-4379-ac76-f6cd7f2f8fac --- -# \ Element for \ for \ +# `` Element for `` for \ -Adds a filter to a listener in the `sharedListeners` collection. +Adds a filter to a listener in the `sharedListeners` collection. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\ @@ -22,69 +22,69 @@ Adds a filter to a listener in the `sharedListeners` collection.       [**\**](add-element-for-sharedlisteners.md)\         **\** -## Syntax - -```xml +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**type**|Required attribute.

Specifies the type of the filter. You can use only the full name of the type (in the format of the property), or you can use the fully qualified type name including the assembly information (in the format of the property). For information on creating a fully qualified type name, see [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| -|**initializeData**|Optional attribute.

The string passed to the constructor for the specified class.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`sharedListeners`|A collection of listeners that any source or trace element can reference.| -|`add`|Adds a listener to the **sharedListeners** collection.| - -## Remarks - - If a listener is defined in an `` element of the `` element, the filter for that listener should be defined in a `` element that is a child of the `` element. - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use the `` element to add a filter to the trace listener `console` in the `sharedListeners` collection. - -```xml - - - - - - - - - - - + initializeData="Warning" /> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|**type**|Required attribute.

Specifies the type of the filter. You can use only the full name of the type (in the format of the property), or you can use the fully qualified type name including the assembly information (in the format of the property). For information on creating a fully qualified type name, see [Specifying Fully Qualified Type Names](../../../../fundamentals/reflection/specifying-fully-qualified-type-names.md).| +|**initializeData**|Optional attribute.

The string passed to the constructor for the specified class.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`sharedListeners`|A collection of listeners that any source or trace element can reference.| +|`add`|Adds a listener to the `sharedListeners` collection.| + +## Remarks + + If a listener is defined in an `` element of the `` element, the filter for that listener should be defined in a `` element that is a child of the `` element. + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use the `` element to add a filter to the trace listener `console` in the `sharedListeners` collection. + +```xml + + + + + + + + + + + + type="System.Diagnostics.ConsoleTraceListener" > - - - - -``` - + initializeData="Error" /> + + +
+
+``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/listeners-element-for-source.md b/docs/framework/configure-apps/file-schema/trace-debug/listeners-element-for-source.md index 7efcf783d0c26..0c0883a76e8f8 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/listeners-element-for-source.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/listeners-element-for-source.md @@ -2,91 +2,91 @@ description: "Learn more about: Element for " title: " Element for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/sources/source/listeners" -helpviewer_keywords: +helpviewer_keywords: - "listeners element for " - " element for " ms.assetid: a2991f43-b4d3-4614-a8e7-da392de9697f --- -# \ Element for \ - -Adds or removes listeners in the collection for a . A listener directs the tracing output to an appropriate target, such as a log, window, or text file. - -[**\**](../configuration-element.md) -  [**\**](system-diagnostics-element.md) -    [**\**](sources-element.md) -      [**\**](source-element.md) -        **\** - -## Syntax - -```xml +# `` Element for \ + +Adds or removes listeners in the collection for a . A listener directs the tracing output to an appropriate target, such as a log, window, or text file. + +[**\**](../configuration-element.md) +  [**\**](system-diagnostics-element.md) +    [**\**](sources-element.md) +      [**\**](source-element.md) +        **\** + +## Syntax + +```xml - ... - - - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](add-element-for-listeners-for-source.md)|Adds a listener to the `Listeners` collection.| -|[\](remove-element-for-listeners-for-source.md)|Removes a listener from the `Listeners` collection.| -|[\](clear-element-for-listeners-for-source.md)|Clears the `Listeners` collection for a trace source.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`sources`|Contains trace sources that initiate tracing messages.| -|`source`|Specifies a trace source that initiates tracing messages.| - -## Remarks - -## Configuration File - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use the `` element to add a console trace listener to the `mySource` source and to remove the default trace listener. - -```xml - - - + ... + + + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](add-element-for-listeners-for-source.md)|Adds a listener to the `Listeners` collection.| +|[\](remove-element-for-listeners-for-source.md)|Removes a listener from the `Listeners` collection.| +|[\](clear-element-for-listeners-for-source.md)|Clears the `Listeners` collection for a trace source.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`sources`|Contains trace sources that initiate tracing messages.| +|`source`|Specifies a trace source that initiates tracing messages.| + +## Remarks + +## Configuration File + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use the `` element to add a console trace listener to the `mySource` source and to remove the default trace listener. + +```xml + + + - + switchType="System.Diagnostics.SourceSwitch"> + + type="System.Diagnostics.ConsoleTraceListener"> - - - - - - - - - - -``` - + initializeData="Error"/> + + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/listeners-element-for-trace.md b/docs/framework/configure-apps/file-schema/trace-debug/listeners-element-for-trace.md index 76fe94840a79a..fd7faa86f165e 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/listeners-element-for-trace.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/listeners-element-for-trace.md @@ -2,89 +2,89 @@ description: "Learn more about: Element for " title: " Element for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/trace/listeners" -helpviewer_keywords: +helpviewer_keywords: - " element" - "listeners element" ms.assetid: 1394c2c3-6304-46db-87c1-8e8b16f5ad5b --- -# \ Element for \ +# `` Element for \ -Specifies a listener that collects, stores, and routes messages. Listeners direct the tracing output to an appropriate target. +Specifies a listener that collects, stores, and routes messages. Listeners direct the tracing output to an appropriate target. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\     [**\**](trace-element.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml - ... - - - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](add-element-for-listeners-for-trace.md)|Adds a listener to the `Listeners` collection.| -|[\](clear-element-for-listeners-for-trace.md)|Clears the `Listeners` collection for trace.| -|[\](remove-element-for-listeners-for-trace.md)|Removes a listener from the `Listeners` collection.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies the root element for the ASP.NET configuration section.| -|`trace`|Contains listeners that collect, store, and route tracing messages.| - -## Remarks - - The and classes share the same **Listeners** collection. If you add a listener object to the collection in one of these classes, the other class uses the same listener. The listener classes shipped with the .NET Framework derive from the class. - -## Configuration File - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use the **\** element to add the listeners `MyListener` and `MyEventListener` to the **Listeners** collection. `MyListener` creates a file called `MyListener.log` and writes the output to the file. `MyEventListener` creates an entry in the event log. - -```xml - - - - + ... + + + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](add-element-for-listeners-for-trace.md)|Adds a listener to the `Listeners` collection.| +|[\](clear-element-for-listeners-for-trace.md)|Clears the `Listeners` collection for trace.| +|[\](remove-element-for-listeners-for-trace.md)|Removes a listener from the `Listeners` collection.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies the root element for the ASP.NET configuration section.| +|`trace`|Contains listeners that collect, store, and route tracing messages.| + +## Remarks + + The and classes share the same `Listeners` collection. If you add a listener object to the collection in one of these classes, the other class uses the same listener. The listener classes shipped with the .NET Framework derive from the class. + +## Configuration File + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use the `` element to add the listeners `MyListener` and `MyEventListener` to the `Listeners` collection. `MyListener` creates a file called `MyListener.log` and writes the output to the file. `MyEventListener` creates an entry in the event log. + +```xml + + + + - + - - - - -``` - + PublicKeyToken=b77a5c561934e089" + initializeData="MyConfigEventLog"/> + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/performancecounters-element.md b/docs/framework/configure-apps/file-schema/trace-debug/performancecounters-element.md index d6dd03844d627..9ff8967878b2a 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/performancecounters-element.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/performancecounters-element.md @@ -11,13 +11,13 @@ helpviewer_keywords: ms.assetid: a71f605b-c7d9-4501-a5c3-abcbb964a43f --- -# \ Element +# `` Element Specifies the size of the global memory shared by performance counters. -[**\**](../configuration-element.md) -  [**\**](system-diagnostics-element.md) -    **\** +[**\**](../configuration-element.md) +  [**\**](system-diagnostics-element.md) +    **\** ## Syntax diff --git a/docs/framework/configure-apps/file-schema/trace-debug/remove-element-for-listeners-for-source.md b/docs/framework/configure-apps/file-schema/trace-debug/remove-element-for-listeners-for-source.md index 352d34b4b910a..f5ed6f6d519ed 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/remove-element-for-listeners-for-source.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/remove-element-for-listeners-for-source.md @@ -2,16 +2,16 @@ description: "Learn more about: Element for for " title: " Element for for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/sources/source/listeners/remove" -helpviewer_keywords: +helpviewer_keywords: - "remove element for for " - " element for for " ms.assetid: 3ff6b578-273d-407f-b07f-8251f1f9f5d0 --- -# \ Element for \ for \ +# `` Element for `` for \ -Removes a listener from the `Listeners` collection for a trace source. +Removes a listener from the `Listeners` collection for a trace source. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\ @@ -20,65 +20,65 @@ Removes a listener from the `Listeners` collection for a trace source.         [**\**](listeners-element-for-source.md)\           **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`name`|Required attribute.

The name of the listener to remove from the `Listeners` collection.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`sources`|Contains trace sources that initiate tracing messages.| -|`source`|Specifies a trace source that initiates tracing messages.| -|`listeners`|Specifies listeners that collect, store, and route messages.| - -## Remarks - - The `` element removes a specified listener from the `Listeners` collection for a trace source. - - You can remove an element from the `Listeners` collection for a trace source programmatically by calling the method on the property of the instance. - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use the `` element before using the `` element to add the listener `console` to the `Listeners` collection for the trace source `TraceSourceApp`. - -```xml - - - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`name`|Required attribute.

The name of the listener to remove from the `Listeners` collection.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`sources`|Contains trace sources that initiate tracing messages.| +|`source`|Specifies a trace source that initiates tracing messages.| +|`listeners`|Specifies listeners that collect, store, and route messages.| + +## Remarks + + The `` element removes a specified listener from the `Listeners` collection for a trace source. + + You can remove an element from the `Listeners` collection for a trace source programmatically by calling the method on the property of the instance. + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use the `` element before using the `` element to add the listener `console` to the `Listeners` collection for the trace source `TraceSourceApp`. + +```xml + + + - - + switchType="System.Diagnostics.SourceSwitch" > + + - - - - + type="System.Diagnostics.ConsoleTraceListener" /> +
+ +
+
-``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/remove-element-for-listeners-for-trace.md b/docs/framework/configure-apps/file-schema/trace-debug/remove-element-for-listeners-for-trace.md index c1f827b2ab4d4..dfb91e63ad20a 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/remove-element-for-listeners-for-trace.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/remove-element-for-listeners-for-trace.md @@ -2,16 +2,16 @@ description: "Learn more about: Element for for " title: " Element for for " ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/trace/listeners/remove" -helpviewer_keywords: +helpviewer_keywords: - "remove element" - " element" ms.assetid: 9a5cd1b5-be1a-485f-8f0c-2890ad3ef3e0 --- -# \ Element for \ for \ +# `` Element for `` for \ -Removes a listener from the **Listeners** collection. +Removes a listener from the `Listeners` collection. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\ @@ -19,56 +19,56 @@ Removes a listener from the **Listeners** collection.       [**\**](listeners-element-for-trace.md)\         **\** -## Syntax - -```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**name**|Required attribute.

The name of the listener to remove from the **Listeners** collection.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`listeners`|Specifies a listener that collects, stores, and routes messages. Listeners direct the tracing output to an appropriate target.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`trace`|Configures the ASP.NET trace service.| - -## Remarks - +## Syntax + +```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|**name**|Required attribute.

The name of the listener to remove from the `Listeners` collection.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`listeners`|Specifies a listener that collects, stores, and routes messages. Listeners direct the tracing output to an appropriate target.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`trace`|Configures the ASP.NET trace service.| + +## Remarks + > [!NOTE] -> Removing the from the `Listeners` collection alters the behavior of the , , , and methods. Calling an `Assert` or `Fail` method normally results in the display of a message box, however the message box is not displayed if the is not in the `Listeners` collection. - -## Example - - The following example shows how to remove the default trace listener from the trace **Listeners** collection. - -```xml - - - - - - - - - -``` - +> Removing the from the `Listeners` collection alters the behavior of the , , , and methods. Calling an `Assert` or `Fail` method normally results in the display of a message box, however the message box is not displayed if the is not in the `Listeners` collection. + +## Example + + The following example shows how to remove the default trace listener from the trace `Listeners` collection. + +```xml + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/sharedlisteners-element.md b/docs/framework/configure-apps/file-schema/trace-debug/sharedlisteners-element.md index f68d80f209815..ff5e81a201af4 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/sharedlisteners-element.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/sharedlisteners-element.md @@ -2,10 +2,10 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#sharedListeners" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/sharedListeners" -helpviewer_keywords: +helpviewer_keywords: - " element" - "listeners" - "shared listeners" @@ -13,81 +13,81 @@ helpviewer_keywords: - "sharedListeners element" ms.assetid: de200534-19dd-4156-86cf-c50521802c4c --- -# \ Element - -Contains listeners that any source or trace element can reference. These listeners do not receive any traces by default, and it is not possible to retrieve these listeners at run time. Listeners identified as shared listeners can be added to sources or traces by name. - -[**\**](../configuration-element.md) -  [**\**](system-diagnostics-element.md) -    **\** - -## Syntax - -```xml +# `` Element + +Contains listeners that any source or trace element can reference. These listeners do not receive any traces by default, and it is not possible to retrieve these listeners at run time. Listeners identified as shared listeners can be added to sources or traces by name. + +[**\**](../configuration-element.md) +  [**\**](system-diagnostics-element.md) +    **\** + +## Syntax + +```xml - ... - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](add-element-for-listeners-for-trace.md)|Adds a listener to the `sharedListeners` collection.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`Configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies the root element for the ASP.NET configuration section.| - -## Remarks - - Adding a listener to the shared listeners collection does not make it an active listener. It must still be added to a trace source or a trace by adding it to the `Listeners` collection for that trace element. The listener classes in the .NET Framework derive from the class. - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use the `` element to add the listener `console` to the `Listeners` collection for both the and classes. The console trace listener writes trace information to the console through calls to either or . - -```xml - - - - - - - - - - - - - - - - - - - - - - - + ... + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](add-element-for-listeners-for-trace.md)|Adds a listener to the `sharedListeners` collection.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`Configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies the root element for the ASP.NET configuration section.| + +## Remarks + + Adding a listener to the shared listeners collection does not make it an active listener. It must still be added to a trace source or a trace by adding it to the `Listeners` collection for that trace element. The listener classes in the .NET Framework derive from the class. + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use the `` element to add the listener `console` to the `Listeners` collection for both the and classes. The console trace listener writes trace information to the console through calls to either or . + +```xml + + + + + + + + + + + + + + + + + + + + + + + -``` - +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/source-element.md b/docs/framework/configure-apps/file-schema/trace-debug/source-element.md index 97d84714ef55d..f61d5f89eef95 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/source-element.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/source-element.md @@ -2,85 +2,85 @@ description: "Learn more about: Element" title: " Element" ms.date: "09/29/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/sources/source" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#source" -helpviewer_keywords: +helpviewer_keywords: - " element" - "source element" --- -# \ Element +# `` Element -Specifies a trace source that initiates tracing messages. +Specifies a trace source that initiates tracing messages. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\     [**\**](sources-element.md)\       **\** -## Syntax - -```xml +## Syntax + +```xml - ... - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`name`|Optional attribute.

Specifies the name of the trace source.| -|`switchName`|Optional attribute.

Specifies the name of a trace switch instance in the application. If the switch is not identified in a `` element, the value specifies the level for the switch.| -|`switchType`|Optional attribute.

Specifies the type of the trace switch. If present, the type must be a valid class name and cannot be an empty string.| -|`extraAttribute`|Optional attribute.

Specifies the value for a trace source-specific attribute identified by the method for that trace source.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](listeners-element-for-source.md)|Contains listeners that collect, store, and route messages.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| -|`sources`|Contains trace sources that initiate tracing messages.| - -## Remarks - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use the `` element to add the trace source `mySource` and to set the level for the source switch named `sourceSwitch`. A console trace listener is added that writes trace information to the console. - -```xml - - - - - - - - - - - - - - + ... + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`name`|Optional attribute.

Specifies the name of the trace source.| +|`switchName`|Optional attribute.

Specifies the name of a trace switch instance in the application. If the switch is not identified in a `` element, the value specifies the level for the switch.| +|`switchType`|Optional attribute.

Specifies the type of the trace switch. If present, the type must be a valid class name and cannot be an empty string.| +|`extraAttribute`|Optional attribute.

Specifies the value for a trace source-specific attribute identified by the method for that trace source.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](listeners-element-for-source.md)|Contains listeners that collect, store, and route messages.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| +|`sources`|Contains trace sources that initiate tracing messages.| + +## Remarks + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use the `` element to add the trace source `mySource` and to set the level for the source switch named `sourceSwitch`. A console trace listener is added that writes trace information to the console. + +```xml + + + + + + + + + + + + + + - -``` - +
+``` + ## See also - [Trace and Debug Settings Schema](index.md) diff --git a/docs/framework/configure-apps/file-schema/trace-debug/sources-element.md b/docs/framework/configure-apps/file-schema/trace-debug/sources-element.md index 8672bb7886d82..134d7361e7e11 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/sources-element.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/sources-element.md @@ -2,83 +2,83 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/sources" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#sources" -helpviewer_keywords: +helpviewer_keywords: - "sources element" - "trace sources" - " element" ms.assetid: c727b2e2-423a-4463-a223-013f40ff16a3 --- -# \ Element +# `` Element -Specifies trace sources that initiate tracing messages. +Specifies trace sources that initiate tracing messages. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\     **\** -## Syntax - -```xml - - ... - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](source-element.md)|Required element.

Specifies a trace source that initiates tracing messages.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| - -## Remarks - - This element can be used in the machine configuration file (Machine.config) and the application configuration file. - -## Example - - The following example shows how to use the `` element to add the trace source `mySource` and to set the level for the source switch named `sourceSwitch`. A console trace listener is added that writes trace information to the console. - -```xml - - - +## Syntax + +```xml + + ... + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](source-element.md)|Required element.

Specifies a trace source that initiates tracing messages.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| + +## Remarks + + This element can be used in the machine configuration file (Machine.config) and the application configuration file. + +## Example + + The following example shows how to use the `` element to add the trace source `mySource` and to set the level for the source switch named `sourceSwitch`. A console trace listener is added that writes trace information to the console. + +```xml + + + - + switchType="System.Diagnostics.SourceSwitch" > + + type="System.Diagnostics.ConsoleTraceListener" > - - - - - - - + initializeData="Error" /> + + +
+ +
+ +
-
-``` - +
+``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/switches-element.md b/docs/framework/configure-apps/file-schema/trace-debug/switches-element.md index 2ac122cb27b30..335960a29a657 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/switches-element.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/switches-element.md @@ -2,70 +2,70 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/switches" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#switches" -helpviewer_keywords: +helpviewer_keywords: - " element" - "switches element" - "trace switches, element" ms.assetid: 4cf36786-b89a-40e2-a0f1-86bb9b783343 --- -# \ Element +# `` Element -Contains trace switches and the level where the trace switches are set. +Contains trace switches and the level where the trace switches are set. [**\**](../configuration-element.md)\   [**\**](system-diagnostics-element.md)\     **\** -## Syntax - -```xml +## Syntax + +```xml + + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](add-element-for-switches.md)|Specifies the level where a trace switch is set.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`System.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| + +## Remarks + + You can change the level of a trace switch by putting it in a configuration file. If the switch is a , you can turn it on and off. If the switch is a , you can assign different levels to it to specify the types of trace or debug messages the application outputs. + +## Example + + The following example shows how to use the `` element to set the `General` trace switch to the level, and enable the `Data` Boolean trace switch. + +```xml + + - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](add-element-for-switches.md)|Specifies the level where a trace switch is set.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`System.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| - -## Remarks - - You can change the level of a trace switch by putting it in a configuration file. If the switch is a , you can turn it on and off. If the switch is a , you can assign different levels to it to specify the types of trace or debug messages the application outputs. - -## Example - - The following example shows how to use the **\** element to set the `General` trace switch to the level, and enable the `Data` Boolean trace switch. - -```xml - - - - - - - - -``` - + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/system-diagnostics-element.md b/docs/framework/configure-apps/file-schema/trace-debug/system-diagnostics-element.md index 5e96b96ab80ba..2af3adc022796 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/system-diagnostics-element.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/system-diagnostics-element.md @@ -2,75 +2,75 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#system.diagnostics" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics" -helpviewer_keywords: +helpviewer_keywords: - " element" - "system.diagnostics element" ms.assetid: 3f348f42-fa72-4ff2-aa1c-bb9eecad4bb2 --- -# \ Element - -Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set. - -[**\**](../configuration-element.md) -  **\** - -## Syntax - -```xml +# `` Element + +Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set. + +[**\**](../configuration-element.md) +  **\** + +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](assert-element.md)|Specifies whether to display a message box when you call the method; also specifies the name of the file to write messages to.| -|[\](performancecounters-element.md)|Specifies the size of the global memory shared by performance counters.| -|[\](sharedlisteners-element.md)|Contains listeners that any source or trace element can reference. Listeners identified as shared listeners can be added to sources or traces by name.| -|[\](sources-element.md)|Specifies trace sources that initiate tracing messages.| -|[\](switches-element.md)|Contains trace switches and the levels where the trace switches are set.| -|[\](trace-element.md)|Contains listeners that collect, store, and route tracing messages.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| - -## Example - - The following example shows how to embed a trace switch and a trace listener inside the **\** element. The `General` trace switch is set to the level. The trace listener `myListener` creates a file called `MyListener.log` and writes the output to the file. - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](assert-element.md)|Specifies whether to display a message box when you call the method; also specifies the name of the file to write messages to.| +|[\](performancecounters-element.md)|Specifies the size of the global memory shared by performance counters.| +|[\](sharedlisteners-element.md)|Contains listeners that any source or trace element can reference. Listeners identified as shared listeners can be added to sources or traces by name.| +|[\](sources-element.md)|Specifies trace sources that initiate tracing messages.| +|[\](switches-element.md)|Contains trace switches and the levels where the trace switches are set.| +|[\](trace-element.md)|Contains listeners that collect, store, and route tracing messages.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| + +## Example + + The following example shows how to embed a trace switch and a trace listener inside the `` element. The `General` trace switch is set to the level. The trace listener `myListener` creates a file called `MyListener.log` and writes the output to the file. + > [!NOTE] -> In .NET Framework version 2.0, you can use text to specify the value for a switch. For example, you can specify `true` for a or use the text representing an enumeration value such as `Error` for a . The line `` is equivalent to ``. - -```xml - - - - - - - - - - - - -``` - +> In .NET Framework version 2.0, you can use text to specify the value for a switch. For example, you can specify `true` for a or use the text representing an enumeration value such as `Error` for a . The line `` is equivalent to ``. + +```xml + + + + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/trace-debug/trace-element.md b/docs/framework/configure-apps/file-schema/trace-debug/trace-element.md index 6b64fcc662a31..0006bfd6a867c 100644 --- a/docs/framework/configure-apps/file-schema/trace-debug/trace-element.md +++ b/docs/framework/configure-apps/file-schema/trace-debug/trace-element.md @@ -2,87 +2,87 @@ description: "Learn more about: Element" title: " Element" ms.date: "03/30/2017" -f1_keywords: +f1_keywords: - "http://schemas.microsoft.com/.NetConfiguration/v2.0#configuration/system.diagnostics/trace" - "http://schemas.microsoft.com/.NetConfiguration/v2.0#trace" -helpviewer_keywords: +helpviewer_keywords: - " element" - "listeners" - "trace element" - "trace listener, element" ms.assetid: 7931c942-63c1-47c3-a045-9d9de3cacdbf --- -# \ Element - -Contains listeners that collect, store, and route tracing messages. - -[**\**](../configuration-element.md) -  [**\**](system-diagnostics-element.md) -    **\** - -## Syntax - -```xml +# `` Element + +Contains listeners that collect, store, and route tracing messages. + +[**\**](../configuration-element.md) +  [**\**](system-diagnostics-element.md) +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`autoflush`|Optional attribute.

Specifies whether the trace listeners automatically flush the output buffer after every write operation.| -|`indentsize`|Optional attribute.

Specifies the number of spaces to indent.| -|`useGlobalLock`|Optional attribute.

Indicates whether the global lock should be used.| - -## autoflush Attribute - -|Value|Description| -|-----------|-----------------| -|`false`|Does not automatically flush the output buffer. This is the default.| -|`true`|Automatically flushes the output buffer.| - -## useGlobalLock Attribute - -|Value|Description| -|-----------|-----------------| -|`false`|Does not use the global lock if the listener is thread safe; otherwise, uses the global lock.| -|`true`|Uses the global lock regardless of whether the listener is thread safe. This is the default.| - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](listeners-element-for-trace.md)|Specifies a listener that collects, stores, and routes messages.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| -|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| - -## Example - - The following example shows how to use the `` element to add the listener `MyListener` to the `Listeners` collection. `MyListener` creates a file that is named `MyListener.log` and writes the output to the file. The `useGlobalLock` attribute is set to `false`, which causes the global lock not to be used if the trace listener is thread safe. The `autoflush` attribute is set to `true`, which causes the trace listener to write to the file regardless of whether the method is called. The `indentsize` attribute is set to 0 (zero), which causes the listener to indent zero spaces when the method is called. - -```xml - - - - - - - - - -``` - + indentsize="indent value" + useGlobalLock="true| false"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`autoflush`|Optional attribute.

Specifies whether the trace listeners automatically flush the output buffer after every write operation.| +|`indentsize`|Optional attribute.

Specifies the number of spaces to indent.| +|`useGlobalLock`|Optional attribute.

Indicates whether the global lock should be used.| + +## autoflush Attribute + +|Value|Description| +|-----------|-----------------| +|`false`|Does not automatically flush the output buffer. This is the default.| +|`true`|Automatically flushes the output buffer.| + +## useGlobalLock Attribute + +|Value|Description| +|-----------|-----------------| +|`false`|Does not use the global lock if the listener is thread safe; otherwise, uses the global lock.| +|`true`|Uses the global lock regardless of whether the listener is thread safe. This is the default.| + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](listeners-element-for-trace.md)|Specifies a listener that collects, stores, and routes messages.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|`configuration`|The root element in every configuration file used by the common language runtime and .NET Framework applications.| +|`system.diagnostics`|Specifies trace listeners that collect, store, and route messages and the level where a trace switch is set.| + +## Example + + The following example shows how to use the `` element to add the listener `MyListener` to the `Listeners` collection. `MyListener` creates a file that is named `MyListener.log` and writes the output to the file. The `useGlobalLock` attribute is set to `false`, which causes the global lock not to be used if the trace listener is thread safe. The `autoflush` attribute is set to `true`, which causes the trace listener to write to the file regardless of whether the method is called. The `indentsize` attribute is set to 0 (zero), which causes the listener to indent zero spaces when the method is called. + +```xml + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/web/applicationpool-element-web-settings.md b/docs/framework/configure-apps/file-schema/web/applicationpool-element-web-settings.md index e771ca269d078..5efe02a0a8979 100644 --- a/docs/framework/configure-apps/file-schema/web/applicationpool-element-web-settings.md +++ b/docs/framework/configure-apps/file-schema/web/applicationpool-element-web-settings.md @@ -2,89 +2,89 @@ description: "Learn more about: Element (Web Settings)" title: " Element (Web Settings)" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "applicationPool element" - " element" ms.assetid: 46d1baaa-e343-4639-b70d-2a43a9f62b2a --- -# \ Element (Web Settings) +# `` Element (Web Settings) + +Specifies configuration settings that are used by ASP.NET to manage process-wide behavior when an ASP.NET application is running in Integrated mode on IIS 7.0 or a later version. -Specifies configuration settings that are used by ASP.NET to manage process-wide behavior when an ASP.NET application is running in Integrated mode on IIS 7.0 or a later version. - > [!IMPORTANT] -> This element and the feature it supports only work if your ASP.NET application is hosted on IIS 7.0 or later versions. - -[**\**](../configuration-element.md) -  [**\**](system-web-element-web-settings.md) -    **\** - -## Syntax - -```xml +> This element and the feature it supports only work if your ASP.NET application is hosted on IIS 7.0 or later versions. + +[**\**](../configuration-element.md) +  [**\**](system-web-element-web-settings.md) +    **\** + +## Syntax + +```xml -``` - -## Attributes and Elements - -The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|`maxConcurrentRequestsPerCPU`|Specifies how many simultaneous requests ASP.NET allows per CPU.| -|`maxConcurrentThreadsPerCPU`|Specifies how many simultaneous threads can be running for an application pool for each CPU. This provides an alternative way to control ASP.NET concurrency, because you can limit the number of managed threads that can be used per CPU to serve requests. By default this setting is 0, which means that ASP.NET does not limit the number of threads that can be created per CPU, although the CLR thread pool also limits the number of threads that can be created.| -|`requestQueueLimit`|Specifies the maximum number of requests that can be queued for ASP.NET in a single process. When two or more ASP.NET applications run in a single application pool, the cumulative set of requests being made to any application in the application pool is subject to this setting.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](system-web-element-web-settings.md)|Contains information about how ASP.NET interacts with a host application.| - -## Remarks - -When you run IIS 7.0 or a later version in Integrated mode, this element combination lets you configure how ASP.NET manages threads and queues requests when the application is hosted in an IIS application pool. If you run IIS 6 or you run IIS 7.0 in Classic mode or in ISAPI mode, these settings are ignored. - -The `applicationPool` settings apply to all application pools that run on a particular version of the .NET Framework. The settings are contained in an aspnet.config file. There is a version of this file for versions 2.0 and 4.0 of the .NET Framework. (Versions 3.0 and 3.5 of the .NET Framework share the aspnet.config file with version 2.0.) - + requestQueueLimit="5000" /> +``` + +## Attributes and Elements + +The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|`maxConcurrentRequestsPerCPU`|Specifies how many simultaneous requests ASP.NET allows per CPU.| +|`maxConcurrentThreadsPerCPU`|Specifies how many simultaneous threads can be running for an application pool for each CPU. This provides an alternative way to control ASP.NET concurrency, because you can limit the number of managed threads that can be used per CPU to serve requests. By default this setting is 0, which means that ASP.NET does not limit the number of threads that can be created per CPU, although the CLR thread pool also limits the number of threads that can be created.| +|`requestQueueLimit`|Specifies the maximum number of requests that can be queued for ASP.NET in a single process. When two or more ASP.NET applications run in a single application pool, the cumulative set of requests being made to any application in the application pool is subject to this setting.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](system-web-element-web-settings.md)|Contains information about how ASP.NET interacts with a host application.| + +## Remarks + +When you run IIS 7.0 or a later version in Integrated mode, this element combination lets you configure how ASP.NET manages threads and queues requests when the application is hosted in an IIS application pool. If you run IIS 6 or you run IIS 7.0 in Classic mode or in ISAPI mode, these settings are ignored. + +The `applicationPool` settings apply to all application pools that run on a particular version of the .NET Framework. The settings are contained in an aspnet.config file. There is a version of this file for versions 2.0 and 4.0 of the .NET Framework. (Versions 3.0 and 3.5 of the .NET Framework share the aspnet.config file with version 2.0.) + > [!IMPORTANT] -> If you run IIS 7.0 on Windows 7, you can configure a separate aspnet.config file for every application pool. This lets you tailor the performance of the threads for each application pool. - -For the `maxConcurrentRequestsPerCPU` setting, the default setting of "5000" in the .NET Framework 4 effectively turns off request throttling that is controlled by ASP.NET, unless you actually have 5000 or more requests per CPU. The default setting depends instead on the CLR thread-pool to automatically manage concurrency per CPU. Applications that make extensive use of asynchronous request processing, or that have many long-running requests blocked on network I/O, will benefit from the increased default limit in the .NET Framework 4. Setting `maxConcurrentRequestsPerCPU` to zero turns off the use of managed threads for processing ASP.NET requests. When an application runs in an IIS application pool, requests stay on the IIS I/O thread and therefore concurrency is throttled by IIS thread settings. - -The `requestQueueLimit` setting works the same way as the `requestQueueLimit` attribute of the [processModel](/previous-versions/dotnet/netframework-4.0/7w2sway1(v=vs.100)) element, which is set in the Web.config files for ASP.NET applications. However, the `requestQueueLimit` setting in an aspnet.config file overrides the `requestQueueLimit` setting in a Web.config file. In other words, if both attributes are set (by default, this is true), the `requestQueueLimit` setting in the aspnet.config file takes precedence. - -## Example - -The following example shows how to configure ASP.NET process-wide behavior in the aspnet.config file in the following circumstances: - -- The application is hosted in an IIS 7.0 application pool. - -- IIS 7.0 is running in Integrated mode. - -- The application is using the .NET Framework 3.5 SP1 or a later version. - -The values in the example are the default values. - -```xml - - +> If you run IIS 7.0 on Windows 7, you can configure a separate aspnet.config file for every application pool. This lets you tailor the performance of the threads for each application pool. + +For the `maxConcurrentRequestsPerCPU` setting, the default setting of "5000" in the .NET Framework 4 effectively turns off request throttling that is controlled by ASP.NET, unless you actually have 5000 or more requests per CPU. The default setting depends instead on the CLR thread-pool to automatically manage concurrency per CPU. Applications that make extensive use of asynchronous request processing, or that have many long-running requests blocked on network I/O, will benefit from the increased default limit in the .NET Framework 4. Setting `maxConcurrentRequestsPerCPU` to zero turns off the use of managed threads for processing ASP.NET requests. When an application runs in an IIS application pool, requests stay on the IIS I/O thread and therefore concurrency is throttled by IIS thread settings. + +The `requestQueueLimit` setting works the same way as the `requestQueueLimit` attribute of the [processModel](/previous-versions/dotnet/netframework-4.0/7w2sway1(v=vs.100)) element, which is set in the Web.config files for ASP.NET applications. However, the `requestQueueLimit` setting in an aspnet.config file overrides the `requestQueueLimit` setting in a Web.config file. In other words, if both attributes are set (by default, this is true), the `requestQueueLimit` setting in the aspnet.config file takes precedence. + +## Example + +The following example shows how to configure ASP.NET process-wide behavior in the aspnet.config file in the following circumstances: + +- The application is hosted in an IIS 7.0 application pool. + +- IIS 7.0 is running in Integrated mode. + +- The application is using the .NET Framework 3.5 SP1 or a later version. + +The values in the example are the default values. + +```xml + + - - + requestQueueLimit="5000" /> + + ``` - + ## See also -- [\ Element (Web Settings)](system-web-element-web-settings.md) +- [`` Element (Web Settings)](system-web-element-web-settings.md) diff --git a/docs/framework/configure-apps/file-schema/web/system-web-element-web-settings.md b/docs/framework/configure-apps/file-schema/web/system-web-element-web-settings.md index 159724ac5df32..e70df1eb7f5da 100644 --- a/docs/framework/configure-apps/file-schema/web/system-web-element-web-settings.md +++ b/docs/framework/configure-apps/file-schema/web/system-web-element-web-settings.md @@ -2,7 +2,7 @@ description: "Learn more about: Element (Web Settings)" title: " Element (Web Settings)" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "Web.config configuration file [ASP.NET]" - "system.Web element" - " element" @@ -10,59 +10,59 @@ helpviewer_keywords: - "configuration files [ASP.NET]" ms.assetid: 24c4cf4f-ad32-42b2-b040-8e4549e2855e --- -# \ Element (Web Settings) - -Contains information about how the ASP.NET hosting layer manages process-wide behavior. - -[**\**](../configuration-element.md) -  **\** - -## Syntax - -```xml - - -``` - -## Attributes and Elements - -The following sections describe attributes, child elements, and parent elements. - -### Attributes - -None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](applicationpool-element-web-settings.md)|Specifies configuration settings for IIS application pools in an aspnet.config file.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](../configuration-element.md)|Specifies the root element in every configuration file that is used by the common language runtime and .NET Framework applications.| - -## Remarks - -The `system.web` element and its child `applicationPool` element were added to the .NET Framework as of .NET Framework 3.5 SP1. When you run IIS 7.0 or later versions in Integrated mode, this element combination lets you configure how ASP.NET manages threads and how it queues requests when ASP.NET is hosted in an IIS application pool. If you run IIS 7.0 or later versions in Classic or ISAPI mode, these settings are ignored. - -## Example - -The following example shows how to configure ASP.NET process-wide behavior in the aspnet.config file when ASP.NET is hosted in an IIS application pool. The example assumes that IIS is running in Integrated mode and that the application is using the .NET Framework 3.5 SP1 or a later version. This behavior does not occur in versions of the .NET Framework earlier than the .NET Framework 3.5 SP1. The values in the example are the default values. - -```xml - - +# `` Element (Web Settings) + +Contains information about how the ASP.NET hosting layer manages process-wide behavior. + +[**\**](../configuration-element.md) +  **\** + +## Syntax + +```xml + + +``` + +## Attributes and Elements + +The following sections describe attributes, child elements, and parent elements. + +### Attributes + +None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](applicationpool-element-web-settings.md)|Specifies configuration settings for IIS application pools in an aspnet.config file.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](../configuration-element.md)|Specifies the root element in every configuration file that is used by the common language runtime and .NET Framework applications.| + +## Remarks + +The `system.web` element and its child `applicationPool` element were added to the .NET Framework as of .NET Framework 3.5 SP1. When you run IIS 7.0 or later versions in Integrated mode, this element combination lets you configure how ASP.NET manages threads and how it queues requests when ASP.NET is hosted in an IIS application pool. If you run IIS 7.0 or later versions in Classic or ISAPI mode, these settings are ignored. + +## Example + +The following example shows how to configure ASP.NET process-wide behavior in the aspnet.config file when ASP.NET is hosted in an IIS application pool. The example assumes that IIS is running in Integrated mode and that the application is using the .NET Framework 3.5 SP1 or a later version. This behavior does not occur in versions of the .NET Framework earlier than the .NET Framework 3.5 SP1. The values in the example are the default values. + +```xml + + - - + requestQueueLimit="5000" /> + + ``` - + ## See also -- [\ Element (Web Settings)](applicationpool-element-web-settings.md) +- [`` Element (Web Settings)](applicationpool-element-web-settings.md) diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/activityscheduledqueries.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/activityscheduledqueries.md index a94faa2a69d1d..4da9634caf1ff 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/activityscheduledqueries.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/activityscheduledqueries.md @@ -6,20 +6,20 @@ ms.assetid: ca6e82f1-54f2-48d6-899c-9873065b5547 --- # \ -Represents a collection of queries that are used to track an activity scheduled for execution by a parent activity. The query is necessary for a tracking participant to subscribe to activity scheduled records. - - For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md) - +Represents a collection of queries that are used to track an activity scheduled for execution by a parent activity. The query is necessary for a tracking participant to subscribe to activity scheduled records. + + For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md) + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\       [**\**](trackingprofile.md)\         [**\**](workflow.md)\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml @@ -29,29 +29,29 @@ Represents a collection of queries that are used to track an activity scheduled - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](activityscheduledquery.md)|A query that is used to track an activity scheduled for execution by a parent activity.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the **activityDefinitionId** property.| - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](activityscheduledquery.md)|A query that is used to track an activity scheduled for execution by a parent activity.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the `activityDefinitionId` property.| + ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/activitystatequeries.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/activitystatequeries.md index 218371b0151ad..c4443ede45a28 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/activitystatequeries.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/activitystatequeries.md @@ -6,19 +6,19 @@ ms.assetid: bdd3c8ae-a13f-4df1-9b3c-a9d6c4bb1b5f --- # \ -Represents a collection of queries that are used to track life cycle changes of the activities that make up a workflow instance. For example, you may want to keep track of every time the "Send E-Mail" activity completes within a workflow instance. This query is necessary for a tracking participant to subscribe to activity state record objects. The available states to subscribe to are specified in ActivityStates. - - For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). - +Represents a collection of queries that are used to track life cycle changes of the activities that make up a workflow instance. For example, you may want to keep track of every time the "Send E-Mail" activity completes within a workflow instance. This query is necessary for a tracking participant to subscribe to activity state record objects. The available states to subscribe to are specified in ActivityStates. + + For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\       [**\**](trackingprofile.md)\         [**\**](workflow.md)\ -          **\** - -## Syntax - +          **\** + +## Syntax + ```xml @@ -37,29 +37,29 @@ Represents a collection of queries that are used to track life cycle changes of - -``` - -## Attributes and Elements + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](activitystatequery.md)|A query that is used to track the handling of faults that occur within an activity. This event occurs each time a FaultHandler processes a fault.| + +### Parent Elements - The following sections describe attributes, child elements, and parent elements. - -### Attributes +|Element|Description| +|-------------|-----------------| +|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the `activityDefinitionId` property.| - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](activitystatequery.md)|A query that is used to track the handling of faults that occur within an activity. This event occurs each time a FaultHandler processes a fault.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the **activityDefinitionId** property.| - ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/add-of-participants.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/add-of-participants.md index f8d2fe3b0cb13..99d8be1ac942f 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/add-of-participants.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/add-of-participants.md @@ -6,63 +6,63 @@ ms.assetid: 3c730850-6f8e-4102-acb8-8effb4e09463 --- # \ of \ -Configure a tracking participant that listens to the tracking records being emitted from the runtime directly and process them in whatever way it was configured. This includes writing to a specific output (e.g., file, Console, ETW), processing/aggregating the records, or any other combination that might be required. - - For more information in workflow tracking and tracking participants, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Tracking Participants](../../../windows-workflow-foundation/tracking-participants.md). - +Configure a tracking participant that listens to the tracking records being emitted from the runtime directly and process them in whatever way it was configured. This includes writing to a specific output (e.g., file, Console, ETW), processing/aggregating the records, or any other combination that might be required. + + For more information in workflow tracking and tracking participants, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Tracking Participants](../../../windows-workflow-foundation/tracking-participants.md). + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\       [**\**](participants.md)\ -        **\** - -## Syntax - +        **\** + +## Syntax + ```xml -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Element|Description| -|-------------|-----------------| -|name|A string that specifies the name of a tracking participant.| -|profileName|A string that specifies the name of the tracking profile which defines the tracking records the tracking participant has subscribed to.| -|type|A string that specifies the type of a tracking participant.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](participants.md)|A list of tracking participants| - -## Remarks - - Tracking participants are used to get the tracking data emitted from the workflow and store it into different mediums. Likewise, any post processing on the tracking Records can also be done within the tracking participant. - - Multiple tracking participants can consume the tracking events simultaneously. Each tracking participant can be associated with a different tracking profile. - - A standard tracking participant is provided which writes the tracking records to an ETW session. The participant is configured on a workflow service by adding a tracking-specific behavior in a configuration file. Enabling an ETW tracking participant allows tracking records to be viewed in the event viewer. If that does not meet your requirements, you can also write a custom tracking participant. - -## Example - - The following configuration example shows the standard ETW tracking participant being configured in the Web.config file. - - The Provider Id that the ETW Tracking Participant uses for writing the Tracking Records to ETW is defined in the **\** section. The tracking participant has a profile associated with it to specify the tracking records it has subscribed to. This is defined by the **profileName** attribute of the **\** element. Once these are defined, the Tracking Participant is added to the **\** service behavior. This will add the selected Tracking Participants to the Workflow instance’s extensions, so that they begin to receive the Tracking Records. - -```xml +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Element|Description| +|-------------|-----------------| +|name|A string that specifies the name of a tracking participant.| +|profileName|A string that specifies the name of the tracking profile which defines the tracking records the tracking participant has subscribed to.| +|type|A string that specifies the type of a tracking participant.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](participants.md)|A list of tracking participants| + +## Remarks + + Tracking participants are used to get the tracking data emitted from the workflow and store it into different mediums. Likewise, any post processing on the tracking Records can also be done within the tracking participant. + + Multiple tracking participants can consume the tracking events simultaneously. Each tracking participant can be associated with a different tracking profile. + + A standard tracking participant is provided which writes the tracking records to an ETW session. The participant is configured on a workflow service by adding a tracking-specific behavior in a configuration file. Enabling an ETW tracking participant allows tracking records to be viewed in the event viewer. If that does not meet your requirements, you can also write a custom tracking participant. + +## Example + + The following configuration example shows the standard ETW tracking participant being configured in the Web.config file. + + The Provider Id that the ETW Tracking Participant uses for writing the Tracking Records to ETW is defined in the **\** section. The tracking participant has a profile associated with it to specify the tracking records it has subscribed to. This is defined by the `profileName` attribute of the **\** element. Once these are defined, the Tracking Participant is added to the **\** service behavior. This will add the selected Tracking Participants to the Workflow instance’s extensions, so that they begin to receive the Tracking Records. + +```xml @@ -79,14 +79,14 @@ Configure a tracking participant that listens to the tracking records being emit - + - -``` - + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/behaviors-of-workflow.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/behaviors-of-workflow.md index 4e9f05d1cf97d..c818fdeb1340b 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/behaviors-of-workflow.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/behaviors-of-workflow.md @@ -6,41 +6,41 @@ ms.assetid: 3c6017b6-0c4f-4192-bd67-9515f5d1ec82 --- # \ of workflow -This element contains the **serviceBehaviors** collection. Each element in the collection defines behavior elements consumed by workflow services. Each behavior element is identified by its unique **name** attribute. - +This element contains the `serviceBehaviors` collection. Each element in the collection defines behavior elements consumed by workflow services. Each behavior element is identified by its unique `name` attribute. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\ -    **\** - -## Syntax - -```xml - - - - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](servicebehaviors-of-workflow.md)|This configuration section represents all the behaviors defined for a specific workflow service.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](../wcf/system-servicemodel.md)|The root element of all workflow configuration elements.| - +    **\** + +## Syntax + +```xml + + + + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](servicebehaviors-of-workflow.md)|This configuration section represents all the behaviors defined for a specific workflow service.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](../wcf/system-servicemodel.md)|The root element of all workflow configuration elements.| + ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/bookmarkresumptionqueries.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/bookmarkresumptionqueries.md index 277b14a37b9d6..aa00c25f0155f 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/bookmarkresumptionqueries.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/bookmarkresumptionqueries.md @@ -6,20 +6,20 @@ ms.assetid: 8ed61a7f-4254-439c-bdd8-b474971533f7 --- # \ -Represents a collection of queries that are used to track resumption of a bookmark within a workflow instance. The query is necessary for a tracking participant to subscribe to bookmark resumption records. - - For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md) - +Represents a collection of queries that are used to track resumption of a bookmark within a workflow instance. The query is necessary for a tracking participant to subscribe to bookmark resumption records. + + For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md) + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\       [**\**](trackingprofile.md)\         [**\**](workflow.md)\ -          **\** +          **\** + +## Syntax -## Syntax - -```xml +```xml @@ -28,29 +28,29 @@ Represents a collection of queries that are used to track resumption of a bookma - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](bookmarkresumptionquery.md)|A query that is used to track resumption of a bookmark within a workflow instance. The query is necessary for a tracking participant to subscribe to bookmark resumption records.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the **activityDefinitionId** property.| - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](bookmarkresumptionquery.md)|A query that is used to track resumption of a bookmark within a workflow instance. The query is necessary for a tracking participant to subscribe to bookmark resumption records.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the `activityDefinitionId` property.| + ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/cancelrequestedqueries.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/cancelrequestedqueries.md index 38ff7bc77b7aa..39f8da884691d 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/cancelrequestedqueries.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/cancelrequestedqueries.md @@ -6,20 +6,20 @@ ms.assetid: eab5af7e-76fa-434d-9d36-873e995cee05 --- # \ -Represents a collection of queries that are used to track requests to cancel a child activity by the parent activity. The query is necessary for a tracking participant to subscribe to cancel request record objects. - - For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md) - +Represents a collection of queries that are used to track requests to cancel a child activity by the parent activity. The query is necessary for a tracking participant to subscribe to cancel request record objects. + + For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md) + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\       [**\**](trackingprofile.md)\         [**\**](workflow.md)\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml @@ -29,29 +29,29 @@ Represents a collection of queries that are used to track requests to cancel a c - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](cancelrequestedquery.md)|A query that is used to track requests to cancel a child activity by the parent activity| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the **activityDefinitionId** property.| - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](cancelrequestedquery.md)|A query that is used to track requests to cancel a child activity by the parent activity| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the `activityDefinitionId` property.| + ## See also - [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/customtrackingqueries.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/customtrackingqueries.md index be25809c2025c..78bf061b61c5f 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/customtrackingqueries.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/customtrackingqueries.md @@ -6,20 +6,20 @@ ms.assetid: 4e9e732d-911d-45a3-a569-4b5e9cd1ffbe --- # \ -Represents a collection of queries that are used to track events that you define in your code activities. The query is necessary for a tracking participant to subscribe to custom tracking records. - - For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md) - +Represents a collection of queries that are used to track events that you define in your code activities. The query is necessary for a tracking participant to subscribe to custom tracking records. + + For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md) + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\       [**\**](trackingprofile.md)\         [**\**](workflow.md)\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml @@ -29,29 +29,29 @@ Represents a collection of queries that are used to track events that you define - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](customtrackingquery.md)|A query that is used to track events that you define in your code activities.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the **activityDefinitionId** property.| - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](customtrackingquery.md)|A query that is used to track events that you define in your code activities.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the `activityDefinitionId` property.| + ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/etwtracking.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/etwtracking.md index e4d88384c2190..27a626021ed18 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/etwtracking.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/etwtracking.md @@ -6,60 +6,60 @@ ms.assetid: cb45c82e-6ea1-4c4d-924c-118a25ae1f35 --- # \ -A service behavior that allows a service to utilize ETW tracking using an . - +A service behavior that allows a service to utilize ETW tracking using an . + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](behaviors-of-workflow.md)\       [**\**](servicebehaviors-of-workflow.md)\         [**\**](behavior-of-servicebehaviors-of-workflow.md)\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|profileName|A string that specifies the name of the tracking profile associated with this behavior.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\ of \](behavior-of-servicebehaviors-of-workflow.md)|Specifies a behavior element.| - -## Remarks - - When added to the service’s behavior configuration, this configuration element configures a tracking participant on a workflow service. - - Tracking participants are used to get the tracking data emitted from the workflow and store it into different mediums. Likewise, any post processing on the tracking Records can also be done within the tracking participant. - -## Example - - The following configuration example shows the standard ETW tracking participant being configured in the Web.config file. - - The Provider Id that the ETW Tracking Participant uses for writing the Tracking Records to ETW is defined in the **\** section. The tracking participant has a profile associated with it to specify the tracking records it has subscribed to. This is defined by the **profileName** attribute of the **\** element. Once these are defined, the Tracking Participant is added to the **\** service behavior. This will add the selected Tracking Participants to the Workflow instance’s extensions, so that they begin to receive the Tracking Records. - -```xml + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|profileName|A string that specifies the name of the tracking profile associated with this behavior.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\ of \](behavior-of-servicebehaviors-of-workflow.md)|Specifies a behavior element.| + +## Remarks + + When added to the service’s behavior configuration, this configuration element configures a tracking participant on a workflow service. + + Tracking participants are used to get the tracking data emitted from the workflow and store it into different mediums. Likewise, any post processing on the tracking Records can also be done within the tracking participant. + +## Example + + The following configuration example shows the standard ETW tracking participant being configured in the Web.config file. + + The Provider Id that the ETW Tracking Participant uses for writing the Tracking Records to ETW is defined in the **\** section. The tracking participant has a profile associated with it to specify the tracking records it has subscribed to. This is defined by the `profileName` attribute of the **\** element. Once these are defined, the Tracking Participant is added to the **\** service behavior. This will add the selected Tracking Participants to the Workflow instance’s extensions, so that they begin to receive the Tracking Records. + +```xml @@ -76,14 +76,14 @@ A service behavior that allows a service to utilize ETW tracking using an - + - -``` - + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/faultpropagationqueries.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/faultpropagationqueries.md index 567ff351c4589..e1fc17416db43 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/faultpropagationqueries.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/faultpropagationqueries.md @@ -6,20 +6,20 @@ ms.assetid: 00ff90ae-ebe0-4c85-a93f-61557288d0a3 --- # \ -Represents a collection of queries that are used to track the handling of faults that occur within an activity. This event occurs each time a FaultHandler processes a fault. You should use such query to track the handling of faults that occur within an activity. The query is necessary for a tracking participant to subscribe to fault propagation records. - - For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). - +Represents a collection of queries that are used to track the handling of faults that occur within an activity. This event occurs each time a FaultHandler processes a fault. You should use such query to track the handling of faults that occur within an activity. The query is necessary for a tracking participant to subscribe to fault propagation records. + + For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md). + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\       [**\**](trackingprofile.md)\         [**\**](workflow.md)\           **\** - -## Syntax - -```xml + +## Syntax + +```xml @@ -29,29 +29,29 @@ Represents a collection of queries that are used to track the handling of faults - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](faultpropagationquery.md)|A query that is used to track the handling of faults that occur within an activity. This event occurs each time a FaultHandler processes a fault.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the **activityDefinitionId** property.| - + +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](faultpropagationquery.md)|A query that is used to track the handling of faults that occur within an activity. This event occurs each time a FaultHandler processes a fault.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the `activityDefinitionId` property.| + ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/index.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/index.md index 01de0f2d92232..893754192743c 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/index.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/index.md @@ -6,11 +6,11 @@ ms.assetid: 7ae70357-b150-4342-8f2a-d5eb6f9c6a0d --- # Windows Workflow Foundation Configuration Schema -Windows Workflow Foundation (WF) configuration elements enable you to configure workflow applications. For a workflow application, you can configure among other things, tracking and tracing. For more information about tracking and tracing, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md). For workflow services, you can also use Windows Communication Foundation (WCF) configuration elements. For more details about WCF, see [WCF Configuration Schema](../wcf/index.md). - - Because configuration files are formatted as XML, you must be familiar with XML if you want to manually edit them using a text editor. Otherwise, you may run into issues such as an unfound XML element tag or attribute. This is because XML element tags and attributes are case-sensitive. - -## In This Section +Windows Workflow Foundation (WF) configuration elements enable you to configure workflow applications. For a workflow application, you can configure among other things, tracking and tracing. For more information about tracking and tracing, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md). For workflow services, you can also use Windows Communication Foundation (WCF) configuration elements. For more details about WCF, see [WCF Configuration Schema](../wcf/index.md). - [\](system-servicemodel-of-workflow.md) - Describes the **ServiceModel** element. + Because configuration files are formatted as XML, you must be familiar with XML if you want to manually edit them using a text editor. Otherwise, you may run into issues such as an unfound XML element tag or attribute. This is because XML element tags and attributes are case-sensitive. + +## In This Section + + [\](system-servicemodel-of-workflow.md) + Describes the `ServiceModel` element. diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/microsoft-visualstudio-activities-asr-clientactivitybuilder-ctor.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/microsoft-visualstudio-activities-asr-clientactivitybuilder-ctor.md index 8906a4ecd357c..a7f50991e1d54 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/microsoft-visualstudio-activities-asr-clientactivitybuilder-ctor.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/microsoft-visualstudio-activities-asr-clientactivitybuilder-ctor.md @@ -2,40 +2,40 @@ description: "Learn more about: Microsoft.VisualStudio.Activities.Asr.ClientActivityBuilder..ctor" title: "Microsoft.VisualStudio.Activities.Asr.ClientActivityBuilder..ctor" ms.date: "03/30/2017" -api_name: +api_name: - "Microsoft.VisualStudio.Activities.Asr.ClientActivityBuilder..ctor" -api_location: +api_location: - "Microsoft.VisualStudio.Activities.dll" -api_type: +api_type: - "Assembly" ms.assetid: 6b44b13c-7a23-4df2-8f9f-45e2b1430002 --- # Microsoft.VisualStudio.Activities.Asr.ClientActivityBuilder..ctor -Creates an instance of the [Microsoft.VisualStudio.Activities.Asr.ClientActivityBuilder](microsoft-visualstudio-activities-asr-clientactivitybuilder.md) class. - -## Syntax - -```csharp -public ClientActivityBuilder(OperationDescription operationDescription, string configurationName, string proxyNamespace); -``` - -## Parameters - -## Parameter Values - - *operationDescription* - - Describes the operation to be performed in the workflow activity that is to be generated, including the operation name, return type, and parameter information. The value of this parameter must not be **null**. It should describe a synchronous operation which uses a message contract and takes an argument with one message. If these conditions are not satisfied, the runtime result of using the constructor and the other methods of this class are undefined. - - *configurationName* - - Specifies the endpoint configuration name. The value of this parameter must not be either **null** or empty. If these conditions are not satisfied, the runtime result of using the constructor and the other methods of this class are undefined. - - *proxyNamespace* - - Specifies the service namespace for the operation. The value of this parameter must not be either **null** or empty. If these conditions are not satisfied, the runtime result of using the constructor and the other methods of this class are undefined. - +Creates an instance of the [Microsoft.VisualStudio.Activities.Asr.ClientActivityBuilder](microsoft-visualstudio-activities-asr-clientactivitybuilder.md) class. + +## Syntax + +```csharp +public ClientActivityBuilder(OperationDescription operationDescription, string configurationName, string proxyNamespace); +``` + +## Parameters + +## Parameter Values + + *operationDescription* + + Describes the operation to be performed in the workflow activity that is to be generated, including the operation name, return type, and parameter information. The value of this parameter must not be **null**. It should describe a synchronous operation which uses a message contract and takes an argument with one message. If these conditions are not satisfied, the runtime result of using the constructor and the other methods of this class are undefined. + + *configurationName* + + Specifies the endpoint configuration name. The value of this parameter must not be either `null` or empty. If these conditions are not satisfied, the runtime result of using the constructor and the other methods of this class are undefined. + + *proxyNamespace* + + Specifies the service namespace for the operation. The value of this parameter must not be either `null` or empty. If these conditions are not satisfied, the runtime result of using the constructor and the other methods of this class are undefined. + ## See also - [Microsoft.VisualStudio.Activities.Asr.ClientActivityBuilder](microsoft-visualstudio-activities-asr-clientactivitybuilder.md) diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/participants.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/participants.md index f57860fd1d6df..c21f3923eab90 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/participants.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/participants.md @@ -6,17 +6,17 @@ ms.assetid: 560dd0bb-f9fb-423c-8857-2101a3654b06 --- # \ -Configure a list of tracking participants that listen to the tracking records being emitted from the runtime directly and process them in whatever way they are configured. This includes writing to a specific output (e.g., file, Console, ETW), processing/aggregating the records, or any other combination that might be required. - - For more information in workflow tracking and tracking participants, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Tracking Participants](../../../windows-workflow-foundation/tracking-participants.md). - +Configure a list of tracking participants that listen to the tracking records being emitted from the runtime directly and process them in whatever way they are configured. This includes writing to a specific output (e.g., file, Console, ETW), processing/aggregating the records, or any other combination that might be required. + + For more information in workflow tracking and tracking participants, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Tracking Participants](../../../windows-workflow-foundation/tracking-participants.md). + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\ -      **\** - -## Syntax - +      **\** + +## Syntax + ```xml @@ -25,42 +25,42 @@ Configure a list of tracking participants that listen to the tracking records be type="String" /> -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - - None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](add-of-participants.md)|Contains settings for a tracking participant.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](tracking.md)|Represents a configuration section for defining tracking settings for a workflow service.| - -## Remarks - - Tracking participants are used to get the tracking data emitted from the workflow and store it into different mediums. Likewise, any post processing on the tracking Records can also be done within the tracking participant. - - Multiple tracking participants can consume the tracking events simultaneously. Each tracking participant can be associated with a different tracking profile. - - A standard tracking participant is provided which writes the tracking records to an ETW session. The participant is configured on a workflow service by adding a tracking-specific behavior in a configuration file. Enabling an ETW tracking participant allows tracking records to be viewed in the event viewer. If that does not meet your requirements, you can also write a custom tracking participant. - -## Example - - The following configuration example shows the standard ETW tracking participant being configured in the Web.config file. - - The Provider Id that the ETW Tracking Participant uses for writing the Tracking Records to ETW is defined in the **\** section. The tracking participant has a profile associated with it to specify the tracking records it has subscribed to. This is defined by the **profileName** attribute of the **\** element. Once these are defined, the Tracking Participant is added to the **\** service behavior. This will add the selected Tracking Participants to the Workflow instance’s extensions, so that they begin to receive the Tracking Records. - +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + + None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](add-of-participants.md)|Contains settings for a tracking participant.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](tracking.md)|Represents a configuration section for defining tracking settings for a workflow service.| + +## Remarks + + Tracking participants are used to get the tracking data emitted from the workflow and store it into different mediums. Likewise, any post processing on the tracking Records can also be done within the tracking participant. + + Multiple tracking participants can consume the tracking events simultaneously. Each tracking participant can be associated with a different tracking profile. + + A standard tracking participant is provided which writes the tracking records to an ETW session. The participant is configured on a workflow service by adding a tracking-specific behavior in a configuration file. Enabling an ETW tracking participant allows tracking records to be viewed in the event viewer. If that does not meet your requirements, you can also write a custom tracking participant. + +## Example + + The following configuration example shows the standard ETW tracking participant being configured in the Web.config file. + + The Provider Id that the ETW Tracking Participant uses for writing the Tracking Records to ETW is defined in the **\** section. The tracking participant has a profile associated with it to specify the tracking records it has subscribed to. This is defined by the `profileName` attribute of the **\** element. Once these are defined, the Tracking Participant is added to the **\** service behavior. This will add the selected Tracking Participants to the Workflow instance’s extensions, so that they begin to receive the Tracking Records. + ```xml @@ -78,14 +78,14 @@ Configure a list of tracking participants that listen to the tracking records be - + - -``` - + +``` + ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/system-servicemodel-of-workflow.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/system-servicemodel-of-workflow.md index cbd1c3d9ca722..e3bcf192da420 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/system-servicemodel-of-workflow.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/system-servicemodel-of-workflow.md @@ -101,7 +101,7 @@ This configuration section contains all the workflow configuration elements. |Element|Description| |-------------|-----------------| -|[\](behaviors-of-workflow.md)|This section defines the **serviceBehaviors** collection. Each element in the collection defines behavior elements consumed by services. Each behavior element is identified by its unique **name** attribute.| +|[\](behaviors-of-workflow.md)|This section defines the `serviceBehaviors` collection. Each element in the collection defines behavior elements consumed by services. Each behavior element is identified by its unique `name` attribute.| |[\](tracking.md)|Represents a configuration section for defining tracking settings for a workflow service.

For more information in workflow tracking and its configuration, see [Workflow Tracking and Tracing](../../../windows-workflow-foundation/workflow-tracking-and-tracing.md) and [Configuring Tracking for a Workflow](../../../windows-workflow-foundation/configuring-tracking-for-a-workflow.md).| ### Parent Elements diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflowidle.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflowidle.md index a6431832c458b..41a9fc1acd525 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflowidle.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflowidle.md @@ -6,18 +6,18 @@ ms.assetid: b2ef703c-3e01-4213-9d2e-c14c7dba94d2 --- # \ -A service behavior that controls when idle workflow instances are unloaded and persisted. - +A service behavior that controls when idle workflow instances are unloaded and persisted. + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](behaviors-of-workflow.md)\       [**\**](servicebehaviors-of-workflow.md)\         [**\**](behavior-of-servicebehaviors-of-workflow.md)\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml @@ -25,30 +25,30 @@ A service behavior that controls when idle workflow instances are unloaded and p timeToUnload="TimeSpan" /> - -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|timeToPersist|A Timespan value that specifies the duration between the time the workflow becomes idle and is persisted. The default value is TimeSpan.MaxValue.

The duration begins to elapse when the workflow instance becomes idle. This attribute is useful if you want to persist a workflow instance more aggressively while still keeping the instance in memory for as long as possible. This attribute is only valid if its value is less than the **timeToUnload** attribute. If it is greater, it is ignored. If this attribute elapses before the value specified by the **timeToUnload** attribute, persistence must complete before the workflow is unloaded. This implies that the unload operation may be delayed until the workflow is persisted. The persistence layer is responsible for handling any retries for transient errors and only throws exceptions on non-recoverable errors. Therefore, any exceptions thrown during persistence are treated as fatal and the workflow instance is aborted.| -|timeToUnload|A Timespan value that specifies the duration between the time the workflow becomes idle and is unloaded. The default value is 1 minute.

Unloading a workflow implies that it is also persisted. If this attribute is set to zero the workflow instance is persisted and unloaded immediately after the workflow becomes idle. Setting this attribute to TimeSpan.MaxValue effectively disables the unload operation. Idle workflow instances are never unloaded.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\ of \](behavior-of-servicebehaviors-of-workflow.md)|Specifies a behavior element.| - +
+``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|timeToPersist|A Timespan value that specifies the duration between the time the workflow becomes idle and is persisted. The default value is TimeSpan.MaxValue.

The duration begins to elapse when the workflow instance becomes idle. This attribute is useful if you want to persist a workflow instance more aggressively while still keeping the instance in memory for as long as possible. This attribute is only valid if its value is less than the `timeToUnload` attribute. If it is greater, it is ignored. If this attribute elapses before the value specified by the `timeToUnload` attribute, persistence must complete before the workflow is unloaded. This implies that the unload operation may be delayed until the workflow is persisted. The persistence layer is responsible for handling any retries for transient errors and only throws exceptions on non-recoverable errors. Therefore, any exceptions thrown during persistence are treated as fatal and the workflow instance is aborted.| +|timeToUnload|A Timespan value that specifies the duration between the time the workflow becomes idle and is unloaded. The default value is 1 minute.

Unloading a workflow implies that it is also persisted. If this attribute is set to zero the workflow instance is persisted and unloaded immediately after the workflow becomes idle. Setting this attribute to TimeSpan.MaxValue effectively disables the unload operation. Idle workflow instances are never unloaded.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\ of \](behavior-of-servicebehaviors-of-workflow.md)|Specifies a behavior element.| + ## See also - diff --git a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflowinstancequeries.md b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflowinstancequeries.md index 3781da66664eb..c4a32db211af0 100644 --- a/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflowinstancequeries.md +++ b/docs/framework/configure-apps/file-schema/windows-workflow-foundation/workflowinstancequeries.md @@ -6,20 +6,20 @@ ms.assetid: 4fe7ce85-cf9a-4dbf-a8f7-bc9b1fc2fe35 --- # \ -Represents a collection of configuration elements that track workflow instance life cycle changes such as a started or completed event. - -For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md) - +Represents a collection of configuration elements that track workflow instance life cycle changes such as a started or completed event. + +For more information on tracking profile queries, see [Tracking Profiles](../../../windows-workflow-foundation/tracking-profiles.md) + [**\**](../configuration-element.md)\   [**\**](system-servicemodel-of-workflow.md)\     [**\**](tracking.md)\       [**\**](trackingprofile.md)\         [**\**](workflow.md)\ -          **\** - -## Syntax - -```xml +          **\** + +## Syntax + +```xml @@ -32,57 +32,57 @@ For more information on tracking profile queries, see [Tracking Profiles](../../ - -``` - -## Attributes and Elements - -The following sections describe attributes, child elements, and parent elements. - -### Attributes - -None. - -### Child Elements - -|Element|Description| -|-------------|-----------------| -|[\](workflowinstancequery.md)|A query that is used to track workflow instance life cycle changes.| - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the **activityDefinitionId** property.| - -## Remarks - -The is used to subscribe to the following objects: - -- - -- - -- - -- - -- - -## Example - -The following configuration subscribes to workflow instance-level tracking records for the `Started` instance state using this query. - -```xml - - - - - - - -``` - +
+``` + +## Attributes and Elements + +The following sections describe attributes, child elements, and parent elements. + +### Attributes + +None. + +### Child Elements + +|Element|Description| +|-------------|-----------------| +|[\](workflowinstancequery.md)|A query that is used to track workflow instance life cycle changes.| + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\](workflow.md)|A configuration element that contains all queries for a specific workflow identified by the `activityDefinitionId` property.| + +## Remarks + +The is used to subscribe to the following objects: + +- + +- + +- + +- + +- + +## Example + +The following configuration subscribes to workflow instance-level tracking records for the `Started` instance state using this query. + +```xml + + + + + + + +``` + ## See also - diff --git a/docs/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection.md b/docs/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection.md index f252b9521adbc..e2b0540d6073c 100644 --- a/docs/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection.md +++ b/docs/framework/configure-apps/how-to-enable-and-disable-automatic-binding-redirection.md @@ -63,7 +63,7 @@ You can enable automatic binding redirects in existing apps that target older ve - In Visual Studio, select the project in **Solution Explorer**, and then choose **Open Folder in File Explorer** from the shortcut menu. In File Explorer, find the project (.csproj or .vbproj) file and open it in Notepad. - In Visual Studio, in **Solution Explorer**, right-click the project and choose **Unload Project**. Right-click the unloaded project again, and then choose **Edit [projectname.csproj]**. -2. Add the following element to the first configuration property group (under the \ tag): +2. Add the following element to the first configuration property group (under the `` tag): ```xml true @@ -106,5 +106,5 @@ To add binding redirects to a **web.config** file: ## See also -- [\ Element](./file-schema/runtime/bindingredirect-element.md) +- [`` Element](./file-schema/runtime/bindingredirect-element.md) - [Redirecting Assembly Versions](redirect-assembly-versions.md) diff --git a/docs/framework/configure-apps/how-to-locate-assemblies-by-using-devpath.md b/docs/framework/configure-apps/how-to-locate-assemblies-by-using-devpath.md index 9a3082d24499c..b9a2cb3df26de 100644 --- a/docs/framework/configure-apps/how-to-locate-assemblies-by-using-devpath.md +++ b/docs/framework/configure-apps/how-to-locate-assemblies-by-using-devpath.md @@ -19,7 +19,7 @@ Developers might want to make sure that a shared assembly they are building work For example, assume that you are building a shared assembly called MySharedAssembly and the output directory is C:\MySharedAssembly\Debug. You can put C:\MySharedAssembly\Debug in the DEVPATH variable. You must then specify the [\](./file-schema/runtime/developmentmode-element.md) element in the machine configuration file. This element tells the common language runtime to use DEVPATH to locate assemblies. - The shared assembly must be discoverable by the runtime. To specify a private directory for resolving assembly references use the [\ Element](./file-schema/runtime/codebase-element.md) or [\ Element](./file-schema/runtime/probing-element.md) in a configuration file, as described in [Specifying an Assembly's Location](specify-assembly-location.md). You can also put the assembly in a subdirectory of the application directory. For more information, see [How the Runtime Locates Assemblies](../deployment/how-the-runtime-locates-assemblies.md). + The shared assembly must be discoverable by the runtime. To specify a private directory for resolving assembly references use the [`` Element](./file-schema/runtime/codebase-element.md) or [`` Element](./file-schema/runtime/probing-element.md) in a configuration file, as described in [Specifying an Assembly's Location](specify-assembly-location.md). You can also put the assembly in a subdirectory of the application directory. For more information, see [How the Runtime Locates Assemblies](../deployment/how-the-runtime-locates-assemblies.md). > [!NOTE] > This is an advanced feature, intended only for development. diff --git a/docs/framework/configure-apps/index.md b/docs/framework/configure-apps/index.md index 635d54ed5cb6a..ac5103e45c585 100644 --- a/docs/framework/configure-apps/index.md +++ b/docs/framework/configure-apps/index.md @@ -54,7 +54,7 @@ This article describes the syntax of configuration files and provides informatio The machine configuration file, *Machine.config*, contains settings that apply to an entire computer. This file is located in the %*runtime install path*%\Config directory. *Machine.config* contains configuration settings for machine-wide assembly binding, built-in [remoting channels](/previous-versions/dotnet/netframework-4.0/dkfd3wha(v=vs.100)), and ASP.NET. - The configuration system first looks in the machine configuration file for the [**\** element](./file-schema/appsettings/index.md) and other configuration sections that a developer might define. It then looks in the application configuration file. To keep the machine configuration file manageable, it is best to put these settings in the application configuration file. However, putting the settings in the machine configuration file can make your system more maintainable. For example, if you have a third-party component that both your client and server application uses, it is easier to put the settings for that component in one place. In this case, the machine configuration file is the appropriate place for the settings, so you don't have the same settings in two different files. + The configuration system first looks in the machine configuration file for the [`` element](./file-schema/appsettings/index.md) and other configuration sections that a developer might define. It then looks in the application configuration file. To keep the machine configuration file manageable, it is best to put these settings in the application configuration file. However, putting the settings in the machine configuration file can make your system more maintainable. For example, if you have a third-party component that both your client and server application uses, it is easier to put the settings for that component in one place. In this case, the machine configuration file is the appropriate place for the settings, so you don't have the same settings in two different files. > [!NOTE] > Deploying an application using XCOPY will not copy the settings in the machine configuration file. diff --git a/docs/framework/configure-apps/map-algorithm-names-to-cryptography-classes.md b/docs/framework/configure-apps/map-algorithm-names-to-cryptography-classes.md index 94b32957cd3d3..4803214e65165 100644 --- a/docs/framework/configure-apps/map-algorithm-names-to-cryptography-classes.md +++ b/docs/framework/configure-apps/map-algorithm-names-to-cryptography-classes.md @@ -15,15 +15,15 @@ ms.assetid: 01327c69-c5e1-4ef6-b73f-0a58351f0492 There are four ways a developer can create a cryptography object using the Windows SDK: -- Create an object by using the **new** operator. +- Create an object by using the `new` operator. -- Create an object that implements a particular cryptography algorithm by calling the **Create** method on the abstract class for that algorithm. +- Create an object that implements a particular cryptography algorithm by calling the `Create` method on the abstract class for that algorithm. - Create an object that implements a particular cryptography algorithm by calling the method. -- Create an object that implements a class of cryptographic algorithms (such as a symmetric block cipher) by calling the **Create** method on the abstract class for that type of algorithm (such as ). +- Create an object that implements a class of cryptographic algorithms (such as a symmetric block cipher) by calling the `Create` method on the abstract class for that type of algorithm (such as ). - For example, suppose a developer wants to compute the SHA1 hash of a set of bytes. The namespace contains two implementations of the SHA1 algorithm, one purely managed implementation and one that wraps CryptoAPI. The developer can choose to instantiate a particular SHA1 implementation (such as the ) by calling the **new** operator. However, if it does not matter which class the common language runtime loads as long as the class implements the SHA1 hash algorithm, the developer can create an object by calling the method. This method calls **System.Security.Cryptography.CryptoConfig.CreateFromName("System.Security.Cryptography.SHA1")**, which must return an implementation of the SHA1 hash algorithm. + For example, suppose a developer wants to compute the SHA1 hash of a set of bytes. The namespace contains two implementations of the SHA1 algorithm, one purely managed implementation and one that wraps CryptoAPI. The developer can choose to instantiate a particular SHA1 implementation (such as the ) by calling the `new` operator. However, if it does not matter which class the common language runtime loads as long as the class implements the SHA1 hash algorithm, the developer can create an object by calling the method. This method calls **System.Security.Cryptography.CryptoConfig.CreateFromName("System.Security.Cryptography.SHA1")**, which must return an implementation of the SHA1 hash algorithm. The developer can also call **System.Security.Cryptography.CryptoConfig.CreateFromName("SHA1")** because, by default, cryptography configuration includes short names for the algorithms shipped in the .NET Framework. @@ -57,9 +57,9 @@ There are four ways a developer can create a cryptography object using the Windo
``` - You can specify the name of the attribute in the [ element](./file-schema/cryptography/cryptoclass-element.md) (the previous example names the attribute `MySHA1Hash`). The value of the attribute in the **\** element is a string that the common language runtime uses to find the class. You can use any string that meets the requirements specified in [Specifying Fully Qualified Type Names](../../fundamentals/reflection/specifying-fully-qualified-type-names.md). + You can specify the name of the attribute in the [`` element](./file-schema/cryptography/cryptoclass-element.md) (the previous example names the attribute `MySHA1Hash`). The value of the attribute in the `` element is a string that the common language runtime uses to find the class. You can use any string that meets the requirements specified in [Specifying Fully Qualified Type Names](../../fundamentals/reflection/specifying-fully-qualified-type-names.md). - Many algorithm names can map to the same class. The [\ element](./file-schema/cryptography/nameentry-element.md) maps a class to one friendly algorithm name. The **name** attribute can be either a string that is used when calling the **System.Security.Cryptography.CryptoConfig.CreateFromName** method or the name of an abstract cryptography class in the namespace. The value of the **class** attribute is the name of the attribute in the **\** element. + Many algorithm names can map to the same class. The [`` element](./file-schema/cryptography/nameentry-element.md) maps a class to one friendly algorithm name. The `name` attribute can be either a string that is used when calling the **System.Security.Cryptography.CryptoConfig.CreateFromName** method or the name of an abstract cryptography class in the namespace. The value of the `class` attribute is the name of the attribute in the `` element. > [!NOTE] > You can get an SHA1 algorithm by calling the or the **Security.CryptoConfig.CreateFromName("SHA1")** method. Each method guarantees only that it returns an object that implements the SHA1 algorithm. You do not have to map each friendly name of an algorithm to the same class in the configuration file. diff --git a/docs/framework/configure-apps/map-object-identifiers-to-cryptography-algorithms.md b/docs/framework/configure-apps/map-object-identifiers-to-cryptography-algorithms.md index 7add7a241b84c..abe86d2cfe20e 100644 --- a/docs/framework/configure-apps/map-object-identifiers-to-cryptography-algorithms.md +++ b/docs/framework/configure-apps/map-object-identifiers-to-cryptography-algorithms.md @@ -36,7 +36,7 @@ Digital signatures ensure that data is not tampered with when it is sent from on
``` - The [\ element](./file-schema/cryptography/oidentry-element.md) contains two attributes. The **OID** attribute is the object identifier number. The **name** attribute is the value of the **name** attribute from the [\ element](./file-schema/cryptography/nameentry-element.md). There must be a mapping from an algorithm name to a class before an object identifier can be mapped to a simple name. + The [`` element](./file-schema/cryptography/oidentry-element.md) contains two attributes. The `OID` attribute is the object identifier number. The `name` attribute is the value of the `name` attribute from the [`` element](./file-schema/cryptography/nameentry-element.md). There must be a mapping from an algorithm name to a class before an object identifier can be mapped to a simple name. ## See also diff --git a/docs/framework/configure-apps/redirect-assembly-versions.md b/docs/framework/configure-apps/redirect-assembly-versions.md index d9c39ab5fa34e..07db79c23f721 100644 --- a/docs/framework/configure-apps/redirect-assembly-versions.md +++ b/docs/framework/configure-apps/redirect-assembly-versions.md @@ -176,7 +176,7 @@ For example, to redirect one reference to a .NET Framework 3.5 assembly and anot ## See also - [How to: Enable and Disable Automatic Binding Redirection](how-to-enable-and-disable-automatic-binding-redirection.md) -- [\ Element](./file-schema/runtime/bindingredirect-element.md) +- [`` Element](./file-schema/runtime/bindingredirect-element.md) - [Assembly Binding Redirection Security Permission](assembly-binding-redirection-security-permission.md) - [Assemblies in .NET](../../standard/assembly/index.md) - [Programming with Assemblies](../../standard/assembly/index.md) diff --git a/docs/framework/configure-apps/specify-assembly-location.md b/docs/framework/configure-apps/specify-assembly-location.md index f773baec0e0b2..cea42a05487a5 100644 --- a/docs/framework/configure-apps/specify-assembly-location.md +++ b/docs/framework/configure-apps/specify-assembly-location.md @@ -20,9 +20,9 @@ There are two ways to specify an assembly's location: You can also use the [.NET Framework Configuration Tool (Mscorcfg.msc)](/previous-versions/dotnet/netframework-4.0/2bc0cxhc(v=vs.100)) to specify assembly locations or specify locations for the common language runtime to probe for assemblies. -## Using the \ Element +## Using the `` Element - You can use the **\** element only in machine configuration or publisher policy files that also redirect the assembly version. When the runtime determines which assembly version to use, it applies the code base setting from the file that determines the version. If no code base is indicated, the runtime probes for the assembly in the normal way. For details, see [How the Runtime Locates Assemblies](../deployment/how-the-runtime-locates-assemblies.md). + You can use the `` element only in machine configuration or publisher policy files that also redirect the assembly version. When the runtime determines which assembly version to use, it applies the code base setting from the file that determines the version. If no code base is indicated, the runtime probes for the assembly in the normal way. For details, see [How the Runtime Locates Assemblies](../deployment/how-the-runtime-locates-assemblies.md). The following example shows how to specify an assembly's location. @@ -42,12 +42,12 @@ There are two ways to specify an assembly's location:
``` - The **version** attribute is required for all strong-named assemblies but should be omitted for assemblies that are not strong-named. The **\** element requires the **href** attribute. You cannot specify version ranges in the **\** element. + The `version` attribute is required for all strong-named assemblies but should be omitted for assemblies that aren't strong-named. The `` element requires the `href` attribute. You cannot specify version ranges in the `` element. > [!NOTE] > If you are supplying a code base hint for an assembly that is not strong-named, the hint must point to the application base or a subdirectory of the application base directory. -## Using the \ Element +## Using the `` Element The runtime locates assemblies that do not have a code base by probing. For more information about probing, see [How the Runtime Locates Assemblies](../deployment/how-the-runtime-locates-assemblies.md). @@ -63,7 +63,7 @@ There are two ways to specify an assembly's location:
``` - The **privatePath** attribute contains the directories that the runtime should search for assemblies. If the application is located at C:\Program Files\MyApp, the runtime will look for assemblies that do not specify a code base in C:\Program Files\MyApp\Bin, C:\Program Files\MyApp\Bin2\Subbin, and C:\Program Files\MyApp\Bin3. The directories specified in **privatePath** must be subdirectories of the application base directory. + The `privatePath` attribute contains the directories that the runtime should search for assemblies. If the application is located at C:\Program Files\MyApp, the runtime will look for assemblies that do not specify a code base in C:\Program Files\MyApp\Bin, C:\Program Files\MyApp\Bin2\Subbin, and C:\Program Files\MyApp\Bin3. The directories specified in `privatePath` must be subdirectories of the application base directory. ## See also diff --git a/docs/framework/data/adonet/adding-existing-constraints-to-a-dataset.md b/docs/framework/data/adonet/adding-existing-constraints-to-a-dataset.md index 33c25096bbded..4296b6aa50b3d 100644 --- a/docs/framework/data/adonet/adding-existing-constraints-to-a-dataset.md +++ b/docs/framework/data/adonet/adding-existing-constraints-to-a-dataset.md @@ -2,61 +2,61 @@ description: "Learn more about: Adding Existing Constraints to a DataSet" title: "Adding Existing Constraints to a DataSet" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 307d2809-208b-4cf8-b6a9-5d16f15fc16c --- # Adding Existing Constraints to a DataSet -The **Fill** method of the **DataAdapter** fills a only with table columns and rows from a data source; though constraints are commonly set by the data source, the **Fill** method does not add this schema information to the **DataSet** by default. To populate a **DataSet** with existing primary key constraint information from a data source, you can either call the **FillSchema** method of the **DataAdapter**, or set the **MissingSchemaAction** property of the **DataAdapter** to **AddWithKey** before calling **Fill**. This will ensure that primary key constraints in the **DataSet** reflect those at the data source. Foreign key constraint information is not included and must be created explicitly, as shown in [DataTable Constraints](./dataset-datatable-dataview/datatable-constraints.md). - -Adding schema information to a **DataSet** before filling it with data ensures that primary key constraints are included with the objects in the **DataSet**. As a result, when additional calls to fill the **DataSet** are made, the primary key column information is used to match new rows from the data source with current rows in each **DataTable**, and current data in the tables is overwritten with data from the data source. Without the schema information, the new rows from the data source are appended to the **DataSet**, resulting in duplicate rows. - +The `Fill` method of the `DataAdapter` fills a only with table columns and rows from a data source; though constraints are commonly set by the data source, the `Fill` method does not add this schema information to the `DataSet` by default. To populate a `DataSet` with existing primary key constraint information from a data source, you can either call the `FillSchema` method of the **DataAdapter**, or set the `MissingSchemaAction` property of the `DataAdapter` to `AddWithKey` before calling **Fill**. This will ensure that primary key constraints in the `DataSet` reflect those at the data source. Foreign key constraint information is not included and must be created explicitly, as shown in [DataTable Constraints](./dataset-datatable-dataview/datatable-constraints.md). + +Adding schema information to a `DataSet` before filling it with data ensures that primary key constraints are included with the objects in the **DataSet**. As a result, when additional calls to fill the `DataSet` are made, the primary key column information is used to match new rows from the data source with current rows in each **DataTable**, and current data in the tables is overwritten with data from the data source. Without the schema information, the new rows from the data source are appended to the **DataSet**, resulting in duplicate rows. + > [!NOTE] -> If a column in a data source is identified as auto-incrementing, the **FillSchema** method, or the **Fill** method with a **MissingSchemaAction** of **AddWithKey**, creates a **DataColumn** with an **AutoIncrement** property set to `true`. However, you will need to set the **AutoIncrementStep** and **AutoIncrementSeed** values yourself. For more information about auto-incrementing columns, see [Creating AutoIncrement Columns](./dataset-datatable-dataview/creating-autoincrement-columns.md). - -Using **FillSchema** or setting the **MissingSchemaAction** to **AddWithKey** requires extra processing at the data source to determine primary key column information. This additional processing can hinder performance. If you know the primary key information at design time, we recommend that you explicitly specify the primary key column or columns in order to achieve optimal performance. For information about explicitly setting primary key information for a table, see [Defining Primary Keys](./dataset-datatable-dataview/defining-primary-keys.md). - -The following code example shows how to add schema information to a **DataSet** using **FillSchema**: - -```vb -Dim custDataSet As New DataSet() - -custAdapter.FillSchema(custDataSet, SchemaType.Source, "Customers") -custAdapter.Fill(custDataSet, "Customers") -``` - -```csharp -var custDataSet = new DataSet(); - -custAdapter.FillSchema(custDataSet, SchemaType.Source, "Customers"); -custAdapter.Fill(custDataSet, "Customers"); -``` - -The following code example shows how to add schema information to a **DataSet** using the **MissingSchemaAction.AddWithKey** property of the **Fill** method: - -```vb -Dim custDataSet As New DataSet() - -custAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey -custAdapter.Fill(custDataSet, "Customers") -``` - -```csharp -var custDataSet = new DataSet(); - -custAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; -custAdapter.Fill(custDataSet, "Customers"); -``` - -## Handling multiple result sets - -If the **DataAdapter** encounters multiple result sets returned from the **SelectCommand**, it will create multiple tables in the **DataSet**. The tables will be given a zero-based incremental default name of **Table** *N*, starting with **Table** instead of "Table0". If a table name is passed as an argument to the **FillSchema** method, the tables will be given a zero-based incremental name of **TableName** *N*, starting with **TableName** instead of "TableName0". - +> If a column in a data source is identified as auto-incrementing, the `FillSchema` method, or the `Fill` method with a `MissingSchemaAction` of **AddWithKey**, creates a `DataColumn` with an `AutoIncrement` property set to `true`. However, you will need to set the `AutoIncrementStep` and `AutoIncrementSeed` values yourself. For more information about auto-incrementing columns, see [Creating AutoIncrement Columns](./dataset-datatable-dataview/creating-autoincrement-columns.md). + +Using `FillSchema` or setting the `MissingSchemaAction` to `AddWithKey` requires extra processing at the data source to determine primary key column information. This additional processing can hinder performance. If you know the primary key information at design time, we recommend that you explicitly specify the primary key column or columns in order to achieve optimal performance. For information about explicitly setting primary key information for a table, see [Defining Primary Keys](./dataset-datatable-dataview/defining-primary-keys.md). + +The following code example shows how to add schema information to a `DataSet` using **FillSchema**: + +```vb +Dim custDataSet As New DataSet() + +custAdapter.FillSchema(custDataSet, SchemaType.Source, "Customers") +custAdapter.Fill(custDataSet, "Customers") +``` + +```csharp +var custDataSet = new DataSet(); + +custAdapter.FillSchema(custDataSet, SchemaType.Source, "Customers"); +custAdapter.Fill(custDataSet, "Customers"); +``` + +The following code example shows how to add schema information to a `DataSet` using the **MissingSchemaAction.AddWithKey** property of the `Fill` method: + +```vb +Dim custDataSet As New DataSet() + +custAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey +custAdapter.Fill(custDataSet, "Customers") +``` + +```csharp +var custDataSet = new DataSet(); + +custAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; +custAdapter.Fill(custDataSet, "Customers"); +``` + +## Handling multiple result sets + +If the `DataAdapter` encounters multiple result sets returned from the **SelectCommand**, it will create multiple tables in the **DataSet**. The tables will be given a zero-based incremental default name of `Table` *N*, starting with `Table` instead of "Table0". If a table name is passed as an argument to the `FillSchema` method, the tables will be given a zero-based incremental name of `TableName` *N*, starting with `TableName` instead of "TableName0". + > [!NOTE] -> If the **FillSchema** method of the **OleDbDataAdapter** object is called for a command that returns multiple result sets, only the schema information from the first result set is returned. When returning schema information for multiple result sets using the **OleDbDataAdapter**, it is recommended that you specify a **MissingSchemaAction** of **AddWithKey** and obtain the schema information when calling the **Fill** method. - +> If the `FillSchema` method of the `OleDbDataAdapter` object is called for a command that returns multiple result sets, only the schema information from the first result set is returned. When returning schema information for multiple result sets using the **OleDbDataAdapter**, it is recommended that you specify a `MissingSchemaAction` of `AddWithKey` and obtain the schema information when calling the `Fill` method. + ## See also - [DataAdapters and DataReaders](dataadapters-and-datareaders.md) diff --git a/docs/framework/data/adonet/ado-net-datasets.md b/docs/framework/data/adonet/ado-net-datasets.md index e14ef23ff5977..b2146fec72df1 100644 --- a/docs/framework/data/adonet/ado-net-datasets.md +++ b/docs/framework/data/adonet/ado-net-datasets.md @@ -6,47 +6,47 @@ ms.assetid: 82b641bb-6001-4512-bf1a-2830acdd92ab --- # ADO.NET DataSets -The object is central to supporting disconnected, distributed data scenarios with ADO.NET. The **DataSet** is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple and differing data sources, with XML data, or to manage data local to the application. The **DataSet** represents a complete set of data, including related tables, constraints, and relationships among the tables. The following illustration shows the **DataSet** object model. - - ![ADO.Net graphic](./media/ado-1-bpuedev11.png "ado_1_bpuedev11") -DataSet Object Model - - The methods and objects in a **DataSet** are consistent with those in the relational database model. - - The **DataSet** can also persist and reload its contents as XML, and its schema as XML schema definition language (XSD) schema. For more information, see [Using XML in a DataSet](./dataset-datatable-dataview/using-xml-in-a-dataset.md). - -## The DataTableCollection - - An ADO.NET **DataSet** contains a collection of zero or more tables represented by objects. The contains all the **DataTable** objects in a **DataSet**. - - A **DataTable** is defined in the namespace and represents a single table of memory-resident data. It contains a collection of columns represented by a , and constraints represented by a , which together define the schema of the table. A **DataTable** also contains a collection of rows represented by the , which contains the data in the table. Along with its current state, a retains both its current and original versions to identify changes to the values stored in the row. - -## The DataView Class - - A enables you to create different views of the data stored in a , a capability that is often used in data-binding applications. Using a , you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression. For more information, see [DataViews](./dataset-datatable-dataview/dataviews.md). - -## The DataRelationCollection - - A **DataSet** contains relationships in its object. A relationship, represented by the object, associates rows in one **DataTable** with rows in another **DataTable**. A relationship is analogous to a join path that might exist between primary and foreign key columns in a relational database. A **DataRelation** identifies matching columns in two tables of a **DataSet**. - - Relationships enable navigation from one table to another in a **DataSet**. The essential elements of a **DataRelation** are the name of the relationship, the name of the tables being related, and the related columns in each table. Relationships can be built with more than one column per table by specifying an array of objects as the key columns. When you add a relationship to the , you can optionally add a **UniqueKeyConstraint** and a **ForeignKeyConstraint** to enforce integrity constraints when changes are made to related column values. - - For more information, see [Adding DataRelations](./dataset-datatable-dataview/adding-datarelations.md). - -## XML - - You can fill a **DataSet** from an XML stream or document. You can use the XML stream or document to supply to the **DataSet** either data, schema information, or both. The information supplied from the XML stream or document can be combined with existing data or schema information already present in the **DataSet**. For more information, see [Using XML in a DataSet](./dataset-datatable-dataview/using-xml-in-a-dataset.md). - -## ExtendedProperties - - The **DataSet**, **DataTable**, and **DataColumn** all have an **ExtendedProperties** property. **ExtendedProperties** is a **PropertyCollection** where you can place custom information, such as the SELECT statement that was used to generate the result set, or the time when the data was generated. The **ExtendedProperties** collection is persisted with the schema information for the **DataSet**. - -## LINQ to DataSet - - LINQ to DataSet provides language-integrated querying capabilities for disconnected data stored in a DataSet. LINQ to DataSet uses standard LINQ syntax and provides compile-time syntax checking, static typing, and IntelliSense support when you are using the Visual Studio IDE. - - For more information, see [LINQ to DataSet](linq-to-dataset.md). - +The object is central to supporting disconnected, distributed data scenarios with ADO.NET. The `DataSet` is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple and differing data sources, with XML data, or to manage data local to the application. The `DataSet` represents a complete set of data, including related tables, constraints, and relationships among the tables. The following illustration shows the `DataSet` object model. + + ![ADO.Net graphic](./media/ado-1-bpuedev11.png "ado_1_bpuedev11") +DataSet Object Model + + The methods and objects in a `DataSet` are consistent with those in the relational database model. + + The `DataSet` can also persist and reload its contents as XML, and its schema as XML schema definition language (XSD) schema. For more information, see [Using XML in a DataSet](./dataset-datatable-dataview/using-xml-in-a-dataset.md). + +## The DataTableCollection + + An ADO.NET `DataSet` contains a collection of zero or more tables represented by objects. The contains all the `DataTable` objects in a **DataSet**. + + A `DataTable` is defined in the namespace and represents a single table of memory-resident data. It contains a collection of columns represented by a , and constraints represented by a , which together define the schema of the table. A `DataTable` also contains a collection of rows represented by the , which contains the data in the table. Along with its current state, a retains both its current and original versions to identify changes to the values stored in the row. + +## The DataView Class + + A enables you to create different views of the data stored in a , a capability that is often used in data-binding applications. Using a , you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression. For more information, see [DataViews](./dataset-datatable-dataview/dataviews.md). + +## The DataRelationCollection + + A `DataSet` contains relationships in its object. A relationship, represented by the object, associates rows in one `DataTable` with rows in another **DataTable**. A relationship is analogous to a join path that might exist between primary and foreign key columns in a relational database. A `DataRelation` identifies matching columns in two tables of a **DataSet**. + + Relationships enable navigation from one table to another in a **DataSet**. The essential elements of a `DataRelation` are the name of the relationship, the name of the tables being related, and the related columns in each table. Relationships can be built with more than one column per table by specifying an array of objects as the key columns. When you add a relationship to the , you can optionally add a `UniqueKeyConstraint` and a `ForeignKeyConstraint` to enforce integrity constraints when changes are made to related column values. + + For more information, see [Adding DataRelations](./dataset-datatable-dataview/adding-datarelations.md). + +## XML + + You can fill a `DataSet` from an XML stream or document. You can use the XML stream or document to supply to the `DataSet` either data, schema information, or both. The information supplied from the XML stream or document can be combined with existing data or schema information already present in the **DataSet**. For more information, see [Using XML in a DataSet](./dataset-datatable-dataview/using-xml-in-a-dataset.md). + +## ExtendedProperties + + The **DataSet**, **DataTable**, and `DataColumn` all have an `ExtendedProperties` property. `ExtendedProperties` is a `PropertyCollection` where you can place custom information, such as the SELECT statement that was used to generate the result set, or the time when the data was generated. The `ExtendedProperties` collection is persisted with the schema information for the **DataSet**. + +## LINQ to DataSet + + LINQ to DataSet provides language-integrated querying capabilities for disconnected data stored in a DataSet. LINQ to DataSet uses standard LINQ syntax and provides compile-time syntax checking, static typing, and IntelliSense support when you are using the Visual Studio IDE. + + For more information, see [LINQ to DataSet](linq-to-dataset.md). + ## See also - [ADO.NET Overview](ado-net-overview.md) diff --git a/docs/framework/data/adonet/asynchronous-programming.md b/docs/framework/data/adonet/asynchronous-programming.md index 4a34f460a4bd5..250a1fe985ae9 100644 --- a/docs/framework/data/adonet/asynchronous-programming.md +++ b/docs/framework/data/adonet/asynchronous-programming.md @@ -552,10 +552,10 @@ namespace SqlBulkCopyAsyncCodeSample { ## Asynchronously use multiple commands with MARS -The example opens a single connection to the **AdventureWorks** database. Using a object, a is created. As the reader is used, a second is opened, using data from the first as input to the WHERE clause for the second reader. +The example opens a single connection to the `AdventureWorks` database. Using a object, a is created. As the reader is used, a second is opened, using data from the first as input to the WHERE clause for the second reader. > [!NOTE] -> The following example uses the sample **AdventureWorks** database included with SQL Server. The connection string provided in the sample code assumes that the database is installed and available on the local computer. Modify the connection string as necessary for your environment. +> The following example uses the sample `AdventureWorks` database included with SQL Server. The connection string provided in the sample code assumes that the database is installed and available on the local computer. Modify the connection string as necessary for your environment. ```csharp using System; @@ -620,12 +620,12 @@ class Class1 { ## Asynchronously read and update data with MARS -MARS allows a connection to be used for both read operations and data manipulation language (DML) operations with more than one pending operation. This feature eliminates the need for an application to deal with connection-busy errors. In addition, MARS can replace the user of server-side cursors, which generally consume more resources. Finally, because multiple operations can operate on a single connection, they can share the same transaction context, eliminating the need to use **sp_getbindtoken** and **sp_bindsession** system stored procedures. +MARS allows a connection to be used for both read operations and data manipulation language (DML) operations with more than one pending operation. This feature eliminates the need for an application to deal with connection-busy errors. In addition, MARS can replace the user of server-side cursors, which generally consume more resources. Finally, because multiple operations can operate on a single connection, they can share the same transaction context, eliminating the need to use `sp_getbindtoken` and `sp_bindsession` system stored procedures. -The following Console application demonstrates how to use two objects with three objects and a single object with MARS enabled. The first command object retrieves a list of vendors whose credit rating is 5. The second command object uses the vendor ID provided from a to load the second with all of the products for the particular vendor. Each product record is visited by the second . A calculation is performed to determine what the new **OnOrderQty** should be. The third command object is then used to update the **ProductVendor** table with the new value. This entire process takes place within a single transaction, which is rolled back at the end. +The following Console application demonstrates how to use two objects with three objects and a single object with MARS enabled. The first command object retrieves a list of vendors whose credit rating is 5. The second command object uses the vendor ID provided from a to load the second with all of the products for the particular vendor. Each product record is visited by the second . A calculation is performed to determine what the new `OnOrderQty` should be. The third command object is then used to update the `ProductVendor` table with the new value. This entire process takes place within a single transaction, which is rolled back at the end. > [!NOTE] -> The following example uses the sample **AdventureWorks** database included with SQL Server. The connection string provided in the sample code assumes that the database is installed and available on the local computer. Modify the connection string as necessary for your environment. +> The following example uses the sample `AdventureWorks` database included with SQL Server. The connection string provided in the sample code assumes that the database is installed and available on the local computer. Modify the connection string as necessary for your environment. ```csharp using System; diff --git a/docs/framework/data/adonet/common-schema-collections.md b/docs/framework/data/adonet/common-schema-collections.md index a76e558b06d64..14a85e1441bf2 100644 --- a/docs/framework/data/adonet/common-schema-collections.md +++ b/docs/framework/data/adonet/common-schema-collections.md @@ -6,95 +6,95 @@ ms.assetid: 50127ced-2ac8-4d7a-9cd1-5c98c655ff03 --- # Common Schema Collections -The common schema collections are the schema collections that are implemented by each of the .NET Framework managed providers. You can query a .NET Framework managed provider to determine the list of supported schema collections by calling the **GetSchema** method with no arguments, or with the schema collection name "MetaDataCollections". This will return a with a list of the supported schema collections, the number of restrictions that they each support, and the number of identifier parts that they use. These collections describe all of the required columns. Providers are free to add additional columns if they wish. For example, `SqlClient` and `OracleClient` add ParameterName to the restrictions collection. - - If a provider is unable to determine the value of a required column, it will return null. - - For more information about using the **GetSchema** methods, see [GetSchema and Schema Collections](getschema-and-schema-collections.md). - -## MetaDataCollections - - This schema collection exposes information about all of the schema collections supported by the .NET Framework managed provider that is currently used to connect to the database. - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|CollectionName|string|The name of the collection to pass to the **GetSchema** method to return the collection.| -|NumberOfRestrictions|int|The number of restrictions that may be specified for the collection.| -|NumberOfIdentifierParts|int|The number of parts in the composite identifier/database object name. For example, in SQL Server, this would be 3 for tables and 4 for columns. In Oracle, it would be 2 for tables and 3 for columns.| - -## DataSourceInformation - - This schema collection exposes information about data source that the .NET Framework managed provider is currently connect to. - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|CompositeIdentifierSeparatorPattern|string|The regular expression to match the composite separators in a composite identifier. For example, "\\." (for SQL Server) or "\@|\\." (for Oracle).

A composite identifier is typically what is used for a database object name, for example: pubs.dbo.authors or pubs\@dbo.authors.

For SQL Server, use the regular expression "\\.". For OracleClient, use "\@|\\.".

For ODBC use the Catalog_name_separator.

For OLE DB use DBLITERAL_CATALOG_SEPARATOR or DBLITERAL_SCHEMA_SEPARATOR.| -|DataSourceProductName|string|The name of the product accessed by the provider, such as "Oracle" or "SQLServer".| -|DataSourceProductVersion|string|Indicates the version of the product accessed by the provider, in the data sources native format and not in Microsoft format.

In some cases DataSourceProductVersion and DataSourceProductVersionNormalized will be the same value. In the case of OLE DB and ODBC, these will always be the same as they are mapped to the same function call in the underlying native API.| -|DataSourceProductVersionNormalized|string|A normalized version for the data source, such that it can be compared with `String.Compare()`. The format of this is consistent for all versions of the provider to prevent version 10 from sorting between version 1 and version 2.

For example, the Oracle provider uses a format of "nn.nn.nn.nn.nn" for its normalized version, which causes an Oracle 8i data source to return "08.01.07.04.01". SQL Server uses the typical Microsoft "nn.nn.nnnn" format.

In some cases, DataSourceProductVersion and DataSourceProductVersionNormalized will be the same value. In the case of OLE DB and ODBC these will always be the same as they are mapped to the same function call in the underlying native API.| -|GroupByBehavior||Specifies the relationship between the columns in a GROUP BY clause and the non-aggregated columns in the select list.| -|IdentifierPattern|string|A regular expression that matches an identifier and has a match value of the identifier. For example "[A-Za-z0-9_#$]".| -|IdentifierCase||Indicates whether non-quoted identifiers are treated as case sensitive or not.| -|OrderByColumnsInSelect|bool|Specifies whether columns in an ORDER BY clause must be in the select list. A value of true indicates that they are required to be in the select list, a value of false indicates that they are not required to be in the select list.| -|ParameterMarkerFormat|string|A format string that represents how to format a parameter.

If named parameters are supported by the data source, the first placeholder in this string should be where the parameter name should be formatted.

For example, if the data source expects parameters to be named and prefixed with an ':' this would be ":{0}". When formatting this with a parameter name of "p1" the resulting string is ":p1".

If the data source expects parameters to be prefixed with the '\@', but the names already include them, this would be '{0}', and the result of formatting a parameter named "\@p1" would simply be "\@p1".

For data sources that do not expect named parameters and expect the use of the '?' character, the format string can be specified as simply '?', which would ignore the parameter name. For OLE DB we return '?'.| -|ParameterMarkerPattern|string|A regular expression that matches a parameter marker. It will have a match value of the parameter name, if any.

For example, if named parameters are supported with an '\@' lead-in character that will be included in the parameter name, this would be: "(\@[A-Za-z0-9_$#]*)".

However, if named parameters are supported with a ':' as the lead-in character and it is not part of the parameter name, this would be: ":([A-Za-z0-9_$#]\*)".

Of course, if the data source doesn't support named parameters, this would simply be "?".| -|ParameterNameMaxLength|int|The maximum length of a parameter name in characters. Visual Studio expects that if parameter names are supported, the minimum value for the maximum length is 30 characters.

If the data source does not support named parameters, this property returns zero.| -|ParameterNamePattern|string|A regular expression that matches the valid parameter names. Different data sources have different rules regarding the characters that may be used for parameter names.

Visual Studio expects that if parameter names are supported, the characters "\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Nd}" are the minimum supported set of characters that are valid for parameter names.| -|QuotedIdentifierPattern|string|A regular expression that matches a quoted identifier and has a match value of the identifier itself without the quotes. For example, if the data source used double-quotes to identify quoted identifiers, this would be: "(([^\\"]|\\"\\")*)".| -|QuotedIdentifierCase||Indicates whether quoted identifiers are treated as case sensitive or not.| -|StatementSeparatorPattern|string|A regular expression that matches the statement separator.| -|StringLiteralPattern|string|A regular expression that matches a string literal and has a match value of the literal itself. For example, if the data source used single-quotes to identify strings, this would be: "('([^']|'')*')"'| -|SupportedJoinOperators||Specifies what types of SQL join statements are supported by the data source.| - -## DataTypes - - This schema collection exposes information about the data types that are supported by the database that the .NET Framework managed provider is currently connected to. - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|TypeName|string|The provider-specific data type name.| -|ProviderDbType|int|The provider-specific type value that should be used when specifying a parameter's type. For example, SqlDbType.Money or OracleType.Blob.| -|ColumnSize|long|The length of a non-numeric column or parameter refers to either the maximum or the length defined for this type by the provider.

For character data, this is the maximum or defined length in units, defined by the data source. Oracle has the concept of specifying a length and then specifying the actual storage size for some character data types. This defines only the length in units for Oracle.

For date-time data types, this is the length of the string representation (assuming the maximum allowed precision of the fractional seconds component).

If the data type is numeric, this is the upper bound on the maximum precision of the data type.| -|CreateFormat|string|Format string that represents how to add this column to a data definition statement, such as CREATE TABLE. Each element in the CreateParameter array should be represented by a "parameter marker" in the format string.

For example, the SQL data type DECIMAL needs a precision and a scale. In this case, the format string would be "DECIMAL({0},{1})".| -|CreateParameters|string|The creation parameters that must be specified when creating a column of this data type. Each creation parameter is listed in the string, separated by a comma in the order they are to be supplied.

For example, the SQL data type DECIMAL needs a precision and a scale. In this case, the creation parameters should contain the string "precision, scale".

In a text command to create a DECIMAL column with a precision of 10 and a scale of 2, the value of the CreateFormat column might be DECIMAL({0},{1})" and the complete type specification would be DECIMAL(10,2).| -|DataType|string|The name of the .NET Framework type of the data type.| -|IsAutoincrementable|bool|true—Values of this data type may be auto-incrementing.

false—Values of this data type may not be auto-incrementing.

Note that this merely indicates whether a column of this data type may be auto-incrementing, not that all columns of this type are auto-incrementing.| -|IsBestMatch|bool|true—The data type is the best match between all data types in the data store and the .NET Framework data type indicated by the value in the DataType column.

false—The data type is not the best match.

For each set of rows in which the value of the DataType column is the same, the IsBestMatch column is set to true in only one row.| -|IsCaseSensitive|bool|true—The data type is a character type and is case-sensitive.

false—The data type is not a character type or is not case-sensitive.| -|IsFixedLength|bool|true—Columns of this data type created by the data definition language (DDL) will be of fixed length.

false—Columns of this data type created by the DDL will be of variable length.

DBNull.Value—It is not known whether the provider will map this field with a fixed-length or variable-length column.| -|IsFixedPrecisionScale|bool|true—The data type has a fixed precision and scale.

false—The data type does not have a fixed precision and scale.| -|IsLong|bool|true—The data type contains very long data; the definition of very long data is provider-specific.

false—The data type does not contain very long data.| -|IsNullable|bool|true—The data type is nullable.

false—The data type is not nullable.

DBNull.Value—It is not known whether the data type is nullable.| -|IsSearchable|bool|true—The data type can be used in a WHERE clause with any operator except the LIKE predicate.

false—The data type cannot be used in a WHERE clause with any operator except the LIKE predicate.| -|IsSearchableWithLike|bool|true—The data type can be used with the LIKE predicate

false—The data type cannot be used with the LIKE predicate.| -|IsUnsigned|bool|true—The data type is unsigned.

false—The data type is signed.

DBNull.Value—Not applicable to data type.| -|MaximumScale|short|If the type indicator is a numeric type, this is the maximum number of digits allowed to the right of the decimal point. Otherwise, this is DBNull.Value.| -|MinimumScale|short|If the type indicator is a numeric type, this is the minimum number of digits allowed to the right of the decimal point. Otherwise, this is DBNull.Value.| -|IsConcurrencyType|bool|true – the data type is updated by the database every time the row is changed and the value of the column is different from all previous values

false – the data type is note updated by the database every time the row is changed

DBNull.Value – the database does not support this type of data type| -|IsLiteralSupported|bool|true – the data type can be expressed as a literal

false – the data type can not be expressed as a literal| -|LiteralPrefix|string|The prefix applied to a given literal.| -|LiteralSuffix|string|The suffix applied to a given literal.| -|NativeDataType|String|NativeDataType is an OLE DB specific column for exposing the OLE DB type of the data type .| - -## Restrictions - - This schema collection exposed information about the restrictions that are supported by the .NET Framework managed provider that is currently used to connect to the database. - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|CollectionName|string|The name of the collection that these restrictions apply to.| -|RestrictionName|string|The name of the restriction in the collection.| -|RestrictionDefault|string|Ignored.| -|RestrictionNumber|int|The actual location in the collections restrictions that this particular restriction falls in.| - -## ReservedWords - - This schema collection exposes information about the words that are reserved by the database that the .NET Framework managed provider that is currently connected to. - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|ReservedWord|string|Provider specific reserved word.| - +The common schema collections are the schema collections that are implemented by each of the .NET Framework managed providers. You can query a .NET Framework managed provider to determine the list of supported schema collections by calling the `GetSchema` method with no arguments, or with the schema collection name "MetaDataCollections". This will return a with a list of the supported schema collections, the number of restrictions that they each support, and the number of identifier parts that they use. These collections describe all of the required columns. Providers are free to add additional columns if they wish. For example, `SqlClient` and `OracleClient` add ParameterName to the restrictions collection. + + If a provider is unable to determine the value of a required column, it will return null. + + For more information about using the `GetSchema` methods, see [GetSchema and Schema Collections](getschema-and-schema-collections.md). + +## MetaDataCollections + + This schema collection exposes information about all of the schema collections supported by the .NET Framework managed provider that is currently used to connect to the database. + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|CollectionName|string|The name of the collection to pass to the `GetSchema` method to return the collection.| +|NumberOfRestrictions|int|The number of restrictions that may be specified for the collection.| +|NumberOfIdentifierParts|int|The number of parts in the composite identifier/database object name. For example, in SQL Server, this would be 3 for tables and 4 for columns. In Oracle, it would be 2 for tables and 3 for columns.| + +## DataSourceInformation + + This schema collection exposes information about data source that the .NET Framework managed provider is currently connect to. + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|CompositeIdentifierSeparatorPattern|string|The regular expression to match the composite separators in a composite identifier. For example, "\\." (for SQL Server) or "\@|\\." (for Oracle).

A composite identifier is typically what is used for a database object name, for example: pubs.dbo.authors or pubs\@dbo.authors.

For SQL Server, use the regular expression "\\.". For OracleClient, use "\@|\\.".

For ODBC use the Catalog_name_separator.

For OLE DB use DBLITERAL_CATALOG_SEPARATOR or DBLITERAL_SCHEMA_SEPARATOR.| +|DataSourceProductName|string|The name of the product accessed by the provider, such as "Oracle" or "SQLServer".| +|DataSourceProductVersion|string|Indicates the version of the product accessed by the provider, in the data sources native format and not in Microsoft format.

In some cases DataSourceProductVersion and DataSourceProductVersionNormalized will be the same value. In the case of OLE DB and ODBC, these will always be the same as they are mapped to the same function call in the underlying native API.| +|DataSourceProductVersionNormalized|string|A normalized version for the data source, such that it can be compared with `String.Compare()`. The format of this is consistent for all versions of the provider to prevent version 10 from sorting between version 1 and version 2.

For example, the Oracle provider uses a format of "nn.nn.nn.nn.nn" for its normalized version, which causes an Oracle 8i data source to return "08.01.07.04.01". SQL Server uses the typical Microsoft "nn.nn.nnnn" format.

In some cases, DataSourceProductVersion and DataSourceProductVersionNormalized will be the same value. In the case of OLE DB and ODBC these will always be the same as they are mapped to the same function call in the underlying native API.| +|GroupByBehavior||Specifies the relationship between the columns in a GROUP BY clause and the non-aggregated columns in the select list.| +|IdentifierPattern|string|A regular expression that matches an identifier and has a match value of the identifier. For example "[A-Za-z0-9_#$]".| +|IdentifierCase||Indicates whether non-quoted identifiers are treated as case sensitive or not.| +|OrderByColumnsInSelect|bool|Specifies whether columns in an ORDER BY clause must be in the select list. A value of true indicates that they are required to be in the select list, a value of false indicates that they are not required to be in the select list.| +|ParameterMarkerFormat|string|A format string that represents how to format a parameter.

If named parameters are supported by the data source, the first placeholder in this string should be where the parameter name should be formatted.

For example, if the data source expects parameters to be named and prefixed with an ':' this would be ":{0}". When formatting this with a parameter name of "p1" the resulting string is ":p1".

If the data source expects parameters to be prefixed with the '\@', but the names already include them, this would be '{0}', and the result of formatting a parameter named "\@p1" would simply be "\@p1".

For data sources that do not expect named parameters and expect the use of the '?' character, the format string can be specified as simply '?', which would ignore the parameter name. For OLE DB we return '?'.| +|ParameterMarkerPattern|string|A regular expression that matches a parameter marker. It will have a match value of the parameter name, if any.

For example, if named parameters are supported with an '\@' lead-in character that will be included in the parameter name, this would be: "(\@[A-Za-z0-9_$#]*)".

However, if named parameters are supported with a ':' as the lead-in character and it is not part of the parameter name, this would be: ":([A-Za-z0-9_$#]\*)".

Of course, if the data source doesn't support named parameters, this would simply be "?".| +|ParameterNameMaxLength|int|The maximum length of a parameter name in characters. Visual Studio expects that if parameter names are supported, the minimum value for the maximum length is 30 characters.

If the data source does not support named parameters, this property returns zero.| +|ParameterNamePattern|string|A regular expression that matches the valid parameter names. Different data sources have different rules regarding the characters that may be used for parameter names.

Visual Studio expects that if parameter names are supported, the characters "\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Nd}" are the minimum supported set of characters that are valid for parameter names.| +|QuotedIdentifierPattern|string|A regular expression that matches a quoted identifier and has a match value of the identifier itself without the quotes. For example, if the data source used double-quotes to identify quoted identifiers, this would be: "(([^\\"]|\\"\\")*)".| +|QuotedIdentifierCase||Indicates whether quoted identifiers are treated as case sensitive or not.| +|StatementSeparatorPattern|string|A regular expression that matches the statement separator.| +|StringLiteralPattern|string|A regular expression that matches a string literal and has a match value of the literal itself. For example, if the data source used single-quotes to identify strings, this would be: "('([^']|'')*')"'| +|SupportedJoinOperators||Specifies what types of SQL join statements are supported by the data source.| + +## DataTypes + + This schema collection exposes information about the data types that are supported by the database that the .NET Framework managed provider is currently connected to. + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|TypeName|string|The provider-specific data type name.| +|ProviderDbType|int|The provider-specific type value that should be used when specifying a parameter's type. For example, SqlDbType.Money or OracleType.Blob.| +|ColumnSize|long|The length of a non-numeric column or parameter refers to either the maximum or the length defined for this type by the provider.

For character data, this is the maximum or defined length in units, defined by the data source. Oracle has the concept of specifying a length and then specifying the actual storage size for some character data types. This defines only the length in units for Oracle.

For date-time data types, this is the length of the string representation (assuming the maximum allowed precision of the fractional seconds component).

If the data type is numeric, this is the upper bound on the maximum precision of the data type.| +|CreateFormat|string|Format string that represents how to add this column to a data definition statement, such as CREATE TABLE. Each element in the CreateParameter array should be represented by a "parameter marker" in the format string.

For example, the SQL data type DECIMAL needs a precision and a scale. In this case, the format string would be "DECIMAL({0},{1})".| +|CreateParameters|string|The creation parameters that must be specified when creating a column of this data type. Each creation parameter is listed in the string, separated by a comma in the order they are to be supplied.

For example, the SQL data type DECIMAL needs a precision and a scale. In this case, the creation parameters should contain the string "precision, scale".

In a text command to create a DECIMAL column with a precision of 10 and a scale of 2, the value of the CreateFormat column might be DECIMAL({0},{1})" and the complete type specification would be DECIMAL(10,2).| +|DataType|string|The name of the .NET Framework type of the data type.| +|IsAutoincrementable|bool|true—Values of this data type may be auto-incrementing.

false—Values of this data type may not be auto-incrementing.

Note that this merely indicates whether a column of this data type may be auto-incrementing, not that all columns of this type are auto-incrementing.| +|IsBestMatch|bool|true—The data type is the best match between all data types in the data store and the .NET Framework data type indicated by the value in the DataType column.

false—The data type is not the best match.

For each set of rows in which the value of the DataType column is the same, the IsBestMatch column is set to true in only one row.| +|IsCaseSensitive|bool|true—The data type is a character type and is case-sensitive.

false—The data type is not a character type or is not case-sensitive.| +|IsFixedLength|bool|true—Columns of this data type created by the data definition language (DDL) will be of fixed length.

false—Columns of this data type created by the DDL will be of variable length.

DBNull.Value—It is not known whether the provider will map this field with a fixed-length or variable-length column.| +|IsFixedPrecisionScale|bool|true—The data type has a fixed precision and scale.

false—The data type does not have a fixed precision and scale.| +|IsLong|bool|true—The data type contains very long data; the definition of very long data is provider-specific.

false—The data type does not contain very long data.| +|IsNullable|bool|true—The data type is nullable.

false—The data type is not nullable.

DBNull.Value—It is not known whether the data type is nullable.| +|IsSearchable|bool|true—The data type can be used in a WHERE clause with any operator except the LIKE predicate.

false—The data type cannot be used in a WHERE clause with any operator except the LIKE predicate.| +|IsSearchableWithLike|bool|true—The data type can be used with the LIKE predicate

false—The data type cannot be used with the LIKE predicate.| +|IsUnsigned|bool|true—The data type is unsigned.

false—The data type is signed.

DBNull.Value—Not applicable to data type.| +|MaximumScale|short|If the type indicator is a numeric type, this is the maximum number of digits allowed to the right of the decimal point. Otherwise, this is DBNull.Value.| +|MinimumScale|short|If the type indicator is a numeric type, this is the minimum number of digits allowed to the right of the decimal point. Otherwise, this is DBNull.Value.| +|IsConcurrencyType|bool|true – the data type is updated by the database every time the row is changed and the value of the column is different from all previous values

false – the data type is note updated by the database every time the row is changed

DBNull.Value – the database does not support this type of data type| +|IsLiteralSupported|bool|true – the data type can be expressed as a literal

false – the data type can not be expressed as a literal| +|LiteralPrefix|string|The prefix applied to a given literal.| +|LiteralSuffix|string|The suffix applied to a given literal.| +|NativeDataType|String|NativeDataType is an OLE DB specific column for exposing the OLE DB type of the data type .| + +## Restrictions + + This schema collection exposed information about the restrictions that are supported by the .NET Framework managed provider that is currently used to connect to the database. + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|CollectionName|string|The name of the collection that these restrictions apply to.| +|RestrictionName|string|The name of the restriction in the collection.| +|RestrictionDefault|string|Ignored.| +|RestrictionNumber|int|The actual location in the collections restrictions that this particular restriction falls in.| + +## ReservedWords + + This schema collection exposes information about the words that are reserved by the database that the .NET Framework managed provider that is currently connected to. + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|ReservedWord|string|Provider specific reserved word.| + ## See also - [Retrieving Database Schema Information](retrieving-database-schema-information.md) diff --git a/docs/framework/data/adonet/connecting-to-a-data-source.md b/docs/framework/data/adonet/connecting-to-a-data-source.md index e18ba5dad36b8..5c377e53168d0 100644 --- a/docs/framework/data/adonet/connecting-to-a-data-source.md +++ b/docs/framework/data/adonet/connecting-to-a-data-source.md @@ -6,18 +6,18 @@ ms.assetid: 9abc3f92-1be3-4e1a-b360-762dc689650e --- # Connecting to a Data Source in ADO.NET -In ADO.NET, you use a **Connection** object to connect to a specific data source by supplying necessary authentication information in a connection string. The **Connection** object you use depends on the type of data source. - - Each .NET Framework data provider included with the .NET Framework has a object: the .NET Framework Data Provider for OLE DB includes an object, the .NET Framework Data Provider for SQL Server includes a object, the .NET Framework Data Provider for ODBC includes an object, and the .NET Framework Data Provider for Oracle includes an object. - -## In This Section +In ADO.NET, you use a `Connection` object to connect to a specific data source by supplying necessary authentication information in a connection string. The `Connection` object you use depends on the type of data source. + + Each .NET Framework data provider included with the .NET Framework has a object: the .NET Framework Data Provider for OLE DB includes an object, the .NET Framework Data Provider for SQL Server includes a object, the .NET Framework Data Provider for ODBC includes an object, and the .NET Framework Data Provider for Oracle includes an object. + +## In This Section [Establishing the Connection](establishing-the-connection.md)\ - Describes how to use a **Connection** object to establish a connection to a data source. - + Describes how to use a `Connection` object to establish a connection to a data source. + [Connection Events](connection-events.md)\ - Describes how to use an **InfoMessage** event to retrieve informational messages from a data source. - + Describes how to use an `InfoMessage` event to retrieve informational messages from a data source. + ## See also - [Connection Strings](connection-strings.md) diff --git a/docs/framework/data/adonet/connection-events.md b/docs/framework/data/adonet/connection-events.md index ee9366e5838f8..f8134da12827a 100644 --- a/docs/framework/data/adonet/connection-events.md +++ b/docs/framework/data/adonet/connection-events.md @@ -2,109 +2,109 @@ description: "Learn more about: Connection Events" title: "Connection Events" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 5a29de74-acfc-4134-8616-829dd7ce0710 --- # Connection Events -All of the .NET Framework data providers have **Connection** objects with two events that you can use to retrieve informational messages from a data source or to determine if the state of a **Connection** has changed. The following table describes the events of the **Connection** object. - -|Event|Description| -|-----------|-----------------| -|**InfoMessage**|Occurs when an informational message is returned from a data source. Informational messages are messages from a data source that do not result in an exception being thrown.| -|**StateChange**|Occurs when the state of the **Connection** changes.| - -## Working with the InfoMessage Event +All of the .NET Framework data providers have `Connection` objects with two events that you can use to retrieve informational messages from a data source or to determine if the state of a `Connection` has changed. The following table describes the events of the `Connection` object. + +|Event|Description| +|-----------|-----------------| +|**InfoMessage**|Occurs when an informational message is returned from a data source. Informational messages are messages from a data source that do not result in an exception being thrown.| +|**StateChange**|Occurs when the state of the `Connection` changes.| + +## Working with the InfoMessage Event You can retrieve warnings and informational messages from a SQL Server data source using the event of the object. Errors returned from the data source with a severity level of 11 through 16 cause an exception to be thrown. However, the event can be used to obtain messages from the data source that are not associated with an error. In the case of Microsoft SQL Server, any error with a severity of 10 or less is considered to be an informational message, and can be captured by using the event. For more information, see the [Database Engine Error Severities](/sql/relational-databases/errors-events/database-engine-error-severities) article. - - The event receives an object containing, in its **Errors** property, a collection of the messages from the data source. You can query the **Error** objects in this collection for the error number and message text, as well as the source of the error. The .NET Framework Data Provider for SQL Server also includes detail about the database, stored procedure, and line number that the message came from. - -### Example - - The following code example shows how to add an event handler for the event. - -```vb -' Assumes that connection represents a SqlConnection object. - AddHandler connection.InfoMessage, _ - New SqlInfoMessageEventHandler(AddressOf OnInfoMessage) - -Private Shared Sub OnInfoMessage(sender As Object, _ - args As SqlInfoMessageEventArgs) - Dim err As SqlError - For Each err In args.Errors - Console.WriteLine("The {0} has received a severity {1}, _ - state {2} error number {3}\n" & _ - "on line {4} of procedure {5} on server {6}:\n{7}", _ - err.Source, err.Class, err.State, err.Number, err.LineNumber, _ - err.Procedure, err.Server, err.Message) - Next -End Sub -``` - -```csharp -// Assumes that connection represents a SqlConnection object. + + The event receives an object containing, in its `Errors` property, a collection of the messages from the data source. You can query the `Error` objects in this collection for the error number and message text, as well as the source of the error. The .NET Framework Data Provider for SQL Server also includes detail about the database, stored procedure, and line number that the message came from. + +### Example + + The following code example shows how to add an event handler for the event. + +```vb +' Assumes that connection represents a SqlConnection object. + AddHandler connection.InfoMessage, _ + New SqlInfoMessageEventHandler(AddressOf OnInfoMessage) + +Private Shared Sub OnInfoMessage(sender As Object, _ + args As SqlInfoMessageEventArgs) + Dim err As SqlError + For Each err In args.Errors + Console.WriteLine("The {0} has received a severity {1}, _ + state {2} error number {3}\n" & _ + "on line {4} of procedure {5} on server {6}:\n{7}", _ + err.Source, err.Class, err.State, err.Number, err.LineNumber, _ + err.Procedure, err.Server, err.Message) + Next +End Sub +``` + +```csharp +// Assumes that connection represents a SqlConnection object. connection.InfoMessage += - new SqlInfoMessageEventHandler(OnInfoMessage); - -protected static void OnInfoMessage( - object sender, SqlInfoMessageEventArgs args) -{ - foreach (SqlError err in args.Errors) - { - Console.WriteLine( - "The {0} has received a severity {1}, state {2} error number {3}\n" + - "on line {4} of procedure {5} on server {6}:\n{7}", + new SqlInfoMessageEventHandler(OnInfoMessage); + +protected static void OnInfoMessage( + object sender, SqlInfoMessageEventArgs args) +{ + foreach (SqlError err in args.Errors) + { + Console.WriteLine( + "The {0} has received a severity {1}, state {2} error number {3}\n" + + "on line {4} of procedure {5} on server {6}:\n{7}", err.Source, err.Class, err.State, err.Number, err.LineNumber, - err.Procedure, err.Server, err.Message); - } -} -``` - -## Handling Errors as InfoMessages - - The event will normally fire only for informational and warning messages that are sent from the server. However, when an actual error occurs, the execution of the **ExecuteNonQuery** or **ExecuteReader** method that initiated the server operation is halted and an exception is thrown. - - If you want to continue processing the rest of the statements in a command regardless of any errors produced by the server, set the property of the to `true`. Doing this causes the connection to fire the event for errors instead of throwing an exception and interrupting processing. The client application can then handle this event and respond to error conditions. - + err.Procedure, err.Server, err.Message); + } +} +``` + +## Handling Errors as InfoMessages + + The event will normally fire only for informational and warning messages that are sent from the server. However, when an actual error occurs, the execution of the `ExecuteNonQuery` or `ExecuteReader` method that initiated the server operation is halted and an exception is thrown. + + If you want to continue processing the rest of the statements in a command regardless of any errors produced by the server, set the property of the to `true`. Doing this causes the connection to fire the event for errors instead of throwing an exception and interrupting processing. The client application can then handle this event and respond to error conditions. + > [!NOTE] -> An error with a severity level of 17 or above that causes the server to stop processing the command must be handled as an exception. In this case, an exception is thrown regardless of how the error is handled in the event. - -## Working with the StateChange Event - - The **StateChange** event occurs when the state of a **Connection** changes. The **StateChange** event receives that enable you to determine the change in state of the **Connection** by using the **OriginalState** and **CurrentState** properties. The **OriginalState** property is a enumeration that indicates the state of the **Connection** before it changed. **CurrentState** is a enumeration that indicates the state of the **Connection** after it changed. - - The following code example uses the **StateChange** event to write a message to the console when the state of the **Connection** changes. - -```vb -' Assumes connection represents a SqlConnection object. - AddHandler connection.StateChange, _ - New StateChangeEventHandler(AddressOf OnStateChange) - -Protected Shared Sub OnStateChange( _ - sender As Object, args As StateChangeEventArgs) - - Console.WriteLine( _ - "The current Connection state has changed from {0} to {1}.", _ - args.OriginalState, args.CurrentState) -End Sub -``` - -```csharp -// Assumes connection represents a SqlConnection object. - connection.StateChange += new StateChangeEventHandler(OnStateChange); - +> An error with a severity level of 17 or above that causes the server to stop processing the command must be handled as an exception. In this case, an exception is thrown regardless of how the error is handled in the event. + +## Working with the StateChange Event + + The `StateChange` event occurs when the state of a `Connection` changes. The `StateChange` event receives that enable you to determine the change in state of the `Connection` by using the `OriginalState` and `CurrentState` properties. The `OriginalState` property is a enumeration that indicates the state of the `Connection` before it changed. `CurrentState` is a enumeration that indicates the state of the `Connection` after it changed. + + The following code example uses the `StateChange` event to write a message to the console when the state of the `Connection` changes. + +```vb +' Assumes connection represents a SqlConnection object. + AddHandler connection.StateChange, _ + New StateChangeEventHandler(AddressOf OnStateChange) + +Protected Shared Sub OnStateChange( _ + sender As Object, args As StateChangeEventArgs) + + Console.WriteLine( _ + "The current Connection state has changed from {0} to {1}.", _ + args.OriginalState, args.CurrentState) +End Sub +``` + +```csharp +// Assumes connection represents a SqlConnection object. + connection.StateChange += new StateChangeEventHandler(OnStateChange); + protected static void OnStateChange(object sender, - StateChangeEventArgs args) -{ - Console.WriteLine( - "The current Connection state has changed from {0} to {1}.", - args.OriginalState, args.CurrentState); -} -``` - + StateChangeEventArgs args) +{ + Console.WriteLine( + "The current Connection state has changed from {0} to {1}.", + args.OriginalState, args.CurrentState); +} +``` + ## See also - [Connecting to a Data Source](connecting-to-a-data-source.md) diff --git a/docs/framework/data/adonet/connection-string-syntax.md b/docs/framework/data/adonet/connection-string-syntax.md index 78159bcf5782b..57290b31b4f87 100644 --- a/docs/framework/data/adonet/connection-string-syntax.md +++ b/docs/framework/data/adonet/connection-string-syntax.md @@ -50,7 +50,7 @@ The syntax for a connection string is ### Windows authentication with SqlClient - Each of the following forms of syntax uses Windows Authentication to connect to the **AdventureWorks** database on a local server. + Each of the following forms of syntax uses Windows Authentication to connect to the `AdventureWorks` database on a local server. ```csharp "Persist Security Info=False;Integrated Security=true; @@ -148,7 +148,7 @@ Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\Northwind.mdb;Jet OLEDB:System D ``` > [!IMPORTANT] -> It is possible to supply connection information for an **OleDbConnection** in a Universal Data Link (UDL) file; however you should avoid doing so. UDL files are not encrypted, and expose connection string information in clear text. Because a UDL file is an external file-based resource to your application, it cannot be secured using .NET Framework. UDL files are not supported for **SqlClient**. +> It is possible to supply connection information for an `OleDbConnection` in a Universal Data Link (UDL) file; however you should avoid doing so. UDL files are not encrypted, and expose connection string information in clear text. Because a UDL file is an external file-based resource to your application, it cannot be secured using .NET Framework. UDL files are not supported for **SqlClient**. [!INCLUDE [managed-identities](../../../includes/managed-identities.md)] diff --git a/docs/framework/data/adonet/connection-strings-and-configuration-files.md b/docs/framework/data/adonet/connection-strings-and-configuration-files.md index a918648453701..253a5ff92c5eb 100644 --- a/docs/framework/data/adonet/connection-strings-and-configuration-files.md +++ b/docs/framework/data/adonet/connection-strings-and-configuration-files.md @@ -19,9 +19,9 @@ Embedding connection strings in your application's code can lead to security vul ### The `connectionStrings` Section - Connection strings can be stored as key/value pairs in the **connectionStrings** section of the **configuration** element of an application configuration file. Child elements include **add**, **clear**, and **remove**. + Connection strings can be stored as key/value pairs in the `connectionStrings` section of the `configuration` element of an application configuration file. Child elements include **add**, **clear**, and **remove**. - The following configuration file fragment demonstrates the schema and syntax for storing a connection string. The **name** attribute is a name that you provide to uniquely identify a connection string so that it can be retrieved at run time. The **providerName** is the invariant name of the .NET Framework data provider, which is registered in the machine.config file. + The following configuration file fragment demonstrates the schema and syntax for storing a connection string. The `name` attribute is a name that you provide to uniquely identify a connection string so that it can be retrieved at run time. The `providerName` is the invariant name of the .NET Framework data provider, which is registered in the machine.config file. ```xml @@ -40,9 +40,9 @@ Embedding connection strings in your application's code can lead to security vul ### Use External Configuration Files - External configuration files are separate files that contain a fragment of a configuration file consisting of a single section. The external configuration file is then referenced by the main configuration file. Storing the **connectionStrings** section in a physically separate file is useful in situations where connection strings might be edited after the application is deployed. For example, the standard ASP.NET behavior is to restart an application domain when configuration files are modified, which results in state information being lost. However, modifying an external configuration file does not cause an application restart. External configuration files are not limited to ASP.NET; they can also be used by Windows applications. In addition, file access security and permissions can be used to restrict access to external configuration files. Working with external configuration files at run time is transparent, and requires no special coding. + External configuration files are separate files that contain a fragment of a configuration file consisting of a single section. The external configuration file is then referenced by the main configuration file. Storing the `connectionStrings` section in a physically separate file is useful in situations where connection strings might be edited after the application is deployed. For example, the standard ASP.NET behavior is to restart an application domain when configuration files are modified, which results in state information being lost. However, modifying an external configuration file does not cause an application restart. External configuration files are not limited to ASP.NET; they can also be used by Windows applications. In addition, file access security and permissions can be used to restrict access to external configuration files. Working with external configuration files at run time is transparent, and requires no special coding. - To store connection strings in an external configuration file, create a separate file that contains only the **connectionStrings** section. Do not include any additional elements, sections, or attributes. This example shows the syntax for an external configuration file. + To store connection strings in an external configuration file, create a separate file that contains only the `connectionStrings` section. Do not include any additional elements, sections, or attributes. This example shows the syntax for an external configuration file. ```xml @@ -52,7 +52,7 @@ Embedding connection strings in your application's code can lead to security vul ``` - In the main application configuration file, you use the **configSource** attribute to specify the fully qualified name and location of the external file. This example refers to an external configuration file named `connections.config`. + In the main application configuration file, you use the `configSource` attribute to specify the fully qualified name and location of the external file. This example refers to an external configuration file named `connections.config`. ```xml @@ -66,7 +66,7 @@ Embedding connection strings in your application's code can lead to security vul .NET Framework 2.0 introduced new classes in the namespace to simplify retrieving connection strings from configuration files at run time. You can programmatically retrieve a connection string by name or by provider name. > [!NOTE] -> The **machine.config** file also contains a **connectionStrings** section, which contains connection strings used by Visual Studio. When retrieving connection strings by provider name from the **app.config** file in a Windows application, the connection strings in **machine.config** get loaded first, and then the entries from **app.config**. Adding **clear** immediately after the **connectionStrings** element removes all inherited references from the data structure in memory, so that only the connection strings defined in the local **app.config** file are considered. +> The **machine.config** file also contains a `connectionStrings` section, which contains connection strings used by Visual Studio. When retrieving connection strings by provider name from the **app.config** file in a Windows application, the connection strings in **machine.config** get loaded first, and then the entries from **app.config**. Adding `clear` immediately after the `connectionStrings` element removes all inherited references from the data structure in memory, so that only the connection strings defined in the local **app.config** file are considered. ### Work with the Configuration Classes @@ -75,13 +75,13 @@ Embedding connection strings in your application's code can lead to security vul > [!NOTE] > Accessing configuration files at run time requires granting permissions to the caller; the required permissions depend on the type of application, configuration file, and location. For more information, see for ASP.NET applications, and for Windows applications. - You can use the to retrieve connection strings from application configuration files. It contains a collection of objects, each of which represents a single entry in the **connectionStrings** section. Its properties map to connection string attributes, allowing you to retrieve a connection string by specifying the name or the provider name. + You can use the to retrieve connection strings from application configuration files. It contains a collection of objects, each of which represents a single entry in the `connectionStrings` section. Its properties map to connection string attributes, allowing you to retrieve a connection string by specifying the name or the provider name. | Property | Description | |--------------------------------------------------------------|--------------------------------------------------------------------| -| | The name of the connection string. Maps to the **name** attribute. | -||The fully qualified provider name. Maps to the **providerName** attribute.| -||The connection string. Maps to the **connectionString** attribute.| +| | The name of the connection string. Maps to the `name` attribute. | +||The fully qualified provider name. Maps to the `providerName` attribute.| +||The connection string. Maps to the `connectionString` attribute.| ### Example: List All Connection Strings @@ -111,7 +111,7 @@ Embedding connection strings in your application's code can lead to security vul ASP.NET 2.0 introduced a new feature, called *protected configuration*, that enables you to encrypt sensitive information in a configuration file. Although primarily designed for ASP.NET, protected configuration can also be used to encrypt configuration file sections in Windows applications. - The following configuration file fragment shows the **connectionStrings** section after it has been encrypted. The **configProtectionProvider** specifies the protected configuration provider used to encrypt and decrypt the connection strings. The **EncryptedData** section contains the cipher text. + The following configuration file fragment shows the `connectionStrings` section after it has been encrypted. The `configProtectionProvider` specifies the protected configuration provider used to encrypt and decrypt the connection strings. The `EncryptedData` section contains the cipher text. ```xml @@ -123,11 +123,11 @@ Embedding connection strings in your application's code can lead to security vul ``` - When the encrypted connection string is retrieved at run time, .NET Framework uses the specified provider to decrypt the **CipherValue** and make it available to your application. You do not need to write any additional code to manage the decryption process. + When the encrypted connection string is retrieved at run time, .NET Framework uses the specified provider to decrypt the `CipherValue` and make it available to your application. You do not need to write any additional code to manage the decryption process. ### Protected Configuration Providers - Protected configuration providers are registered in the **configProtectedData** section of the **machine.config** file on the local computer, as shown in the following fragment, which shows the two protected configuration providers supplied with .NET Framework. The values shown here have been truncated for readability. + Protected configuration providers are registered in the `configProtectedData` section of the **machine.config** file on the local computer, as shown in the following fragment, which shows the two protected configuration providers supplied with .NET Framework. The values shown here have been truncated for readability. ```xml @@ -158,9 +158,9 @@ Embedding connection strings in your application's code can lead to security vul ### App.config Example - This example demonstrates how to toggle encrypting the **connectionStrings** section in an **app.config** file for a Windows application. In this example, the procedure takes the name of the application as an argument, for example, "MyApplication.exe". The **app.config** file is then encrypted and copied to the folder that contains the executable under the name of "MyApplication.exe.config". + This example demonstrates how to toggle encrypting the `connectionStrings` section in an **app.config** file for a Windows application. In this example, the procedure takes the name of the application as an argument, for example, "MyApplication.exe". The **app.config** file is then encrypted and copied to the folder that contains the executable under the name of "MyApplication.exe.config". - The code uses the method to open the **app.config** file for editing, and the method returns the **connectionStrings** section. The code then checks the property, calling the to encrypt the section if it is not encrypted. The method is invoked to decrypt the section. (The connection string can only be decrypted on the computer on which it was encrypted.) The method completes the operation and saves the changes. + The code uses the method to open the **app.config** file for editing, and the method returns the `connectionStrings` section. The code then checks the property, calling the to encrypt the section if it is not encrypted. The method is invoked to decrypt the section. (The connection string can only be decrypted on the computer on which it was encrypted.) The method completes the operation and saves the changes. You must add a reference to `System.Configuration.dll` in your project for the code to run. diff --git a/docs/framework/data/adonet/dataadapter-datatable-and-datacolumn-mappings.md b/docs/framework/data/adonet/dataadapter-datatable-and-datacolumn-mappings.md index b546ecd994142..1f80eb1e21910 100644 --- a/docs/framework/data/adonet/dataadapter-datatable-and-datacolumn-mappings.md +++ b/docs/framework/data/adonet/dataadapter-datatable-and-datacolumn-mappings.md @@ -2,107 +2,107 @@ description: "Learn more about: DataAdapter DataTable and DataColumn Mappings" title: "DataAdapter DataTable and DataColumn Mappings" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: d023260a-a66a-4c39-b8f4-090cd130e730 --- # DataAdapter DataTable and DataColumn Mappings -A **DataAdapter** contains a collection of zero or more objects in its **TableMappings** property. A **DataTableMapping** provides a primary mapping between the data returned from a query against a data source, and a . The **DataTableMapping** name can be passed in place of the **DataTable** name to the **Fill** method of the **DataAdapter**. The following example creates a **DataTableMapping** named **AuthorsMapping** for the **Authors** table. - -```vb -workAdapter.TableMappings.Add("AuthorsMapping", "Authors") -``` - -```csharp -workAdapter.TableMappings.Add("AuthorsMapping", "Authors"); -``` - - A **DataTableMapping** enables you to use column names in a **DataTable** that are different from those in the database. The **DataAdapter** uses the mapping to match the columns when the table is updated. - - If you do not specify a **TableName** or a **DataTableMapping** name when calling the **Fill** or **Update** method of the **DataAdapter**, the **DataAdapter** looks for a **DataTableMapping** named "Table". If that **DataTableMapping** does not exist, the **TableName** of the **DataTable** is "Table". You can specify a default **DataTableMapping** by creating a **DataTableMapping** with the name of "Table". - - The following code example creates a **DataTableMapping** (from the namespace) and makes it the default mapping for the specified **DataAdapter** by naming it "Table". The example then maps the columns from the first table in the query result (the **Customers** table of the **Northwind** database) to a set of more user-friendly names in the **Northwind Customers** table in the . For columns that are not mapped, the name of the column from the data source is used. - -```vb -Dim mapping As DataTableMapping = _ - adapter.TableMappings.Add("Table", "NorthwindCustomers") -mapping.ColumnMappings.Add("CompanyName", "Company") -mapping.ColumnMappings.Add("ContactName", "Contact") -mapping.ColumnMappings.Add("PostalCode", "ZIPCode") - -adapter.Fill(custDS) -``` - -```csharp +A `DataAdapter` contains a collection of zero or more objects in its `TableMappings` property. A `DataTableMapping` provides a primary mapping between the data returned from a query against a data source, and a . The `DataTableMapping` name can be passed in place of the `DataTable` name to the `Fill` method of the **DataAdapter**. The following example creates a `DataTableMapping` named `AuthorsMapping` for the `Authors` table. + +```vb +workAdapter.TableMappings.Add("AuthorsMapping", "Authors") +``` + +```csharp +workAdapter.TableMappings.Add("AuthorsMapping", "Authors"); +``` + + A `DataTableMapping` enables you to use column names in a `DataTable` that are different from those in the database. The `DataAdapter` uses the mapping to match the columns when the table is updated. + + If you do not specify a `TableName` or a `DataTableMapping` name when calling the `Fill` or `Update` method of the **DataAdapter**, the `DataAdapter` looks for a `DataTableMapping` named "Table". If that `DataTableMapping` does not exist, the `TableName` of the `DataTable` is "Table". You can specify a default `DataTableMapping` by creating a `DataTableMapping` with the name of "Table". + + The following code example creates a `DataTableMapping` (from the namespace) and makes it the default mapping for the specified `DataAdapter` by naming it "Table". The example then maps the columns from the first table in the query result (the `Customers` table of the `Northwind` database) to a set of more user-friendly names in the **Northwind Customers** table in the . For columns that are not mapped, the name of the column from the data source is used. + +```vb +Dim mapping As DataTableMapping = _ + adapter.TableMappings.Add("Table", "NorthwindCustomers") +mapping.ColumnMappings.Add("CompanyName", "Company") +mapping.ColumnMappings.Add("ContactName", "Contact") +mapping.ColumnMappings.Add("PostalCode", "ZIPCode") + +adapter.Fill(custDS) +``` + +```csharp DataTableMapping mapping = - adapter.TableMappings.Add("Table", "NorthwindCustomers"); -mapping.ColumnMappings.Add("CompanyName", "Company"); -mapping.ColumnMappings.Add("ContactName", "Contact"); -mapping.ColumnMappings.Add("PostalCode", "ZIPCode"); - -adapter.Fill(custDS); -``` - - In more advanced situations, you may decide that you want the same **DataAdapter** to support loading different tables with different mappings. To do this, simply add additional **DataTableMapping** objects. - - When the **Fill** method is passed an instance of a **DataSet** and a **DataTableMapping** name, if a mapping with that name exists it is used; otherwise, a **DataTable** with that name is used. - - The following examples create a **DataTableMapping** with a name of **Customers** and a **DataTable** name of **BizTalkSchema**. The example then maps the rows returned by the SELECT statement to the **BizTalkSchema** **DataTable**. - -```vb -Dim mapping As ITableMapping = _ - adapter.TableMappings.Add("Customers", "BizTalkSchema") -mapping.ColumnMappings.Add("CustomerID", "ClientID") -mapping.ColumnMappings.Add("CompanyName", "ClientName") -mapping.ColumnMappings.Add("ContactName", "Contact") -mapping.ColumnMappings.Add("PostalCode", "ZIP") - -adapter.Fill(custDS, "Customers") -``` - -```csharp + adapter.TableMappings.Add("Table", "NorthwindCustomers"); +mapping.ColumnMappings.Add("CompanyName", "Company"); +mapping.ColumnMappings.Add("ContactName", "Contact"); +mapping.ColumnMappings.Add("PostalCode", "ZIPCode"); + +adapter.Fill(custDS); +``` + + In more advanced situations, you may decide that you want the same `DataAdapter` to support loading different tables with different mappings. To do this, simply add additional `DataTableMapping` objects. + + When the `Fill` method is passed an instance of a `DataSet` and a `DataTableMapping` name, if a mapping with that name exists it is used; otherwise, a `DataTable` with that name is used. + + The following examples create a `DataTableMapping` with a name of `Customers` and a `DataTable` name of **BizTalkSchema**. The example then maps the rows returned by the SELECT statement to the `BizTalkSchema` **DataTable**. + +```vb +Dim mapping As ITableMapping = _ + adapter.TableMappings.Add("Customers", "BizTalkSchema") +mapping.ColumnMappings.Add("CustomerID", "ClientID") +mapping.ColumnMappings.Add("CompanyName", "ClientName") +mapping.ColumnMappings.Add("ContactName", "Contact") +mapping.ColumnMappings.Add("PostalCode", "ZIP") + +adapter.Fill(custDS, "Customers") +``` + +```csharp ITableMapping mapping = - adapter.TableMappings.Add("Customers", "BizTalkSchema"); -mapping.ColumnMappings.Add("CustomerID", "ClientID"); -mapping.ColumnMappings.Add("CompanyName", "ClientName"); -mapping.ColumnMappings.Add("ContactName", "Contact"); -mapping.ColumnMappings.Add("PostalCode", "ZIP"); - -adapter.Fill(custDS, "Customers"); -``` - + adapter.TableMappings.Add("Customers", "BizTalkSchema"); +mapping.ColumnMappings.Add("CustomerID", "ClientID"); +mapping.ColumnMappings.Add("CompanyName", "ClientName"); +mapping.ColumnMappings.Add("ContactName", "Contact"); +mapping.ColumnMappings.Add("PostalCode", "ZIP"); + +adapter.Fill(custDS, "Customers"); +``` + > [!NOTE] -> If a source column name is not supplied for a column mapping or a source table name is not supplied for a table mapping, default names will be automatically generated. If no source column is supplied for a column mapping, the column mapping is given an incremental default name of **SourceColumn** *N,* starting with **SourceColumn1**. If no source table name is supplied for a table mapping, the table mapping is given an incremental default name of **SourceTable** *N*, starting with **SourceTable1**. - +> If a source column name is not supplied for a column mapping or a source table name is not supplied for a table mapping, default names will be automatically generated. If no source column is supplied for a column mapping, the column mapping is given an incremental default name of `SourceColumn` *N,* starting with **SourceColumn1**. If no source table name is supplied for a table mapping, the table mapping is given an incremental default name of `SourceTable` *N*, starting with **SourceTable1**. + > [!NOTE] -> We recommend that you avoid the naming convention of **SourceColumn** *N* for a column mapping, or **SourceTable** *N* for a table mapping, because the name you supply may conflict with an existing default column mapping name in the **ColumnMappingCollection** or table mapping name in the **DataTableMappingCollection**. If the supplied name already exists, an exception will be thrown. - -## Handling Multiple Result Sets - - If your **SelectCommand** returns multiple tables, **Fill** automatically generates table names with incremental values for the tables in the **DataSet**, starting with the specified table name and continuing on in the form **TableName** *N*, starting with **TableName1**. You can use table mappings to map the automatically generated table name to a name you want specified for the table in the **DataSet**. For example, for a **SelectCommand** that returns two tables, **Customers** and **Orders**, issue the following call to **Fill**. - -```vb -adapter.Fill(customersDataSet, "Customers") -``` - -```csharp -adapter.Fill(customersDataSet, "Customers"); -``` - - Two tables are created in the **DataSet**: **Customers** and **Customers1**. You can use table mappings to ensure that the second table is named **Orders** instead of **Customers1**. To do this, map the source table of **Customers1** to the **DataSet** table **Orders**, as shown in the following example. - -```vb -adapter.TableMappings.Add("Customers1", "Orders") -adapter.Fill(customersDataSet, "Customers") -``` - -```csharp -adapter.TableMappings.Add("Customers1", "Orders"); -adapter.Fill(customersDataSet, "Customers"); +> We recommend that you avoid the naming convention of `SourceColumn` *N* for a column mapping, or `SourceTable` *N* for a table mapping, because the name you supply may conflict with an existing default column mapping name in the `ColumnMappingCollection` or table mapping name in the **DataTableMappingCollection**. If the supplied name already exists, an exception will be thrown. + +## Handling Multiple Result Sets + + If your `SelectCommand` returns multiple tables, `Fill` automatically generates table names with incremental values for the tables in the **DataSet**, starting with the specified table name and continuing on in the form `TableName` *N*, starting with **TableName1**. You can use table mappings to map the automatically generated table name to a name you want specified for the table in the **DataSet**. For example, for a `SelectCommand` that returns two tables, `Customers` and **Orders**, issue the following call to **Fill**. + +```vb +adapter.Fill(customersDataSet, "Customers") ``` - + +```csharp +adapter.Fill(customersDataSet, "Customers"); +``` + + Two tables are created in the **DataSet**: `Customers` and **Customers1**. You can use table mappings to ensure that the second table is named `Orders` instead of **Customers1**. To do this, map the source table of **Customers1** to the `DataSet` table **Orders**, as shown in the following example. + +```vb +adapter.TableMappings.Add("Customers1", "Orders") +adapter.Fill(customersDataSet, "Customers") +``` + +```csharp +adapter.TableMappings.Add("Customers1", "Orders"); +adapter.Fill(customersDataSet, "Customers"); +``` + ## See also - [DataAdapters and DataReaders](dataadapters-and-datareaders.md) diff --git a/docs/framework/data/adonet/dataadapter-parameters.md b/docs/framework/data/adonet/dataadapter-parameters.md index b7dd9a838b73f..efa6f52b797c3 100644 --- a/docs/framework/data/adonet/dataadapter-parameters.md +++ b/docs/framework/data/adonet/dataadapter-parameters.md @@ -2,167 +2,167 @@ title: "DataAdapter Parameters" description: Learn about the properties of DbDataAdapter that return data from a data source and manage changes to the data source. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: f21e6aba-b76d-46ad-a83e-2ad8e0af1e12 --- # DataAdapter Parameters -The has four properties that are used to retrieve data from and update data to the data source: the property returns data from the data source; and the , , and properties are used to manage changes at the data source. The `SelectCommand` property must be set before you call the `Fill` method of the `DataAdapter`. The `InsertCommand`, `UpdateCommand`, or `DeleteCommand` properties must be set before the `Update` method of the `DataAdapter` is called, depending on what changes were made to the data in the . For example, if rows have been added, the `InsertCommand` must be set before you call `Update`. When `Update` is processing an inserted, updated, or deleted row, the `DataAdapter` uses the respective `Command` property to process the action. Current information about the modified row is passed to the `Command` object through the `Parameters` collection. - - When you update a row at the data source, you call the UPDATE statement, which uses a unique identifier to identify the row in the table to be updated. The unique identifier is typically the value of a primary key field. The UPDATE statement uses parameters that contain both the unique identifier and the columns and values to be updated, as shown in the following Transact-SQL statement. - +The has four properties that are used to retrieve data from and update data to the data source: the property returns data from the data source; and the , , and properties are used to manage changes at the data source. The `SelectCommand` property must be set before you call the `Fill` method of the `DataAdapter`. The `InsertCommand`, `UpdateCommand`, or `DeleteCommand` properties must be set before the `Update` method of the `DataAdapter` is called, depending on what changes were made to the data in the . For example, if rows have been added, the `InsertCommand` must be set before you call `Update`. When `Update` is processing an inserted, updated, or deleted row, the `DataAdapter` uses the respective `Command` property to process the action. Current information about the modified row is passed to the `Command` object through the `Parameters` collection. + + When you update a row at the data source, you call the UPDATE statement, which uses a unique identifier to identify the row in the table to be updated. The unique identifier is typically the value of a primary key field. The UPDATE statement uses parameters that contain both the unique identifier and the columns and values to be updated, as shown in the following Transact-SQL statement. + ```sql UPDATE Customers SET CompanyName = @CompanyName - WHERE CustomerID = @CustomerID -``` - + WHERE CustomerID = @CustomerID +``` + > [!NOTE] -> The syntax for parameter placeholders depends on the data source. This example shows placeholders for a SQL Server data source. Use question mark (?) placeholders for and parameters. - - In this Visual Basic example, the `CompanyName` field is updated with the value of the `@CompanyName` parameter for the row where `CustomerID` equals the value of the `@CustomerID` parameter. The parameters retrieve information from the modified row using the property of the object. The following are the parameters for the previous sample UPDATE statement. The code assumes that the variable `adapter` represents a valid object. - +> The syntax for parameter placeholders depends on the data source. This example shows placeholders for a SQL Server data source. Use question mark (?) placeholders for and parameters. + + In this Visual Basic example, the `CompanyName` field is updated with the value of the `@CompanyName` parameter for the row where `CustomerID` equals the value of the `@CustomerID` parameter. The parameters retrieve information from the modified row using the property of the object. The following are the parameters for the previous sample UPDATE statement. The code assumes that the variable `adapter` represents a valid object. + ```vb -adapter.Parameters.Add( _ - "@CompanyName", SqlDbType.NChar, 15, "CompanyName") -Dim parameter As SqlParameter = _ - adapter.UpdateCommand.Parameters.Add("@CustomerID", _ - SqlDbType.NChar, 5, "CustomerID") -parameter.SourceVersion = DataRowVersion.Original -``` - - The `Add` method of the `Parameters` collection takes the name of the parameter, the data type, the size (if applicable to the type), and the name of the from the `DataTable`. Notice that the of the `@CustomerID` parameter is set to `Original`. This guarantees that the existing row in the data source is updated if the value of the identifying column or columns has been changed in the modified . In that case, the `Original` row value would match the current value at the data source, and the `Current` row value would contain the updated value. The `SourceVersion` for the `@CompanyName` parameter is not set and uses the default, `Current` row value. - +adapter.Parameters.Add( _ + "@CompanyName", SqlDbType.NChar, 15, "CompanyName") +Dim parameter As SqlParameter = _ + adapter.UpdateCommand.Parameters.Add("@CustomerID", _ + SqlDbType.NChar, 5, "CustomerID") +parameter.SourceVersion = DataRowVersion.Original +``` + + The `Add` method of the `Parameters` collection takes the name of the parameter, the data type, the size (if applicable to the type), and the name of the from the `DataTable`. Notice that the of the `@CustomerID` parameter is set to `Original`. This guarantees that the existing row in the data source is updated if the value of the identifying column or columns has been changed in the modified . In that case, the `Original` row value would match the current value at the data source, and the `Current` row value would contain the updated value. The `SourceVersion` for the `@CompanyName` parameter is not set and uses the default, `Current` row value. + > [!NOTE] -> For both the `Fill` operations of the `DataAdapter` and the `Get` methods of the `DataReader`, the .NET Framework type is inferred from the type returned from the .NET Framework data provider. The inferred .NET Framework types and accessor methods for Microsoft SQL Server, OLE DB, and ODBC data types are described in [Data Type Mappings in ADO.NET](data-type-mappings-in-ado-net.md). - -## Parameter.SourceColumn, Parameter.SourceVersion - - The `SourceColumn` and `SourceVersion` may be passed as arguments to the `Parameter` constructor, or set as properties of an existing `Parameter`. The `SourceColumn` is the name of the from the where the value of the `Parameter` will be retrieved. The `SourceVersion` specifies the `DataRow` version that the `DataAdapter` uses to retrieve the value. - - The following table shows the enumeration values available for use with `SourceVersion`. - -|DataRowVersion Enumeration|Description| -|--------------------------------|-----------------| -|`Current`|The parameter uses the current value of the column. This is the default.| -|`Default`|The parameter uses the `DefaultValue` of the column.| -|`Original`|The parameter uses the original value of the column.| -|`Proposed`|The parameter uses a proposed value.| - - The `SqlClient` code example in the next section defines a parameter for an in which the `CustomerID` column is used as a `SourceColumn` for two parameters: `@CustomerID` (`SET CustomerID = @CustomerID`), and `@OldCustomerID` (`WHERE CustomerID = @OldCustomerID`). The `@CustomerID` parameter is used to update the **CustomerID** column to the current value in the `DataRow`. As a result, the `CustomerID` `SourceColumn` with a `SourceVersion` of `Current` is used. The `@OldCustomerID` parameter is used to identify the current row in the data source. Because the matching column value is found in the `Original` version of the row, the same `SourceColumn` (`CustomerID`) with a `SourceVersion` of `Original` is used. - -## Working with SqlClient Parameters - - The following example demonstrates how to create a and set the to in order to retrieve additional schema information from the database. The , , , and properties set and their corresponding objects added to the collection. The method returns a `SqlDataAdapter` object. - +> For both the `Fill` operations of the `DataAdapter` and the `Get` methods of the `DataReader`, the .NET Framework type is inferred from the type returned from the .NET Framework data provider. The inferred .NET Framework types and accessor methods for Microsoft SQL Server, OLE DB, and ODBC data types are described in [Data Type Mappings in ADO.NET](data-type-mappings-in-ado-net.md). + +## Parameter.SourceColumn, Parameter.SourceVersion + + The `SourceColumn` and `SourceVersion` may be passed as arguments to the `Parameter` constructor, or set as properties of an existing `Parameter`. The `SourceColumn` is the name of the from the where the value of the `Parameter` will be retrieved. The `SourceVersion` specifies the `DataRow` version that the `DataAdapter` uses to retrieve the value. + + The following table shows the enumeration values available for use with `SourceVersion`. + +|DataRowVersion Enumeration|Description| +|--------------------------------|-----------------| +|`Current`|The parameter uses the current value of the column. This is the default.| +|`Default`|The parameter uses the `DefaultValue` of the column.| +|`Original`|The parameter uses the original value of the column.| +|`Proposed`|The parameter uses a proposed value.| + + The `SqlClient` code example in the next section defines a parameter for an in which the `CustomerID` column is used as a `SourceColumn` for two parameters: `@CustomerID` (`SET CustomerID = @CustomerID`), and `@OldCustomerID` (`WHERE CustomerID = @OldCustomerID`). The `@CustomerID` parameter is used to update the `CustomerID` column to the current value in the `DataRow`. As a result, the `CustomerID` `SourceColumn` with a `SourceVersion` of `Current` is used. The `@OldCustomerID` parameter is used to identify the current row in the data source. Because the matching column value is found in the `Original` version of the row, the same `SourceColumn` (`CustomerID`) with a `SourceVersion` of `Original` is used. + +## Working with SqlClient Parameters + + The following example demonstrates how to create a and set the to in order to retrieve additional schema information from the database. The , , , and properties set and their corresponding objects added to the collection. The method returns a `SqlDataAdapter` object. + [!code-csharp[Classic WebData SqlDataAdapter.SqlDataAdapter Example#1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataAdapter.SqlDataAdapter Example/CS/source.cs#1)] - [!code-vb[Classic WebData SqlDataAdapter.SqlDataAdapter Example#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlDataAdapter.SqlDataAdapter Example/VB/source.vb#1)] - -## OleDb Parameter Placeholders - - For the and objects, you must use question mark (?) placeholders to identify the parameters. - -```vb -Dim selectSQL As String = _ - "SELECT CustomerID, CompanyName FROM Customers " & _ - "WHERE CountryRegion = ? AND City = ?" -Dim insertSQL AS String = _ - "INSERT INTO Customers (CustomerID, CompanyName) VALUES (?, ?)" -Dim updateSQL AS String = _ - "UPDATE Customers SET CustomerID = ?, CompanyName = ? " & _ - WHERE CustomerID = ?" -Dim deleteSQL As String = "DELETE FROM Customers WHERE CustomerID = ?" -``` - -```csharp + [!code-vb[Classic WebData SqlDataAdapter.SqlDataAdapter Example#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/Classic WebData SqlDataAdapter.SqlDataAdapter Example/VB/source.vb#1)] + +## OleDb Parameter Placeholders + + For the and objects, you must use question mark (?) placeholders to identify the parameters. + +```vb +Dim selectSQL As String = _ + "SELECT CustomerID, CompanyName FROM Customers " & _ + "WHERE CountryRegion = ? AND City = ?" +Dim insertSQL AS String = _ + "INSERT INTO Customers (CustomerID, CompanyName) VALUES (?, ?)" +Dim updateSQL AS String = _ + "UPDATE Customers SET CustomerID = ?, CompanyName = ? " & _ + WHERE CustomerID = ?" +Dim deleteSQL As String = "DELETE FROM Customers WHERE CustomerID = ?" +``` + +```csharp string selectSQL = - "SELECT CustomerID, CompanyName FROM Customers " + - "WHERE CountryRegion = ? AND City = ?"; + "SELECT CustomerID, CompanyName FROM Customers " + + "WHERE CountryRegion = ? AND City = ?"; string insertSQL = - "INSERT INTO Customers (CustomerID, CompanyName) " + - "VALUES (?, ?)"; + "INSERT INTO Customers (CustomerID, CompanyName) " + + "VALUES (?, ?)"; string updateSQL = - "UPDATE Customers SET CustomerID = ?, CompanyName = ? " + - "WHERE CustomerID = ? "; -string deleteSQL = "DELETE FROM Customers WHERE CustomerID = ?"; -``` - - The parameterized query statements define which input and output parameters must be created. To create a parameter, use the `Parameters.Add` method or the `Parameter` constructor to specify the column name, data type, and size. For intrinsic data types, such as `Integer`, you do not have to include the size, or you can specify the default size. - - The following code example creates the parameters for a SQL statement and then fills a `DataSet`. - -## OleDb Example - -```vb -' Assumes that connection is a valid OleDbConnection object. + "UPDATE Customers SET CustomerID = ?, CompanyName = ? " + + "WHERE CustomerID = ? "; +string deleteSQL = "DELETE FROM Customers WHERE CustomerID = ?"; +``` + + The parameterized query statements define which input and output parameters must be created. To create a parameter, use the `Parameters.Add` method or the `Parameter` constructor to specify the column name, data type, and size. For intrinsic data types, such as `Integer`, you do not have to include the size, or you can specify the default size. + + The following code example creates the parameters for a SQL statement and then fills a `DataSet`. + +## OleDb Example + +```vb +' Assumes that connection is a valid OleDbConnection object. Dim adapter As OleDbDataAdapter = New OleDbDataAdapter - -Dim selectCMD AS OleDbCommand = New OleDbCommand(selectSQL, connection) -adapter.SelectCommand = selectCMD - -' Add parameters and set values. -selectCMD.Parameters.Add( _ - "@CountryRegion", OleDbType.VarChar, 15).Value = "UK" -selectCMD.Parameters.Add( _ - "@City", OleDbType.VarChar, 15).Value = "London" - -Dim customers As DataSet = New DataSet -adapter.Fill(customers, "Customers") -``` - -```csharp -// Assumes that connection is a valid OleDbConnection object. -OleDbDataAdapter adapter = new OleDbDataAdapter(); - -OleDbCommand selectCMD = new OleDbCommand(selectSQL, connection); -adapter.SelectCommand = selectCMD; - -// Add parameters and set values. -selectCMD.Parameters.Add( - "@CountryRegion", OleDbType.VarChar, 15).Value = "UK"; -selectCMD.Parameters.Add( - "@City", OleDbType.VarChar, 15).Value = "London"; - -DataSet customers = new DataSet(); -adapter.Fill(customers, "Customers"); -``` - -## Odbc Parameters - -```vb -' Assumes that connection is a valid OdbcConnection object. -Dim adapter As OdbcDataAdapter = New OdbcDataAdapter - -Dim selectCMD AS OdbcCommand = New OdbcCommand(selectSQL, connection) -adapter.SelectCommand = selectCMD - -' Add Parameters and set values. -selectCMD.Parameters.Add("@CountryRegion", OdbcType.VarChar, 15).Value = "UK" -selectCMD.Parameters.Add("@City", OdbcType.VarChar, 15).Value = "London" - -Dim customers As DataSet = New DataSet -adapter.Fill(customers, "Customers") -``` - -```csharp -// Assumes that connection is a valid OdbcConnection object. -OdbcDataAdapter adapter = new OdbcDataAdapter(); - -OdbcCommand selectCMD = new OdbcCommand(selectSQL, connection); -adapter.SelectCommand = selectCMD; - -//Add Parameters and set values. -selectCMD.Parameters.Add("@CountryRegion", OdbcType.VarChar, 15).Value = "UK"; -selectCMD.Parameters.Add("@City", OdbcType.VarChar, 15).Value = "London"; - -DataSet customers = new DataSet(); -adapter.Fill(customers, "Customers"); -``` - + +Dim selectCMD AS OleDbCommand = New OleDbCommand(selectSQL, connection) +adapter.SelectCommand = selectCMD + +' Add parameters and set values. +selectCMD.Parameters.Add( _ + "@CountryRegion", OleDbType.VarChar, 15).Value = "UK" +selectCMD.Parameters.Add( _ + "@City", OleDbType.VarChar, 15).Value = "London" + +Dim customers As DataSet = New DataSet +adapter.Fill(customers, "Customers") +``` + +```csharp +// Assumes that connection is a valid OleDbConnection object. +OleDbDataAdapter adapter = new OleDbDataAdapter(); + +OleDbCommand selectCMD = new OleDbCommand(selectSQL, connection); +adapter.SelectCommand = selectCMD; + +// Add parameters and set values. +selectCMD.Parameters.Add( + "@CountryRegion", OleDbType.VarChar, 15).Value = "UK"; +selectCMD.Parameters.Add( + "@City", OleDbType.VarChar, 15).Value = "London"; + +DataSet customers = new DataSet(); +adapter.Fill(customers, "Customers"); +``` + +## Odbc Parameters + +```vb +' Assumes that connection is a valid OdbcConnection object. +Dim adapter As OdbcDataAdapter = New OdbcDataAdapter + +Dim selectCMD AS OdbcCommand = New OdbcCommand(selectSQL, connection) +adapter.SelectCommand = selectCMD + +' Add Parameters and set values. +selectCMD.Parameters.Add("@CountryRegion", OdbcType.VarChar, 15).Value = "UK" +selectCMD.Parameters.Add("@City", OdbcType.VarChar, 15).Value = "London" + +Dim customers As DataSet = New DataSet +adapter.Fill(customers, "Customers") +``` + +```csharp +// Assumes that connection is a valid OdbcConnection object. +OdbcDataAdapter adapter = new OdbcDataAdapter(); + +OdbcCommand selectCMD = new OdbcCommand(selectSQL, connection); +adapter.SelectCommand = selectCMD; + +//Add Parameters and set values. +selectCMD.Parameters.Add("@CountryRegion", OdbcType.VarChar, 15).Value = "UK"; +selectCMD.Parameters.Add("@City", OdbcType.VarChar, 15).Value = "London"; + +DataSet customers = new DataSet(); +adapter.Fill(customers, "Customers"); +``` + > [!NOTE] -> If a parameter name is not supplied for a parameter, the parameter is given an incremental default name of Parameter*N* *,* starting with "Parameter1". We recommend that you avoid the Parameter*N* naming convention when you supply a parameter name, because the name that you supply might conflict with an existing default parameter name in the `ParameterCollection`. If the supplied name already exists, an exception is thrown. - +> If a parameter name is not supplied for a parameter, the parameter is given an incremental default name of Parameter*N* *,* starting with "Parameter1". We recommend that you avoid the Parameter*N* naming convention when you supply a parameter name, because the name that you supply might conflict with an existing default parameter name in the `ParameterCollection`. If the supplied name already exists, an exception is thrown. + ## See also - [DataAdapters and DataReaders](dataadapters-and-datareaders.md) diff --git a/docs/framework/data/adonet/dataadapters-and-datareaders.md b/docs/framework/data/adonet/dataadapters-and-datareaders.md index 8f409c06b96e5..6a1b269075a97 100644 --- a/docs/framework/data/adonet/dataadapters-and-datareaders.md +++ b/docs/framework/data/adonet/dataadapters-and-datareaders.md @@ -6,41 +6,41 @@ ms.assetid: cc952ca2-ec19-46ab-9189-15174b52cb74 --- # DataAdapters and DataReaders -You can use the ADO.NET **DataReader** to retrieve a read-only, forward-only stream of data from a database. Results are returned as the query executes, and are stored in the network buffer on the client until you request them using the **Read** method of the **DataReader**. Using the **DataReader** can increase application performance both by retrieving data as soon as it is available, and (by default) storing only one row at a time in memory, reducing system overhead. - - A is used to retrieve data from a data source and populate tables within a . The `DataAdapter` also resolves changes made to the `DataSet` back to the data source. The `DataAdapter` uses the `Connection` object of the .NET Framework data provider to connect to a data source, and it uses `Command` objects to retrieve data from and resolve changes to the data source. - - Each .NET Framework data provider included with the .NET Framework has a and a object: the .NET Framework Data Provider for OLE DB includes an and an object, the .NET Framework Data Provider for SQL Server includes a and a object, the .NET Framework Data Provider for ODBC includes an and an object, and the .NET Framework Data Provider for Oracle includes an and an object. - -## In This Section - - [Retrieving Data Using a DataReader](retrieving-data-using-a-datareader.md) - Describes the ADO.NET **DataReader** object and how to use it to return a stream of results from a data source. - - [Populating a DataSet from a DataAdapter](populating-a-dataset-from-a-dataadapter.md) - Describes how to fill a `DataSet` with tables, columns, and rows by using a `DataAdapter`. - - [DataAdapter Parameters](dataadapter-parameters.md) - Describes how to use parameters with the command properties of a `DataAdapter` including how to map the contents of a column in a `DataSet` to a command parameter. - - [Adding Existing Constraints to a DataSet](adding-existing-constraints-to-a-dataset.md) - Describes how to add existing constraints to a `DataSet`. - - [DataAdapter DataTable and DataColumn Mappings](dataadapter-datatable-and-datacolumn-mappings.md) - Describes how to set up `DataTableMappings` and `ColumnMappings` for a `DataAdapter`. - - [Paging Through a Query Result](paging-through-a-query-result.md) - Provides an example of viewing the results of a query as pages of data. - - [Updating Data Sources with DataAdapters](updating-data-sources-with-dataadapters.md) - Describes how to use a `DataAdapter` to resolve changes in a `DataSet` back to the database. - - [Handling DataAdapter Events](handling-dataadapter-events.md) - Describes `DataAdapter` events and how to use them. - - [Performing Batch Operations Using DataAdapters](performing-batch-operations-using-dataadapters.md) - Describes enhancing application performance by reducing the number of round trips to SQL Server when applying updates from the `DataSet`. - +You can use the ADO.NET `DataReader` to retrieve a read-only, forward-only stream of data from a database. Results are returned as the query executes, and are stored in the network buffer on the client until you request them using the `Read` method of the **DataReader**. Using the `DataReader` can increase application performance both by retrieving data as soon as it is available, and (by default) storing only one row at a time in memory, reducing system overhead. + + A is used to retrieve data from a data source and populate tables within a . The `DataAdapter` also resolves changes made to the `DataSet` back to the data source. The `DataAdapter` uses the `Connection` object of the .NET Framework data provider to connect to a data source, and it uses `Command` objects to retrieve data from and resolve changes to the data source. + + Each .NET Framework data provider included with the .NET Framework has a and a object: the .NET Framework Data Provider for OLE DB includes an and an object, the .NET Framework Data Provider for SQL Server includes a and a object, the .NET Framework Data Provider for ODBC includes an and an object, and the .NET Framework Data Provider for Oracle includes an and an object. + +## In This Section + + [Retrieving Data Using a DataReader](retrieving-data-using-a-datareader.md) + Describes the ADO.NET `DataReader` object and how to use it to return a stream of results from a data source. + + [Populating a DataSet from a DataAdapter](populating-a-dataset-from-a-dataadapter.md) + Describes how to fill a `DataSet` with tables, columns, and rows by using a `DataAdapter`. + + [DataAdapter Parameters](dataadapter-parameters.md) + Describes how to use parameters with the command properties of a `DataAdapter` including how to map the contents of a column in a `DataSet` to a command parameter. + + [Adding Existing Constraints to a DataSet](adding-existing-constraints-to-a-dataset.md) + Describes how to add existing constraints to a `DataSet`. + + [DataAdapter DataTable and DataColumn Mappings](dataadapter-datatable-and-datacolumn-mappings.md) + Describes how to set up `DataTableMappings` and `ColumnMappings` for a `DataAdapter`. + + [Paging Through a Query Result](paging-through-a-query-result.md) + Provides an example of viewing the results of a query as pages of data. + + [Updating Data Sources with DataAdapters](updating-data-sources-with-dataadapters.md) + Describes how to use a `DataAdapter` to resolve changes in a `DataSet` back to the database. + + [Handling DataAdapter Events](handling-dataadapter-events.md) + Describes `DataAdapter` events and how to use them. + + [Performing Batch Operations Using DataAdapters](performing-batch-operations-using-dataadapters.md) + Describes enhancing application performance by reducing the number of round trips to SQL Server when applying updates from the `DataSet`. + ## See also - [Connecting to a Data Source](connecting-to-a-data-source.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/acceptchanges-and-rejectchanges.md b/docs/framework/data/adonet/dataset-datatable-dataview/acceptchanges-and-rejectchanges.md index c0847318b1fee..04000d0f34783 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/acceptchanges-and-rejectchanges.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/acceptchanges-and-rejectchanges.md @@ -2,56 +2,56 @@ description: "Learn more about: AcceptChanges and RejectChanges" title: "AcceptChanges and RejectChanges" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: e2d1a6fe-31f9-4b83-9728-06c406a3394e --- # AcceptChanges and RejectChanges -After verifying the accuracy of changes made to data in a , you can accept the changes using the method of the , , or , which will set the **Current** row values to be the **Original** values and will set the **RowState** property to **Unchanged**. Accepting or rejecting changes clears out any **RowError** information and sets the **HasErrors** property to **false**. Accepting or rejecting changes can also affect updating data in the data source. For more information, see [Updating Data Sources with DataAdapters](../updating-data-sources-with-dataadapters.md). - - If foreign key constraints exist on the **DataTable**, changes accepted or rejected using **AcceptChanges** and **RejectChanges** are propagated to child rows of the **DataRow** according to the **ForeignKeyConstraint.AcceptRejectRule**. For more information, see [DataTable Constraints](datatable-constraints.md). - - The following example checks for rows with errors, resolves the errors where applicable, and rejects the rows where the error cannot be resolved. Note that, for resolved errors, the **RowError** value is reset to an empty string, causing the **HasErrors** property to be set to **false**. When all the rows with errors have been resolved or rejected, **AcceptChanges** is called to accept all changes for the entire **DataTable**. - -```vb -If workTable.HasErrors Then - Dim errRow As DataRow - - For Each errRow in workTable.GetErrors() - - If errRow.RowError = "Total cannot exceed 1000." Then - errRow("Total") = 1000 - errRow.RowError = "" ' Clear the error. - Else - errRow.RejectChanges() - End If - Next -End If - -workTable.AcceptChanges() -``` - -```csharp -if (workTable.HasErrors) -{ - - foreach (DataRow errRow in workTable.GetErrors()) - { - if (errRow.RowError == "Total cannot exceed 1000.") - { - errRow["Total"] = 1000; - errRow.RowError = ""; // Clear the error. - } - else - errRow.RejectChanges(); - } -} - -workTable.AcceptChanges(); -``` - +After verifying the accuracy of changes made to data in a , you can accept the changes using the method of the , , or , which will set the `Current` row values to be the `Original` values and will set the `RowState` property to **Unchanged**. Accepting or rejecting changes clears out any `RowError` information and sets the `HasErrors` property to **false**. Accepting or rejecting changes can also affect updating data in the data source. For more information, see [Updating Data Sources with DataAdapters](../updating-data-sources-with-dataadapters.md). + + If foreign key constraints exist on the **DataTable**, changes accepted or rejected using `AcceptChanges` and `RejectChanges` are propagated to child rows of the `DataRow` according to the **ForeignKeyConstraint.AcceptRejectRule**. For more information, see [DataTable Constraints](datatable-constraints.md). + + The following example checks for rows with errors, resolves the errors where applicable, and rejects the rows where the error cannot be resolved. Note that, for resolved errors, the `RowError` value is reset to an empty string, causing the `HasErrors` property to be set to **false**. When all the rows with errors have been resolved or rejected, `AcceptChanges` is called to accept all changes for the entire **DataTable**. + +```vb +If workTable.HasErrors Then + Dim errRow As DataRow + + For Each errRow in workTable.GetErrors() + + If errRow.RowError = "Total cannot exceed 1000." Then + errRow("Total") = 1000 + errRow.RowError = "" ' Clear the error. + Else + errRow.RejectChanges() + End If + Next +End If + +workTable.AcceptChanges() +``` + +```csharp +if (workTable.HasErrors) +{ + + foreach (DataRow errRow in workTable.GetErrors()) + { + if (errRow.RowError == "Total cannot exceed 1000.") + { + errRow["Total"] = 1000; + errRow.RowError = ""; // Clear the error. + } + else + errRow.RejectChanges(); + } +} + +workTable.AcceptChanges(); +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/adding-a-datatable-to-a-dataset.md b/docs/framework/data/adonet/dataset-datatable-dataview/adding-a-datatable-to-a-dataset.md index db02968018d95..77900b50a9ff2 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/adding-a-datatable-to-a-dataset.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/adding-a-datatable-to-a-dataset.md @@ -2,35 +2,35 @@ title: "Adding a DataTable to a DataSet" description: Refer to this example code to learn how to create DataTable objects and add them to an existing DataSet in ADO.NET. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 556d29a3-8fc9-4e38-b3ee-c188f7e7b155 --- # Adding a DataTable to a DataSet -ADO.NET enables you to create objects and add them to an existing . You can set constraint information for a by using the and properties. - -## Example +ADO.NET enables you to create objects and add them to an existing . You can set constraint information for a by using the and properties. + +## Example + + The following example constructs a , adds a new object to the , and then adds three objects to the table. Finally, the code sets one column as the primary key column. - The following example constructs a , adds a new object to the , and then adds three objects to the table. Finally, the code sets one column as the primary key column. - [!code-csharp[DataWorks Data.DataTableAdd#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/CS/source.cs#1)] - [!code-vb[DataWorks Data.DataTableAdd#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/VB/source.vb#1)] - -## Case Sensitivity - - Two or more tables or relations with the same name, but different casing, can exist in a . In such cases, references by name to tables and relations are case sensitive. For example, if the **dataSet** contains tables **Table1** and **table1**, you would reference **Table1** by name as **dataSet.Tables["Table1"]**, and **table1** as **dataSet.Tables["table1"]**. Attempting to reference either of the tables as **dataSet.Tables["TABLE1"]** would generate an exception. - - The case-sensitivity behavior does not apply if only one table or relation has a particular name. For example, if the has only **Table1**, you can reference it using **dataSet.Tables["TABLE1"]**. - + [!code-vb[DataWorks Data.DataTableAdd#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks Data.DataTableAdd/VB/source.vb#1)] + +## Case Sensitivity + + Two or more tables or relations with the same name, but different casing, can exist in a . In such cases, references by name to tables and relations are case sensitive. For example, if the `dataSet` contains tables **Table1** and **table1**, you would reference **Table1** by name as **dataSet.Tables["Table1"]**, and **table1** as **dataSet.Tables["table1"]**. Attempting to reference either of the tables as **dataSet.Tables["TABLE1"]** would generate an exception. + + The case-sensitivity behavior does not apply if only one table or relation has a particular name. For example, if the has only **Table1**, you can reference it using **dataSet.Tables["TABLE1"]**. + > [!NOTE] -> The property of the does not affect this behavior. The property applies to the data in the and affects sorting, searching, filtering, enforcing constraints, and so on. - -## Namespace Support +> The property of the does not affect this behavior. The property applies to the data in the and affects sorting, searching, filtering, enforcing constraints, and so on. + +## Namespace Support + + In versions of ADO.NET earlier than 2.0, two tables could not have the same name, even if they were in different namespaces. This limitation was removed in ADO.NET 2.0. A can contain two tables that have the same property value but different property values. - In versions of ADO.NET earlier than 2.0, two tables could not have the same name, even if they were in different namespaces. This limitation was removed in ADO.NET 2.0. A can contain two tables that have the same property value but different property values. - ## See also - [DataSets, DataTables, and DataViews](index.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable.md b/docs/framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable.md index 739745e24181e..de74693924884 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable.md @@ -2,51 +2,51 @@ title: "Adding Columns to a DataTable" description: A DataTable contains DataColumn objects referenced by the Columns property of the table. Use this example code to add columns to a table in ADO.NET. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: e85c4a0e-4f3f-458c-b58b-0ddbc06bf974 --- # Adding Columns to a DataTable -A contains a collection of objects referenced by the **Columns** property of the table. This collection of columns, along with any constraints, defines the schema, or structure, of the table. - - You create **DataColumn** objects within a table by using the **DataColumn** constructor, or by calling the **Add** method of the **Columns** property of the table, which is a . The **Add** method accepts optional **ColumnName**, **DataType**, and **Expression** arguments and creates a new **DataColumn** as a member of the collection. It also accepts an existing **DataColumn** object and adds it to the collection, and returns a reference to the added **DataColumn** if requested. Because **DataTable** objects are not specific to any data source, .NET Framework types are used when specifying the data type of a **DataColumn**. - - The following example adds four columns to a **DataTable**. - -```vb -Dim workTable As DataTable = New DataTable("Customers") - -Dim workCol As DataColumn = workTable.Columns.Add( _ - "CustID", Type.GetType("System.Int32")) -workCol.AllowDBNull = false -workCol.Unique = true - -workTable.Columns.Add("CustLName", Type.GetType("System.String")) -workTable.Columns.Add("CustFName", Type.GetType("System.String")) -workTable.Columns.Add("Purchases", Type.GetType("System.Double")) -``` - -```csharp -DataTable workTable = new DataTable("Customers"); - -DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32)); -workCol.AllowDBNull = false; -workCol.Unique = true; - -workTable.Columns.Add("CustLName", typeof(String)); -workTable.Columns.Add("CustFName", typeof(String)); -workTable.Columns.Add("Purchases", typeof(Double)); -``` - - In the example, notice that the properties for the **CustID** column are set to not allow **DBNull** values and to constrain values to be unique. However, if you define the **CustID** column as the primary key column of the table, the **AllowDBNull** property will automatically be set to **false** and the **Unique** property will automatically be set to **true**. For more information, see [Defining Primary Keys](defining-primary-keys.md). - +A contains a collection of objects referenced by the `Columns` property of the table. This collection of columns, along with any constraints, defines the schema, or structure, of the table. + + You create `DataColumn` objects within a table by using the `DataColumn` constructor, or by calling the `Add` method of the `Columns` property of the table, which is a . The `Add` method accepts optional **ColumnName**, **DataType**, and `Expression` arguments and creates a new `DataColumn` as a member of the collection. It also accepts an existing `DataColumn` object and adds it to the collection, and returns a reference to the added `DataColumn` if requested. Because `DataTable` objects are not specific to any data source, .NET Framework types are used when specifying the data type of a **DataColumn**. + + The following example adds four columns to a **DataTable**. + +```vb +Dim workTable As DataTable = New DataTable("Customers") + +Dim workCol As DataColumn = workTable.Columns.Add( _ + "CustID", Type.GetType("System.Int32")) +workCol.AllowDBNull = false +workCol.Unique = true + +workTable.Columns.Add("CustLName", Type.GetType("System.String")) +workTable.Columns.Add("CustFName", Type.GetType("System.String")) +workTable.Columns.Add("Purchases", Type.GetType("System.Double")) +``` + +```csharp +DataTable workTable = new DataTable("Customers"); + +DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32)); +workCol.AllowDBNull = false; +workCol.Unique = true; + +workTable.Columns.Add("CustLName", typeof(String)); +workTable.Columns.Add("CustFName", typeof(String)); +workTable.Columns.Add("Purchases", typeof(Double)); +``` + + In the example, notice that the properties for the `CustID` column are set to not allow `DBNull` values and to constrain values to be unique. However, if you define the `CustID` column as the primary key column of the table, the `AllowDBNull` property will automatically be set to `false` and the `Unique` property will automatically be set to **true**. For more information, see [Defining Primary Keys](defining-primary-keys.md). + > [!CAUTION] -> If a column name is not supplied for a column, the column is given an incremental default name of Column*N,* starting with "Column1", when it is added to the **DataColumnCollection**. We recommend that you avoid the naming convention of "Column*N*" when you supply a column name, because the name you supply may conflict with an existing default column name in the **DataColumnCollection**. If the supplied name already exists, an exception is thrown. - - If you are using as the of a in the , XML serialization will not work when you read in data. For example, if you write out a by using the `DataTable.WriteXml` method, upon serialization to XML there is an additional parent node in the . To work around this problem, use the type instead of . `ReadXml` and `WriteXml` work correctly with . - +> If a column name is not supplied for a column, the column is given an incremental default name of Column*N,* starting with "Column1", when it is added to the **DataColumnCollection**. We recommend that you avoid the naming convention of "Column*N*" when you supply a column name, because the name you supply may conflict with an existing default column name in the **DataColumnCollection**. If the supplied name already exists, an exception is thrown. + + If you are using as the of a in the , XML serialization will not work when you read in data. For example, if you write out a by using the `DataTable.WriteXml` method, upon serialization to XML there is an additional parent node in the . To work around this problem, use the type instead of . `ReadXml` and `WriteXml` work correctly with . + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/adding-data-to-a-datatable.md b/docs/framework/data/adonet/dataset-datatable-dataview/adding-data-to-a-datatable.md index 6f9d5128bb77a..5d49640ce1849 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/adding-data-to-a-datatable.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/adding-data-to-a-datatable.md @@ -2,85 +2,85 @@ title: "Adding Data to a DataTable" description: Refer to this example code to add new rows of data to a table in ADO.NET, after you create a DataTable and define its structure using columns and constraints. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: d6aa8474-7bde-48f7-949d-20dc38a1625b --- # Adding Data to a DataTable -After you create a and define its structure using columns and constraints, you can add new rows of data to the table. To add a new row, declare a new variable as type . A new **DataRow** object is returned when you call the method. The **DataTable** then creates the **DataRow** object based on the structure of the table, as defined by the . - - The following example demonstrates how to create a new row by calling the **NewRow** method. - -```vb -Dim workRow As DataRow = workTable.NewRow() -``` - -```csharp -DataRow workRow = workTable.NewRow(); -``` - - You then can manipulate the newly added row using an index or the column name, as shown in the following example. - -```vb -workRow("CustLName") = "Smith" -workRow(1) = "Smith" -``` - -```csharp -workRow["CustLName"] = "Smith"; -workRow[1] = "Smith"; -``` - - After data is inserted into the new row, the **Add** method is used to add the row to the , shown in the following code. - -```vb -workTable.Rows.Add(workRow) -``` - -```csharp -workTable.Rows.Add(workRow); -``` - - You can also call the **Add** method to add a new row by passing in an array of values, typed as , as shown in the following example. - -```vb -workTable.Rows.Add(new Object() {1, "Smith"}) -``` - -```csharp -workTable.Rows.Add(new Object[] {1, "Smith"}); -``` - - Passing an array of values, typed as **Object**, to the **Add** method creates a new row inside the table and sets its column values to the values in the object array. Note that values in the array are matched sequentially to the columns, based on the order in which they appear in the table. - - The following example adds 10 rows to the newly created **Customers** table. - -```vb -Dim workRow As DataRow -Dim i As Integer - -For i = 0 To 9 - workRow = workTable.NewRow() - workRow(0) = i - workRow(1) = "CustName" & I.ToString() - workTable.Rows.Add(workRow) -Next -``` - -```csharp -DataRow workRow; - +After you create a and define its structure using columns and constraints, you can add new rows of data to the table. To add a new row, declare a new variable as type . A new `DataRow` object is returned when you call the method. The `DataTable` then creates the `DataRow` object based on the structure of the table, as defined by the . + + The following example demonstrates how to create a new row by calling the `NewRow` method. + +```vb +Dim workRow As DataRow = workTable.NewRow() +``` + +```csharp +DataRow workRow = workTable.NewRow(); +``` + + You then can manipulate the newly added row using an index or the column name, as shown in the following example. + +```vb +workRow("CustLName") = "Smith" +workRow(1) = "Smith" +``` + +```csharp +workRow["CustLName"] = "Smith"; +workRow[1] = "Smith"; +``` + + After data is inserted into the new row, the `Add` method is used to add the row to the , shown in the following code. + +```vb +workTable.Rows.Add(workRow) +``` + +```csharp +workTable.Rows.Add(workRow); +``` + + You can also call the `Add` method to add a new row by passing in an array of values, typed as , as shown in the following example. + +```vb +workTable.Rows.Add(new Object() {1, "Smith"}) +``` + +```csharp +workTable.Rows.Add(new Object[] {1, "Smith"}); +``` + + Passing an array of values, typed as **Object**, to the `Add` method creates a new row inside the table and sets its column values to the values in the object array. Note that values in the array are matched sequentially to the columns, based on the order in which they appear in the table. + + The following example adds 10 rows to the newly created `Customers` table. + +```vb +Dim workRow As DataRow +Dim i As Integer + +For i = 0 To 9 + workRow = workTable.NewRow() + workRow(0) = i + workRow(1) = "CustName" & I.ToString() + workTable.Rows.Add(workRow) +Next +``` + +```csharp +DataRow workRow; + for (int i = 0; i <= 9; i++) -{ - workRow = workTable.NewRow(); - workRow[0] = i; - workRow[1] = "CustName" + i.ToString(); - workTable.Rows.Add(workRow); -} -``` - +{ + workRow = workTable.NewRow(); + workRow[0] = i; + workRow[1] = "CustName" + i.ToString(); + workTable.Rows.Add(workRow); +} +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/adding-datarelations.md b/docs/framework/data/adonet/dataset-datatable-dataview/adding-datarelations.md index 6a071134e2292..69671f237408b 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/adding-datarelations.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/adding-datarelations.md @@ -2,35 +2,35 @@ description: "Learn more about: Adding DataRelations" title: "Adding DataRelations" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: a4a564fb-c1c4-4135-b6c2-b030e51195e4 --- # Adding DataRelations -In a with multiple objects, you can use objects to relate one table to another, to navigate through the tables, and to return child or parent rows from a related table. - - The arguments required to create a **DataRelation** are a name for the **DataRelation** being created, and an array of one or more references to the columns that serve as the parent and child columns in the relationship. After you have created a **DataRelation**, you can use it to navigate between tables and to retrieve values. - - Adding a **DataRelation** to a adds, by default, a to the parent table and a to the child table. For more information about these default constraints, see [DataTable Constraints](datatable-constraints.md). - - The following code example creates a **DataRelation** using two objects in a . Each contains a column named **CustID**, which serves as a link between the two objects. The example adds a single **DataRelation** to the **Relations** collection of the . The first argument in the example specifies the name of the **DataRelation** being created. The second argument sets the parent **DataColumn** and the third argument sets the child **DataColumn**. - -```vb -customerOrders.Relations.Add("CustOrders", _ - customerOrders.Tables("Customers").Columns("CustID"), _ - customerOrders.Tables("Orders").Columns("CustID")) -``` - -```csharp -customerOrders.Relations.Add("CustOrders", - customerOrders.Tables["Customers"].Columns["CustID"], - customerOrders.Tables["Orders"].Columns["CustID"]); -``` - - A **DataRelation** also has a **Nested** property which, when set to **true**, causes the rows from the child table to be nested within the associated row from the parent table when written as XML elements using . For more information, see [Using XML in a DataSet](using-xml-in-a-dataset.md). - +In a with multiple objects, you can use objects to relate one table to another, to navigate through the tables, and to return child or parent rows from a related table. + + The arguments required to create a `DataRelation` are a name for the `DataRelation` being created, and an array of one or more references to the columns that serve as the parent and child columns in the relationship. After you have created a **DataRelation**, you can use it to navigate between tables and to retrieve values. + + Adding a `DataRelation` to a adds, by default, a to the parent table and a to the child table. For more information about these default constraints, see [DataTable Constraints](datatable-constraints.md). + + The following code example creates a `DataRelation` using two objects in a . Each contains a column named **CustID**, which serves as a link between the two objects. The example adds a single `DataRelation` to the `Relations` collection of the . The first argument in the example specifies the name of the `DataRelation` being created. The second argument sets the parent `DataColumn` and the third argument sets the child **DataColumn**. + +```vb +customerOrders.Relations.Add("CustOrders", _ + customerOrders.Tables("Customers").Columns("CustID"), _ + customerOrders.Tables("Orders").Columns("CustID")) +``` + +```csharp +customerOrders.Relations.Add("CustOrders", + customerOrders.Tables["Customers"].Columns["CustID"], + customerOrders.Tables["Orders"].Columns["CustID"]); +``` + + A `DataRelation` also has a `Nested` property which, when set to **true**, causes the rows from the child table to be nested within the associated row from the parent table when written as XML elements using . For more information, see [Using XML in a DataSet](using-xml-in-a-dataset.md). + ## See also - [DataSets, DataTables, and DataViews](index.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/annotating-typed-datasets.md b/docs/framework/data/adonet/dataset-datatable-dataview/annotating-typed-datasets.md index b490862edac09..cd496c8fc89e3 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/annotating-typed-datasets.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/annotating-typed-datasets.md @@ -2,222 +2,222 @@ description: "Learn more about: Annotating Typed DataSets" title: "Annotating Typed DataSets" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: f82aaa62-321e-4c8a-b51b-9d1114700170 --- # Annotating Typed DataSets -Annotations enable you to modify the names of the elements in your typed without modifying the underlying schema. Modifying the names of the elements in your underlying schema would cause the typed **DataSet** to refer to objects that do not exist in the data source, as well as lose a reference to the objects that do exist in the data source. - - Using annotations, you can customize the names of objects in your typed **DataSet** with more meaningful names, making code more readable and your typed **DataSet** easier for clients to use, while leaving underlying schema intact. For example, the following schema element for the **Customers** table of the **Northwind** database would result in a **DataRow** object name of **CustomersRow** and a named **Customers**. - -```xml - - - - - - - -``` - - A **DataRowCollection** name of **Customers** is meaningful in client code, but a **DataRow** name of **CustomersRow** is misleading because it is a single object. Also, in common scenarios, the object would be referred to without the **Row** identifier and instead would be simply referred to as a **Customer** object. The solution is to annotate the schema and identify new names for the **DataRow** and **DataRowCollection** objects. Following is the annotated version of the previous schema. - -```xml - - - - - - - -``` - - Specifying a **typedName** value of **Customer** will result in a **DataRow** object name of **Customer**. Specifying a **typedPlural** value of **Customers** preserves the **DataRowCollection** name of **Customers**. - - The following table shows the annotations available for use. - -|Annotation|Description| -|----------------|-----------------| -|**typedName**|Name of the object.| -|**typedPlural**|Name of a collection of objects.| -|**typedParent**|Name of the object when referred to in a parent relationship.| -|**typedChildren**|Name of the method to return objects from a child relationship.| -|**nullValue**|Value if the underlying value is **DBNull**. See the following table for **nullValue** annotations. The default is **_throw**.| - - The following table shows the values that can be specified for the **nullValue** annotation. - -|nullValue Value|Description| -|---------------------|-----------------| -|*Replacement Value*|Specify a value to be returned. The returned value must match the type of the element. For example, use `nullValue="0"` to return 0 for null integer fields.| -|**_throw**|Throw an exception. This is the default.| -|**_null**|Return a null reference or throw an exception if a primitive type is encountered.| -|**_empty**|For strings, return **String.Empty**, otherwise return an object created from an empty constructor. If a primitive type is encountered, throw an exception.| - - The following table shows default values for objects in a typed **DataSet** and the available annotations. - -|Object/Method/Event|Default|Annotation| -|---------------------------|-------------|----------------| -|**DataTable**|TableNameDataTable|typedPlural| -|**DataTable** Methods|NewTableNameRow

AddTableNameRow

DeleteTableNameRow|typedName| -|**DataRowCollection**|TableName|typedPlural| -|**DataRow**|TableNameRow|typedName| -|**DataColumn**|DataTable.ColumnNameColumn

DataRow.ColumnName|typedName| -|**Property**|PropertyName|typedName| -|**Child** Accessor|GetChildTableNameRows|typedChildren| -|**Parent** Accessor|TableNameRow|typedParent| -|**DataSet** Events|TableNameRowChangeEvent

TableNameRowChangeEventHandler|typedName| - - To use typed **DataSet** annotations, you must include the following **xmlns** reference in your XML Schema definition language (XSD) schema. To create an xsd from database tables, see or [Working with Datasets in Visual Studio](/visualstudio/data-tools/dataset-tools-in-visual-studio). - -```xml -xmlns:codegen="urn:schemas-microsoft-com:xml-msprop" -``` - - The following is a sample annotated schema that exposes the **Customers** table of the **Northwind** database with a relation to the **Orders** table included. - -```xml - +Annotations enable you to modify the names of the elements in your typed without modifying the underlying schema. Modifying the names of the elements in your underlying schema would cause the typed `DataSet` to refer to objects that do not exist in the data source, as well as lose a reference to the objects that do exist in the data source. + + Using annotations, you can customize the names of objects in your typed `DataSet` with more meaningful names, making code more readable and your typed `DataSet` easier for clients to use, while leaving underlying schema intact. For example, the following schema element for the `Customers` table of the `Northwind` database would result in a `DataRow` object name of `CustomersRow` and a named **Customers**. + +```xml + + + + + + + +``` + + A `DataRowCollection` name of `Customers` is meaningful in client code, but a `DataRow` name of `CustomersRow` is misleading because it is a single object. Also, in common scenarios, the object would be referred to without the `Row` identifier and instead would be simply referred to as a `Customer` object. The solution is to annotate the schema and identify new names for the `DataRow` and `DataRowCollection` objects. Following is the annotated version of the previous schema. + +```xml + + + + + + + +``` + + Specifying a `typedName` value of `Customer` will result in a `DataRow` object name of **Customer**. Specifying a `typedPlural` value of `Customers` preserves the `DataRowCollection` name of **Customers**. + + The following table shows the annotations available for use. + +|Annotation|Description| +|----------------|-----------------| +|**typedName**|Name of the object.| +|**typedPlural**|Name of a collection of objects.| +|**typedParent**|Name of the object when referred to in a parent relationship.| +|**typedChildren**|Name of the method to return objects from a child relationship.| +|**nullValue**|Value if the underlying value is **DBNull**. See the following table for `nullValue` annotations. The default is **_throw**.| + + The following table shows the values that can be specified for the `nullValue` annotation. + +|nullValue Value|Description| +|---------------------|-----------------| +|*Replacement Value*|Specify a value to be returned. The returned value must match the type of the element. For example, use `nullValue="0"` to return 0 for null integer fields.| +|**_throw**|Throw an exception. This is the default.| +|**_null**|Return a null reference or throw an exception if a primitive type is encountered.| +|**_empty**|For strings, return **String.Empty**, otherwise return an object created from an empty constructor. If a primitive type is encountered, throw an exception.| + + The following table shows default values for objects in a typed `DataSet` and the available annotations. + +|Object/Method/Event|Default|Annotation| +|---------------------------|-------------|----------------| +|**DataTable**|TableNameDataTable|typedPlural| +|**DataTable** Methods|NewTableNameRow

AddTableNameRow

DeleteTableNameRow|typedName| +|**DataRowCollection**|TableName|typedPlural| +|**DataRow**|TableNameRow|typedName| +|**DataColumn**|DataTable.ColumnNameColumn

DataRow.ColumnName|typedName| +|**Property**|PropertyName|typedName| +|**Child** Accessor|GetChildTableNameRows|typedChildren| +|**Parent** Accessor|TableNameRow|typedParent| +|**DataSet** Events|TableNameRowChangeEvent

TableNameRowChangeEventHandler|typedName| + + To use typed `DataSet` annotations, you must include the following `xmlns` reference in your XML Schema definition language (XSD) schema. To create an xsd from database tables, see or [Working with Datasets in Visual Studio](/visualstudio/data-tools/dataset-tools-in-visual-studio). + +```xml +xmlns:codegen="urn:schemas-microsoft-com:xml-msprop" +``` + + The following is a sample annotated schema that exposes the `Customers` table of the `Northwind` database with a relation to the `Orders` table included. + +```xml + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + - + - - - - - - - - - - - - - - - -``` - - The following code example uses a strongly typed **DataSet** created from the sample schema. It uses one to populate the **Customers** table and another to populate the **Orders** table. The strongly typed **DataSet** defines the **DataRelations**. - -```vb -' Assumes a valid SqlConnection object named connection. -Dim customerAdapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT CustomerID, CompanyName, Phone FROM Customers", & - connection) -Dim orderAdapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT OrderID, CustomerID, EmployeeID, OrderAdapter FROM Orders", & - connection) - -' Populate a strongly typed DataSet. -connection.Open() -Dim customers As CustomerDataSet = New CustomerDataSet() -customerAdapter.Fill(customers, "Customers") -orderAdapter.Fill(customers, "Orders") -connection.Close() - -' Add a strongly typed event. -AddHandler customers.Customers.CustomerChanged, & - New CustomerDataSet.CustomerChangeEventHandler( _ - AddressOf OnCustomerChanged) - -' Add a strongly typed DataRow. -Dim newCustomer As CustomerDataSet.Customer = _ - customers.Customers.NewCustomer() -newCustomer.CustomerID = "NEW01" -newCustomer.CompanyName = "My New Company" -customers.Customers.AddCustomer(newCustomer) - -' Navigate the child relation. -Dim customer As CustomerDataSet.Customer -Dim order As CustomerDataSet.Order - -For Each customer In customers.Customers - Console.WriteLine(customer.CustomerID) - For Each order In customer.GetOrders() - Console.WriteLine(vbTab & order.OrderID) - Next -Next - -Private Shared Sub OnCustomerChanged( _ - sender As Object, e As CustomerDataSet.CustomerChangeEvent) - -End Sub -``` - -```csharp -// Assumes a valid SqlConnection object named connection. -SqlDataAdapter customerAdapter = new SqlDataAdapter( - "SELECT CustomerID, CompanyName, Phone FROM Customers", - connection); -SqlDataAdapter orderAdapter = new SqlDataAdapter( +type="xs:dateTime" minOccurs="0" /> + + + + + + + + + + + + + + + +``` + + The following code example uses a strongly typed `DataSet` created from the sample schema. It uses one to populate the `Customers` table and another to populate the `Orders` table. The strongly typed `DataSet` defines the **DataRelations**. + +```vb +' Assumes a valid SqlConnection object named connection. +Dim customerAdapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT CustomerID, CompanyName, Phone FROM Customers", & + connection) +Dim orderAdapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT OrderID, CustomerID, EmployeeID, OrderAdapter FROM Orders", & + connection) + +' Populate a strongly typed DataSet. +connection.Open() +Dim customers As CustomerDataSet = New CustomerDataSet() +customerAdapter.Fill(customers, "Customers") +orderAdapter.Fill(customers, "Orders") +connection.Close() + +' Add a strongly typed event. +AddHandler customers.Customers.CustomerChanged, & + New CustomerDataSet.CustomerChangeEventHandler( _ + AddressOf OnCustomerChanged) + +' Add a strongly typed DataRow. +Dim newCustomer As CustomerDataSet.Customer = _ + customers.Customers.NewCustomer() +newCustomer.CustomerID = "NEW01" +newCustomer.CompanyName = "My New Company" +customers.Customers.AddCustomer(newCustomer) + +' Navigate the child relation. +Dim customer As CustomerDataSet.Customer +Dim order As CustomerDataSet.Order + +For Each customer In customers.Customers + Console.WriteLine(customer.CustomerID) + For Each order In customer.GetOrders() + Console.WriteLine(vbTab & order.OrderID) + Next +Next + +Private Shared Sub OnCustomerChanged( _ + sender As Object, e As CustomerDataSet.CustomerChangeEvent) + +End Sub +``` + +```csharp +// Assumes a valid SqlConnection object named connection. +SqlDataAdapter customerAdapter = new SqlDataAdapter( + "SELECT CustomerID, CompanyName, Phone FROM Customers", + connection); +SqlDataAdapter orderAdapter = new SqlDataAdapter( "SELECT OrderID, CustomerID, EmployeeID, OrderAdapter FROM Orders", - connection); - -// Populate a strongly typed DataSet. -connection.Open(); -CustomerDataSet customers = new CustomerDataSet(); -customerAdapter.Fill(customers, "Customers"); -orderAdapter.Fill(customers, "Orders"); -connection.Close(); - -// Add a strongly typed event. + connection); + +// Populate a strongly typed DataSet. +connection.Open(); +CustomerDataSet customers = new CustomerDataSet(); +customerAdapter.Fill(customers, "Customers"); +orderAdapter.Fill(customers, "Orders"); +connection.Close(); + +// Add a strongly typed event. customers.Customers.CustomerChanged += new - CustomerDataSet.CustomerChangeEventHandler(OnCustomerChanged); - -// Add a strongly typed DataRow. + CustomerDataSet.CustomerChangeEventHandler(OnCustomerChanged); + +// Add a strongly typed DataRow. CustomerDataSet.Customer newCustomer = - customers.Customers.NewCustomer(); -newCustomer.CustomerID = "NEW01"; -newCustomer.CompanyName = "My New Company"; -customers.Customers.AddCustomer(newCustomer); - -// Navigate the child relation. -foreach(CustomerDataSet.Customer customer in customers.Customers) -{ - Console.WriteLine(customer.CustomerID); - foreach(CustomerDataSet.Order order in customer.GetOrders()) - Console.WriteLine("\t" + order.OrderID); -} - -protected static void OnCustomerChanged(object sender, CustomerDataSet.CustomerChangeEvent e) - { - - } -``` - + customers.Customers.NewCustomer(); +newCustomer.CustomerID = "NEW01"; +newCustomer.CompanyName = "My New Company"; +customers.Customers.AddCustomer(newCustomer); + +// Navigate the child relation. +foreach(CustomerDataSet.Customer customer in customers.Customers) +{ + Console.WriteLine(customer.CustomerID); + foreach(CustomerDataSet.Order order in customer.GetOrders()) + Console.WriteLine("\t" + order.OrderID); +} + +protected static void OnCustomerChanged(object sender, CustomerDataSet.CustomerChangeEvent e) + { + + } +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/applying-an-xslt-transform-to-a-dataset.md b/docs/framework/data/adonet/dataset-datatable-dataview/applying-an-xslt-transform-to-a-dataset.md index e84a3eb9238d5..79a613166a1be 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/applying-an-xslt-transform-to-a-dataset.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/applying-an-xslt-transform-to-a-dataset.md @@ -2,123 +2,123 @@ description: "Learn more about: Applying an XSLT Transform to a DataSet" title: "Applying an XSLT Transform to a DataSet" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 09f2e4ee-1d08-4ba8-8936-83394fee319d --- # Applying an XSLT Transform to a DataSet -The **WriteXml** method of the enables you to write the contents of a **DataSet** as XML data. A common task is to then transform that XML to another format using XSL transformations (XSLT). However, synchronizing a **DataSet** with an enables you to apply an XSLT stylesheet to the contents of a **DataSet** without having to first write the contents of the **DataSet** as XML data using **WriteXml**. - - The following example populates a **DataSet** with tables and relationships, synchronizes the **DataSet** with an **XmlDataDocument**, and writes a portion of the **DataSet** as an HTML file using an XSLT stylesheet. The following are the contents of the XSLT stylesheet: - -```xml - - - - - - - - -
- - -
- - - - ,
- - -
- - - - - - - -
Order:
Date:
Ship To:
-
- ,
-
-
- -
-``` - - The following code fills the **DataSet** and applies the XSLT style sheet. - +The `WriteXml` method of the enables you to write the contents of a `DataSet` as XML data. A common task is to then transform that XML to another format using XSL transformations (XSLT). However, synchronizing a `DataSet` with an enables you to apply an XSLT stylesheet to the contents of a `DataSet` without having to first write the contents of the `DataSet` as XML data using **WriteXml**. + + The following example populates a `DataSet` with tables and relationships, synchronizes the `DataSet` with an **XmlDataDocument**, and writes a portion of the `DataSet` as an HTML file using an XSLT stylesheet. The following are the contents of the XSLT stylesheet: + +```xml + + + + + + + + +
+ + +
+ + + + ,
+ + +
+ + + + + + + +
Order:
Date:
Ship To:
+
+ ,
+
+
+ +
+``` + + The following code fills the `DataSet` and applies the XSLT style sheet. + > [!NOTE] -> If you are applying an XSLT style sheet to a **DataSet** that contains relations, you achieve best performance if you set the **Nested** property of the to **true** for each nested relation. This allows you to use XSLT style sheets that implement natural top-down processing to navigate the hierarchy and transform the data, as opposed to using performance-intensive XPath location axes (for example, preceding-sibling and following-sibling in style sheet node test expressions) to navigate it. For more information on nested relations, see [Nesting DataRelations](nesting-datarelations.md). - -```vb -' Assumes connection is a valid SqlConnection. -Dim dataSet As DataSet = New DataSet("CustomerOrders") - -Dim customerAdapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT * FROM Customers", connection) -customerAdapter.Fill(dataSet, "Customers") - -Dim orderAdapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT * FROM Orders", connection) -orderAdapter.Fill(dataSet, "Orders") - -connection.Close() - -dataSet.Relations.Add("CustOrders", _ -dataSet.Tables("Customers").Columns("CustomerID"), _ -dataSet.Tables("Orders").Columns("CustomerID")).Nested = true - +> If you are applying an XSLT style sheet to a `DataSet` that contains relations, you achieve best performance if you set the `Nested` property of the to `true` for each nested relation. This allows you to use XSLT style sheets that implement natural top-down processing to navigate the hierarchy and transform the data, as opposed to using performance-intensive XPath location axes (for example, preceding-sibling and following-sibling in style sheet node test expressions) to navigate it. For more information on nested relations, see [Nesting DataRelations](nesting-datarelations.md). + +```vb +' Assumes connection is a valid SqlConnection. +Dim dataSet As DataSet = New DataSet("CustomerOrders") + +Dim customerAdapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT * FROM Customers", connection) +customerAdapter.Fill(dataSet, "Customers") + +Dim orderAdapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT * FROM Orders", connection) +orderAdapter.Fill(dataSet, "Orders") + +connection.Close() + +dataSet.Relations.Add("CustOrders", _ +dataSet.Tables("Customers").Columns("CustomerID"), _ +dataSet.Tables("Orders").Columns("CustomerID")).Nested = true + Dim xmlDoc As XmlDataDocument = New XmlDataDocument(dataSet) - -Dim xslTran As XslTransform = New XslTransform -xslTran.Load("transform.xsl") - -Dim writer As XmlTextWriter = New XmlTextWriter( _ - "xslt_output.html", System.Text.Encoding.UTF8) - -xslTran.Transform(xmlDoc, Nothing, writer) -writer.Close() -``` - -```csharp -// Assumes connection is a valid SqlConnection. -connection.Open(); - -DataSet custDS = new DataSet("CustomerDataSet"); - -SqlDataAdapter customerAdapter = new SqlDataAdapter( - "SELECT * FROM Customers", connection); -customerAdapter.Fill(custDS, "Customers"); - -SqlDataAdapter orderAdapter = new SqlDataAdapter( - "SELECT * FROM Orders", connection); -orderAdapter.Fill(custDS, "Orders"); - -connection.Close(); - -custDS.Relations.Add("CustOrders", - custDS.Tables["Customers"].Columns["CustomerID"], - custDS.Tables["Orders"].Columns["CustomerID"]).Nested = true; - + +Dim xslTran As XslTransform = New XslTransform +xslTran.Load("transform.xsl") + +Dim writer As XmlTextWriter = New XmlTextWriter( _ + "xslt_output.html", System.Text.Encoding.UTF8) + +xslTran.Transform(xmlDoc, Nothing, writer) +writer.Close() +``` + +```csharp +// Assumes connection is a valid SqlConnection. +connection.Open(); + +DataSet custDS = new DataSet("CustomerDataSet"); + +SqlDataAdapter customerAdapter = new SqlDataAdapter( + "SELECT * FROM Customers", connection); +customerAdapter.Fill(custDS, "Customers"); + +SqlDataAdapter orderAdapter = new SqlDataAdapter( + "SELECT * FROM Orders", connection); +orderAdapter.Fill(custDS, "Orders"); + +connection.Close(); + +custDS.Relations.Add("CustOrders", + custDS.Tables["Customers"].Columns["CustomerID"], + custDS.Tables["Orders"].Columns["CustomerID"]).Nested = true; + XmlDataDocument xmlDoc = new XmlDataDocument(custDS); - -XslTransform xslTran = new XslTransform(); -xslTran.Load("transform.xsl"); - + +XslTransform xslTran = new XslTransform(); +xslTran.Load("transform.xsl"); + XmlTextWriter writer = new XmlTextWriter("xslt_output.html", - System.Text.Encoding.UTF8); - -xslTran.Transform(xmlDoc, null, writer); -writer.Close(); -``` - + System.Text.Encoding.UTF8); + +xslTran.Transform(xmlDoc, null, writer); +writer.Close(); +``` + ## See also - [DataSet and XmlDataDocument Synchronization](dataset-and-xmldatadocument-synchronization.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/childviews-and-relations.md b/docs/framework/data/adonet/dataset-datatable-dataview/childviews-and-relations.md index e759ed364969e..2cf7129fb785d 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/childviews-and-relations.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/childviews-and-relations.md @@ -2,73 +2,73 @@ description: "Learn more about: ChildViews and Relations" title: "ChildViews and Relations" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: d475d356-6abb-4701-8fd1-2906fb93dfba --- # ChildViews and Relations -If a relationship exists between tables in a , you can create a containing rows from the related child table by using the method of the for the rows in the parent table. For example, the following code displays **Categories** and their related **Products** in alphabetical order sorted by **CategoryName** and **ProductName**. - -```vb -Dim catTable As DataTable = catDS.Tables("Categories") -Dim prodTable As DataTable = catDS.Tables("Products") - -' Create a relation between the Categories and Products tables. -Dim relation As DataRelation = catDS.Relations.Add("CatProdRel", _ - catTable.Columns("CategoryID"), _ - prodTable.Columns("CategoryID")) - -' Create DataViews for the Categories and Products tables. -Dim catView As DataView = New DataView(catTable, "", _ - "CategoryName", DataViewRowState.CurrentRows) -Dim prodView As DataView - -' Iterate through the Categories table. -Dim catDRV, prodDRV As DataRowView - -For Each catDRV In catView - Console.WriteLine(catDRV("CategoryName")) - - ' Create a DataView of the child product records. - prodView = catDRV.CreateChildView(relation) - prodView.Sort = "ProductName" - - For Each prodDRV In prodView - Console.WriteLine(vbTab & prodDRV("ProductName")) - Next -Next -``` - -```csharp -DataTable catTable = catDS.Tables["Categories"]; -DataTable prodTable = catDS.Tables["Products"]; - -// Create a relation between the Categories and Products tables. +If a relationship exists between tables in a , you can create a containing rows from the related child table by using the method of the for the rows in the parent table. For example, the following code displays `Categories` and their related `Products` in alphabetical order sorted by `CategoryName` and **ProductName**. + +```vb +Dim catTable As DataTable = catDS.Tables("Categories") +Dim prodTable As DataTable = catDS.Tables("Products") + +' Create a relation between the Categories and Products tables. +Dim relation As DataRelation = catDS.Relations.Add("CatProdRel", _ + catTable.Columns("CategoryID"), _ + prodTable.Columns("CategoryID")) + +' Create DataViews for the Categories and Products tables. +Dim catView As DataView = New DataView(catTable, "", _ + "CategoryName", DataViewRowState.CurrentRows) +Dim prodView As DataView + +' Iterate through the Categories table. +Dim catDRV, prodDRV As DataRowView + +For Each catDRV In catView + Console.WriteLine(catDRV("CategoryName")) + + ' Create a DataView of the child product records. + prodView = catDRV.CreateChildView(relation) + prodView.Sort = "ProductName" + + For Each prodDRV In prodView + Console.WriteLine(vbTab & prodDRV("ProductName")) + Next +Next +``` + +```csharp +DataTable catTable = catDS.Tables["Categories"]; +DataTable prodTable = catDS.Tables["Products"]; + +// Create a relation between the Categories and Products tables. DataRelation relation = catDS.Relations.Add("CatProdRel", - catTable.Columns["CategoryID"], - prodTable.Columns["CategoryID"]); - -// Create DataViews for the Categories and Products tables. + catTable.Columns["CategoryID"], + prodTable.Columns["CategoryID"]); + +// Create DataViews for the Categories and Products tables. DataView catView = new DataView(catTable, "", "CategoryName", - DataViewRowState.CurrentRows); -DataView prodView; - -// Iterate through the Categories table. -foreach (DataRowView catDRV in catView) -{ - Console.WriteLine(catDRV["CategoryName"]); - - // Create a DataView of the child product records. - prodView = catDRV.CreateChildView(relation); - prodView.Sort = "ProductName"; - - foreach (DataRowView prodDRV in prodView) - Console.WriteLine("\t" + prodDRV["ProductName"]); -} -``` - + DataViewRowState.CurrentRows); +DataView prodView; + +// Iterate through the Categories table. +foreach (DataRowView catDRV in catView) +{ + Console.WriteLine(catDRV["CategoryName"]); + + // Create a DataView of the child product records. + prodView = catDRV.CreateChildView(relation); + prodView.Sort = "ProductName"; + + foreach (DataRowView prodDRV in prodView) + Console.WriteLine("\t" + prodDRV["ProductName"]); +} +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/consuming-a-dataset-from-an-xml-web-service.md b/docs/framework/data/adonet/dataset-datatable-dataview/consuming-a-dataset-from-an-xml-web-service.md index 7b652f17b5145..019a24d915cf2 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/consuming-a-dataset-from-an-xml-web-service.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/consuming-a-dataset-from-an-xml-web-service.md @@ -2,262 +2,262 @@ description: "Learn more about: Consume a DataSet from an XML web service" title: Consume a DataSet from an XML Web Service ms.date: 07/14/2020 -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 9edd6b71-0fa5-4649-ae1d-ac1c12541019 --- # Consume a DataSet from an XML web service -The was architected with a disconnected design, in part to facilitate the convenient transport of data over the Internet. The **DataSet** is "serializable" in that it can be specified as an input to or output from XML Web services without any additional coding required to stream the contents of the **DataSet** from an XML Web service to a client and back. The **DataSet** is implicitly converted to an XML stream using the DiffGram format, sent over the network, and then reconstructed from the XML stream as a **DataSet** on the receiving end. This gives you a simple and flexible method for transmitting and returning relational data using XML Web services. For more information about the DiffGram format, see [DiffGrams](diffgrams.md). - - The following example shows how to create an XML Web service and client that use the **DataSet** to transport relational data (including modified data) and resolve any updates back to the original data source. - +The was architected with a disconnected design, in part to facilitate the convenient transport of data over the Internet. The `DataSet` is "serializable" in that it can be specified as an input to or output from XML Web services without any additional coding required to stream the contents of the `DataSet` from an XML Web service to a client and back. The `DataSet` is implicitly converted to an XML stream using the DiffGram format, sent over the network, and then reconstructed from the XML stream as a `DataSet` on the receiving end. This gives you a simple and flexible method for transmitting and returning relational data using XML Web services. For more information about the DiffGram format, see [DiffGrams](diffgrams.md). + + The following example shows how to create an XML Web service and client that use the `DataSet` to transport relational data (including modified data) and resolve any updates back to the original data source. + > [!NOTE] > Transmitting `DataSet` or `DataTable` instances as part of XML Web service calls is not safe if the input is not trusted. For more information, see [DataSet and DataTable security guidance](security-guidance.md). -> We also recommend that you always consider security implications when creating an XML Web service. For information on securing an XML Web service, see [Securing XML Web Services Created Using ASP.NET](/previous-versions/dotnet/netframework-4.0/w67h0dw7(v=vs.100)). - +> We also recommend that you always consider security implications when creating an XML Web service. For information on securing an XML Web service, see [Securing XML Web Services Created Using ASP.NET](/previous-versions/dotnet/netframework-4.0/w67h0dw7(v=vs.100)). + ## Create an XML web service - -1. Create the XML Web service. - - In the example, an XML Web service is created that returns data, in this case a list of customers from the **Northwind** database, and receives a **DataSet** with updates to the data, which the XML Web service resolves back to the original data source. - - The XML Web service exposes two methods: **GetCustomers**, to return the list of customers, and **UpdateCustomers**, to resolve updates back to the data source. The XML Web service is stored in a file on the Web server called DataSetSample.asmx. The following code outlines the contents of DataSetSample.asmx. - - ```vb - <% @ WebService Language = "vb" Class = "Sample" %> - Imports System - Imports System.Data - Imports System.Data.SqlClient - Imports System.Web.Services - - _ - Public Class Sample - - Public connection As SqlConnection = New SqlConnection("Data Source=(local);Integrated Security=SSPI;Initial Catalog=Northwind") - - _ - Public Function GetCustomers() As DataSet - Dim adapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT CustomerID, CompanyName FROM Customers", connection) - - Dim custDS As DataSet = New DataSet() - adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey - adapter.Fill(custDS, "Customers") - - Return custDS - End Function - - _ - Public Function UpdateCustomers(custDS As DataSet) As DataSet - Dim adapter As SqlDataAdapter = New SqlDataAdapter() - - adapter.InsertCommand = New SqlCommand( _ - "INSERT INTO Customers (CustomerID, CompanyName) " & _ - "Values(@CustomerID, @CompanyName)", connection) - adapter.InsertCommand.Parameters.Add( _ - "@CustomerID", SqlDbType.NChar, 5, "CustomerID") - adapter.InsertCommand.Parameters.Add( _ - "@CompanyName", SqlDbType.NChar, 15, "CompanyName") - - adapter.UpdateCommand = New SqlCommand( _ - "UPDATE Customers Set CustomerID = @CustomerID, " & _ - "CompanyName = @CompanyName WHERE CustomerID = " & _ - @OldCustomerID", connection) - adapter.UpdateCommand.Parameters.Add( _ - "@CustomerID", SqlDbType.NChar, 5, "CustomerID") - adapter.UpdateCommand.Parameters.Add( _ - "@CompanyName", SqlDbType.NChar, 15, "CompanyName") - - Dim parameter As SqlParameter = _ - adapter.UpdateCommand.Parameters.Add( _ - "@OldCustomerID", SqlDbType.NChar, 5, "CustomerID") - parameter.SourceVersion = DataRowVersion.Original - - adapter.DeleteCommand = New SqlCommand( _ - "DELETE FROM Customers WHERE CustomerID = @CustomerID", _ - connection) - parameter = adapter.DeleteCommand.Parameters.Add( _ - "@CustomerID", SqlDbType.NChar, 5, "CustomerID") - parameter.SourceVersion = DataRowVersion.Original - - adapter.Update(custDS, "Customers") - - Return custDS - End Function - End Class - ``` - - ```csharp - <% @ WebService Language = "C#" Class = "Sample" %> - using System; - using System.Data; - using System.Data.SqlClient; - using System.Web.Services; - - [WebService(Namespace="http://microsoft.com/webservices/")] - public class Sample - { - public SqlConnection connection = new SqlConnection("Data Source=(local);Integrated Security=SSPI;Initial Catalog=Northwind"); - - [WebMethod( Description = "Returns Northwind Customers", EnableSession = false )] - public DataSet GetCustomers() - { - SqlDataAdapter adapter = new SqlDataAdapter( - "SELECT CustomerID, CompanyName FROM Customers", connection); - - DataSet custDS = new DataSet(); - adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; - adapter.Fill(custDS, "Customers"); - - return custDS; - } - - [WebMethod( Description = "Updates Northwind Customers", - EnableSession = false )] - public DataSet UpdateCustomers(DataSet custDS) - { - SqlDataAdapter adapter = new SqlDataAdapter(); - - adapter.InsertCommand = new SqlCommand( - "INSERT INTO Customers (CustomerID, CompanyName) " + - "Values(@CustomerID, @CompanyName)", connection); - adapter.InsertCommand.Parameters.Add( - "@CustomerID", SqlDbType.NChar, 5, "CustomerID"); - adapter.InsertCommand.Parameters.Add( - "@CompanyName", SqlDbType.NChar, 15, "CompanyName"); - - adapter.UpdateCommand = new SqlCommand( - "UPDATE Customers Set CustomerID = @CustomerID, " + - "CompanyName = @CompanyName WHERE CustomerID = " + - "@OldCustomerID", connection); - adapter.UpdateCommand.Parameters.Add( - "@CustomerID", SqlDbType.NChar, 5, "CustomerID"); - adapter.UpdateCommand.Parameters.Add( - "@CompanyName", SqlDbType.NChar, 15, "CompanyName"); - SqlParameter parameter = adapter.UpdateCommand.Parameters.Add( - "@OldCustomerID", SqlDbType.NChar, 5, "CustomerID"); - parameter.SourceVersion = DataRowVersion.Original; - - adapter.DeleteCommand = new SqlCommand( - "DELETE FROM Customers WHERE CustomerID = @CustomerID", - connection); - parameter = adapter.DeleteCommand.Parameters.Add( - "@CustomerID", SqlDbType.NChar, 5, "CustomerID"); - parameter.SourceVersion = DataRowVersion.Original; - - adapter.Update(custDS, "Customers"); - - return custDS; - } - } - ``` - - In a typical scenario, the **UpdateCustomers** method would be written to catch optimistic concurrency violations. For simplicity, the example does not include this. For more information about optimistic concurrency, see [Optimistic Concurrency](../optimistic-concurrency.md). - -2. Create an XML Web service proxy. - - Clients of the XML Web service require a SOAP proxy in order to consume the exposed methods. You can have Visual Studio generate this proxy for you. By setting a Web reference to an existing Web service from within Visual Studio, all the behavior described in this step occurs transparently. If you want to create the proxy class yourself, continue with this discussion. In most circumstances, however, using Visual Studio to create the proxy class for the client application is sufficient. - - A proxy can be created using the Web Services Description Language Tool. For example, if the XML Web service is exposed at the URL `http://myserver/data/DataSetSample.asmx`, issue a command such as the following to create a Visual Basic .NET proxy with a namespace of **WebData.DSSample** and store it in the file sample.vb. - + +1. Create the XML Web service. + + In the example, an XML Web service is created that returns data, in this case a list of customers from the `Northwind` database, and receives a `DataSet` with updates to the data, which the XML Web service resolves back to the original data source. + + The XML Web service exposes two methods: **GetCustomers**, to return the list of customers, and **UpdateCustomers**, to resolve updates back to the data source. The XML Web service is stored in a file on the Web server called DataSetSample.asmx. The following code outlines the contents of DataSetSample.asmx. + + ```vb + <% @ WebService Language = "vb" Class = "Sample" %> + Imports System + Imports System.Data + Imports System.Data.SqlClient + Imports System.Web.Services + + _ + Public Class Sample + + Public connection As SqlConnection = New SqlConnection("Data Source=(local);Integrated Security=SSPI;Initial Catalog=Northwind") + + _ + Public Function GetCustomers() As DataSet + Dim adapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT CustomerID, CompanyName FROM Customers", connection) + + Dim custDS As DataSet = New DataSet() + adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey + adapter.Fill(custDS, "Customers") + + Return custDS + End Function + + _ + Public Function UpdateCustomers(custDS As DataSet) As DataSet + Dim adapter As SqlDataAdapter = New SqlDataAdapter() + + adapter.InsertCommand = New SqlCommand( _ + "INSERT INTO Customers (CustomerID, CompanyName) " & _ + "Values(@CustomerID, @CompanyName)", connection) + adapter.InsertCommand.Parameters.Add( _ + "@CustomerID", SqlDbType.NChar, 5, "CustomerID") + adapter.InsertCommand.Parameters.Add( _ + "@CompanyName", SqlDbType.NChar, 15, "CompanyName") + + adapter.UpdateCommand = New SqlCommand( _ + "UPDATE Customers Set CustomerID = @CustomerID, " & _ + "CompanyName = @CompanyName WHERE CustomerID = " & _ + @OldCustomerID", connection) + adapter.UpdateCommand.Parameters.Add( _ + "@CustomerID", SqlDbType.NChar, 5, "CustomerID") + adapter.UpdateCommand.Parameters.Add( _ + "@CompanyName", SqlDbType.NChar, 15, "CompanyName") + + Dim parameter As SqlParameter = _ + adapter.UpdateCommand.Parameters.Add( _ + "@OldCustomerID", SqlDbType.NChar, 5, "CustomerID") + parameter.SourceVersion = DataRowVersion.Original + + adapter.DeleteCommand = New SqlCommand( _ + "DELETE FROM Customers WHERE CustomerID = @CustomerID", _ + connection) + parameter = adapter.DeleteCommand.Parameters.Add( _ + "@CustomerID", SqlDbType.NChar, 5, "CustomerID") + parameter.SourceVersion = DataRowVersion.Original + + adapter.Update(custDS, "Customers") + + Return custDS + End Function + End Class + ``` + + ```csharp + <% @ WebService Language = "C#" Class = "Sample" %> + using System; + using System.Data; + using System.Data.SqlClient; + using System.Web.Services; + + [WebService(Namespace="http://microsoft.com/webservices/")] + public class Sample + { + public SqlConnection connection = new SqlConnection("Data Source=(local);Integrated Security=SSPI;Initial Catalog=Northwind"); + + [WebMethod( Description = "Returns Northwind Customers", EnableSession = false )] + public DataSet GetCustomers() + { + SqlDataAdapter adapter = new SqlDataAdapter( + "SELECT CustomerID, CompanyName FROM Customers", connection); + + DataSet custDS = new DataSet(); + adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; + adapter.Fill(custDS, "Customers"); + + return custDS; + } + + [WebMethod( Description = "Updates Northwind Customers", + EnableSession = false )] + public DataSet UpdateCustomers(DataSet custDS) + { + SqlDataAdapter adapter = new SqlDataAdapter(); + + adapter.InsertCommand = new SqlCommand( + "INSERT INTO Customers (CustomerID, CompanyName) " + + "Values(@CustomerID, @CompanyName)", connection); + adapter.InsertCommand.Parameters.Add( + "@CustomerID", SqlDbType.NChar, 5, "CustomerID"); + adapter.InsertCommand.Parameters.Add( + "@CompanyName", SqlDbType.NChar, 15, "CompanyName"); + + adapter.UpdateCommand = new SqlCommand( + "UPDATE Customers Set CustomerID = @CustomerID, " + + "CompanyName = @CompanyName WHERE CustomerID = " + + "@OldCustomerID", connection); + adapter.UpdateCommand.Parameters.Add( + "@CustomerID", SqlDbType.NChar, 5, "CustomerID"); + adapter.UpdateCommand.Parameters.Add( + "@CompanyName", SqlDbType.NChar, 15, "CompanyName"); + SqlParameter parameter = adapter.UpdateCommand.Parameters.Add( + "@OldCustomerID", SqlDbType.NChar, 5, "CustomerID"); + parameter.SourceVersion = DataRowVersion.Original; + + adapter.DeleteCommand = new SqlCommand( + "DELETE FROM Customers WHERE CustomerID = @CustomerID", + connection); + parameter = adapter.DeleteCommand.Parameters.Add( + "@CustomerID", SqlDbType.NChar, 5, "CustomerID"); + parameter.SourceVersion = DataRowVersion.Original; + + adapter.Update(custDS, "Customers"); + + return custDS; + } + } + ``` + + In a typical scenario, the `UpdateCustomers` method would be written to catch optimistic concurrency violations. For simplicity, the example does not include this. For more information about optimistic concurrency, see [Optimistic Concurrency](../optimistic-concurrency.md). + +2. Create an XML Web service proxy. + + Clients of the XML Web service require a SOAP proxy in order to consume the exposed methods. You can have Visual Studio generate this proxy for you. By setting a Web reference to an existing Web service from within Visual Studio, all the behavior described in this step occurs transparently. If you want to create the proxy class yourself, continue with this discussion. In most circumstances, however, using Visual Studio to create the proxy class for the client application is sufficient. + + A proxy can be created using the Web Services Description Language Tool. For example, if the XML Web service is exposed at the URL `http://myserver/data/DataSetSample.asmx`, issue a command such as the following to create a Visual Basic .NET proxy with a namespace of **WebData.DSSample** and store it in the file sample.vb. + + ```console + wsdl /l:VB -out:sample.vb http://myserver/data/DataSetSample.asmx /n:WebData.DSSample + ``` + + To create a C# proxy in the file sample.cs, issue the following command. + ```console - wsdl /l:VB -out:sample.vb http://myserver/data/DataSetSample.asmx /n:WebData.DSSample - ``` - - To create a C# proxy in the file sample.cs, issue the following command. - + wsdl -l:CS -out:sample.cs http://myserver/data/DataSetSample.asmx -n:WebData.DSSample + ``` + + The proxy can then be compiled as a library and imported into the XML Web service client. To compile the Visual Basic .NET proxy code stored in sample.vb as sample.dll, issue the following command. + ```console - wsdl -l:CS -out:sample.cs http://myserver/data/DataSetSample.asmx -n:WebData.DSSample - ``` - - The proxy can then be compiled as a library and imported into the XML Web service client. To compile the Visual Basic .NET proxy code stored in sample.vb as sample.dll, issue the following command. - - ```console - vbc -t:library -out:sample.dll sample.vb -r:System.dll -r:System.Web.Services.dll -r:System.Data.dll -r:System.Xml.dll - ``` - - To compile the C# proxy code stored in sample.cs as sample.dll, issue the following command. - + vbc -t:library -out:sample.dll sample.vb -r:System.dll -r:System.Web.Services.dll -r:System.Data.dll -r:System.Xml.dll + ``` + + To compile the C# proxy code stored in sample.cs as sample.dll, issue the following command. + ```console - csc -t:library -out:sample.dll sample.cs -r:System.dll -r:System.Web.Services.dll -r:System.Data.dll -r:System.Xml.dll - ``` - -3. Create an XML Web service client. - - If you want to have Visual Studio generate the Web service proxy class for you, simply create the client project, and, in the Solution Explorer window, right-click the project, and then select **Add** > **Service Reference**. In the **Add Service Reference** dialog box, select **Advanced**, and then select **Add Web Reference**. Select the Web service from the list of available Web services (this may require supplying the address of the Web service endpoint if the Web service isn't available within the current solution or on the current computer). If you create the XML Web service proxy yourself (as described in the previous step), you can import it into your client code and consume the XML Web service methods. - - The following sample code imports the proxy library, calls **GetCustomers** to get a list of customers, adds a new customer, and then returns a **DataSet** with the updates to **UpdateCustomers**. - - The example passes the **DataSet** returned by **DataSet.GetChanges** to **UpdateCustomers** because only modified rows need to be passed to **UpdateCustomers**. **UpdateCustomers** returns the resolved **DataSet**, which you can then **Merge** into the existing **DataSet** to incorporate the resolved changes and any row error information from the update. The following code assumes that you have used Visual Studio to create the Web reference, and that you have renamed the Web reference to DsSample in the **Add Web Reference** dialog box. - - ```vb - Imports System - Imports System.Data - - Public Class Client - - Public Shared Sub Main() - Dim proxySample As New DsSample.Sample () ' Proxy object. - Dim customersDataSet As DataSet = proxySample.GetCustomers() - Dim customersTable As DataTable = _ - customersDataSet.Tables("Customers") - - Dim rowAs DataRow = customersTable.NewRow() - row("CustomerID") = "ABCDE" - row("CompanyName") = "New Company Name" - customersTable.Rows.Add(row) - - Dim updateDataSet As DataSet = _ - proxySample.UpdateCustomers(customersDataSet.GetChanges()) - - customersDataSet.Merge(updateDataSet) - customersDataSet.AcceptChanges() - End Sub - End Class - ``` - - ```csharp - using System; - using System.Data; - - public class Client - { - public static void Main() - { - Sample proxySample = new DsSample.Sample(); // Proxy object. - DataSet customersDataSet = proxySample.GetCustomers(); - DataTable customersTable = customersDataSet.Tables["Customers"]; - - DataRow row = customersTable.NewRow(); - row["CustomerID"] = "ABCDE"; - row["CompanyName"] = "New Company Name"; - customersTable.Rows.Add(row); - - DataSet updateDataSet = new DataSet(); - + csc -t:library -out:sample.dll sample.cs -r:System.dll -r:System.Web.Services.dll -r:System.Data.dll -r:System.Xml.dll + ``` + +3. Create an XML Web service client. + + If you want to have Visual Studio generate the Web service proxy class for you, simply create the client project, and, in the Solution Explorer window, right-click the project, and then select `Add` > **Service Reference**. In the **Add Service Reference** dialog box, select **Advanced**, and then select **Add Web Reference**. Select the Web service from the list of available Web services (this may require supplying the address of the Web service endpoint if the Web service isn't available within the current solution or on the current computer). If you create the XML Web service proxy yourself (as described in the previous step), you can import it into your client code and consume the XML Web service methods. + + The following sample code imports the proxy library, calls `GetCustomers` to get a list of customers, adds a new customer, and then returns a `DataSet` with the updates to **UpdateCustomers**. + + The example passes the `DataSet` returned by **DataSet.GetChanges** to `UpdateCustomers` because only modified rows need to be passed to **UpdateCustomers**. `UpdateCustomers` returns the resolved **DataSet**, which you can then `Merge` into the existing `DataSet` to incorporate the resolved changes and any row error information from the update. The following code assumes that you have used Visual Studio to create the Web reference, and that you have renamed the Web reference to DsSample in the **Add Web Reference** dialog box. + + ```vb + Imports System + Imports System.Data + + Public Class Client + + Public Shared Sub Main() + Dim proxySample As New DsSample.Sample () ' Proxy object. + Dim customersDataSet As DataSet = proxySample.GetCustomers() + Dim customersTable As DataTable = _ + customersDataSet.Tables("Customers") + + Dim rowAs DataRow = customersTable.NewRow() + row("CustomerID") = "ABCDE" + row("CompanyName") = "New Company Name" + customersTable.Rows.Add(row) + + Dim updateDataSet As DataSet = _ + proxySample.UpdateCustomers(customersDataSet.GetChanges()) + + customersDataSet.Merge(updateDataSet) + customersDataSet.AcceptChanges() + End Sub + End Class + ``` + + ```csharp + using System; + using System.Data; + + public class Client + { + public static void Main() + { + Sample proxySample = new DsSample.Sample(); // Proxy object. + DataSet customersDataSet = proxySample.GetCustomers(); + DataTable customersTable = customersDataSet.Tables["Customers"]; + + DataRow row = customersTable.NewRow(); + row["CustomerID"] = "ABCDE"; + row["CompanyName"] = "New Company Name"; + customersTable.Rows.Add(row); + + DataSet updateDataSet = new DataSet(); + updateDataSet = - proxySample.UpdateCustomers(customersDataSet.GetChanges()); - - customersDataSet.Merge(updateDataSet); - customersDataSet.AcceptChanges(); - } - } - ``` - - If you decide to create the proxy class yourself, you must take the following extra steps. To compile the sample, supply the proxy library that was created (sample.dll) and the related .NET libraries. To compile the Visual Basic .NET version of the sample, stored in the file client.vb, issue the following command. - + proxySample.UpdateCustomers(customersDataSet.GetChanges()); + + customersDataSet.Merge(updateDataSet); + customersDataSet.AcceptChanges(); + } + } + ``` + + If you decide to create the proxy class yourself, you must take the following extra steps. To compile the sample, supply the proxy library that was created (sample.dll) and the related .NET libraries. To compile the Visual Basic .NET version of the sample, stored in the file client.vb, issue the following command. + ```console - vbc client.vb -r:sample.dll -r:System.dll -r:System.Data.dll -r:System.Xml.dll -r:System.Web.Services.dll - ``` - - To compile the C# version of the sample, stored in the file client.cs, issue the following command. - + vbc client.vb -r:sample.dll -r:System.dll -r:System.Data.dll -r:System.Xml.dll -r:System.Web.Services.dll + ``` + + To compile the C# version of the sample, stored in the file client.cs, issue the following command. + ```console - csc client.cs -r:sample.dll -r:System.dll -r:System.Data.dll -r:System.Xml.dll -r:System.Web.Services.dll - ``` - + csc client.cs -r:sample.dll -r:System.dll -r:System.Data.dll -r:System.Xml.dll -r:System.Web.Services.dll + ``` + ## See also - [ADO.NET](../index.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/copying-dataset-contents.md b/docs/framework/data/adonet/dataset-datatable-dataview/copying-dataset-contents.md index f4c3d5e1ce381..ab9403c175ec6 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/copying-dataset-contents.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/copying-dataset-contents.md @@ -2,94 +2,94 @@ description: "Learn more about: Copying DataSet Contents" title: "Copying DataSet Contents" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: cb846617-2b1a-44ff-bd7f-5835f5ea37fa --- # Copying DataSet Contents -You can create a copy of a so that you can work with data without affecting the original data, or work with a subset of the data from a **DataSet**. When copying a **DataSet**, you can: - -- Create an exact copy of the **DataSet**, including the schema, data, row state information, and row versions. - -- Create a **DataSet** that contains the schema of an existing **DataSet**, but only rows that have been modified. You can return all rows that have been modified, or specify a specific **DataRowState**. For more information about row states, see [Row States and Row Versions](row-states-and-row-versions.md). - -- Copy the schema, or relational structure, of the **DataSet** only, without copying any rows. Rows can be imported into an existing using . - - To create an exact copy of the **DataSet** that includes both schema and data, use the method of the **DataSet**. The following code example shows how to create an exact copy of the **DataSet**. - -```vb -Dim copyDataSet As DataSet = customerDataSet.Copy() -``` - -```csharp -DataSet copyDataSet = customerDataSet.Copy(); -``` - - To create a copy of a **DataSet** that includes schema and only the data representing **Added**, **Modified**, or **Deleted** rows, use the method of the **DataSet**. You can also use **GetChanges** to return only rows with a specified row state by passing a **DataRowState** value when calling **GetChanges**. The following code example shows how to pass a **DataRowState** when calling **GetChanges**. - -```vb -' Copy all changes. -Dim changeDataSet As DataSet = customerDataSet.GetChanges() -' Copy only new rows. -Dim addedDataSetAs DataSet = _ - customerDataSet.GetChanges(DataRowState.Added) -``` - -```csharp -// Copy all changes. -DataSet changeDataSet = customerDataSet.GetChanges(); -// Copy only new rows. -DataSet addedDataSet= customerDataSet.GetChanges(DataRowState.Added); -``` - - To create a copy of a **DataSet** that only includes schema, use the method of the **DataSet**. You can also add existing rows to the cloned **DataSet** using the **ImportRow** method of the **DataTable**. **ImportRow** adds data, row state, and row version information to the specified table. Column values are added only where the column name matches and the data type is compatible. - - The following code example creates a clone of a **DataSet** and then adds the rows from the original **DataSet** to the **Customers** table in the **DataSet** clone for customers where the **CountryRegion** column has the value "Germany". - -```vb -Dim customerDataSet As New DataSet - customerDataSet.Tables.Add(New DataTable("Customers")) - customerDataSet.Tables("Customers").Columns.Add("Name", GetType(String)) - customerDataSet.Tables("Customers").Columns.Add("CountryRegion", GetType(String)) - customerDataSet.Tables("Customers").Rows.Add("Juan", "Spain") - customerDataSet.Tables("Customers").Rows.Add("Johann", "Germany") - customerDataSet.Tables("Customers").Rows.Add("John", "UK") - -Dim germanyCustomers As DataSet = customerDataSet.Clone() - -Dim copyRows() As DataRow = _ - customerDataSet.Tables("Customers").Select("CountryRegion = 'Germany'") - -Dim customerTable As DataTable = germanyCustomers.Tables("Customers") -Dim copyRow As DataRow - -For Each copyRow In copyRows - customerTable.ImportRow(copyRow) -Next -``` - -```csharp -DataSet customerDataSet = new DataSet(); -customerDataSet.Tables.Add(new DataTable("Customers")); -customerDataSet.Tables["Customers"].Columns.Add("Name", typeof(string)); -customerDataSet.Tables["Customers"].Columns.Add("CountryRegion", typeof(string)); -customerDataSet.Tables["Customers"].Rows.Add("Juan", "Spain"); -customerDataSet.Tables["Customers"].Rows.Add("Johann", "Germany"); -customerDataSet.Tables["Customers"].Rows.Add("John", "UK"); - -DataSet germanyCustomers = customerDataSet.Clone(); - +You can create a copy of a so that you can work with data without affecting the original data, or work with a subset of the data from a **DataSet**. When copying a **DataSet**, you can: + +- Create an exact copy of the **DataSet**, including the schema, data, row state information, and row versions. + +- Create a `DataSet` that contains the schema of an existing **DataSet**, but only rows that have been modified. You can return all rows that have been modified, or specify a specific **DataRowState**. For more information about row states, see [Row States and Row Versions](row-states-and-row-versions.md). + +- Copy the schema, or relational structure, of the `DataSet` only, without copying any rows. Rows can be imported into an existing using . + + To create an exact copy of the `DataSet` that includes both schema and data, use the method of the **DataSet**. The following code example shows how to create an exact copy of the **DataSet**. + +```vb +Dim copyDataSet As DataSet = customerDataSet.Copy() +``` + +```csharp +DataSet copyDataSet = customerDataSet.Copy(); +``` + + To create a copy of a `DataSet` that includes schema and only the data representing **Added**, **Modified**, or `Deleted` rows, use the method of the **DataSet**. You can also use `GetChanges` to return only rows with a specified row state by passing a `DataRowState` value when calling **GetChanges**. The following code example shows how to pass a `DataRowState` when calling **GetChanges**. + +```vb +' Copy all changes. +Dim changeDataSet As DataSet = customerDataSet.GetChanges() +' Copy only new rows. +Dim addedDataSetAs DataSet = _ + customerDataSet.GetChanges(DataRowState.Added) +``` + +```csharp +// Copy all changes. +DataSet changeDataSet = customerDataSet.GetChanges(); +// Copy only new rows. +DataSet addedDataSet= customerDataSet.GetChanges(DataRowState.Added); +``` + + To create a copy of a `DataSet` that only includes schema, use the method of the **DataSet**. You can also add existing rows to the cloned `DataSet` using the `ImportRow` method of the **DataTable**. `ImportRow` adds data, row state, and row version information to the specified table. Column values are added only where the column name matches and the data type is compatible. + + The following code example creates a clone of a `DataSet` and then adds the rows from the original `DataSet` to the `Customers` table in the `DataSet` clone for customers where the `CountryRegion` column has the value "Germany". + +```vb +Dim customerDataSet As New DataSet + customerDataSet.Tables.Add(New DataTable("Customers")) + customerDataSet.Tables("Customers").Columns.Add("Name", GetType(String)) + customerDataSet.Tables("Customers").Columns.Add("CountryRegion", GetType(String)) + customerDataSet.Tables("Customers").Rows.Add("Juan", "Spain") + customerDataSet.Tables("Customers").Rows.Add("Johann", "Germany") + customerDataSet.Tables("Customers").Rows.Add("John", "UK") + +Dim germanyCustomers As DataSet = customerDataSet.Clone() + +Dim copyRows() As DataRow = _ + customerDataSet.Tables("Customers").Select("CountryRegion = 'Germany'") + +Dim customerTable As DataTable = germanyCustomers.Tables("Customers") +Dim copyRow As DataRow + +For Each copyRow In copyRows + customerTable.ImportRow(copyRow) +Next +``` + +```csharp +DataSet customerDataSet = new DataSet(); +customerDataSet.Tables.Add(new DataTable("Customers")); +customerDataSet.Tables["Customers"].Columns.Add("Name", typeof(string)); +customerDataSet.Tables["Customers"].Columns.Add("CountryRegion", typeof(string)); +customerDataSet.Tables["Customers"].Rows.Add("Juan", "Spain"); +customerDataSet.Tables["Customers"].Rows.Add("Johann", "Germany"); +customerDataSet.Tables["Customers"].Rows.Add("John", "UK"); + +DataSet germanyCustomers = customerDataSet.Clone(); + DataRow[] copyRows = - customerDataSet.Tables["Customers"].Select("CountryRegion = 'Germany'"); - -DataTable customerTable = germanyCustomers.Tables["Customers"]; - -foreach (DataRow copyRow in copyRows) - customerTable.ImportRow(copyRow); -``` - + customerDataSet.Tables["Customers"].Select("CountryRegion = 'Germany'"); + +DataTable customerTable = germanyCustomers.Tables["Customers"]; + +foreach (DataRow copyRow in copyRows) + customerTable.ImportRow(copyRow); +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md b/docs/framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md index d8c08b72c493e..28ad8156d2ba3 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md @@ -2,49 +2,49 @@ title: "Creating a DataTable" description: Learn to create a DataTable in ADO.NET, which represents one table of in-memory relational data, to use independently or by other .NET Framework objects. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: eecf9d78-60e3-4fdc-8de0-e56c13a89414 --- # Creating a DataTable -A , which represents one table of in-memory relational data, can be created and used independently, or can be used by other .NET Framework objects, most commonly as a member of a . - - You can create a **DataTable** object by using the appropriate **DataTable** constructor. You can add it to the **DataSet** by using the **Add** method to add it to the **DataSet** object's **Tables** collection. - - You can also create **DataTable** objects within a **DataSet** by using the **Fill** or **FillSchema** methods of the **DataAdapter** object, or from a predefined or inferred XML schema using the **ReadXml**, **ReadXmlSchema**, or **InferXmlSchema** methods of the **DataSet**. Note that after you have added a **DataTable** as a member of the **Tables** collection of one **DataSet**, you cannot add it to the collection of tables of any other **DataSet**. - - When you first create a **DataTable**, it does not have a schema (that is, a structure). To define the schema of the table, you must create and add objects to the **Columns** collection of the table. You can also define a primary key column for the table, and create and add **Constraint** objects to the **Constraints** collection of the table. After you have defined the schema for a **DataTable**, you can add rows of data to the table by adding **DataRow** objects to the **Rows** collection of the table. - - You are not required to supply a value for the property when you create a **DataTable**; you can specify the property at another time, or you can leave it empty. However, when you add a table without a **TableName** value to a **DataSet**, the table will be given an incremental default name of Table*N*, starting with "Table" for Table0. - +A , which represents one table of in-memory relational data, can be created and used independently, or can be used by other .NET Framework objects, most commonly as a member of a . + + You can create a `DataTable` object by using the appropriate `DataTable` constructor. You can add it to the `DataSet` by using the `Add` method to add it to the `DataSet` object's `Tables` collection. + + You can also create `DataTable` objects within a `DataSet` by using the `Fill` or `FillSchema` methods of the `DataAdapter` object, or from a predefined or inferred XML schema using the **ReadXml**, **ReadXmlSchema**, or `InferXmlSchema` methods of the **DataSet**. Note that after you have added a `DataTable` as a member of the `Tables` collection of one **DataSet**, you cannot add it to the collection of tables of any other **DataSet**. + + When you first create a **DataTable**, it does not have a schema (that is, a structure). To define the schema of the table, you must create and add objects to the `Columns` collection of the table. You can also define a primary key column for the table, and create and add `Constraint` objects to the `Constraints` collection of the table. After you have defined the schema for a **DataTable**, you can add rows of data to the table by adding `DataRow` objects to the `Rows` collection of the table. + + You are not required to supply a value for the property when you create a **DataTable**; you can specify the property at another time, or you can leave it empty. However, when you add a table without a `TableName` value to a **DataSet**, the table will be given an incremental default name of Table*N*, starting with "Table" for Table0. + > [!NOTE] -> We recommend that you avoid the "Table*N*" naming convention when you supply a **TableName** value, because the name you supply may conflict with an existing default table name in the **DataSet**. If the supplied name already exists, an exception is thrown. - - The following example creates an instance of a **DataTable** object and assigns it the name "Customers." - -```vb -Dim workTable as DataTable = New DataTable("Customers") -``` - -```csharp -DataTable workTable = new DataTable("Customers"); -``` - - The following example creates an instance of a **DataTable** by adding it to the **Tables** collection of a **DataSet**. - -```vb -Dim customers As DataSet = New DataSet -Dim customersTable As DataTable = _ - customers.Tables.Add("CustomersTable") -``` - -```csharp -DataSet customers = new DataSet(); -DataTable customersTable = customers.Tables.Add("CustomersTable"); -``` - +> We recommend that you avoid the "Table*N*" naming convention when you supply a `TableName` value, because the name you supply may conflict with an existing default table name in the **DataSet**. If the supplied name already exists, an exception is thrown. + + The following example creates an instance of a `DataTable` object and assigns it the name "Customers." + +```vb +Dim workTable as DataTable = New DataTable("Customers") +``` + +```csharp +DataTable workTable = new DataTable("Customers"); +``` + + The following example creates an instance of a `DataTable` by adding it to the `Tables` collection of a **DataSet**. + +```vb +Dim customers As DataSet = New DataSet +Dim customersTable As DataTable = _ + customers.Tables.Add("CustomersTable") +``` + +```csharp +DataSet customers = new DataSet(); +DataTable customersTable = customers.Tables.Add("CustomersTable"); +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/creating-a-dataview.md b/docs/framework/data/adonet/dataset-datatable-dataview/creating-a-dataview.md index f7085318f6a6a..2b2a4dcc3928d 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/creating-a-dataview.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/creating-a-dataview.md @@ -2,45 +2,45 @@ description: "Learn more about: Creating a DataView" title: "Creating a DataView" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: b1cc02d1-23b1-4439-a998-0da1899f3442 --- # Creating a DataView -There are two ways to create a . You can use the **DataView** constructor, or you can create a reference to the property of the . The **DataView** constructor can be empty, or it can take either a **DataTable** as a single argument, or a **DataTable** along with filter criteria, sort criteria, and a row state filter. For more information about the additional arguments available for use with the **DataView**, see [Sorting and Filtering Data](sorting-and-filtering-data.md). - - Because the index for a **DataView** is built both when the **DataView** is created, and when any of the **Sort**, **RowFilter**, or **RowStateFilter** properties are modified, you achieve best performance by supplying any initial sort order or filtering criteria as constructor arguments when you create the **DataView**. Creating a **DataView** without specifying sort or filter criteria and then setting the **Sort**, **RowFilter**, or **RowStateFilter** properties later causes the index to be built at least twice: once when the **DataView** is created, and again when any of the sort or filter properties are modified. - - Note that if you create a **DataView** using the constructor that does not take any arguments, you will not be able to use the **DataView** until you have set the **Table** property. - - The following code example demonstrates how to create a **DataView** using the **DataView** constructor. A **RowFilter**, **Sort** column, and **DataViewRowState** are supplied along with the **DataTable**. - -```vb -Dim custDV As DataView = New DataView(custDS.Tables("Customers"), _ - "Country = 'USA'", _ - "ContactName", _ - DataViewRowState.CurrentRows) -``` - -```csharp +There are two ways to create a . You can use the `DataView` constructor, or you can create a reference to the property of the . The `DataView` constructor can be empty, or it can take either a `DataTable` as a single argument, or a `DataTable` along with filter criteria, sort criteria, and a row state filter. For more information about the additional arguments available for use with the **DataView**, see [Sorting and Filtering Data](sorting-and-filtering-data.md). + + Because the index for a `DataView` is built both when the `DataView` is created, and when any of the **Sort**, **RowFilter**, or `RowStateFilter` properties are modified, you achieve best performance by supplying any initial sort order or filtering criteria as constructor arguments when you create the **DataView**. Creating a `DataView` without specifying sort or filter criteria and then setting the **Sort**, **RowFilter**, or `RowStateFilter` properties later causes the index to be built at least twice: once when the `DataView` is created, and again when any of the sort or filter properties are modified. + + Note that if you create a `DataView` using the constructor that does not take any arguments, you will not be able to use the `DataView` until you have set the `Table` property. + + The following code example demonstrates how to create a `DataView` using the `DataView` constructor. A **RowFilter**, `Sort` column, and `DataViewRowState` are supplied along with the **DataTable**. + +```vb +Dim custDV As DataView = New DataView(custDS.Tables("Customers"), _ + "Country = 'USA'", _ + "ContactName", _ + DataViewRowState.CurrentRows) +``` + +```csharp DataView custDV = new DataView(custDS.Tables["Customers"], "Country = 'USA'", "ContactName", - DataViewRowState.CurrentRows); -``` - - The following code example demonstrates how to obtain a reference to the default **DataView** of a **DataTable** using the **DefaultView** property of the table. - -```vb -Dim custDV As DataView = custDS.Tables("Customers").DefaultView -``` - -```csharp -DataView custDV = custDS.Tables["Customers"].DefaultView; -``` - + DataViewRowState.CurrentRows); +``` + + The following code example demonstrates how to obtain a reference to the default `DataView` of a `DataTable` using the `DefaultView` property of the table. + +```vb +Dim custDV As DataView = custDS.Tables("Customers").DefaultView +``` + +```csharp +DataView custDV = custDS.Tables["Customers"].DefaultView; +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/creating-autoincrement-columns.md b/docs/framework/data/adonet/dataset-datatable-dataview/creating-autoincrement-columns.md index 95df6d16e8053..fef1e87d786de 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/creating-autoincrement-columns.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/creating-autoincrement-columns.md @@ -2,35 +2,35 @@ description: "Learn more about: Creating AutoIncrement Columns" title: "Creating AutoIncrement Columns" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: cf09732a-ab54-4d98-89e2-4d0a1f28fbce --- # Creating AutoIncrement Columns -To ensure unique column values, you can set the column values to increment automatically when new rows are added to the table. To create an auto-incrementing , set the property of the column to **true**. The then starts with the value defined in the property, and with each row added the value of the **AutoIncrement** column increases by the value defined in the property of the column. - - For **AutoIncrement** columns, we recommend that the property of the **DataColumn** be set to **true**. - - The following example demonstrates how to create a column that starts with a value of 200 and adds incrementally in steps of 3. - -```vb -Dim workColumn As DataColumn = workTable.Columns.Add( _ - "CustomerID", typeof(Int32)) -workColumn.AutoIncrement = true -workColumn.AutoIncrementSeed = 200 -workColumn.AutoIncrementStep = 3 -``` - -```csharp -DataColumn workColumn = workTable.Columns.Add( - "CustomerID", typeof(Int32)); -workColumn.AutoIncrement = true; -workColumn.AutoIncrementSeed = 200; -workColumn.AutoIncrementStep = 3; -``` - +To ensure unique column values, you can set the column values to increment automatically when new rows are added to the table. To create an auto-incrementing , set the property of the column to **true**. The then starts with the value defined in the property, and with each row added the value of the `AutoIncrement` column increases by the value defined in the property of the column. + + For `AutoIncrement` columns, we recommend that the property of the `DataColumn` be set to **true**. + + The following example demonstrates how to create a column that starts with a value of 200 and adds incrementally in steps of 3. + +```vb +Dim workColumn As DataColumn = workTable.Columns.Add( _ + "CustomerID", typeof(Int32)) +workColumn.AutoIncrement = true +workColumn.AutoIncrementSeed = 200 +workColumn.AutoIncrementStep = 3 +``` + +```csharp +DataColumn workColumn = workTable.Columns.Add( + "CustomerID", typeof(Int32)); +workColumn.AutoIncrement = true; +workColumn.AutoIncrementSeed = 200; +workColumn.AutoIncrementStep = 3; +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/creating-expression-columns.md b/docs/framework/data/adonet/dataset-datatable-dataview/creating-expression-columns.md index 9f56881fe8390..6c34eae4e73fd 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/creating-expression-columns.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/creating-expression-columns.md @@ -2,38 +2,38 @@ description: "Learn more about: Creating Expression Columns" title: "Creating Expression Columns" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 0af3bd64-92a2-4b47-ae62-f5df35f131a6 --- # Creating Expression Columns -You can define an expression for a column, enabling it to contain a value calculated from other column values in the same row or from the column values of multiple rows in the table. To define the expression to be evaluated, use the property of the target column, and use the property to refer to other columns in the expression. The for the expression column must be appropriate for the value that the expression returns. - - The following table lists several possible uses for expression columns in a table. - -|Expression type|Example| -|---------------------|-------------| -|Comparison|"Total >= 500"| -|Computation|"UnitPrice * Quantity"| -|Aggregation|Sum(Price)| - - You can set the **Expression** property on an existing **DataColumn** object, or you can include the property as the third argument passed to the constructor, as shown in the following example. - -```vb -workTable.Columns.Add("Total",Type.GetType("System.Double")) -workTable.Columns.Add("SalesTax", Type.GetType("System.Double"), _ - "Total * 0.086") -``` - -```csharp -workTable.Columns.Add("Total", typeof(Double)); -workTable.Columns.Add("SalesTax", typeof(Double), "Total * 0.086"); -``` - - Expressions can reference other expression columns; however, a circular reference, in which two expressions reference each other, will generate an exception. For rules about writing expressions, see the property of the **DataColumn** class. - +You can define an expression for a column, enabling it to contain a value calculated from other column values in the same row or from the column values of multiple rows in the table. To define the expression to be evaluated, use the property of the target column, and use the property to refer to other columns in the expression. The for the expression column must be appropriate for the value that the expression returns. + + The following table lists several possible uses for expression columns in a table. + +|Expression type|Example| +|---------------------|-------------| +|Comparison|"Total >= 500"| +|Computation|"UnitPrice * Quantity"| +|Aggregation|Sum(Price)| + + You can set the `Expression` property on an existing `DataColumn` object, or you can include the property as the third argument passed to the constructor, as shown in the following example. + +```vb +workTable.Columns.Add("Total",Type.GetType("System.Double")) +workTable.Columns.Add("SalesTax", Type.GetType("System.Double"), _ + "Total * 0.086") +``` + +```csharp +workTable.Columns.Add("Total", typeof(Double)); +workTable.Columns.Add("SalesTax", typeof(Double), "Total * 0.086"); +``` + + Expressions can reference other expression columns; however, a circular reference, in which two expressions reference each other, will generate an exception. For rules about writing expressions, see the property of the `DataColumn` class. + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/datarow-deletion.md b/docs/framework/data/adonet/dataset-datatable-dataview/datarow-deletion.md index 926cd26ec2147..c51da58415c9c 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/datarow-deletion.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/datarow-deletion.md @@ -2,44 +2,44 @@ description: "Learn more about: DataRow Deletion" title: "DataRow Deletion" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: c34f531d-4b9b-4071-b2d7-342c402aa586 --- # DataRow Deletion -There are two methods you can use to delete a object from a object: the **Remove** method of the object, and the method of the **DataRow** object. Whereas the method deletes a **DataRow** from the **DataRowCollection**, the method only marks the row for deletion. The actual removal occurs when the application calls the **AcceptChanges** method. By using , you can programmatically check which rows are marked for deletion before actually removing them. When a row is marked for deletion, its property is set to . - - Neither nor should be called in a foreach loop while iterating through a object. nor modify the state of the collection. - - When using a or **DataTable** in conjunction with a **DataAdapter** and a relational data source, use the **Delete** method of the **DataRow** to remove the row. The **Delete** method marks the row as **Deleted** in the **DataSet** or **DataTable** but does not remove it. Instead, when the **DataAdapter** encounters a row marked as **Deleted**, it executes its **DeleteCommand** method to delete the row at the data source. The row can then be permanently removed using the **AcceptChanges** method. If you use **Remove** to delete the row, the row is removed entirely from the table, but the **DataAdapter** will not delete the row at the data source. - - The **Remove** method of the **DataRowCollection** takes a **DataRow** as an argument and removes it from the collection, as shown in the following example. - -```vb -workTable.Rows.Remove(workRow) -``` - -```csharp -workTable.Rows.Remove(workRow); -``` - - In contrast, the following example demonstrates how to call the **Delete** method on a **DataRow** to change its **RowState** to **Deleted**. - -```vb -workRow.Delete -``` - -```csharp -workRow.Delete(); -``` - - If a row is marked for deletion and you call the **AcceptChanges** method of the **DataTable** object, the row is removed from the **DataTable**. In contrast, if you call **RejectChanges**, the **RowState** of the row reverts to what it was before being marked as **Deleted**. - +There are two methods you can use to delete a object from a object: the `Remove` method of the object, and the method of the `DataRow` object. Whereas the method deletes a `DataRow` from the **DataRowCollection**, the method only marks the row for deletion. The actual removal occurs when the application calls the `AcceptChanges` method. By using , you can programmatically check which rows are marked for deletion before actually removing them. When a row is marked for deletion, its property is set to . + + Neither nor should be called in a foreach loop while iterating through a object. nor modify the state of the collection. + + When using a or `DataTable` in conjunction with a `DataAdapter` and a relational data source, use the `Delete` method of the `DataRow` to remove the row. The `Delete` method marks the row as `Deleted` in the `DataSet` or `DataTable` but does not remove it. Instead, when the `DataAdapter` encounters a row marked as **Deleted**, it executes its `DeleteCommand` method to delete the row at the data source. The row can then be permanently removed using the `AcceptChanges` method. If you use `Remove` to delete the row, the row is removed entirely from the table, but the `DataAdapter` will not delete the row at the data source. + + The `Remove` method of the `DataRowCollection` takes a `DataRow` as an argument and removes it from the collection, as shown in the following example. + +```vb +workTable.Rows.Remove(workRow) +``` + +```csharp +workTable.Rows.Remove(workRow); +``` + + In contrast, the following example demonstrates how to call the `Delete` method on a `DataRow` to change its `RowState` to **Deleted**. + +```vb +workRow.Delete +``` + +```csharp +workRow.Delete(); +``` + + If a row is marked for deletion and you call the `AcceptChanges` method of the `DataTable` object, the row is removed from the **DataTable**. In contrast, if you call **RejectChanges**, the `RowState` of the row reverts to what it was before being marked as **Deleted**. + > [!NOTE] -> If the **RowState** of a **DataRow** is **Added**, meaning it has just been added to the table, and it is then marked as **Deleted**, it is removed from the table. - +> If the `RowState` of a `DataRow` is **Added**, meaning it has just been added to the table, and it is then marked as **Deleted**, it is removed from the table. + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/datarows-and-datarowviews.md b/docs/framework/data/adonet/dataset-datatable-dataview/datarows-and-datarowviews.md index 933324c145ca5..b26a73e4e2fb6 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/datarows-and-datarowviews.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/datarows-and-datarowviews.md @@ -2,59 +2,59 @@ description: "Learn more about: DataRows and DataRowViews" title: "DataRows and DataRowViews" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 8f5eec26-b809-4aca-8778-7e202356d856 --- # DataRows and DataRowViews -A exposes an enumerable collection of objects. The **DataRowView** objects expose values as object arrays that are indexed by either the name or the ordinal reference of the column in the underlying table. You can access the that is exposed by the **DataRowView** by using the property of the **DataRowView**. - - When you view values by using a **DataRowView**, the property of the **DataView** determines which row version of the underlying **DataRow** is exposed. For information about accessing different row versions using a **DataRow**, see [Row States and Row Versions](row-states-and-row-versions.md). - - The following code example displays all the current and original values in a table. - -```vb -Dim catView As DataView = New DataView(catDS.Tables("Categories")) -Console.WriteLine("Current Values:") -WriteView(catView) -Console.WriteLine("Original Values:") -catView.RowStateFilter = DataViewRowState.ModifiedOriginal +A exposes an enumerable collection of objects. The `DataRowView` objects expose values as object arrays that are indexed by either the name or the ordinal reference of the column in the underlying table. You can access the that is exposed by the `DataRowView` by using the property of the **DataRowView**. + + When you view values by using a **DataRowView**, the property of the `DataView` determines which row version of the underlying `DataRow` is exposed. For information about accessing different row versions using a **DataRow**, see [Row States and Row Versions](row-states-and-row-versions.md). + + The following code example displays all the current and original values in a table. + +```vb +Dim catView As DataView = New DataView(catDS.Tables("Categories")) +Console.WriteLine("Current Values:") WriteView(catView) - -Public Shared Sub WriteView(thisDataView As DataView) - Dim rowView As DataRowView - Dim i As Integer - - For Each rowView In thisDataView - For i = 0 To thisDataView.Table.Columns.Count - 1 - Console.Write(rowView(i) & vbTab) - Next - Console.WriteLine() - Next -End Sub -``` - -```csharp -DataView catView = new DataView(catDS.Tables["Categories"]); -Console.WriteLine("Current Values:"); -WriteView(catView); -Console.WriteLine("Original Values:"); -catView.RowStateFilter = DataViewRowState.ModifiedOriginal; -WriteView(catView); - -public static void WriteView(DataView thisDataView) -{ - foreach (DataRowView rowView in thisDataView) - { - for (int i = 0; i < thisDataView.Table.Columns.Count; i++) - Console.Write(rowView[i] + "\t"); - Console.WriteLine(); - } -} -``` - +Console.WriteLine("Original Values:") +catView.RowStateFilter = DataViewRowState.ModifiedOriginal +WriteView(catView) + +Public Shared Sub WriteView(thisDataView As DataView) + Dim rowView As DataRowView + Dim i As Integer + + For Each rowView In thisDataView + For i = 0 To thisDataView.Table.Columns.Count - 1 + Console.Write(rowView(i) & vbTab) + Next + Console.WriteLine() + Next +End Sub +``` + +```csharp +DataView catView = new DataView(catDS.Tables["Categories"]); +Console.WriteLine("Current Values:"); +WriteView(catView); +Console.WriteLine("Original Values:"); +catView.RowStateFilter = DataViewRowState.ModifiedOriginal; +WriteView(catView); + +public static void WriteView(DataView thisDataView) +{ + foreach (DataRowView rowView in thisDataView) + { + for (int i = 0; i < thisDataView.Table.Columns.Count; i++) + Console.Write(rowView[i] + "\t"); + Console.WriteLine(); + } +} +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/dataset-and-xmldatadocument-synchronization.md b/docs/framework/data/adonet/dataset-datatable-dataview/dataset-and-xmldatadocument-synchronization.md index 047677277364e..aef2874b020b1 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/dataset-and-xmldatadocument-synchronization.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/dataset-and-xmldatadocument-synchronization.md @@ -2,114 +2,114 @@ description: "Learn more about: DataSet and XmlDataDocument Synchronization" title: "DataSet and XmlDataDocument Synchronization" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 0ce3793d-54b2-47e4-8cf7-b0591cc4dd21 --- # DataSet and XmlDataDocument Synchronization -The ADO.NET provides you with a relational representation of data. For hierarchical data access, you can use the XML classes available in the .NET Framework. Historically, these two representations of data have been used separately. However, the .NET Framework enables real-time, synchronous access to both the relational and hierarchical representations of data through the **DataSet** object and the object, respectively. - - When a **DataSet** is synchronized with an **XmlDataDocument**, both objects are working with a single set of data. This means that if a change is made to the **DataSet**, the change will be reflected in the **XmlDataDocument**, and vice versa. The relationship between the **DataSet** and the **XmlDataDocument** creates great flexibility by allowing a single application, using a single set of data, to access the entire suite of services built around the **DataSet** (such as Web Forms and Windows Forms controls, and Visual Studio .NET designers), as well as the suite of XML services including Extensible Stylesheet Language (XSL), XSL Transformations (XSLT), and XML Path Language (XPath). You do not have to choose which set of services to target with the application; both are available. - - There are several ways that you can synchronize a **DataSet** with an **XmlDataDocument**. You can: - -- Populate a **DataSet** with schema (that is, a relational structure) and data and then synchronize it with a new **XmlDataDocument**. This provides a hierarchical view of existing relational data. For example: - - ```vb - Dim dataSet As DataSet = New DataSet - - ' Add code here to populate the DataSet with schema and data. - - Dim xmlDoc As XmlDataDocument = New XmlDataDocument(dataSet) - ``` - - ```csharp - DataSet dataSet = new DataSet(); - - // Add code here to populate the DataSet with schema and data. - - XmlDataDocument xmlDoc = new XmlDataDocument(dataSet); - ``` - -- Populate a **DataSet** with schema only (such as a strongly typed **DataSet**), synchronize it with an **XmlDataDocument**, and then load the **XmlDataDocument** from an XML document. This provides a relational view of existing hierarchical data. The table names and column names in your **DataSet** schema must match the names of the XML elements that you want them synchronized with. This matching is case-sensitive. - - Note that the schema of the **DataSet** only needs to match the XML elements that you want to expose in your relational view. This way, you can have a very large XML document and a very small relational "window" on that document. The **XmlDataDocument** preserves the entire XML document even though the **DataSet** only exposes a small portion of it. (For a detailed example of this, see [Synchronizing a DataSet with an XmlDataDocument](synchronizing-a-dataset-with-an-xmldatadocument.md).) - - The following code example shows the steps for creating a **DataSet** and populating its schema, then synchronizing it with an **XmlDataDocument**. Note that the **DataSet** schema only needs to match the elements from the **XmlDataDocument** that you want to expose using the **DataSet**. - - ```vb - Dim dataSet As DataSet = New DataSet - - ' Add code here to populate the DataSet with schema, but not data. - - Dim xmlDoc As XmlDataDocument = New XmlDataDocument(dataSet) - xmlDoc.Load("XMLDocument.xml") - ``` - - ```csharp - DataSet dataSet = new DataSet(); - - // Add code here to populate the DataSet with schema, but not data. - - XmlDataDocument xmlDoc = new XmlDataDocument(dataSet); - xmlDoc.Load("XMLDocument.xml"); - ``` - - You cannot load an **XmlDataDocument** if it is synchronized with a **DataSet** that contains data. An exception will be thrown. - -- Create a new **XmlDataDocument** and load it from an XML document, and then access the relational view of the data using the **DataSet** property of the **XmlDataDocument**. You need to set the schema of the **DataSet** before you can view any of the data in the **XmlDataDocument** using the **DataSet**. Again, the table names and column names in your **DataSet** schema must match the names of the XML elements that you want them synchronized with. This matching is case-sensitive. - - The following code example shows how to access the relational view of the data in an **XmlDataDocument**. - - ```vb - Dim xmlDoc As XmlDataDocument = New XmlDataDocument - Dim dataSet As DataSet = xmlDoc.DataSet - - ' Add code here to create the schema of the DataSet to view the data. - - xmlDoc.Load("XMLDocument.xml") - ``` - - ```csharp - XmlDataDocument xmlDoc = new XmlDataDocument(); - DataSet dataSet = xmlDoc.DataSet; - - // Add code here to create the schema of the DataSet to view the data. - - xmlDoc.Load("XMLDocument.xml"); - ``` - - Another advantage of synchronizing an **XmlDataDocument** with a **DataSet** is that the fidelity of an XML document is preserved. If the **DataSet** is populated from an XML document using **ReadXml**, when the data is written back as an XML document using **WriteXml** it may differ dramatically from the original XML document. This is because the **DataSet** does not maintain formatting, such as white space, or hierarchical information, such as element order, from the XML document. The **DataSet** also does not contain elements from the XML document that were ignored because they did not match the schema of the **Dataset**. Synchronizing an **XmlDataDocument** with a **DataSet** allows the formatting and hierarchical element structure of the original XML document to be maintained in the **XmlDataDocument**, while the **DataSet** contains only data and schema information appropriate to the **DataSet**. - - When synchronizing a **DataSet** with an **XmlDataDocument**, results may differ depending on whether or not your objects are nested. For more information, see [Nesting DataRelations](nesting-datarelations.md). - -## In This Section - - [Synchronizing a DataSet with an XmlDataDocument](synchronizing-a-dataset-with-an-xmldatadocument.md) - Demonstrates synchronizing a strongly typed **DataSet**, with minimal schema, with an **XmlDataDocument**. - - [Performing an XPath Query on a DataSet](performing-an-xpath-query-on-a-dataset.md) - Demonstrates performing an XPath query on the contents of a **DataSet**. - - [Applying an XSLT Transform to a DataSet](applying-an-xslt-transform-to-a-dataset.md) - Demonstrates applying an XSLT transform to the contents of a **DataSet**. - -## Related Sections - - [Using XML in a DataSet](using-xml-in-a-dataset.md) - Describes how the **DataSet** interacts with XML as a data source, including loading and persisting the contents of a **DataSet** as XML data. - - [Nesting DataRelations](nesting-datarelations.md) - Discusses the importance of nested **DataRelation** objects when representing the contents of a **DataSet** as XML data, and describes how to create these relations. - - [DataSets, DataTables, and DataViews](index.md) - Describes the **DataSet** and how to use it to manage application data and to interact with data sources including relational databases and XML. - - - Contains reference information about the **XmlDataDocument** class. - +The ADO.NET provides you with a relational representation of data. For hierarchical data access, you can use the XML classes available in the .NET Framework. Historically, these two representations of data have been used separately. However, the .NET Framework enables real-time, synchronous access to both the relational and hierarchical representations of data through the `DataSet` object and the object, respectively. + + When a `DataSet` is synchronized with an **XmlDataDocument**, both objects are working with a single set of data. This means that if a change is made to the **DataSet**, the change will be reflected in the **XmlDataDocument**, and vice versa. The relationship between the `DataSet` and the `XmlDataDocument` creates great flexibility by allowing a single application, using a single set of data, to access the entire suite of services built around the `DataSet` (such as Web Forms and Windows Forms controls, and Visual Studio .NET designers), as well as the suite of XML services including Extensible Stylesheet Language (XSL), XSL Transformations (XSLT), and XML Path Language (XPath). You do not have to choose which set of services to target with the application; both are available. + + There are several ways that you can synchronize a `DataSet` with an **XmlDataDocument**. You can: + +- Populate a `DataSet` with schema (that is, a relational structure) and data and then synchronize it with a new **XmlDataDocument**. This provides a hierarchical view of existing relational data. For example: + + ```vb + Dim dataSet As DataSet = New DataSet + + ' Add code here to populate the DataSet with schema and data. + + Dim xmlDoc As XmlDataDocument = New XmlDataDocument(dataSet) + ``` + + ```csharp + DataSet dataSet = new DataSet(); + + // Add code here to populate the DataSet with schema and data. + + XmlDataDocument xmlDoc = new XmlDataDocument(dataSet); + ``` + +- Populate a `DataSet` with schema only (such as a strongly typed **DataSet**), synchronize it with an **XmlDataDocument**, and then load the `XmlDataDocument` from an XML document. This provides a relational view of existing hierarchical data. The table names and column names in your `DataSet` schema must match the names of the XML elements that you want them synchronized with. This matching is case-sensitive. + + Note that the schema of the `DataSet` only needs to match the XML elements that you want to expose in your relational view. This way, you can have a very large XML document and a very small relational "window" on that document. The `XmlDataDocument` preserves the entire XML document even though the `DataSet` only exposes a small portion of it. (For a detailed example of this, see [Synchronizing a DataSet with an XmlDataDocument](synchronizing-a-dataset-with-an-xmldatadocument.md).) + + The following code example shows the steps for creating a `DataSet` and populating its schema, then synchronizing it with an **XmlDataDocument**. Note that the `DataSet` schema only needs to match the elements from the `XmlDataDocument` that you want to expose using the **DataSet**. + + ```vb + Dim dataSet As DataSet = New DataSet + + ' Add code here to populate the DataSet with schema, but not data. + + Dim xmlDoc As XmlDataDocument = New XmlDataDocument(dataSet) + xmlDoc.Load("XMLDocument.xml") + ``` + + ```csharp + DataSet dataSet = new DataSet(); + + // Add code here to populate the DataSet with schema, but not data. + + XmlDataDocument xmlDoc = new XmlDataDocument(dataSet); + xmlDoc.Load("XMLDocument.xml"); + ``` + + You cannot load an `XmlDataDocument` if it is synchronized with a `DataSet` that contains data. An exception will be thrown. + +- Create a new `XmlDataDocument` and load it from an XML document, and then access the relational view of the data using the `DataSet` property of the **XmlDataDocument**. You need to set the schema of the `DataSet` before you can view any of the data in the `XmlDataDocument` using the **DataSet**. Again, the table names and column names in your `DataSet` schema must match the names of the XML elements that you want them synchronized with. This matching is case-sensitive. + + The following code example shows how to access the relational view of the data in an **XmlDataDocument**. + + ```vb + Dim xmlDoc As XmlDataDocument = New XmlDataDocument + Dim dataSet As DataSet = xmlDoc.DataSet + + ' Add code here to create the schema of the DataSet to view the data. + + xmlDoc.Load("XMLDocument.xml") + ``` + + ```csharp + XmlDataDocument xmlDoc = new XmlDataDocument(); + DataSet dataSet = xmlDoc.DataSet; + + // Add code here to create the schema of the DataSet to view the data. + + xmlDoc.Load("XMLDocument.xml"); + ``` + + Another advantage of synchronizing an `XmlDataDocument` with a `DataSet` is that the fidelity of an XML document is preserved. If the `DataSet` is populated from an XML document using **ReadXml**, when the data is written back as an XML document using `WriteXml` it may differ dramatically from the original XML document. This is because the `DataSet` does not maintain formatting, such as white space, or hierarchical information, such as element order, from the XML document. The `DataSet` also does not contain elements from the XML document that were ignored because they did not match the schema of the **Dataset**. Synchronizing an `XmlDataDocument` with a `DataSet` allows the formatting and hierarchical element structure of the original XML document to be maintained in the **XmlDataDocument**, while the `DataSet` contains only data and schema information appropriate to the **DataSet**. + + When synchronizing a `DataSet` with an **XmlDataDocument**, results may differ depending on whether or not your objects are nested. For more information, see [Nesting DataRelations](nesting-datarelations.md). + +## In This Section + + [Synchronizing a DataSet with an XmlDataDocument](synchronizing-a-dataset-with-an-xmldatadocument.md) + Demonstrates synchronizing a strongly typed **DataSet**, with minimal schema, with an **XmlDataDocument**. + + [Performing an XPath Query on a DataSet](performing-an-xpath-query-on-a-dataset.md) + Demonstrates performing an XPath query on the contents of a **DataSet**. + + [Applying an XSLT Transform to a DataSet](applying-an-xslt-transform-to-a-dataset.md) + Demonstrates applying an XSLT transform to the contents of a **DataSet**. + +## Related Sections + + [Using XML in a DataSet](using-xml-in-a-dataset.md) + Describes how the `DataSet` interacts with XML as a data source, including loading and persisting the contents of a `DataSet` as XML data. + + [Nesting DataRelations](nesting-datarelations.md) + Discusses the importance of nested `DataRelation` objects when representing the contents of a `DataSet` as XML data, and describes how to create these relations. + + [DataSets, DataTables, and DataViews](index.md) + Describes the `DataSet` and how to use it to manage application data and to interact with data sources including relational databases and XML. + + + Contains reference information about the `XmlDataDocument` class. + ## See also - [ADO.NET Overview](../ado-net-overview.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/datatable-constraints.md b/docs/framework/data/adonet/dataset-datatable-dataview/datatable-constraints.md index 9af89b51ad342..3854003dc900f 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/datatable-constraints.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/datatable-constraints.md @@ -2,96 +2,96 @@ description: "Learn more about: DataTable Constraints" title: "DataTable Constraints" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 27c9f2fd-f64d-4b4e-bbf6-1d24f47067cb --- # DataTable Constraints -You can use constraints to enforce restrictions on the data in a , in order to maintain the integrity of the data. A constraint is an automatic rule, applied to a column or related columns, that determines the course of action when the value of a row is somehow altered. Constraints are enforced when the `System.Data.DataSet.EnforceConstraints` property of the is **true**. For a code example that shows how to set the `EnforceConstraints` property, see the reference topic. - - There are two kinds of constraints in ADO.NET: the and the . By default, both constraints are created automatically when you create a relationship between two or more tables by adding a to the **DataSet**. However, you can disable this behavior by specifying **createConstraints** = **false** when creating the relation. - -## ForeignKeyConstraint - - A **ForeignKeyConstraint** enforces rules about how updates and deletes to related tables are propagated. For example, if a value in a row of one table is updated or deleted, and that same value is also used in one or more related tables, a **ForeignKeyConstraint** determines what happens in the related tables. - - The and properties of the **ForeignKeyConstraint** define the action to be taken when the user attempts to delete or update a row in a related table. The following table describes the different settings available for the **DeleteRule** and **UpdateRule** properties of the **ForeignKeyConstraint**. - -|Rule setting|Description| -|------------------|-----------------| -|**Cascade**|Delete or update related rows.| -|**SetNull**|Set values in related rows to **DBNull**.| -|**SetDefault**|Set values in related rows to the default value.| -|**None**|Take no action on related rows. This is the default.| - - A **ForeignKeyConstraint** can restrict, as well as propagate, changes to related columns. Depending on the properties set for the **ForeignKeyConstraint** of a column, if the **EnforceConstraints** property of the **DataSet** is **true**, performing certain operations on the parent row will result in an exception. For example, if the **DeleteRule** property of the **ForeignKeyConstraint** is **None**, a parent row cannot be deleted if it has any child rows. - - You can create a foreign key constraint between single columns or between an array of columns by using the **ForeignKeyConstraint** constructor. Pass the resulting **ForeignKeyConstraint** object to the **Add** method of the table's **Constraints** property, which is a **ConstraintCollection**. You can also pass constructor arguments to several overloads of the **Add** method of a **ConstraintCollection** to create a **ForeignKeyConstraint**. - - When creating a **ForeignKeyConstraint**, you can pass the **DeleteRule** and **UpdateRule** values to the constructor as arguments, or you can set them as properties as in the following example (where the **DeleteRule** value is set to **None**). - -```vb -Dim custOrderFK As ForeignKeyConstraint = New ForeignKeyConstraint("CustOrderFK", _ - custDS.Tables("CustTable").Columns("CustomerID"), _ - custDS.Tables("OrdersTable").Columns("CustomerID")) +You can use constraints to enforce restrictions on the data in a , in order to maintain the integrity of the data. A constraint is an automatic rule, applied to a column or related columns, that determines the course of action when the value of a row is somehow altered. Constraints are enforced when the `System.Data.DataSet.EnforceConstraints` property of the is **true**. For a code example that shows how to set the `EnforceConstraints` property, see the reference topic. + + There are two kinds of constraints in ADO.NET: the and the . By default, both constraints are created automatically when you create a relationship between two or more tables by adding a to the **DataSet**. However, you can disable this behavior by specifying `createConstraints` = `false` when creating the relation. + +## ForeignKeyConstraint + + A `ForeignKeyConstraint` enforces rules about how updates and deletes to related tables are propagated. For example, if a value in a row of one table is updated or deleted, and that same value is also used in one or more related tables, a `ForeignKeyConstraint` determines what happens in the related tables. + + The and properties of the `ForeignKeyConstraint` define the action to be taken when the user attempts to delete or update a row in a related table. The following table describes the different settings available for the `DeleteRule` and `UpdateRule` properties of the **ForeignKeyConstraint**. + +|Rule setting|Description| +|------------------|-----------------| +|**Cascade**|Delete or update related rows.| +|**SetNull**|Set values in related rows to **DBNull**.| +|**SetDefault**|Set values in related rows to the default value.| +|**None**|Take no action on related rows. This is the default.| + + A `ForeignKeyConstraint` can restrict, as well as propagate, changes to related columns. Depending on the properties set for the `ForeignKeyConstraint` of a column, if the `EnforceConstraints` property of the `DataSet` is **true**, performing certain operations on the parent row will result in an exception. For example, if the `DeleteRule` property of the `ForeignKeyConstraint` is **None**, a parent row cannot be deleted if it has any child rows. + + You can create a foreign key constraint between single columns or between an array of columns by using the `ForeignKeyConstraint` constructor. Pass the resulting `ForeignKeyConstraint` object to the `Add` method of the table's `Constraints` property, which is a **ConstraintCollection**. You can also pass constructor arguments to several overloads of the `Add` method of a `ConstraintCollection` to create a **ForeignKeyConstraint**. + + When creating a **ForeignKeyConstraint**, you can pass the `DeleteRule` and `UpdateRule` values to the constructor as arguments, or you can set them as properties as in the following example (where the `DeleteRule` value is set to **None**). + +```vb +Dim custOrderFK As ForeignKeyConstraint = New ForeignKeyConstraint("CustOrderFK", _ + custDS.Tables("CustTable").Columns("CustomerID"), _ + custDS.Tables("OrdersTable").Columns("CustomerID")) custOrderFK.DeleteRule = Rule.None -' Cannot delete a customer value that has associated existing orders. -custDS.Tables("OrdersTable").Constraints.Add(custOrderFK) -``` - -```csharp -ForeignKeyConstraint custOrderFK = new ForeignKeyConstraint("CustOrderFK", +' Cannot delete a customer value that has associated existing orders. +custDS.Tables("OrdersTable").Constraints.Add(custOrderFK) +``` + +```csharp +ForeignKeyConstraint custOrderFK = new ForeignKeyConstraint("CustOrderFK", custDS.Tables["CustTable"].Columns["CustomerID"], - custDS.Tables["OrdersTable"].Columns["CustomerID"]); + custDS.Tables["OrdersTable"].Columns["CustomerID"]); custOrderFK.DeleteRule = Rule.None; -// Cannot delete a customer value that has associated existing orders. -custDS.Tables["OrdersTable"].Constraints.Add(custOrderFK); -``` - -### AcceptRejectRule - - Changes to rows can be accepted using the **AcceptChanges** method or canceled using the **RejectChanges** method of the **DataSet**, **DataTable**, or **DataRow**. When a **DataSet** contains **ForeignKeyConstraints**, invoking the **AcceptChanges** or **RejectChanges** methods enforces the **AcceptRejectRule**. The **AcceptRejectRule** property of the **ForeignKeyConstraint** determines which action will be taken on the child rows when **AcceptChanges** or **RejectChanges** is called on the parent row. - - The following table lists the available settings for the **AcceptRejectRule**. - -|Rule setting|Description| -|------------------|-----------------| -|**Cascade**|Accept or reject changes to child rows.| -|**None**|Take no action on child rows. This is the default.| - -### Example - - The following example creates a , sets several of its properties, including the , and adds it to the of a object. - +// Cannot delete a customer value that has associated existing orders. +custDS.Tables["OrdersTable"].Constraints.Add(custOrderFK); +``` + +### AcceptRejectRule + + Changes to rows can be accepted using the `AcceptChanges` method or canceled using the `RejectChanges` method of the **DataSet**, **DataTable**, or **DataRow**. When a `DataSet` contains **ForeignKeyConstraints**, invoking the `AcceptChanges` or `RejectChanges` methods enforces the **AcceptRejectRule**. The `AcceptRejectRule` property of the `ForeignKeyConstraint` determines which action will be taken on the child rows when `AcceptChanges` or `RejectChanges` is called on the parent row. + + The following table lists the available settings for the **AcceptRejectRule**. + +|Rule setting|Description| +|------------------|-----------------| +|**Cascade**|Accept or reject changes to child rows.| +|**None**|Take no action on child rows. This is the default.| + +### Example + + The following example creates a , sets several of its properties, including the , and adds it to the of a object. + [!code-csharp[DataWorks Data.AcceptRejectRule#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/CS/source.cs#1)] - [!code-vb[DataWorks Data.AcceptRejectRule#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/VB/source.vb#1)] - -## UniqueConstraint - - The **UniqueConstraint** object, which can be assigned either to a single column or to an array of columns in a **DataTable**, ensures that all data in the specified column or columns is unique per row. You can create a unique constraint for a column or array of columns by using the **UniqueConstraint** constructor. Pass the resulting **UniqueConstraint** object to the **Add** method of the table's **Constraints** property, which is a **ConstraintCollection**. You can also pass constructor arguments to several overloads of the **Add** method of a **ConstraintCollection** to create a **UniqueConstraint**. When creating a **UniqueConstraint** for a column or columns, you can optionally specify whether the column or columns are a primary key. - - You can also create a unique constraint for a column by setting the **Unique** property of the column to **true**. Alternatively, setting the **Unique** property of a single column to **false** removes any unique constraint that may exist. Defining a column or columns as the primary key for a table will automatically create a unique constraint for the specified column or columns. If you remove a column from the **PrimaryKey** property of a **DataTable**, the **UniqueConstraint** is removed. - - The following example creates a **UniqueConstraint** for two columns of a **DataTable**. - -```vb -Dim custTable As DataTable = custDS.Tables("Customers") -Dim custUnique As UniqueConstraint = _ - New UniqueConstraint(New DataColumn() {custTable.Columns("CustomerID"), _ - custTable.Columns("CompanyName")}) -custDS.Tables("Customers").Constraints.Add(custUnique) -``` - -```csharp -DataTable custTable = custDS.Tables["Customers"]; + [!code-vb[DataWorks Data.AcceptRejectRule#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks Data.AcceptRejectRule/VB/source.vb#1)] + +## UniqueConstraint + + The `UniqueConstraint` object, which can be assigned either to a single column or to an array of columns in a **DataTable**, ensures that all data in the specified column or columns is unique per row. You can create a unique constraint for a column or array of columns by using the `UniqueConstraint` constructor. Pass the resulting `UniqueConstraint` object to the `Add` method of the table's `Constraints` property, which is a **ConstraintCollection**. You can also pass constructor arguments to several overloads of the `Add` method of a `ConstraintCollection` to create a **UniqueConstraint**. When creating a `UniqueConstraint` for a column or columns, you can optionally specify whether the column or columns are a primary key. + + You can also create a unique constraint for a column by setting the `Unique` property of the column to **true**. Alternatively, setting the `Unique` property of a single column to `false` removes any unique constraint that may exist. Defining a column or columns as the primary key for a table will automatically create a unique constraint for the specified column or columns. If you remove a column from the `PrimaryKey` property of a **DataTable**, the `UniqueConstraint` is removed. + + The following example creates a `UniqueConstraint` for two columns of a **DataTable**. + +```vb +Dim custTable As DataTable = custDS.Tables("Customers") +Dim custUnique As UniqueConstraint = _ + New UniqueConstraint(New DataColumn() {custTable.Columns("CustomerID"), _ + custTable.Columns("CompanyName")}) +custDS.Tables("Customers").Constraints.Add(custUnique) +``` + +```csharp +DataTable custTable = custDS.Tables["Customers"]; UniqueConstraint custUnique = new UniqueConstraint(new DataColumn[] {custTable.Columns["CustomerID"], - custTable.Columns["CompanyName"]}); -custDS.Tables["Customers"].Constraints.Add(custUnique); -``` - + custTable.Columns["CompanyName"]}); +custDS.Tables["Customers"].Constraints.Add(custUnique); +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/datatable-edits.md b/docs/framework/data/adonet/dataset-datatable-dataview/datatable-edits.md index 1c1b8b7dcf246..c22479c648322 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/datatable-edits.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/datatable-edits.md @@ -2,86 +2,86 @@ description: "Learn more about: DataTable Edits" title: "DataTable Edits" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: f08008a9-042e-4de9-94f3-4f0e502b1eb5 --- # DataTable Edits -When you make changes to column values in a , the changes are immediately placed in the current state of the row. The is then set to **Modified**, and the changes are accepted or rejected using the or methods of the **DataRow**. The **DataRow** also provides three methods that you can use to suspend the state of the row while you are editing it. These methods are , , and . - - When you modify column values in a **DataRow** directly, the **DataRow** manages the column values using the **Current**, **Default**, and **Original** row versions. In addition to these row versions, the **BeginEdit**, **EndEdit**, and **CancelEdit** methods use a fourth row version: **Proposed**. For more information about row versions, see [Row States and Row Versions](row-states-and-row-versions.md). - - The **Proposed** row version exists during an edit operation that begins by calling **BeginEdit** and that ends either by using **EndEdit** or **CancelEdit,** or by calling **AcceptChanges** or **RejectChanges**. - - During the edit operation, you can apply validation logic to individual columns by evaluating the **ProposedValue** in the **ColumnChanged** event of the **DataTable**. The **ColumnChanged** event holds **DataColumnChangeEventArgs** that keep a reference to the column that is changing and to the **ProposedValue**. After you evaluate the proposed value, you can either modify it or cancel the edit. When the edit is ended, the row moves out of the **Proposed** state. - - You can confirm edits by calling **EndEdit**, or you can cancel them by calling **CancelEdit**. Note that while **EndEdit** does confirm your edits, the **DataSet** does not actually accept the changes until **AcceptChanges** is called. Note also that if you call **AcceptChanges** before you have ended the edit with **EndEdit** or **CancelEdit**, the edit is ended and the **Proposed** row values are accepted for both the **Current** and **Original** row versions. In the same manner, calling **RejectChanges** ends the edit and discards the **Current** and **Proposed** row versions. Calling **EndEdit** or **CancelEdit** after calling **AcceptChanges** or **RejectChanges** has no effect because the edit has already ended. - - The following example demonstrates how to use **BeginEdit** with **EndEdit** and **CancelEdit**. The example also checks the **ProposedValue** in the **ColumnChanged** event and decides whether to cancel the edit. - -```vb -Dim workTable As DataTable = New DataTable -workTable.Columns.Add("LastName", Type.GetType("System.String")) - -AddHandler workTable.ColumnChanged, _ - New DataColumnChangeEventHandler(AddressOf OnColumnChanged) - -Dim workRow As DataRow = workTable.NewRow() -workRow(0) = "Smith" -workTable.Rows.Add(workRow) - -workRow.BeginEdit() -' Causes the ColumnChanged event to write a message and cancel the edit. +When you make changes to column values in a , the changes are immediately placed in the current state of the row. The is then set to **Modified**, and the changes are accepted or rejected using the or methods of the **DataRow**. The `DataRow` also provides three methods that you can use to suspend the state of the row while you are editing it. These methods are , , and . + + When you modify column values in a `DataRow` directly, the `DataRow` manages the column values using the **Current**, **Default**, and `Original` row versions. In addition to these row versions, the **BeginEdit**, **EndEdit**, and `CancelEdit` methods use a fourth row version: **Proposed**. For more information about row versions, see [Row States and Row Versions](row-states-and-row-versions.md). + + The `Proposed` row version exists during an edit operation that begins by calling `BeginEdit` and that ends either by using `EndEdit` or **CancelEdit,** or by calling `AcceptChanges` or **RejectChanges**. + + During the edit operation, you can apply validation logic to individual columns by evaluating the `ProposedValue` in the `ColumnChanged` event of the **DataTable**. The `ColumnChanged` event holds `DataColumnChangeEventArgs` that keep a reference to the column that is changing and to the **ProposedValue**. After you evaluate the proposed value, you can either modify it or cancel the edit. When the edit is ended, the row moves out of the `Proposed` state. + + You can confirm edits by calling **EndEdit**, or you can cancel them by calling **CancelEdit**. Note that while `EndEdit` does confirm your edits, the `DataSet` does not actually accept the changes until `AcceptChanges` is called. Note also that if you call `AcceptChanges` before you have ended the edit with `EndEdit` or **CancelEdit**, the edit is ended and the `Proposed` row values are accepted for both the `Current` and `Original` row versions. In the same manner, calling `RejectChanges` ends the edit and discards the `Current` and `Proposed` row versions. Calling `EndEdit` or `CancelEdit` after calling `AcceptChanges` or `RejectChanges` has no effect because the edit has already ended. + + The following example demonstrates how to use `BeginEdit` with `EndEdit` and **CancelEdit**. The example also checks the `ProposedValue` in the `ColumnChanged` event and decides whether to cancel the edit. + +```vb +Dim workTable As DataTable = New DataTable +workTable.Columns.Add("LastName", Type.GetType("System.String")) + +AddHandler workTable.ColumnChanged, _ + New DataColumnChangeEventHandler(AddressOf OnColumnChanged) + +Dim workRow As DataRow = workTable.NewRow() +workRow(0) = "Smith" +workTable.Rows.Add(workRow) + +workRow.BeginEdit() +' Causes the ColumnChanged event to write a message and cancel the edit. workRow(0) = "" -workRow.EndEdit() - -' Displays "Smith, New". -Console.WriteLine("{0}, {1}", workRow(0), workRow.RowState) - -Private Shared Sub OnColumnChanged( _ - sender As Object, args As DataColumnChangeEventArgs) - If args.Column.ColumnName = "LastName" Then - If args.ProposedValue.ToString() = "" Then - Console.WriteLine("Last Name cannot be blank. Edit canceled.") - args.Row.CancelEdit() - End If - End If -End Sub -``` - -```csharp -DataTable workTable = new DataTable(); -workTable.Columns.Add("LastName", typeof(String)); - +workRow.EndEdit() + +' Displays "Smith, New". +Console.WriteLine("{0}, {1}", workRow(0), workRow.RowState) + +Private Shared Sub OnColumnChanged( _ + sender As Object, args As DataColumnChangeEventArgs) + If args.Column.ColumnName = "LastName" Then + If args.ProposedValue.ToString() = "" Then + Console.WriteLine("Last Name cannot be blank. Edit canceled.") + args.Row.CancelEdit() + End If + End If +End Sub +``` + +```csharp +DataTable workTable = new DataTable(); +workTable.Columns.Add("LastName", typeof(String)); + workTable.ColumnChanged += - new DataColumnChangeEventHandler(OnColumnChanged); - -DataRow workRow = workTable.NewRow(); -workRow[0] = "Smith"; -workTable.Rows.Add(workRow); - -workRow.BeginEdit(); -// Causes the ColumnChanged event to write a message and cancel the edit. + new DataColumnChangeEventHandler(OnColumnChanged); + +DataRow workRow = workTable.NewRow(); +workRow[0] = "Smith"; +workTable.Rows.Add(workRow); + +workRow.BeginEdit(); +// Causes the ColumnChanged event to write a message and cancel the edit. workRow[0] = ""; -workRow.EndEdit(); - -// Displays "Smith, New". +workRow.EndEdit(); + +// Displays "Smith, New". Console.WriteLine("{0}, {1}", workRow[0], workRow.RowState); - -protected static void OnColumnChanged( - Object sender, DataColumnChangeEventArgs args) -{ - if (args.Column.ColumnName == "LastName") - if (args.ProposedValue.ToString() == "") - { - Console.WriteLine("Last Name cannot be blank. Edit canceled."); - args.Row.CancelEdit(); - } -} -``` - + +protected static void OnColumnChanged( + Object sender, DataColumnChangeEventArgs args) +{ + if (args.Column.ColumnName == "LastName") + if (args.ProposedValue.ToString() == "") + { + Console.WriteLine("Last Name cannot be blank. Edit canceled."); + args.Row.CancelEdit(); + } +} +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/datatable-schema-definition.md b/docs/framework/data/adonet/dataset-datatable-dataview/datatable-schema-definition.md index 5e42b6e08a15e..222b3e164a0ac 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/datatable-schema-definition.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/datatable-schema-definition.md @@ -6,32 +6,32 @@ ms.assetid: efbcdda4-f5a9-421d-8be2-4c194c74552f --- # DataTable Schema Definition -The schema, or structure, of a table is represented by columns and constraints. You define the schema of a using objects as well as and objects. The columns in a table can map to columns in a data source, contain calculated values from expressions, automatically increment their values, or contain primary key values. - - References by name to columns, relations, and constraints in a table are case-sensitive. Two or more columns, relations, or constraints can therefore exist in a table that have the same name, but that differ in case. For example, you can have **Col1** and **col1**. In such as case, a reference to one of the columns by name must match the case of the column name exactly; otherwise an exception is thrown. For example, if the table **myTable** contains the columns **Col1** and **col1**, you would reference **Col1** by name as **myTable.Columns["Col1"]**, and **col1** as **myTable.Columns["col1"]**. Attempting to reference either of the columns as **myTable.Columns["COL1"]** would generate an exception. - - The case-sensitivity rule does not apply if only one column, relation, or constraint with a particular name exists. That is, if no other column, relation, or constraint object in the table matches the name of that particular column, relation, or constraint object, you may reference the object by name using any case, and no exception is thrown. For example, if the table has only **Col1**, you can reference it using **my.Columns["COL1"]**. - +The schema, or structure, of a table is represented by columns and constraints. You define the schema of a using objects as well as and objects. The columns in a table can map to columns in a data source, contain calculated values from expressions, automatically increment their values, or contain primary key values. + + References by name to columns, relations, and constraints in a table are case-sensitive. Two or more columns, relations, or constraints can therefore exist in a table that have the same name, but that differ in case. For example, you can have **Col1** and **col1**. In such as case, a reference to one of the columns by name must match the case of the column name exactly; otherwise an exception is thrown. For example, if the table `myTable` contains the columns **Col1** and **col1**, you would reference **Col1** by name as **myTable.Columns["Col1"]**, and **col1** as **myTable.Columns["col1"]**. Attempting to reference either of the columns as **myTable.Columns["COL1"]** would generate an exception. + + The case-sensitivity rule does not apply if only one column, relation, or constraint with a particular name exists. That is, if no other column, relation, or constraint object in the table matches the name of that particular column, relation, or constraint object, you may reference the object by name using any case, and no exception is thrown. For example, if the table has only **Col1**, you can reference it using **my.Columns["COL1"]**. + > [!NOTE] -> The property of the **DataTable** does not affect this behavior. The **CaseSensitive** property applies to the data in a table and affects sorting, searching, filtering, enforcing constraints, and so on, but not to references to the columns, relations, and constraints. - -## In This Section - - [Adding Columns to a DataTable](adding-columns-to-a-datatable.md) - Describes how to define the columns of a table using **DataColumn** objects. - - [Creating Expression Columns](creating-expression-columns.md) - Explains how the **Expression** property of a column can be used to calculate values based on the values from other columns in the row. - - [Creating AutoIncrement Columns](creating-autoincrement-columns.md) - Describes how a column can be set to automatically increment numerical values to ensure a unique column value per row. - - [Defining Primary Keys](defining-primary-keys.md) - Describes how to specify the primary key of a table from one or more **DataColumn** objects. - - [DataTable Constraints](datatable-constraints.md) - Describes how to define foreign key and unique constraints for columns in a table. - +> The property of the `DataTable` does not affect this behavior. The `CaseSensitive` property applies to the data in a table and affects sorting, searching, filtering, enforcing constraints, and so on, but not to references to the columns, relations, and constraints. + +## In This Section + + [Adding Columns to a DataTable](adding-columns-to-a-datatable.md) + Describes how to define the columns of a table using `DataColumn` objects. + + [Creating Expression Columns](creating-expression-columns.md) + Explains how the `Expression` property of a column can be used to calculate values based on the values from other columns in the row. + + [Creating AutoIncrement Columns](creating-autoincrement-columns.md) + Describes how a column can be set to automatically increment numerical values to ensure a unique column value per row. + + [Defining Primary Keys](defining-primary-keys.md) + Describes how to specify the primary key of a table from one or more `DataColumn` objects. + + [DataTable Constraints](datatable-constraints.md) + Describes how to define foreign key and unique constraints for columns in a table. + ## See also - [DataTables](datatables.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/datatablereaders.md b/docs/framework/data/adonet/dataset-datatable-dataview/datatablereaders.md index 6f9c7e9d17972..97860d1d20345 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/datatablereaders.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/datatablereaders.md @@ -6,20 +6,20 @@ ms.assetid: 97546ae2-0e42-4d26-961d-e0b244d81ded --- # DataTableReaders -The presents the contents of a or a in the form of one or more read-only, forward-only result sets. - - When you create a **DataTableReader** from a **DataTable**, the resulting **DataTableReader** object contains one result set with the same data as the **DataTable** from which it was created, except for any rows that have been marked as deleted. The columns appear in the same order as in the original **DataTable**. - - A **DataTableReader** may contain multiple result sets if it was created by calling . The results are in the same order as the **DataTables** in the **DataSet** object's collection. - -## In This Section - - [Creating a DataReader](creating-a-datareader.md) - Discusses how to create a **DataTableReader** object. - - [Navigating DataTables](navigating-datatables.md) - Describes the use of the **Read** method to move through the contents of a **DataTableReader**. - +The presents the contents of a or a in the form of one or more read-only, forward-only result sets. + + When you create a `DataTableReader` from a **DataTable**, the resulting `DataTableReader` object contains one result set with the same data as the `DataTable` from which it was created, except for any rows that have been marked as deleted. The columns appear in the same order as in the original **DataTable**. + + A `DataTableReader` may contain multiple result sets if it was created by calling . The results are in the same order as the `DataTables` in the `DataSet` object's collection. + +## In This Section + + [Creating a DataReader](creating-a-datareader.md) + Discusses how to create a `DataTableReader` object. + + [Navigating DataTables](navigating-datatables.md) + Describes the use of the `Read` method to move through the contents of a **DataTableReader**. + ## See also - [Retrieving and Modifying Data in ADO.NET](../retrieving-and-modifying-data.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/datatables.md b/docs/framework/data/adonet/dataset-datatable-dataview/datatables.md index 888d0ab29de35..94bfbdbd9f74a 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/datatables.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/datatables.md @@ -6,26 +6,26 @@ ms.assetid: 52ff0e32-3e5a-41de-9a3b-7b04ea52b83e --- # DataTables -A is made up of a collection of tables, relationships, and constraints. In ADO.NET, objects are used to represent the tables in a **DataSet**. A **DataTable** represents one table of in-memory relational data; the data is local to the .NET-based application in which it resides, but can be populated from a data source such as Microsoft SQL Server using a **DataAdapter** For more information, see [Populating a DataSet from a DataAdapter](../populating-a-dataset-from-a-dataadapter.md). +A is made up of a collection of tables, relationships, and constraints. In ADO.NET, objects are used to represent the tables in a **DataSet**. A `DataTable` represents one table of in-memory relational data; the data is local to the .NET-based application in which it resides, but can be populated from a data source such as Microsoft SQL Server using a `DataAdapter` For more information, see [Populating a DataSet from a DataAdapter](../populating-a-dataset-from-a-dataadapter.md). - The **DataTable** class is a member of the **System.Data** namespace within the .NET Framework class library. You can create and use a **DataTable** independently or as a member of a **DataSet**, and **DataTable** objects can also be used in conjunction with other .NET Framework objects, including the . You access the collection of tables in a **DataSet** through the **Tables** property of the **DataSet** object. + The `DataTable` class is a member of the **System.Data** namespace within the .NET Framework class library. You can create and use a `DataTable` independently or as a member of a **DataSet**, and `DataTable` objects can also be used in conjunction with other .NET Framework objects, including the . You access the collection of tables in a `DataSet` through the `Tables` property of the `DataSet` object. - The schema, or structure of a table is represented by columns and constraints. You define the schema of a **DataTable** using objects as well as and objects. The columns in a table can map to columns in a data source, contain calculated values from expressions, automatically increment their values, or contain primary key values. + The schema, or structure of a table is represented by columns and constraints. You define the schema of a `DataTable` using objects as well as and objects. The columns in a table can map to columns in a data source, contain calculated values from expressions, automatically increment their values, or contain primary key values. - In addition to a schema, a **DataTable** must also have rows to contain and order data. The class represents the actual data contained in a table. You use the **DataRow** and its properties and methods to retrieve, evaluate, and manipulate the data in a table. As you access and change the data within a row, the **DataRow** object maintains both its current and original state. + In addition to a schema, a `DataTable` must also have rows to contain and order data. The class represents the actual data contained in a table. You use the `DataRow` and its properties and methods to retrieve, evaluate, and manipulate the data in a table. As you access and change the data within a row, the `DataRow` object maintains both its current and original state. - You can create parent-child relationships between tables using one or more related columns in the tables. You create a relationship between **DataTable** objects using a . **DataRelation** objects can then be used to return the related child or parent rows of a particular row. For more information, see [Adding DataRelations](adding-datarelations.md). + You can create parent-child relationships between tables using one or more related columns in the tables. You create a relationship between `DataTable` objects using a . `DataRelation` objects can then be used to return the related child or parent rows of a particular row. For more information, see [Adding DataRelations](adding-datarelations.md). ## In This Section [Creating a DataTable](creating-a-datatable.md) - Explains how to create a **DataTable** and add it to a **DataSet**. + Explains how to create a `DataTable` and add it to a **DataSet**. [DataTable Schema Definition](datatable-schema-definition.md) - Provides information about creating and using **DataColumn** objects and constraints. + Provides information about creating and using `DataColumn` objects and constraints. [Manipulating Data in a DataTable](manipulating-data-in-a-datatable.md) - Explains how to add, modify, and delete data in a table. Explains how to use **DataTable** events to examine changes to data in the table. + Explains how to add, modify, and delete data in a table. Explains how to use `DataTable` events to examine changes to data in the table. [Handling DataTable Events](handling-datatable-events.md) Provides information about the events available for use with a **DataTable**, including events when column values are modified and rows are added or deleted. @@ -39,16 +39,16 @@ A is made up of a collection of tables, relationships Provides information about the ADO.NET including how to create relationships between tables. \ - Provides reference information about the **Constraint** object. + Provides reference information about the `Constraint` object. \ - Provides reference information about the **DataColumn** object. + Provides reference information about the `DataColumn` object. \ - Provides reference information about the **DataSet** object. + Provides reference information about the `DataSet` object. \ - Provides reference information about the **DataTable** object. + Provides reference information about the `DataTable` object. [Core .NET libraries overview](../../../../standard/class-library-overview.md)\ Provides an overview of the .NET class library. diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/dataviews.md b/docs/framework/data/adonet/dataset-datatable-dataview/dataviews.md index 4113c352f4759..3d9abcaa850d0 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/dataviews.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/dataviews.md @@ -8,19 +8,19 @@ ms.assetid: 0fe5dfa2-c1cd-435f-90b6-b4dd2e3ef34b A enables you to create different views of the data stored in a , a capability that is often used in data-binding applications. Using a **DataView**, you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression. - A **DataView** provides a dynamic view of data in the underlying **DataTable**: the content, ordering, and membership reflect changes as they occur. This behavior differs from the **Select** method of the **DataTable**, which returns a array from a table based on a particular filter and/or sort order: this content reflects changes to the underlying table, but its membership and ordering remain static. The dynamic capabilities of the **DataView** make it ideal for data-binding applications. + A `DataView` provides a dynamic view of data in the underlying **DataTable**: the content, ordering, and membership reflect changes as they occur. This behavior differs from the `Select` method of the **DataTable**, which returns a array from a table based on a particular filter and/or sort order: this content reflects changes to the underlying table, but its membership and ordering remain static. The dynamic capabilities of the `DataView` make it ideal for data-binding applications. - A **DataView** provides you with a dynamic view of a single set of data, much like a database view, to which you can apply different sorting and filtering criteria. Unlike a database view, however, a **DataView** cannot be treated as a table and cannot provide a view of joined tables. You also cannot exclude columns that exist in the source table or append columns that do not exist in the source table, such as computational columns. + A `DataView` provides you with a dynamic view of a single set of data, much like a database view, to which you can apply different sorting and filtering criteria. Unlike a database view, however, a `DataView` cannot be treated as a table and cannot provide a view of joined tables. You also cannot exclude columns that exist in the source table or append columns that do not exist in the source table, such as computational columns. - You can use a to manage view settings for all the tables in a **DataSet**. The **DataViewManager** provides you with a convenient way to manage default view settings for each table. When binding a control to more than one table of a **DataSet**, binding to a **DataViewManager** is the ideal choice. + You can use a to manage view settings for all the tables in a **DataSet**. The `DataViewManager` provides you with a convenient way to manage default view settings for each table. When binding a control to more than one table of a **DataSet**, binding to a `DataViewManager` is the ideal choice. ## In This Section [Creating a DataView](creating-a-dataview.md) - Describes how to create a **DataView** for a **DataTable**. + Describes how to create a `DataView` for a **DataTable**. [Sorting and Filtering Data](sorting-and-filtering-data.md) - Describes how to set the properties of a **DataView** to return subsets of data rows meeting specific filter criteria, or to return data in a particular sort order. + Describes how to set the properties of a `DataView` to return subsets of data rows meeting specific filter criteria, or to return data in a particular sort order. [DataRows and DataRowViews](datarows-and-datarowviews.md) Describes how to access the data exposed by the **DataView**. @@ -32,13 +32,13 @@ A enables you to create different views of the data Describes how to create views of data from a parent-child relationship using a **DataView**. [Modifying DataViews](modifying-dataviews.md) - Describes how to modify the data in the underlying **DataTable** via the **DataView**, including enabling or disabling updates. + Describes how to modify the data in the underlying `DataTable` via the **DataView**, including enabling or disabling updates. [Handling DataView Events](handling-dataview-events.md) - Describes how to use the **ListChanged** event to receive notification when the contents or order of a **DataView** is being updated. + Describes how to use the `ListChanged` event to receive notification when the contents or order of a `DataView` is being updated. [Managing DataViews](managing-dataviews.md) - Describes how to use a **DataViewManager** to manage **DataView** settings for each table in a **DataSet**. + Describes how to use a `DataViewManager` to manage `DataView` settings for each table in a **DataSet**. ## Related Sections @@ -49,10 +49,10 @@ A enables you to create different views of the data Provides detailed information about working with Windows Forms and console applications. [DataSets, DataTables, and DataViews](index.md) - Describes the **DataSet** object and how you can use it to manage application data. + Describes the `DataSet` object and how you can use it to manage application data. [DataTables](datatables.md) - Describes the **DataTable** object and how you can use it to manage application data by itself or as part of a **DataSet**. + Describes the `DataTable` object and how you can use it to manage application data by itself or as part of a **DataSet**. [ADO.NET](../index.md) Describes the ADO.NET architecture and components, and how to use ADO.NET to access existing data sources and manage application data. diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/defining-primary-keys.md b/docs/framework/data/adonet/dataset-datatable-dataview/defining-primary-keys.md index ddea5f128eee0..8e3c36fb38452 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/defining-primary-keys.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/defining-primary-keys.md @@ -2,65 +2,65 @@ description: "Learn more about: Defining Primary Keys" title: "Defining Primary Keys" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 2ea85959-e763-4669-8bd9-46a9dab894bd --- # Defining Primary Keys -A database table commonly has a column or group of columns that uniquely identifies each row in the table. This identifying column or group of columns is called the primary key. - - When you identify a single as the for a , the table automatically sets the property of the column to **false** and the property to **true**. For multiple-column primary keys, only the **AllowDBNull** property is automatically set to **false**. - - The **PrimaryKey** property of a receives as its value an array of one or more **DataColumn** objects, as shown in the following examples. The first example defines a single column as the primary key. - -```vb -workTable.PrimaryKey = New DataColumn() {workTable.Columns("CustID")} - -' Or - -Dim columns(1) As DataColumn -columns(0) = workTable.Columns("CustID") -workTable.PrimaryKey = columns -``` - -```csharp -workTable.PrimaryKey = new DataColumn[] {workTable.Columns["CustID"]}; - -// Or - -DataColumn[] columns = new DataColumn[1]; -columns[0] = workTable.Columns["CustID"]; -workTable.PrimaryKey = columns; -``` - - The following example defines two columns as a primary key. - -```vb -workTable.PrimaryKey = New DataColumn() {workTable.Columns("CustLName"), _ - workTable.Columns("CustFName")} - -' Or - -Dim keyColumn(2) As DataColumn -keyColumn(0) = workTable.Columns("CustLName") -keyColumn(1) = workTable.Columns("CustFName") -workTable.PrimaryKey = keyColumn -``` - -```csharp +A database table commonly has a column or group of columns that uniquely identifies each row in the table. This identifying column or group of columns is called the primary key. + + When you identify a single as the for a , the table automatically sets the property of the column to `false` and the property to **true**. For multiple-column primary keys, only the `AllowDBNull` property is automatically set to **false**. + + The `PrimaryKey` property of a receives as its value an array of one or more `DataColumn` objects, as shown in the following examples. The first example defines a single column as the primary key. + +```vb +workTable.PrimaryKey = New DataColumn() {workTable.Columns("CustID")} + +' Or + +Dim columns(1) As DataColumn +columns(0) = workTable.Columns("CustID") +workTable.PrimaryKey = columns +``` + +```csharp +workTable.PrimaryKey = new DataColumn[] {workTable.Columns["CustID"]}; + +// Or + +DataColumn[] columns = new DataColumn[1]; +columns[0] = workTable.Columns["CustID"]; +workTable.PrimaryKey = columns; +``` + + The following example defines two columns as a primary key. + +```vb +workTable.PrimaryKey = New DataColumn() {workTable.Columns("CustLName"), _ + workTable.Columns("CustFName")} + +' Or + +Dim keyColumn(2) As DataColumn +keyColumn(0) = workTable.Columns("CustLName") +keyColumn(1) = workTable.Columns("CustFName") +workTable.PrimaryKey = keyColumn +``` + +```csharp workTable.PrimaryKey = new DataColumn[] {workTable.Columns["CustLName"], - workTable.Columns["CustFName"]}; - -// Or - -DataColumn[] keyColumn = new DataColumn[2]; -keyColumn[0] = workTable.Columns["CustLName"]; -keyColumn[1] = workTable.Columns["CustFName"]; -workTable.PrimaryKey = keyColumn; -``` - + workTable.Columns["CustFName"]}; + +// Or + +DataColumn[] keyColumn = new DataColumn[2]; +keyColumn[0] = workTable.Columns["CustLName"]; +keyColumn[1] = workTable.Columns["CustFName"]; +workTable.PrimaryKey = keyColumn; +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/deriving-dataset-relational-structure-from-xml-schema-xsd.md b/docs/framework/data/adonet/dataset-datatable-dataview/deriving-dataset-relational-structure-from-xml-schema-xsd.md index 904f42491c157..d6831afe4c0ad 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/deriving-dataset-relational-structure-from-xml-schema-xsd.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/deriving-dataset-relational-structure-from-xml-schema-xsd.md @@ -6,94 +6,94 @@ ms.assetid: 8f6cd04d-6197-4bc4-9096-8c51c7e4acae --- # Deriving DataSet Relational Structure from XML Schema (XSD) -This section provides an overview of how the relational schema of a `DataSet` is built from an XML Schema definition language (XSD) schema document. In general, for each `complexType` child element of a schema element, a table is generated in the `DataSet`. The table structure is determined by the definition of the complex type. Tables are created in the `DataSet` for top-level elements in the schema. However, a table is only created for a top-level `complexType` element when the `complexType` element is nested inside another `complexType` element, in which case the nested `complexType` element is mapped to a `DataTable` within the `DataSet`. - - For more information about the XSD, see the World Wide Web Consortium (W3C) [XML Schema Part 0: Primer Recommendation](https://www.w3.org/TR/xmlschema-0/), the [XML Schema Part 1: Structures Recommendation](https://www.w3.org/TR/xmlschema-1/), and the [XML Schema Part 2: Datatypes Recommendation](https://www.w3.org/TR/xmlschema-2/). - - The following example demonstrates an XML Schema where `customers` is the child element of the `MyDataSet` element, which is a **DataSet** element. - -```xml +This section provides an overview of how the relational schema of a `DataSet` is built from an XML Schema definition language (XSD) schema document. In general, for each `complexType` child element of a schema element, a table is generated in the `DataSet`. The table structure is determined by the definition of the complex type. Tables are created in the `DataSet` for top-level elements in the schema. However, a table is only created for a top-level `complexType` element when the `complexType` element is nested inside another `complexType` element, in which case the nested `complexType` element is mapped to a `DataTable` within the `DataSet`. + + For more information about the XSD, see the World Wide Web Consortium (W3C) [XML Schema Part 0: Primer Recommendation](https://www.w3.org/TR/xmlschema-0/), the [XML Schema Part 1: Structures Recommendation](https://www.w3.org/TR/xmlschema-1/), and the [XML Schema Part 2: Datatypes Recommendation](https://www.w3.org/TR/xmlschema-2/). + + The following example demonstrates an XML Schema where `customers` is the child element of the `MyDataSet` element, which is a `DataSet` element. + +```xml - - - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + + + - - + + + minOccurs="0" /> - - - - - - - - -``` - - In the preceding example, the element `customers` is a complex type element. Therefore, the complex type definition is parsed, and the mapping process creates the following table. - -```text -Customers (CustomerID, CompanyName, Phone) -``` - - The data type of each column in the table is derived from the XML Schema type of the corresponding element or attribute specified. - + minOccurs="0" /> + + + + + + + + +``` + + In the preceding example, the element `customers` is a complex type element. Therefore, the complex type definition is parsed, and the mapping process creates the following table. + +```text +Customers (CustomerID, CompanyName, Phone) +``` + + The data type of each column in the table is derived from the XML Schema type of the corresponding element or attribute specified. + > [!NOTE] -> If the element `customers` is of a simple XML Schema data type such as **integer**, no table is generated. Tables are only created for the top-level elements that are complex types. - - In the following XML Schema, the **Schema** element has two element children, `InStateCustomers` and `OutOfStateCustomers`. - -```xml +> If the element `customers` is of a simple XML Schema data type such as **integer**, no table is generated. Tables are only created for the top-level elements that are complex types. + + In the following XML Schema, the `Schema` element has two element children, `InStateCustomers` and `OutOfStateCustomers`. + +```xml - - - - - - - - - - - - - - -``` - - Both the `InStateCustomers` and the `OutOfStateCustomers` child elements are complex type elements (`customerType`). Therefore, the mapping process generates the following two identical tables in the `DataSet`. - -```text -InStateCustomers (CustomerID, CompanyName, Phone) -OutOfStateCustomers (CustomerID, CompanyName, Phone) -``` - -## In This Section - - [Mapping XML Schema (XSD) Constraints to DataSet Constraints](mapping-xml-schema-xsd-constraints-to-dataset-constraints.md) - Describes the XML Schema elements used to create unique and foreign key constraints in a `DataSet`. - - [Generating DataSet Relations from XML Schema (XSD)](generating-dataset-relations-from-xml-schema-xsd.md) - Describes the XML Schema elements used to create relations between table columns in a `DataSet`. - - [XML Schema Constraints and Relationships](xml-schema-constraints-and-relationships.md) - Describes how relations are created implicitly when using XML Schema elements to create constraints in a `DataSet`. - -## Related Sections - - [Using XML in a DataSet](using-xml-in-a-dataset.md) - Describes how to load and persist the relational structure and data in a `DataSet` as XML data. - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + + + + + + + + + + + + + + +``` + + Both the `InStateCustomers` and the `OutOfStateCustomers` child elements are complex type elements (`customerType`). Therefore, the mapping process generates the following two identical tables in the `DataSet`. + +```text +InStateCustomers (CustomerID, CompanyName, Phone) +OutOfStateCustomers (CustomerID, CompanyName, Phone) +``` + +## In This Section + + [Mapping XML Schema (XSD) Constraints to DataSet Constraints](mapping-xml-schema-xsd-constraints-to-dataset-constraints.md) + Describes the XML Schema elements used to create unique and foreign key constraints in a `DataSet`. + + [Generating DataSet Relations from XML Schema (XSD)](generating-dataset-relations-from-xml-schema-xsd.md) + Describes the XML Schema elements used to create relations between table columns in a `DataSet`. + + [XML Schema Constraints and Relationships](xml-schema-constraints-and-relationships.md) + Describes how relations are created implicitly when using XML Schema elements to create constraints in a `DataSet`. + +## Related Sections + + [Using XML in a DataSet](using-xml-in-a-dataset.md) + Describes how to load and persist the relational structure and data in a `DataSet` as XML data. + ## See also - [ADO.NET Overview](../ado-net-overview.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/diffgrams.md b/docs/framework/data/adonet/dataset-datatable-dataview/diffgrams.md index 09a85b4a10987..95f438f5685f8 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/diffgrams.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/diffgrams.md @@ -6,130 +6,130 @@ ms.assetid: 037f3991-7bbc-424b-b52e-8b03585d3e34 --- # DiffGrams -A DiffGram is an XML format that identifies current and original versions of data elements. The uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the , including column values from both the **Original** and **Current** row versions, row error information, and row order. - - When sending and retrieving a from an XML Web service, the DiffGram format is implicitly used. Additionally, when loading the contents of a from XML using the **ReadXml** method, or when writing the contents of a in XML using the **WriteXml** method, you can specify that the contents be read or written as a DiffGram. For more information, see [Loading a DataSet from XML](loading-a-dataset-from-xml.md) and [Writing DataSet Contents as XML Data](writing-dataset-contents-as-xml-data.md). - - While the DiffGram format is primarily used by the .NET Framework as a serialization format for the contents of a , you can also use DiffGrams to modify data in tables in a Microsoft SQL Server database. - - A Diffgram is generated by writing the contents of all tables to a **\** element. - -### To generate a Diffgram - -1. Generate a list of Root tables (that is, tables without any parent). - -2. For each table and its descendants in the list, write out the current version of all rows in the first Diffgram section. - -3. For each table in the , write out the original version of all rows, if any, in the **\** section of the Diffgram. - -4. For rows that have errors, write the error content in the **\** section of the Diffgram. - - A Diffgram is processed in order from beginning of the XML file to the end. - -### To process a Diffgram - -1. Process the first section of the Diffgram that contains the current version of the rows. - -2. Process the second or the **\** section that contains the original row version of modified and deleted rows. - +A DiffGram is an XML format that identifies current and original versions of data elements. The uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the , including column values from both the `Original` and `Current` row versions, row error information, and row order. + + When sending and retrieving a from an XML Web service, the DiffGram format is implicitly used. Additionally, when loading the contents of a from XML using the `ReadXml` method, or when writing the contents of a in XML using the `WriteXml` method, you can specify that the contents be read or written as a DiffGram. For more information, see [Loading a DataSet from XML](loading-a-dataset-from-xml.md) and [Writing DataSet Contents as XML Data](writing-dataset-contents-as-xml-data.md). + + While the DiffGram format is primarily used by the .NET Framework as a serialization format for the contents of a , you can also use DiffGrams to modify data in tables in a Microsoft SQL Server database. + + A Diffgram is generated by writing the contents of all tables to a `` element. + +### To generate a Diffgram + +1. Generate a list of Root tables (that is, tables without any parent). + +2. For each table and its descendants in the list, write out the current version of all rows in the first Diffgram section. + +3. For each table in the , write out the original version of all rows, if any, in the `` section of the Diffgram. + +4. For rows that have errors, write the error content in the `` section of the Diffgram. + + A Diffgram is processed in order from beginning of the XML file to the end. + +### To process a Diffgram + +1. Process the first section of the Diffgram that contains the current version of the rows. + +2. Process the second or the `` section that contains the original row version of modified and deleted rows. + > [!NOTE] - > If a row is marked deleted, the delete operation can delete the row's descendants as well, depending on the `Cascade` property of the current . - -3. Process the **\** section. Set the error information for the specified row and column for each item in this section. - + > If a row is marked deleted, the delete operation can delete the row's descendants as well, depending on the `Cascade` property of the current . + +3. Process the `` section. Set the error information for the specified row and column for each item in this section. + > [!NOTE] -> If you set the to Diffgram, the content of the target and the original may differ. - -## DiffGram Format - - The DiffGram format is divided into three sections: the current data, the original (or "before") data, and an errors section, as shown in the following example. - -```xml - +> If you set the to Diffgram, the content of the target and the original may differ. + +## DiffGram Format + + The DiffGram format is divided into three sections: the current data, the original (or "before") data, and an errors section, as shown in the following example. + +```xml + - - - - - - - - - - -``` - - The DiffGram format consists of the following blocks of data: - - **\<** ***DataInstance*** **>** - The name of this element, ***DataInstance***, is used for explanation purposes in this documentation. A ***DataInstance*** element represents a or a row of a . Instead of *DataInstance*, the element would contain the name of the or . This block of the DiffGram format contains the current data, whether it has been modified or not. An element, or row, that has been modified is identified with the **diffgr:hasChanges** annotation. - - **\** - This block of the DiffGram format contains the original version of a row. Elements in this block are matched to elements in the ***DataInstance*** block using the **diffgr:id** annotation. - - **\** - This block of the DiffGram format contains error information for a particular row in the ***DataInstance*** block. Elements in this block are matched to elements in the ***DataInstance*** block using the **diffgr:id** annotation. - -## DiffGram Annotations - - DiffGrams use several annotations to relate elements from the different DiffGram blocks that represent different row versions or error information in the . - - The following table describes the DiffGram annotations that are defined in the DiffGram namespace **urn:schemas-microsoft-com:xml-diffgram-v1**. - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" + xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" + xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + + + + + + + + + + +``` + + The DiffGram format consists of the following blocks of data: + + **\<** ***DataInstance*** **>** + The name of this element, ***DataInstance***, is used for explanation purposes in this documentation. A ***DataInstance*** element represents a or a row of a . Instead of *DataInstance*, the element would contain the name of the or . This block of the DiffGram format contains the current data, whether it has been modified or not. An element, or row, that has been modified is identified with the **diffgr:hasChanges** annotation. + + **\** + This block of the DiffGram format contains the original version of a row. Elements in this block are matched to elements in the ***DataInstance*** block using the **diffgr:id** annotation. + + **\** + This block of the DiffGram format contains error information for a particular row in the ***DataInstance*** block. Elements in this block are matched to elements in the ***DataInstance*** block using the **diffgr:id** annotation. + +## DiffGram Annotations + + DiffGrams use several annotations to relate elements from the different DiffGram blocks that represent different row versions or error information in the . + + The following table describes the DiffGram annotations that are defined in the DiffGram namespace **urn:schemas-microsoft-com:xml-diffgram-v1**. + | Annotation | Description | |----------------|-------------| -| **id** | Used to pair the elements in the **\** and **\** blocks to elements in the **\<** ***DataInstance*** **>** block. Values with the **diffgr:id** annotation are in the form `[TableName][RowIdentifier]`. For example: ``. | -| **parentId** | Identifies which element from the **\<** ***DataInstance*** **>** block is the parent element of the current element. Values with the **diffgr:parentId** annotation are in the form `[TableName][RowIdentifier]`. For example: ``. | -| **hasChanges** | Identifies a row in the **\<** ***DataInstance*** **>** block as modified. The **hasChanges** annotation can have one of the following two values:

**inserted**
Identifies an **Added** row.

**modified**
Identifies a **Modified** row that contains an **Original** row version in the **\** block. Note that **Deleted** rows will have an **Original** row version in the **\** block, but there will be no annotated element in the **\<** ***DataInstance*** **>** block. | -| **hasErrors** | Identifies a row in the **\<** ***DataInstance*** **>** block with a **RowError**. The error element is placed in the **\** block. | -| **Error** | Contains the text of the **RowError** for a particular element in the **\** block. | - - The includes additional annotations when reading or writing its contents as a DiffGram. The following table describes these additional annotations, which are defined in the namespace **urn:schemas-microsoft-com:xml-msdata**. - -|Annotation|Description| -|----------------|-----------------| -|**RowOrder**|Preserves the row order of the original data and identifies the index of a row in a particular .| -|**Hidden**|Identifies a column as having a **ColumnMapping** property set to **MappingType.Hidden**. The attribute is written in the format **msdata:hidden** *[ColumnName]*="*value*". For example: ``.

Note that hidden columns are only written as a DiffGram attribute if they contain data. Otherwise, they are ignored.| - -## Sample DiffGram - - An example of the DiffGram format is shown below. This example shows the result of an update to a row in a table before the changes have been committed. The row with a CustomerID of "ALFKI" has been modified, but not updated. As a result, there is a **Current** row with a **diffgr:id** of "Customers1" in the **\<** ***DataInstance*** **>** block, and an **Original** row with a **diffgr:id** of "Customers1" in the **\** block. The row with a CustomerID of "ANATR" includes a **RowError**, so it is annotated with `diffgr:hasErrors="true"` and there is a related element in the **\** block. - -```xml - - - - ALFKI - New Company - - - ANATR - Ana Trujillo Emparedados y Helados - - - ANTON - Antonio Moreno Taquera - - - AROUT - Around the Horn - - - - - ALFKI - Alfreds Futterkiste - - - - - - -``` - +| `id` | Used to pair the elements in the `` and `` blocks to elements in the **\<** ***DataInstance*** **>** block. Values with the **diffgr:id** annotation are in the form `[TableName][RowIdentifier]`. For example: ``. | +| `parentId` | Identifies which element from the **\<** ***DataInstance*** **>** block is the parent element of the current element. Values with the **diffgr:parentId** annotation are in the form `[TableName][RowIdentifier]`. For example: ``. | +| `hasChanges` | Identifies a row in the **\<** ***DataInstance*** **>** block as modified. The `hasChanges` annotation can have one of the following two values:

**inserted**
Identifies an `Added` row.

**modified**
Identifies a `Modified` row that contains an `Original` row version in the `` block. Note that `Deleted` rows will have an `Original` row version in the `` block, but there will be no annotated element in the **\<** ***DataInstance*** **>** block. | +| `hasErrors` | Identifies a row in the **\<** ***DataInstance*** **>** block with a **RowError**. The error element is placed in the `` block. | +| `Error` | Contains the text of the `RowError` for a particular element in the `` block. | + + The includes additional annotations when reading or writing its contents as a DiffGram. The following table describes these additional annotations, which are defined in the namespace **urn:schemas-microsoft-com:xml-msdata**. + +|Annotation|Description| +|----------------|-----------------| +|**RowOrder**|Preserves the row order of the original data and identifies the index of a row in a particular .| +|**Hidden**|Identifies a column as having a `ColumnMapping` property set to **MappingType.Hidden**. The attribute is written in the format **msdata:hidden** *[ColumnName]*="*value*". For example: ``.

Note that hidden columns are only written as a DiffGram attribute if they contain data. Otherwise, they are ignored.| + +## Sample DiffGram + + An example of the DiffGram format is shown below. This example shows the result of an update to a row in a table before the changes have been committed. The row with a CustomerID of "ALFKI" has been modified, but not updated. As a result, there is a `Current` row with a **diffgr:id** of "Customers1" in the **\<** ***DataInstance*** **>** block, and an `Original` row with a **diffgr:id** of "Customers1" in the `` block. The row with a CustomerID of "ANATR" includes a **RowError**, so it is annotated with `diffgr:hasErrors="true"` and there is a related element in the `` block. + +```xml + + + + ALFKI + New Company + + + ANATR + Ana Trujillo Emparedados y Helados + + + ANTON + Antonio Moreno Taquera + + + AROUT + Around the Horn + + + + + ALFKI + Alfreds Futterkiste + + + + + + +``` + ## See also - [Using XML in a DataSet](using-xml-in-a-dataset.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/finding-rows.md b/docs/framework/data/adonet/dataset-datatable-dataview/finding-rows.md index 211c00649dde4..3cf3cfcf9434b 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/finding-rows.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/finding-rows.md @@ -2,93 +2,93 @@ description: "Learn more about: Finding Rows" title: "Finding Rows" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 5da300e2-74c0-4d13-9202-fc20ed8212d8 --- # Finding Rows -You can search for rows according to their sort key values by using the and methods of the . The case sensitivity of search values in the **Find** and **FindRows** methods is determined by the **CaseSensitive** property of the underlying . Search values must match existing sort key values in their entirety in order to return a result. - - The **Find** method returns an integer with the index of the that matches the search criteria. If more than one row matches the search criteria, only the index of the first matching **DataRowView** is returned. If no matches are found, **Find** returns -1. - - To return search results that match multiple rows, use the **FindRows** method. **FindRows** works just like the **Find** method, except that it returns a **DataRowView** array that references all matching rows in the **DataView**. If no matches are found, the **DataRowView** array will be empty. - - To use the **Find** or **FindRows** methods you must specify a sort order either by setting **ApplyDefaultSort** to **true** or by using the **Sort** property. If no sort order is specified, an exception is thrown. - - The **Find** and **FindRows** methods take an array of values as input whose length matches the number of columns in the sort order. In the case of a sort on a single column, you can pass a single value. For sort orders containing multiple columns, you pass an array of objects. Note that for a sort on multiple columns, the values in the object array must match the order of the columns specified in the **Sort** property of the **DataView**. - - The following code example shows the **Find** method being called against a **DataView** with a single column sort order. - -```vb -Dim custView As DataView = _ - New DataView(custDS.Tables("Customers"), "", _ - "CompanyName", DataViewRowState.CurrentRows) - -Dim rowIndex As Integer = custView.Find("The Cracker Box") - -If rowIndex = -1 Then - Console.WriteLine("No match found.") -Else - Console.WriteLine("{0}, {1}", _ - custView(rowIndex)("CustomerID").ToString(), _ - custView(rowIndex)("CompanyName").ToString()) -End If -``` - -```csharp +You can search for rows according to their sort key values by using the and methods of the . The case sensitivity of search values in the `Find` and `FindRows` methods is determined by the `CaseSensitive` property of the underlying . Search values must match existing sort key values in their entirety in order to return a result. + + The `Find` method returns an integer with the index of the that matches the search criteria. If more than one row matches the search criteria, only the index of the first matching `DataRowView` is returned. If no matches are found, `Find` returns -1. + + To return search results that match multiple rows, use the `FindRows` method. `FindRows` works just like the `Find` method, except that it returns a `DataRowView` array that references all matching rows in the **DataView**. If no matches are found, the `DataRowView` array will be empty. + + To use the `Find` or `FindRows` methods you must specify a sort order either by setting `ApplyDefaultSort` to `true` or by using the `Sort` property. If no sort order is specified, an exception is thrown. + + The `Find` and `FindRows` methods take an array of values as input whose length matches the number of columns in the sort order. In the case of a sort on a single column, you can pass a single value. For sort orders containing multiple columns, you pass an array of objects. Note that for a sort on multiple columns, the values in the object array must match the order of the columns specified in the `Sort` property of the **DataView**. + + The following code example shows the `Find` method being called against a `DataView` with a single column sort order. + +```vb +Dim custView As DataView = _ + New DataView(custDS.Tables("Customers"), "", _ + "CompanyName", DataViewRowState.CurrentRows) + +Dim rowIndex As Integer = custView.Find("The Cracker Box") + +If rowIndex = -1 Then + Console.WriteLine("No match found.") +Else + Console.WriteLine("{0}, {1}", _ + custView(rowIndex)("CustomerID").ToString(), _ + custView(rowIndex)("CompanyName").ToString()) +End If +``` + +```csharp +DataView custView = new DataView(custDS.Tables["Customers"], "", + "CompanyName", DataViewRowState.CurrentRows); + +int rowIndex = custView.Find("The Cracker Box"); + +if (rowIndex == -1) + Console.WriteLine("No match found."); +else + Console.WriteLine("{0}, {1}", + custView[rowIndex]["CustomerID"].ToString(), + custView[rowIndex]["CompanyName"].ToString()); +``` + + If your `Sort` property specifies multiple columns, you must pass an object array with the search values for each column in the order specified by the `Sort` property, as in the following code example. + +```vb +Dim custView As DataView = _ + New DataView(custDS.Tables("Customers"), "", _ + "CompanyName, ContactName", _ + DataViewRowState.CurrentRows) + +Dim foundRows() As DataRowView = _ + custView.FindRows(New object() {"The Cracker Box", "Liu Wong"}) + +If foundRows.Length = 0 Then + Console.WriteLine("No match found.") +Else + Dim myDRV As DataRowView + For Each myDRV In foundRows + Console.WriteLine("{0}, {1}", _ + myDRV("CompanyName").ToString(), myDRV("ContactName").ToString()) + Next +End If +``` + +```csharp DataView custView = new DataView(custDS.Tables["Customers"], "", - "CompanyName", DataViewRowState.CurrentRows); - -int rowIndex = custView.Find("The Cracker Box"); - -if (rowIndex == -1) - Console.WriteLine("No match found."); -else - Console.WriteLine("{0}, {1}", - custView[rowIndex]["CustomerID"].ToString(), - custView[rowIndex]["CompanyName"].ToString()); -``` - - If your **Sort** property specifies multiple columns, you must pass an object array with the search values for each column in the order specified by the **Sort** property, as in the following code example. - -```vb -Dim custView As DataView = _ - New DataView(custDS.Tables("Customers"), "", _ - "CompanyName, ContactName", _ - DataViewRowState.CurrentRows) - -Dim foundRows() As DataRowView = _ - custView.FindRows(New object() {"The Cracker Box", "Liu Wong"}) - -If foundRows.Length = 0 Then - Console.WriteLine("No match found.") -Else - Dim myDRV As DataRowView - For Each myDRV In foundRows - Console.WriteLine("{0}, {1}", _ - myDRV("CompanyName").ToString(), myDRV("ContactName").ToString()) - Next -End If -``` - -```csharp -DataView custView = new DataView(custDS.Tables["Customers"], "", - "CompanyName, ContactName", - DataViewRowState.CurrentRows); - + "CompanyName, ContactName", + DataViewRowState.CurrentRows); + DataRowView[] foundRows = - custView.FindRows(new object[] {"The Cracker Box", "Liu Wong"}); - -if (foundRows.Length == 0) - Console.WriteLine("No match found."); -else - foreach (DataRowView myDRV in foundRows) + custView.FindRows(new object[] {"The Cracker Box", "Liu Wong"}); + +if (foundRows.Length == 0) + Console.WriteLine("No match found."); +else + foreach (DataRowView myDRV in foundRows) Console.WriteLine("{0}, {1}", myDRV["CompanyName"].ToString(), - myDRV["ContactName"].ToString()); -``` - + myDRV["ContactName"].ToString()); +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/generating-dataset-relations-from-xml-schema-xsd.md b/docs/framework/data/adonet/dataset-datatable-dataview/generating-dataset-relations-from-xml-schema-xsd.md index 1b2a51dfed181..90a674c6d9041 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/generating-dataset-relations-from-xml-schema-xsd.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/generating-dataset-relations-from-xml-schema-xsd.md @@ -6,97 +6,97 @@ ms.assetid: 1c9a1413-c0d2-4447-88ba-9a2b0cbc0aa8 --- # Generating DataSet Relations from XML Schema (XSD) -In a , you form an association between two or more columns by creating a parent-child relation. There are three ways to represent a **DataSet** relation within an XML Schema definition language (XSD) schema: - -- Specify nested complex types. - -- Use the **msdata:Relationship** annotation. - -- Specify an **xs:keyref** without the **msdata:ConstraintOnly** annotation. - -## Nested Complex Types - - Nested complex type definitions in a schema indicate the parent-child relationships of the elements. The following XML Schema fragment shows that **OrderDetail** is a child element of the **Order** element. - -```xml - - +In a , you form an association between two or more columns by creating a parent-child relation. There are three ways to represent a `DataSet` relation within an XML Schema definition language (XSD) schema: + +- Specify nested complex types. + +- Use the **msdata:Relationship** annotation. + +- Specify an **xs:keyref** without the **msdata:ConstraintOnly** annotation. + +## Nested Complex Types + + Nested complex type definitions in a schema indicate the parent-child relationships of the elements. The following XML Schema fragment shows that `OrderDetail` is a child element of the `Order` element. + +```xml + + - + - - - - -``` - - The XML Schema mapping process creates tables in the **DataSet** that correspond to the nested complex types in the schema. It also creates additional columns that are used as parent**-**child columns for the generated tables. Note that these parent**-**child columns specify relationships, which is not the same as specifying primary key/foreign key constraints. - -## msdata:Relationship Annotation - - The **msdata:Relationship** annotation allows you to explicitly specify parent-child relationships between elements in the schema that are not nested. The following example shows the structure of the **Relationship** element. - -```xml + + + + +``` + + The XML Schema mapping process creates tables in the `DataSet` that correspond to the nested complex types in the schema. It also creates additional columns that are used as parent**-**child columns for the generated tables. Note that these parent**-**child columns specify relationships, which is not the same as specifying primary key/foreign key constraints. + +## msdata:Relationship Annotation + + The **msdata:Relationship** annotation allows you to explicitly specify parent-child relationships between elements in the schema that are not nested. The following example shows the structure of the `Relationship` element. + +```xml -``` - - The attributes of the **msdata:Relationship** annotation identify the elements involved in the parent-child relationship, as well as the **parentkey** and **childkey** elements and attributes involved in the relationship. The mapping process uses this information to generate tables in the **DataSet** and to create the primary key/foreign key relationship between these tables. - - For example, the following schema fragment specifies **Order** and **OrderDetail** elements at the same level (not nested). The schema specifies an **msdata:Relationship** annotation, which specifies the parent-child relationship between these two elements. In this case, an explicit relationship must be specified using the **msdata:Relationship** annotation. - -```xml - - - - - - - - - - - - - - - - - - - +``` + + The attributes of the **msdata:Relationship** annotation identify the elements involved in the parent-child relationship, as well as the `parentkey` and `childkey` elements and attributes involved in the relationship. The mapping process uses this information to generate tables in the `DataSet` and to create the primary key/foreign key relationship between these tables. + + For example, the following schema fragment specifies `Order` and `OrderDetail` elements at the same level (not nested). The schema specifies an **msdata:Relationship** annotation, which specifies the parent-child relationship between these two elements. In this case, an explicit relationship must be specified using the **msdata:Relationship** annotation. + +```xml + + + + + + + + + + + + + + + + + + + - - -``` - - The mapping process uses the **Relationship** element to create a parent-child relationship between the **OrderNumber** column in the **Order** table and the **OrderNo** column in the **OrderDetail** table in the **DataSet**. The mapping process only specifies the relationship; it does not automatically specify any constraints on the values in these columns, as do the primary key/foreign key constraints in relational databases. - -### In This Section - - [Map Implicit Relations Between Nested Schema Elements](map-implicit-relations-between-nested-schema-elements.md) - Describes the constraints and relations that are implicitly created in a **DataSet** when nested elements are encountered in XML Schema. - - [Map Relations Specified for Nested Elements](map-relations-specified-for-nested-elements.md) - Describes how to explicitly set relations in a **DataSet** for nested elements in XML Schema. - - [Specify Relations Between Elements with No Nesting](specify-relations-between-elements-with-no-nesting.md) - Describes how to create relations in a **DataSet** between XML Schema elements that are not nested. - -### Related Sections - - [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md) - Describes the relational structure, or schema, of a **DataSet** that is created from XML Schema definition language (XSD) schema. - - [Mapping XML Schema (XSD) Constraints to DataSet Constraints](mapping-xml-schema-xsd-constraints-to-dataset-constraints.md) - Describes the XML Schema elements used to create unique and foreign key constraints in a **DataSet**. - + msdata:parentkey="OrderNumber" + msdata:childkey="OrderNo"/> + + +``` + + The mapping process uses the `Relationship` element to create a parent-child relationship between the `OrderNumber` column in the `Order` table and the `OrderNo` column in the `OrderDetail` table in the **DataSet**. The mapping process only specifies the relationship; it does not automatically specify any constraints on the values in these columns, as do the primary key/foreign key constraints in relational databases. + +### In This Section + + [Map Implicit Relations Between Nested Schema Elements](map-implicit-relations-between-nested-schema-elements.md) + Describes the constraints and relations that are implicitly created in a `DataSet` when nested elements are encountered in XML Schema. + + [Map Relations Specified for Nested Elements](map-relations-specified-for-nested-elements.md) + Describes how to explicitly set relations in a `DataSet` for nested elements in XML Schema. + + [Specify Relations Between Elements with No Nesting](specify-relations-between-elements-with-no-nesting.md) + Describes how to create relations in a `DataSet` between XML Schema elements that are not nested. + +### Related Sections + + [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md) + Describes the relational structure, or schema, of a `DataSet` that is created from XML Schema definition language (XSD) schema. + + [Mapping XML Schema (XSD) Constraints to DataSet Constraints](mapping-xml-schema-xsd-constraints-to-dataset-constraints.md) + Describes the XML Schema elements used to create unique and foreign key constraints in a **DataSet**. + ## See also - [ADO.NET Overview](../ado-net-overview.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/generating-strongly-typed-datasets.md b/docs/framework/data/adonet/dataset-datatable-dataview/generating-strongly-typed-datasets.md index fe4ed68d64548..b74182ba9db95 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/generating-strongly-typed-datasets.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/generating-strongly-typed-datasets.md @@ -2,94 +2,94 @@ description: "Learn more about: Generating Strongly Typed DataSets" title: "Generating Strongly Typed DataSets" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 54333cbf-bb43-4314-a7d4-6dc1dd1c44b3 --- # Generating Strongly Typed DataSets -Given an XML Schema that complies with the XML Schema definition language (XSD) standard, you can generate a strongly typed using the XSD.exe tool provided with the Windows Software Development Kit (SDK). - - (To create an xsd from database tables, see or [Working with Datasets in Visual Studio](/visualstudio/data-tools/dataset-tools-in-visual-studio)). - - The following code shows the syntax for generating a **DataSet** using this tool. - -```console -xsd.exe /d /l:CS XSDSchemaFileName.xsd /eld /n:XSDSchema.Namespace -``` - - In this syntax, the `/d` directive tells the tool to generate a **DataSet**, and the `/l:` tells the tool what language to use (for example, C# or Visual Basic .NET). The optional `/eld` directive specifies that you can use LINQ to DataSet to query against the generated **DataSet.** This option is used when the `/d` option is also specified. For more information, see [Querying Typed DataSets](../querying-typed-datasets.md). The optional `/n:` directive tells the tool to also generate a namespace for the **DataSet** called **XSDSchema.Namespace**. The output of the command is XSDSchemaFileName.cs, which can be compiled and used in an ADO.NET application. The generated code can be compiled as a library or a module. - - The following code shows the syntax for compiling the generated code as a library using the C# compiler (csc.exe). - -```console -csc.exe /t:library XSDSchemaFileName.cs /r:System.dll /r:System.Data.dll -``` - - The `/t:` directive tells the tool to compile to a library, and the `/r:` directives specify dependent libraries required to compile. The output of the command is XSDSchemaFileName.dll, which can be passed to the compiler when compiling an ADO.NET application with the `/r:` directive. - - The following code shows the syntax for accessing the namespace passed to XSD.exe in an ADO.NET application. - -```vb -Imports XSDSchema.Namespace -``` - -```csharp -using XSDSchema.Namespace; -``` - - The following code example uses a typed **DataSet** named **CustomerDataSet** to load a list of customers from the **Northwind** database. Once the data is loaded using the **Fill** method, the example loops through each customer in the **Customers** table using the typed **CustomersRow** (**DataRow**) object. This provides direct access to the **CustomerID** column, as opposed to through the **DataColumnCollection**. - -```vb -Dim customers As CustomerDataSet= New CustomerDataSet() -Dim adapter As SqlDataAdapter New SqlDataAdapter( _ - "SELECT * FROM dbo.Customers;", _ - "Data Source=(local);Integrated " & _ - "Security=SSPI;Initial Catalog=Northwind") - -adapter.Fill(customers, "Customers") - -Dim customerRow As CustomerDataSet.CustomersRow -For Each customerRow In customers.Customers - Console.WriteLine(customerRow.CustomerID) -Next -``` - -```csharp -CustomerDataSet customers = new CustomerDataSet(); -SqlDataAdapter adapter = new SqlDataAdapter( - "SELECT * FROM dbo.Customers;", - "Data Source=(local);Integrated " + - "Security=SSPI;Initial Catalog=Northwind"); - -adapter.Fill(customers, "Customers"); - -foreach(CustomerDataSet.CustomersRow customerRow in customers.Customers) - Console.WriteLine(customerRow.CustomerID); -``` - +Given an XML Schema that complies with the XML Schema definition language (XSD) standard, you can generate a strongly typed using the XSD.exe tool provided with the Windows Software Development Kit (SDK). + + (To create an xsd from database tables, see or [Working with Datasets in Visual Studio](/visualstudio/data-tools/dataset-tools-in-visual-studio)). + + The following code shows the syntax for generating a `DataSet` using this tool. + +```console +xsd.exe /d /l:CS XSDSchemaFileName.xsd /eld /n:XSDSchema.Namespace +``` + + In this syntax, the `/d` directive tells the tool to generate a **DataSet**, and the `/l:` tells the tool what language to use (for example, C# or Visual Basic .NET). The optional `/eld` directive specifies that you can use LINQ to DataSet to query against the generated **DataSet.** This option is used when the `/d` option is also specified. For more information, see [Querying Typed DataSets](../querying-typed-datasets.md). The optional `/n:` directive tells the tool to also generate a namespace for the `DataSet` called **XSDSchema.Namespace**. The output of the command is XSDSchemaFileName.cs, which can be compiled and used in an ADO.NET application. The generated code can be compiled as a library or a module. + + The following code shows the syntax for compiling the generated code as a library using the C# compiler (csc.exe). + +```console +csc.exe /t:library XSDSchemaFileName.cs /r:System.dll /r:System.Data.dll +``` + + The `/t:` directive tells the tool to compile to a library, and the `/r:` directives specify dependent libraries required to compile. The output of the command is XSDSchemaFileName.dll, which can be passed to the compiler when compiling an ADO.NET application with the `/r:` directive. + + The following code shows the syntax for accessing the namespace passed to XSD.exe in an ADO.NET application. + +```vb +Imports XSDSchema.Namespace +``` + +```csharp +using XSDSchema.Namespace; +``` + + The following code example uses a typed `DataSet` named `CustomerDataSet` to load a list of customers from the `Northwind` database. Once the data is loaded using the `Fill` method, the example loops through each customer in the `Customers` table using the typed `CustomersRow` (**DataRow**) object. This provides direct access to the `CustomerID` column, as opposed to through the **DataColumnCollection**. + +```vb +Dim customers As CustomerDataSet= New CustomerDataSet() +Dim adapter As SqlDataAdapter New SqlDataAdapter( _ + "SELECT * FROM dbo.Customers;", _ + "Data Source=(local);Integrated " & _ + "Security=SSPI;Initial Catalog=Northwind") + +adapter.Fill(customers, "Customers") + +Dim customerRow As CustomerDataSet.CustomersRow +For Each customerRow In customers.Customers + Console.WriteLine(customerRow.CustomerID) +Next +``` + +```csharp +CustomerDataSet customers = new CustomerDataSet(); +SqlDataAdapter adapter = new SqlDataAdapter( + "SELECT * FROM dbo.Customers;", + "Data Source=(local);Integrated " + + "Security=SSPI;Initial Catalog=Northwind"); + +adapter.Fill(customers, "Customers"); + +foreach(CustomerDataSet.CustomersRow customerRow in customers.Customers) + Console.WriteLine(customerRow.CustomerID); +``` + The following is the XML Schema used for the example: - -```xml - - - - - - - - - - - - - - - - -``` - + +```xml + + + + + + + + + + + + + + + + +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/handling-dataview-events.md b/docs/framework/data/adonet/dataset-datatable-dataview/handling-dataview-events.md index 9663f7b77a2ee..d5ccaffb364bc 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/handling-dataview-events.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/handling-dataview-events.md @@ -2,51 +2,51 @@ description: "Learn more about: Handling DataView Events" title: "Handling DataView Events" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: e5675663-fc91-4e0d-87a9-481b25b64c0f --- # Handling DataView Events -You can use the event of the to determine if a view has been updated. Updates that raise the event include adding, deleting, or modifying a row in the underlying table; adding or deleting a column to the schema of the underlying table; and a change in a parent or child relationship. The **ListChanged** event also notifies you if the list of rows you are viewing has changed significantly due to the application of a new sort order or a filter. - - The **ListChanged** event implements the **ListChangedEventHandler** delegate of the namespace and takes as input a object. You can determine what type of change has occurred using the enumeration value in the **ListChangedType** property of the **ListChangedEventArgs** object. For changes that involve adding, deleting, or moving rows, the new index of the added or moved row and the previous index of the deleted row can be accessed using the **NewIndex** property of the **ListChangedEventArgs** object. In the case of a moved row, the previous index of the moved row can be accessed using the **OldIndex** property of the **ListChangedEventArgs** object. - - The **DataViewManager** also exposes a **ListChanged** event to notify you if a table has been added or removed, or if a change has been made to the **Relations** collection of the underlying **DataSet**. - - The following code example shows how to add a **ListChanged** event handler. - -```vb -AddHandler custView.ListChanged, _ - New System.ComponentModel.ListChangedEventHandler( _ - AddressOf OnListChanged) - -Private Shared Sub OnListChanged( _ - sender As Object, args As System.ComponentModel.ListChangedEventArgs) - Console.WriteLine("ListChanged:") - Console.WriteLine(vbTab & " Type = " & _ - System.Enum.GetName(args.ListChangedType.GetType(), _ - args.ListChangedType)) - Console.WriteLine(vbTab & "OldIndex = " & args.OldIndex) - Console.WriteLine(vbTab & "NewIndex = " & args.NewIndex) -End Sub -``` - -```csharp +You can use the event of the to determine if a view has been updated. Updates that raise the event include adding, deleting, or modifying a row in the underlying table; adding or deleting a column to the schema of the underlying table; and a change in a parent or child relationship. The `ListChanged` event also notifies you if the list of rows you are viewing has changed significantly due to the application of a new sort order or a filter. + + The `ListChanged` event implements the `ListChangedEventHandler` delegate of the namespace and takes as input a object. You can determine what type of change has occurred using the enumeration value in the `ListChangedType` property of the `ListChangedEventArgs` object. For changes that involve adding, deleting, or moving rows, the new index of the added or moved row and the previous index of the deleted row can be accessed using the `NewIndex` property of the `ListChangedEventArgs` object. In the case of a moved row, the previous index of the moved row can be accessed using the `OldIndex` property of the `ListChangedEventArgs` object. + + The `DataViewManager` also exposes a `ListChanged` event to notify you if a table has been added or removed, or if a change has been made to the `Relations` collection of the underlying **DataSet**. + + The following code example shows how to add a `ListChanged` event handler. + +```vb +AddHandler custView.ListChanged, _ + New System.ComponentModel.ListChangedEventHandler( _ + AddressOf OnListChanged) + +Private Shared Sub OnListChanged( _ + sender As Object, args As System.ComponentModel.ListChangedEventArgs) + Console.WriteLine("ListChanged:") + Console.WriteLine(vbTab & " Type = " & _ + System.Enum.GetName(args.ListChangedType.GetType(), _ + args.ListChangedType)) + Console.WriteLine(vbTab & "OldIndex = " & args.OldIndex) + Console.WriteLine(vbTab & "NewIndex = " & args.NewIndex) +End Sub +``` + +```csharp custView.ListChanged += new - System.ComponentModel.ListChangedEventHandler(OnListChanged); - + System.ComponentModel.ListChangedEventHandler(OnListChanged); + protected static void OnListChanged(object sender, - System.ComponentModel.ListChangedEventArgs args) -{ - Console.WriteLine("ListChanged:"); - Console.WriteLine("\t Type = " + args.ListChangedType); - Console.WriteLine("\tOldIndex = " + args.OldIndex); - Console.WriteLine("\tNewIndex = " + args.NewIndex); -} -``` - + System.ComponentModel.ListChangedEventArgs args) +{ + Console.WriteLine("ListChanged:"); + Console.WriteLine("\t Type = " + args.ListChangedType); + Console.WriteLine("\tOldIndex = " + args.OldIndex); + Console.WriteLine("\tNewIndex = " + args.NewIndex); +} +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/index.md b/docs/framework/data/adonet/dataset-datatable-dataview/index.md index fb4fb4fe71896..bd09dc8919dc2 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/index.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/index.md @@ -6,79 +6,79 @@ ms.assetid: 6d4c4b69-8919-4224-8a65-6cca1c61b48f --- # DataSets, DataTables, and DataViews -The ADO.NET is a memory-resident representation of data that provides a consistent relational programming model regardless of the source of the data it contains. A represents a complete set of data including the tables that contain, order, and constrain the data, as well as the relationships between the tables. - -There are several ways of working with a , which can be applied independently or in combination. You can: - -- Programmatically create a , , and within a and populate the tables with data. - -- Populate the with tables of data from an existing relational data source using a `DataAdapter`. - -- Load and persist the contents using XML. For more information, see [Using XML in a DataSet](using-xml-in-a-dataset.md). - -A strongly typed can also be transported using an XML Web service. The design of the makes it ideal for transporting data using XML Web services. For an overview of XML Web services, see [XML Web Services Overview](/previous-versions/dotnet/netframework-4.0/w9fdtx28(v=vs.100)). For an example of consuming a from an XML Web service, see [Consuming a DataSet from an XML Web Service](consuming-a-dataset-from-an-xml-web-service.md). - +The ADO.NET is a memory-resident representation of data that provides a consistent relational programming model regardless of the source of the data it contains. A represents a complete set of data including the tables that contain, order, and constrain the data, as well as the relationships between the tables. + +There are several ways of working with a , which can be applied independently or in combination. You can: + +- Programmatically create a , , and within a and populate the tables with data. + +- Populate the with tables of data from an existing relational data source using a `DataAdapter`. + +- Load and persist the contents using XML. For more information, see [Using XML in a DataSet](using-xml-in-a-dataset.md). + +A strongly typed can also be transported using an XML Web service. The design of the makes it ideal for transporting data using XML Web services. For an overview of XML Web services, see [XML Web Services Overview](/previous-versions/dotnet/netframework-4.0/w9fdtx28(v=vs.100)). For an example of consuming a from an XML Web service, see [Consuming a DataSet from an XML Web Service](consuming-a-dataset-from-an-xml-web-service.md). + ## In this section - [Security guidance](security-guidance.md) + [Security guidance](security-guidance.md) Provides security guidance for and . - [Creating a DataSet](creating-a-dataset.md) - Describes the syntax for creating an instance of a . - - [Adding a DataTable to a DataSet](adding-a-datatable-to-a-dataset.md) - Describes how to create and add tables and columns to a . - - [Adding DataRelations](adding-datarelations.md) - Describes how to create relations between tables in a . - - [Navigating DataRelations](navigating-datarelations.md) - Describes how to use the relations between tables in a to return the child or parent rows of a parent-child relationship. - - [Merging DataSet Contents](merging-dataset-contents.md) - Describes how to merge the contents of one , , or array into another . - - [Copying DataSet Contents](copying-dataset-contents.md) - Describes how to create a copy of a that can contain schema as well as specified data. - - [Handling DataSet Events](handling-dataset-events.md) - Describes the events of a and how to use them. - - [Typed DataSets](typed-datasets.md) - Discusses what a typed is and how to create and use it. - - [DataTables](datatables.md) - Describes how to create a , define the schema, and manipulate data. - - [DataTableReaders](datatablereaders.md) - Describes how to create and use a . - - [DataViews](dataviews.md) - Describes how to create and work with `DataViews` and work with events. - - [Using XML in a DataSet](using-xml-in-a-dataset.md) - Describes how the interacts with XML as a data source, including loading and persisting the contents of a as XML data. - - [Consuming a DataSet from an XML Web Service](consuming-a-dataset-from-an-xml-web-service.md) - Describes how to create an XML Web service that uses a to transport data. - + [Creating a DataSet](creating-a-dataset.md) + Describes the syntax for creating an instance of a . + + [Adding a DataTable to a DataSet](adding-a-datatable-to-a-dataset.md) + Describes how to create and add tables and columns to a . + + [Adding DataRelations](adding-datarelations.md) + Describes how to create relations between tables in a . + + [Navigating DataRelations](navigating-datarelations.md) + Describes how to use the relations between tables in a to return the child or parent rows of a parent-child relationship. + + [Merging DataSet Contents](merging-dataset-contents.md) + Describes how to merge the contents of one , , or array into another . + + [Copying DataSet Contents](copying-dataset-contents.md) + Describes how to create a copy of a that can contain schema as well as specified data. + + [Handling DataSet Events](handling-dataset-events.md) + Describes the events of a and how to use them. + + [Typed DataSets](typed-datasets.md) + Discusses what a typed is and how to create and use it. + + [DataTables](datatables.md) + Describes how to create a , define the schema, and manipulate data. + + [DataTableReaders](datatablereaders.md) + Describes how to create and use a . + + [DataViews](dataviews.md) + Describes how to create and work with `DataViews` and work with events. + + [Using XML in a DataSet](using-xml-in-a-dataset.md) + Describes how the interacts with XML as a data source, including loading and persisting the contents of a as XML data. + + [Consuming a DataSet from an XML Web Service](consuming-a-dataset-from-an-xml-web-service.md) + Describes how to create an XML Web service that uses a to transport data. + ## Related sections - [What's New in ADO.NET](../whats-new.md) - Introduces features that are new in ADO.NET. - - [ADO.NET Overview](../ado-net-overview.md) - Provides an introduction to the design and components of ADO.NET. - - [Populating a DataSet from a DataAdapter](../populating-a-dataset-from-a-dataadapter.md) - Describes how to load a **DataSet** with data from a data source. - - [Updating Data Sources with DataAdapters](../updating-data-sources-with-dataadapters.md) - Describes how to resolve changes to the data in a **DataSet** back to the data source. - - [Adding Existing Constraints to a DataSet](../adding-existing-constraints-to-a-dataset.md) - Describes how to populate a **DataSet** with primary key information from a data source. - + [What's New in ADO.NET](../whats-new.md) + Introduces features that are new in ADO.NET. + + [ADO.NET Overview](../ado-net-overview.md) + Provides an introduction to the design and components of ADO.NET. + + [Populating a DataSet from a DataAdapter](../populating-a-dataset-from-a-dataadapter.md) + Describes how to load a `DataSet` with data from a data source. + + [Updating Data Sources with DataAdapters](../updating-data-sources-with-dataadapters.md) + Describes how to resolve changes to the data in a `DataSet` back to the data source. + + [Adding Existing Constraints to a DataSet](../adding-existing-constraints-to-a-dataset.md) + Describes how to populate a `DataSet` with primary key information from a data source. + ## See also - [ADO.NET](../index.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/inference-limitations.md b/docs/framework/data/adonet/dataset-datatable-dataview/inference-limitations.md index 8a81cb3d107d3..63f4b42c3bc4d 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/inference-limitations.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/inference-limitations.md @@ -6,50 +6,50 @@ ms.assetid: 78517994-5d57-44f8-9d20-38812977de09 --- # Inference Limitations -The process of inferring a schema from XML can result in different schemas depending on the XML elements in each document. For example, consider the following XML documents. - - Document1: - -```xml - - Text1 - Text2 - -``` - - Document2: - -```xml - - Text1 - -``` - - For "Document1," the inference process produces a **DataSet** named "DocumentElement" and a table named "Element1," because "Element1" is a repeating element. - - **DataSet:** DocumentElement - - **Table:** Element1 - -|Element1_Text| -|--------------------| -|Text1| -|Text2| - - However, for "Document2," the inference process produces a **DataSet** named "NewDataSet" and a table named "DocumentElement." "Element1" is inferred as a column because it has no attributes and no child elements. - - **DataSet:** NewDataSet - - **Table:** DocumentElement - -|Element1| -|--------------| -|Text1| - - These two XML documents may have been intended to produce the same schema, but the inference process produces very different results based on the elements contained in each document. - - To avoid the discrepancies that can occur when generating schema from an XML document, we recommend that you explicitly specify a schema using XML Schema definition language (XSD) or XML-Data Reduced (XDR) when loading a **DataSet** from XML. For more information about explicitly specifying a **DataSet** schema with XML Schema, see [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md). - +The process of inferring a schema from XML can result in different schemas depending on the XML elements in each document. For example, consider the following XML documents. + + Document1: + +```xml + + Text1 + Text2 + +``` + + Document2: + +```xml + + Text1 + +``` + + For "Document1," the inference process produces a `DataSet` named "DocumentElement" and a table named "Element1," because "Element1" is a repeating element. + + **DataSet:** DocumentElement + + **Table:** Element1 + +|Element1_Text| +|--------------------| +|Text1| +|Text2| + + However, for "Document2," the inference process produces a `DataSet` named "NewDataSet" and a table named "DocumentElement." "Element1" is inferred as a column because it has no attributes and no child elements. + + **DataSet:** NewDataSet + + **Table:** DocumentElement + +|Element1| +|--------------| +|Text1| + + These two XML documents may have been intended to produce the same schema, but the inference process produces very different results based on the elements contained in each document. + + To avoid the discrepancies that can occur when generating schema from an XML document, we recommend that you explicitly specify a schema using XML Schema definition language (XSD) or XML-Data Reduced (XDR) when loading a `DataSet` from XML. For more information about explicitly specifying a `DataSet` schema with XML Schema, see [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md). + ## See also - [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/inferring-columns.md b/docs/framework/data/adonet/dataset-datatable-dataview/inferring-columns.md index dea33f90bc4b2..9f2b8cf2a5684 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/inferring-columns.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/inferring-columns.md @@ -6,64 +6,64 @@ ms.assetid: 0e022699-c922-454c-93e2-957dd7e7247a --- # Inferring Columns -After ADO.NET has determined from an XML document which elements to infer as tables for a , it then infers the columns for those tables. ADO.NET 2.0 introduced a new schema inference engine that infers a strongly typed data type for each **simpleType** element. In previous versions, the data type of an inferred **simpleType** element was always **xsd:string**. - -## Migration and Backward Compatibility - - The **ReadXml** method takes an argument of type **InferSchema**. This argument allows you to specify inference behavior compatible with previous versions. The available values for the **InferSchema** enumeration are shown in the following table. - - - Provides backward compatibility by always inferring a simple type as . - - - Infers a strongly typed data type. Throws an exception if used with a . - - - Ignores any inline schema and reads data into the existing schema. - -## Attributes - - As defined in [Inferring Tables](inferring-tables.md), an element with attributes will be inferred as a table. The attributes of that element will then be inferred as columns for the table. The **ColumnMapping** property of the columns will be set to **MappingType.Attribute**, to ensure that the column names will be written as attributes if the schema is written back to XML. The values of the attributes are stored in a row in the table. For example, consider the following XML: - -```xml - - - -``` - - The inference process will produce a table named **Element1** with two columns, **attr1** and **attr2**. The **ColumnMapping** property of both columns will be set to **MappingType.Attribute**. - - **DataSet:** DocumentElement - - **Table:** Element1 - -|attr1|attr2| -|-----------|-----------| -|value1|value2| - -## Elements Without Attributes or Child Elements - - If an element has no child elements or attributes, it will be inferred as a column. The **ColumnMapping** property of the column will be set to **MappingType.Element**. The text for child elements is stored in a row in the table. For example, consider the following XML: - -```xml - - - Text1 - Text2 - - -``` - - The inference process will produce a table named **Element1** with two columns, **ChildElement1** and **ChildElement2**. The **ColumnMapping** property of both columns will be set to **MappingType.Element**. - - **DataSet:** DocumentElement - - **Table:** Element1 - -|ChildElement1|ChildElement2| -|-------------------|-------------------| -|Text1|Text2| - +After ADO.NET has determined from an XML document which elements to infer as tables for a , it then infers the columns for those tables. ADO.NET 2.0 introduced a new schema inference engine that infers a strongly typed data type for each `simpleType` element. In previous versions, the data type of an inferred `simpleType` element was always **xsd:string**. + +## Migration and Backward Compatibility + + The `ReadXml` method takes an argument of type **InferSchema**. This argument allows you to specify inference behavior compatible with previous versions. The available values for the `InferSchema` enumeration are shown in the following table. + + + Provides backward compatibility by always inferring a simple type as . + + + Infers a strongly typed data type. Throws an exception if used with a . + + + Ignores any inline schema and reads data into the existing schema. + +## Attributes + + As defined in [Inferring Tables](inferring-tables.md), an element with attributes will be inferred as a table. The attributes of that element will then be inferred as columns for the table. The `ColumnMapping` property of the columns will be set to **MappingType.Attribute**, to ensure that the column names will be written as attributes if the schema is written back to XML. The values of the attributes are stored in a row in the table. For example, consider the following XML: + +```xml + + + +``` + + The inference process will produce a table named **Element1** with two columns, **attr1** and **attr2**. The `ColumnMapping` property of both columns will be set to **MappingType.Attribute**. + + **DataSet:** DocumentElement + + **Table:** Element1 + +|attr1|attr2| +|-----------|-----------| +|value1|value2| + +## Elements Without Attributes or Child Elements + + If an element has no child elements or attributes, it will be inferred as a column. The `ColumnMapping` property of the column will be set to **MappingType.Element**. The text for child elements is stored in a row in the table. For example, consider the following XML: + +```xml + + + Text1 + Text2 + + +``` + + The inference process will produce a table named **Element1** with two columns, **ChildElement1** and **ChildElement2**. The `ColumnMapping` property of both columns will be set to **MappingType.Element**. + + **DataSet:** DocumentElement + + **Table:** Element1 + +|ChildElement1|ChildElement2| +|-------------------|-------------------| +|Text1|Text2| + ## See also - [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/inferring-element-text.md b/docs/framework/data/adonet/dataset-datatable-dataview/inferring-element-text.md index 92c36e04bf726..52a16835e25ef 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/inferring-element-text.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/inferring-element-text.md @@ -6,46 +6,46 @@ ms.assetid: 789799e5-716f-459f-a168-76c5cf22178b --- # Inferring Element Text -If an element contains text and has no child elements to be inferred as tables (such as elements with attributes or repeated elements), a new column with the name **TableName_Text** will be added to the table that is inferred for the element. The text contained in the element will be added to a row in the table and stored in the new column. The **ColumnMapping** property of the new column will be set to **MappingType.SimpleContent**. - - For example, consider the following XML. - -```xml - - Text1 - -``` - - The inference process will produce a table named **Element1** with two columns: **attr1** and **Element1_Text**. The **ColumnMapping** property of the **attr1** column will be set to **MappingType.Attribute**. The **ColumnMapping** property of the **Element1_Text** column will be set to **MappingType.SimpleContent**. - - **DataSet:** DocumentElement - - **Table:** Element1 - -|attr1|Element1_Text| -|-----------|--------------------| -|value1|Text1| - - If an element contains text, but also has child elements that contain text, a column will not be added to the table to store the text contained in the element. The text contained in the element will be ignored, while the text in the child elements is included in a row in the table. For example, consider the following XML. - -```xml - - Text1 - Text2 - Text3 - -``` - - The inference process will produce a table named **Element1** with one column named **ChildElement1**. The text for the **ChildElement1** element will be included in a row in the table. The other text will be ignored. The **ColumnMapping** property of the **ChildElement1** column will be set to **MappingType.Element**. - - **DataSet:** DocumentElement - - **Table:** Element1 - -|ChildElement1| -|-------------------| -|Text2| - +If an element contains text and has no child elements to be inferred as tables (such as elements with attributes or repeated elements), a new column with the name `TableName_Text` will be added to the table that is inferred for the element. The text contained in the element will be added to a row in the table and stored in the new column. The `ColumnMapping` property of the new column will be set to **MappingType.SimpleContent**. + + For example, consider the following XML. + +```xml + + Text1 + +``` + + The inference process will produce a table named **Element1** with two columns: **attr1** and **Element1_Text**. The `ColumnMapping` property of the **attr1** column will be set to **MappingType.Attribute**. The `ColumnMapping` property of the **Element1_Text** column will be set to **MappingType.SimpleContent**. + + **DataSet:** DocumentElement + + **Table:** Element1 + +|attr1|Element1_Text| +|-----------|--------------------| +|value1|Text1| + + If an element contains text, but also has child elements that contain text, a column will not be added to the table to store the text contained in the element. The text contained in the element will be ignored, while the text in the child elements is included in a row in the table. For example, consider the following XML. + +```xml + + Text1 + Text2 + Text3 + +``` + + The inference process will produce a table named **Element1** with one column named **ChildElement1**. The text for the **ChildElement1** element will be included in a row in the table. The other text will be ignored. The `ColumnMapping` property of the **ChildElement1** column will be set to **MappingType.Element**. + + **DataSet:** DocumentElement + + **Table:** Element1 + +|ChildElement1| +|-------------------| +|Text2| + ## See also - [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/inferring-relationships.md b/docs/framework/data/adonet/dataset-datatable-dataview/inferring-relationships.md index 48c6739d08147..9ff20f6c07383 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/inferring-relationships.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/inferring-relationships.md @@ -6,65 +6,65 @@ ms.assetid: 8fa86a9d-6545-4a9d-b1f5-58d9742179c7 --- # Inferring Relationships -If an element that is inferred as a table has a child element that is also inferred as a table, a will be created between the two tables. A new column with a name of **ParentTableName_Id** will be added to both the table created for the parent element, and the table created for the child element. The **ColumnMapping** property of this identity column will be set to **MappingType.Hidden**. The column will be an auto-incrementing primary key for the parent table, and will be used for the **DataRelation** between the two tables. The data type of the added identity column will be **System.Int32**, unlike the data type of all other inferred columns, which is **System.String**. A with **DeleteRule** = **Cascade** will also be created using the new column in both the parent and child tables. - - For example, consider the following XML: - -```xml - - - - Text2 - - -``` - - The inference process will produce two tables: **Element1** and **ChildElement1**. - - The **Element1** table will have two columns: **Element1_Id** and **ChildElement2**. The **ColumnMapping** property of the **Element1_Id** column will be set to **MappingType.Hidden**. The **ColumnMapping** property of the **ChildElement2** column will be set to **MappingType.Element**. The **Element1_Id** column will be set as the primary key of the **Element1** table. - - The **ChildElement1** table will have three columns: **attr1**, **attr2** and **Element1_Id**. The **ColumnMapping** property for the **attr1** and **attr2** columns will be set to **MappingType.Attribute**. The **ColumnMapping** property of the **Element1_Id** column will be set to **MappingType.Hidden**. - - A **DataRelation** and **ForeignKeyConstraint** will be created using the **Element1_Id** columns from both tables. - - **DataSet:** DocumentElement - - **Table:** Element1 - -|Element1_Id|ChildElement2| -|------------------|-------------------| -|0|Text2| - - **Table:** ChildElement1 - -|attr1|attr2|Element1_Id| -|-----------|-----------|------------------| -|value1|value2|0| - - **DataRelation:** Element1_ChildElement1 - - **ParentTable:** Element1 - - **ParentColumn:** Element1_Id - - **ChildTable:** ChildElement1 - - **ChildColumn:** Element1_Id - - **Nested:** True - - **ForeignKeyConstraint:** Element1_ChildElement1 - - **Column:** Element1_Id - - **ParentTable:** Element1 - - **ChildTable:** ChildElement1 - - **DeleteRule:** Cascade - - **AcceptRejectRule:** None - +If an element that is inferred as a table has a child element that is also inferred as a table, a will be created between the two tables. A new column with a name of `ParentTableName_Id` will be added to both the table created for the parent element, and the table created for the child element. The `ColumnMapping` property of this identity column will be set to **MappingType.Hidden**. The column will be an auto-incrementing primary key for the parent table, and will be used for the `DataRelation` between the two tables. The data type of the added identity column will be **System.Int32**, unlike the data type of all other inferred columns, which is **System.String**. A with `DeleteRule` = `Cascade` will also be created using the new column in both the parent and child tables. + + For example, consider the following XML: + +```xml + + + + Text2 + + +``` + + The inference process will produce two tables: **Element1** and **ChildElement1**. + + The **Element1** table will have two columns: **Element1_Id** and **ChildElement2**. The `ColumnMapping` property of the **Element1_Id** column will be set to **MappingType.Hidden**. The `ColumnMapping` property of the **ChildElement2** column will be set to **MappingType.Element**. The **Element1_Id** column will be set as the primary key of the **Element1** table. + + The **ChildElement1** table will have three columns: **attr1**, **attr2** and **Element1_Id**. The `ColumnMapping` property for the **attr1** and **attr2** columns will be set to **MappingType.Attribute**. The `ColumnMapping` property of the **Element1_Id** column will be set to **MappingType.Hidden**. + + A `DataRelation` and `ForeignKeyConstraint` will be created using the **Element1_Id** columns from both tables. + + **DataSet:** DocumentElement + + **Table:** Element1 + +|Element1_Id|ChildElement2| +|------------------|-------------------| +|0|Text2| + + **Table:** ChildElement1 + +|attr1|attr2|Element1_Id| +|-----------|-----------|------------------| +|value1|value2|0| + + **DataRelation:** Element1_ChildElement1 + + **ParentTable:** Element1 + + **ParentColumn:** Element1_Id + + **ChildTable:** ChildElement1 + + **ChildColumn:** Element1_Id + + **Nested:** True + + **ForeignKeyConstraint:** Element1_ChildElement1 + + **Column:** Element1_Id + + **ParentTable:** Element1 + + **ChildTable:** ChildElement1 + + **DeleteRule:** Cascade + + **AcceptRejectRule:** None + ## See also - [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/inferring-tables.md b/docs/framework/data/adonet/dataset-datatable-dataview/inferring-tables.md index c1cff84f35f6c..c45815e188036 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/inferring-tables.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/inferring-tables.md @@ -6,117 +6,117 @@ ms.assetid: 74a288d4-b8e9-4f1a-b2cd-10df92c1ed1f --- # Inferring Tables -When inferring a schema for a from an XML document, ADO.NET first determines which XML elements represent tables. The following XML structures result in a table for the **DataSet** schema: - -- Elements with attributes - -- Elements with child elements - -- Repeating elements - -## Elements with Attributes - - Elements that have attributes specified in them result in inferred tables. For example, consider the following XML: - -```xml - - - Text1 - -``` - - The inference process produces a table named "Element1." - - **DataSet:** DocumentElement - - **Table:** Element1 - -|attr1|Element1_Text| -|-----------|--------------------| -|value1|| -|value2|Text1| - -## Elements with Child Elements - - Elements that have child elements result in inferred tables. For example, consider the following XML: - -```xml - - - Text1 - - -``` - - The inference process produces a table named "Element1." - - **DataSet:** DocumentElement - - **Table:** Element1 - -|ChildElement1| -|-------------------| -|Text1| - - The document, or root, element result in an inferred table if it has attributes or child elements that are inferred as columns. If the document element has no attributes and no child elements that would be inferred as columns, the element is inferred as a **DataSet**. For example, consider the following XML: - -```xml - - Text1 - Text2 - -``` - - The inference process produces a table named "DocumentElement." - - **DataSet:** NewDataSet - - **Table:** DocumentElement - -|Element1|Element2| -|--------------|--------------| -|Text1|Text2| - - Alternatively, consider the following XML: - -```xml - - - -``` - - The inference process produces a **DataSet** named "DocumentElement" that contains a table named "Element1." - - **DataSet:** DocumentElement - - **Table:** Element1 - -|attr1|attr2| -|-----------|-----------| -|value1|value2| - -## Repeating Elements - - Elements that repeat result in a single inferred table. For example, consider the following XML: - -```xml - - Text1 - Text2 - -``` - - The inference process produces a table named "Element1." - - **DataSet:** DocumentElement - - **Table:** Element1 - -|Element1_Text| -|--------------------| -|Text1| -|Text2| - +When inferring a schema for a from an XML document, ADO.NET first determines which XML elements represent tables. The following XML structures result in a table for the `DataSet` schema: + +- Elements with attributes + +- Elements with child elements + +- Repeating elements + +## Elements with Attributes + + Elements that have attributes specified in them result in inferred tables. For example, consider the following XML: + +```xml + + + Text1 + +``` + + The inference process produces a table named "Element1." + + **DataSet:** DocumentElement + + **Table:** Element1 + +|attr1|Element1_Text| +|-----------|--------------------| +|value1|| +|value2|Text1| + +## Elements with Child Elements + + Elements that have child elements result in inferred tables. For example, consider the following XML: + +```xml + + + Text1 + + +``` + + The inference process produces a table named "Element1." + + **DataSet:** DocumentElement + + **Table:** Element1 + +|ChildElement1| +|-------------------| +|Text1| + + The document, or root, element result in an inferred table if it has attributes or child elements that are inferred as columns. If the document element has no attributes and no child elements that would be inferred as columns, the element is inferred as a **DataSet**. For example, consider the following XML: + +```xml + + Text1 + Text2 + +``` + + The inference process produces a table named "DocumentElement." + + **DataSet:** NewDataSet + + **Table:** DocumentElement + +|Element1|Element2| +|--------------|--------------| +|Text1|Text2| + + Alternatively, consider the following XML: + +```xml + + + +``` + + The inference process produces a `DataSet` named "DocumentElement" that contains a table named "Element1." + + **DataSet:** DocumentElement + + **Table:** Element1 + +|attr1|attr2| +|-----------|-----------| +|value1|value2| + +## Repeating Elements + + Elements that repeat result in a single inferred table. For example, consider the following XML: + +```xml + + Text1 + Text2 + +``` + + The inference process produces a table named "Element1." + + **DataSet:** DocumentElement + + **Table:** Element1 + +|Element1_Text| +|--------------------| +|Text1| +|Text2| + ## See also - [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/loading-a-dataset-from-xml.md b/docs/framework/data/adonet/dataset-datatable-dataview/loading-a-dataset-from-xml.md index 2366d90dc995b..b5b43c54cc929 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/loading-a-dataset-from-xml.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/loading-a-dataset-from-xml.md @@ -2,117 +2,117 @@ title: "Loading a DataSet from XML" description: Learn how to add contents to an ADO.NET DataSet from XML. The .NET Framework offers flexibility for what to load and the structure of the DataSet. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 49c083b7-a5ed-41cf-aabc-5aaba96f00e6 --- # Loading a DataSet from XML -The contents of an ADO.NET can be created from an XML stream or document. In addition, with the .NET Framework you have great flexibility over what information is loaded from XML, and how the schema or relational structure of the is created. - - To fill a with data from XML, use the **ReadXml** method of the object. The **ReadXml** method reads from a file, a stream, or an **XmlReader**, and takes as arguments the source of the XML plus an optional **XmlReadMode** argument. For more information about the **XmlReader**, see [Reading XML Data with XmlTextReader](/previous-versions/dotnet/netframework-4.0/tfz3cz6w(v=vs.100)). The **ReadXml** method reads the contents of the XML stream or document and loads the with data. It will also create the relational schema of the depending on the **XmlReadMode** specified and whether or not a relational schema already exists. - - The following table describes the options for the **XmlReadMode** argument. - -|Option|Description| -|------------|-----------------| -|**Auto**|This is the default. Examines the XML and chooses the most appropriate option in the following order:

- If the XML is a DiffGram, **DiffGram** is used.
- If the contains a schema or the XML contains an inline schema, **ReadSchema** is used.
- If the does not contain a schema and the XML does not contain an inline schema, **InferSchema** is used.

If you know the format of the XML being read, for best performance it is recommended that you set an explicit **XmlReadMode**, rather than accept the **Auto** default.| -|**ReadSchema**|Reads any inline schema and loads the data and schema.

If the already contains a schema, new tables are added from the inline schema to the existing schema in the . If any tables in the inline schema already exist in the , an exception is thrown. You will not be able to modify the schema of an existing table using **XmlReadMode.ReadSchema**.

If the does not contain a schema, and there is no inline schema, no data is read.

Inline schema can be defined using XML Schema definition language (XSD) schema. For details about writing inline schema as XML Schema, see [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md).| -|**IgnoreSchema**|Ignores any inline schema and loads the data into the existing schema. Any data that does not match the existing schema is discarded. If no schema exists in the , no data is loaded.

If the data is a DiffGram, **IgnoreSchema** has the same functionality as **DiffGram** *.*| -|**InferSchema**|Ignores any inline schema and infers the schema per the structure of the XML data, then loads the data.

If the already contains a schema, the current schema is extended by adding columns to existing tables. Extra tables will not be added if there are not existing tables. An exception is thrown if an inferred table already exists with a different namespace, or if any inferred columns conflict with existing columns.

For details about how **ReadXmlSchema** infers a schema from an XML document, see [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md).| -|**DiffGram**|Reads a DiffGram and adds the data to the current schema. **DiffGram** merges new rows with existing rows where the unique identifier values match. See "Merging Data from XML" at the end of this topic. For more information about DiffGrams, see [DiffGrams](diffgrams.md).| -|**Fragment**|Continues reading multiple XML fragments until the end of the stream is reached. Fragments that match the schema are appended to the appropriate tables. Fragments that do not match the schema are discarded.| - +The contents of an ADO.NET can be created from an XML stream or document. In addition, with the .NET Framework you have great flexibility over what information is loaded from XML, and how the schema or relational structure of the is created. + + To fill a with data from XML, use the `ReadXml` method of the object. The `ReadXml` method reads from a file, a stream, or an **XmlReader**, and takes as arguments the source of the XML plus an optional `XmlReadMode` argument. For more information about the **XmlReader**, see [Reading XML Data with XmlTextReader](/previous-versions/dotnet/netframework-4.0/tfz3cz6w(v=vs.100)). The `ReadXml` method reads the contents of the XML stream or document and loads the with data. It will also create the relational schema of the depending on the `XmlReadMode` specified and whether or not a relational schema already exists. + + The following table describes the options for the `XmlReadMode` argument. + +|Option|Description| +|------------|-----------------| +|**Auto**|This is the default. Examines the XML and chooses the most appropriate option in the following order:

- If the XML is a DiffGram, `DiffGram` is used.
- If the contains a schema or the XML contains an inline schema, `ReadSchema` is used.
- If the does not contain a schema and the XML does not contain an inline schema, `InferSchema` is used.

If you know the format of the XML being read, for best performance it is recommended that you set an explicit **XmlReadMode**, rather than accept the `Auto` default.| +|**ReadSchema**|Reads any inline schema and loads the data and schema.

If the already contains a schema, new tables are added from the inline schema to the existing schema in the . If any tables in the inline schema already exist in the , an exception is thrown. You will not be able to modify the schema of an existing table using **XmlReadMode.ReadSchema**.

If the does not contain a schema, and there is no inline schema, no data is read.

Inline schema can be defined using XML Schema definition language (XSD) schema. For details about writing inline schema as XML Schema, see [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md).| +|**IgnoreSchema**|Ignores any inline schema and loads the data into the existing schema. Any data that does not match the existing schema is discarded. If no schema exists in the , no data is loaded.

If the data is a DiffGram, `IgnoreSchema` has the same functionality as `DiffGram` *.*| +|**InferSchema**|Ignores any inline schema and infers the schema per the structure of the XML data, then loads the data.

If the already contains a schema, the current schema is extended by adding columns to existing tables. Extra tables will not be added if there are not existing tables. An exception is thrown if an inferred table already exists with a different namespace, or if any inferred columns conflict with existing columns.

For details about how `ReadXmlSchema` infers a schema from an XML document, see [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md).| +|**DiffGram**|Reads a DiffGram and adds the data to the current schema. `DiffGram` merges new rows with existing rows where the unique identifier values match. See "Merging Data from XML" at the end of this topic. For more information about DiffGrams, see [DiffGrams](diffgrams.md).| +|**Fragment**|Continues reading multiple XML fragments until the end of the stream is reached. Fragments that match the schema are appended to the appropriate tables. Fragments that do not match the schema are discarded.| + > [!NOTE] -> If you pass an **XmlReader** to **ReadXml** that is positioned part of the way into an XML document, **ReadXml** will read to the next element node and will treat that as the root element, reading until the end of the element node only. This does not apply if you specify **XmlReadMode.Fragment**. - -## DTD Entities - - If your XML contains entities defined in a document type definition (DTD) schema, an exception will be thrown if you attempt to load a by passing a file name, stream, or non-validating **XmlReader** to **ReadXml**. Instead, you must create an **XmlValidatingReader**, with **EntityHandling** set to **EntityHandling.ExpandEntities**, and pass your **XmlValidatingReader** to **ReadXml**. The **XmlValidatingReader** will expand the entities prior to being read by the . - - The following code examples show how to load a from an XML stream. The first example shows a file name being passed to the **ReadXml** method. The second example shows a string that contains XML being loaded using a . - -```vb -Dim dataSet As DataSet = New DataSet -dataSet.ReadXml("input.xml", XmlReadMode.ReadSchema) -``` - -```csharp -DataSet dataSet = new DataSet(); -dataSet.ReadXml("input.xml", XmlReadMode.ReadSchema); -``` - -```vb -Dim dataSet As DataSet = New DataSet -Dim dataTable As DataTable = New DataTable("table1") -dataTable.Columns.Add("col1", Type.GetType("System.String")) -dataSet.Tables.Add(dataTable) - -Dim xmlData As String = "Value1Value2" - -Dim xmlSR As System.IO.StringReader = New System.IO.StringReader(xmlData) - -dataSet.ReadXml(xmlSR, XmlReadMode.IgnoreSchema) -``` - -```csharp -DataSet dataSet = new DataSet(); -DataTable dataTable = new DataTable("table1"); -dataTable.Columns.Add("col1", typeof(string)); -dataSet.Tables.Add(dataTable); - -string xmlData = "Value1Value2"; - -System.IO.StringReader xmlSR = new System.IO.StringReader(xmlData); - -dataSet.ReadXml(xmlSR, XmlReadMode.IgnoreSchema); -``` - +> If you pass an `XmlReader` to `ReadXml` that is positioned part of the way into an XML document, `ReadXml` will read to the next element node and will treat that as the root element, reading until the end of the element node only. This does not apply if you specify **XmlReadMode.Fragment**. + +## DTD Entities + + If your XML contains entities defined in a document type definition (DTD) schema, an exception will be thrown if you attempt to load a by passing a file name, stream, or non-validating `XmlReader` to **ReadXml**. Instead, you must create an **XmlValidatingReader**, with `EntityHandling` set to **EntityHandling.ExpandEntities**, and pass your `XmlValidatingReader` to **ReadXml**. The `XmlValidatingReader` will expand the entities prior to being read by the . + + The following code examples show how to load a from an XML stream. The first example shows a file name being passed to the `ReadXml` method. The second example shows a string that contains XML being loaded using a . + +```vb +Dim dataSet As DataSet = New DataSet +dataSet.ReadXml("input.xml", XmlReadMode.ReadSchema) +``` + +```csharp +DataSet dataSet = new DataSet(); +dataSet.ReadXml("input.xml", XmlReadMode.ReadSchema); +``` + +```vb +Dim dataSet As DataSet = New DataSet +Dim dataTable As DataTable = New DataTable("table1") +dataTable.Columns.Add("col1", Type.GetType("System.String")) +dataSet.Tables.Add(dataTable) + +Dim xmlData As String = "Value1Value2" + +Dim xmlSR As System.IO.StringReader = New System.IO.StringReader(xmlData) + +dataSet.ReadXml(xmlSR, XmlReadMode.IgnoreSchema) +``` + +```csharp +DataSet dataSet = new DataSet(); +DataTable dataTable = new DataTable("table1"); +dataTable.Columns.Add("col1", typeof(string)); +dataSet.Tables.Add(dataTable); + +string xmlData = "Value1Value2"; + +System.IO.StringReader xmlSR = new System.IO.StringReader(xmlData); + +dataSet.ReadXml(xmlSR, XmlReadMode.IgnoreSchema); +``` + > [!NOTE] -> If you call **ReadXml** to load a very large file, you may encounter slow performance. To ensure best performance for **ReadXml**, on a large file, call the method for each table in the , and then call **ReadXml**. Finally, call for each table in the , as shown in the following example. - -```vb -Dim dataTable As DataTable - -For Each dataTable In dataSet.Tables - dataTable.BeginLoadData() -Next - -dataSet.ReadXml("file.xml") - -For Each dataTable in dataSet.Tables - dataTable.EndLoadData() -Next -``` - -```csharp -foreach (DataTable dataTable in dataSet.Tables) - dataTable.BeginLoadData(); - +> If you call `ReadXml` to load a very large file, you may encounter slow performance. To ensure best performance for **ReadXml**, on a large file, call the method for each table in the , and then call **ReadXml**. Finally, call for each table in the , as shown in the following example. + +```vb +Dim dataTable As DataTable + +For Each dataTable In dataSet.Tables + dataTable.BeginLoadData() +Next + +dataSet.ReadXml("file.xml") + +For Each dataTable in dataSet.Tables + dataTable.EndLoadData() +Next +``` + +```csharp +foreach (DataTable dataTable in dataSet.Tables) + dataTable.BeginLoadData(); + dataSet.ReadXml("file.xml"); - -foreach (DataTable dataTable in dataSet.Tables) - dataTable.EndLoadData(); -``` - + +foreach (DataTable dataTable in dataSet.Tables) + dataTable.EndLoadData(); +``` + > [!NOTE] -> If the XSD schema for your includes a **targetNamespace**, data may not be read, and you may encounter exceptions, when calling **ReadXml** to load the with XML that contains elements with no qualifying namespace. To read unqualified elements in this case, set **elementFormDefault** equal to "qualified" in your XSD schema. For example: - -```xml +> If the XSD schema for your includes a **targetNamespace**, data may not be read, and you may encounter exceptions, when calling `ReadXml` to load the with XML that contains elements with no qualifying namespace. To read unqualified elements in this case, set `elementFormDefault` equal to "qualified" in your XSD schema. For example: + +```xml - -``` - -## Merging Data from XML - - If the already contains data, the new data from the XML is added to the data already present in the . **ReadXml** does not merge from the XML into the any row information with matching primary keys. To overwrite existing row information with new information from XML, use **ReadXml** to create a new , and then the new into the existing . Note that loading a DiffGram using **ReadXML** with an **XmlReadMode** of **DiffGram** will merge rows that have the same unique identifier. - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + +``` + +## Merging Data from XML + + If the already contains data, the new data from the XML is added to the data already present in the . `ReadXml` does not merge from the XML into the any row information with matching primary keys. To overwrite existing row information with new information from XML, use `ReadXml` to create a new , and then the new into the existing . Note that loading a DiffGram using `ReadXML` with an `XmlReadMode` of `DiffGram` will merge rows that have the same unique identifier. + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/loading-dataset-schema-information-from-xml.md b/docs/framework/data/adonet/dataset-datatable-dataview/loading-dataset-schema-information-from-xml.md index cd861ffe7943c..35e5908220efb 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/loading-dataset-schema-information-from-xml.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/loading-dataset-schema-information-from-xml.md @@ -2,87 +2,87 @@ description: "Learn more about: Loading DataSet Schema Information from XML" title: "Loading DataSet Schema Information from XML" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 43dfb23b-5cef-46f2-8d87-78f0fba1eb8c --- # Loading DataSet Schema Information from XML -The schema of a (its tables, columns, relations, and constraints) can be defined programmatically, created by the **Fill** or **FillSchema** methods of a , or loaded from an XML document. To load **DataSet** schema information from an XML document, you can use either the **ReadXmlSchema** or the **InferXmlSchema** method of the **DataSet**. **ReadXmlSchema** allows you to load or infer **DataSet** schema information from the document containing XML Schema definition language (XSD) schema, or an XML document with inline XML Schema. **InferXmlSchema** allows you to infer the schema from the XML document while ignoring certain XML namespaces that you specify. - +The schema of a (its tables, columns, relations, and constraints) can be defined programmatically, created by the `Fill` or `FillSchema` methods of a , or loaded from an XML document. To load `DataSet` schema information from an XML document, you can use either the `ReadXmlSchema` or the `InferXmlSchema` method of the **DataSet**. `ReadXmlSchema` allows you to load or infer `DataSet` schema information from the document containing XML Schema definition language (XSD) schema, or an XML document with inline XML Schema. `InferXmlSchema` allows you to infer the schema from the XML document while ignoring certain XML namespaces that you specify. + > [!NOTE] -> Table ordering in a **DataSet** might not be preserved when you use Web services or XML serialization to transfer a **DataSet** that was created in-memory by using XSD constructs (such as nested relations). Therefore, the recipient of the **DataSet** should not depend on table ordering in this case. However, table ordering is always preserved if the schema of the **DataSet** being transferred was read from XSD files, instead of being created in-memory. - -## ReadXmlSchema - - To load the schema of a **DataSet** from an XML document without loading any data, you can use the **ReadXmlSchema** method of the **DataSet**. **ReadXmlSchema** creates **DataSet** schema defined using XML Schema definition language (XSD) schema. - - The **ReadXmlSchema** method takes a single argument of a file name, a stream, or an **XmlReader** containing the XML document to be loaded. The XML document can contain only schema, or can contain schema inline with XML elements containing data. For details about writing inline schema as XML Schema, see [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md). - - If the XML document passed to **ReadXmlSchema** contains no inline schema information, **ReadXmlSchema** will infer the schema from the elements in the XML document. If the **DataSet** already contains a schema, the current schema will be extended by adding new tables if they do not already exist. New columns will not be added to added to existing tables. If a column being added already exists in the **DataSet** but has an incompatible type with the column found in the XML, an exception is thrown. For details about how **ReadXmlSchema** infers a schema from an XML document, see [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md). - - Although **ReadXmlSchema** loads or infers only the schema of a **DataSet**, the **ReadXml** method of the **DataSet** loads or infers both the schema and the data contained in the XML document. For more information, see [Loading a DataSet from XML](loading-a-dataset-from-xml.md). - - The following code examples show how to load a **DataSet** schema from an XML document or stream. The first example shows an XML Schema file name being passed to the **ReadXmlSchema** method. The second example shows a **System.IO.StreamReader**. - -```vb -Dim dataSet As DataSet = New DataSet -dataSet.ReadXmlSchema("schema.xsd") -``` - -```csharp -DataSet dataSet = new DataSet(); -dataSet.ReadXmlSchema("schema.xsd"); -``` - -```vb +> Table ordering in a `DataSet` might not be preserved when you use Web services or XML serialization to transfer a `DataSet` that was created in-memory by using XSD constructs (such as nested relations). Therefore, the recipient of the `DataSet` should not depend on table ordering in this case. However, table ordering is always preserved if the schema of the `DataSet` being transferred was read from XSD files, instead of being created in-memory. + +## ReadXmlSchema + + To load the schema of a `DataSet` from an XML document without loading any data, you can use the `ReadXmlSchema` method of the **DataSet**. `ReadXmlSchema` creates `DataSet` schema defined using XML Schema definition language (XSD) schema. + + The `ReadXmlSchema` method takes a single argument of a file name, a stream, or an `XmlReader` containing the XML document to be loaded. The XML document can contain only schema, or can contain schema inline with XML elements containing data. For details about writing inline schema as XML Schema, see [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md). + + If the XML document passed to `ReadXmlSchema` contains no inline schema information, `ReadXmlSchema` will infer the schema from the elements in the XML document. If the `DataSet` already contains a schema, the current schema will be extended by adding new tables if they do not already exist. New columns will not be added to added to existing tables. If a column being added already exists in the `DataSet` but has an incompatible type with the column found in the XML, an exception is thrown. For details about how `ReadXmlSchema` infers a schema from an XML document, see [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md). + + Although `ReadXmlSchema` loads or infers only the schema of a **DataSet**, the `ReadXml` method of the `DataSet` loads or infers both the schema and the data contained in the XML document. For more information, see [Loading a DataSet from XML](loading-a-dataset-from-xml.md). + + The following code examples show how to load a `DataSet` schema from an XML document or stream. The first example shows an XML Schema file name being passed to the `ReadXmlSchema` method. The second example shows a **System.IO.StreamReader**. + +```vb +Dim dataSet As DataSet = New DataSet +dataSet.ReadXmlSchema("schema.xsd") +``` + +```csharp +DataSet dataSet = new DataSet(); +dataSet.ReadXmlSchema("schema.xsd"); +``` + +```vb Dim xmlStream As New System.IO.StreamReader("schema.xsd") -Dim dataSet As DataSet = New DataSet -dataSet.ReadXmlSchema(xmlStream) -xmlStream.Close() -``` - -```csharp -System.IO.StreamReader xmlStream = new System.IO.StreamReader("schema.xsd"); -DataSet dataSet = new DataSet(); -dataSet.ReadXmlSchema(xmlStream); -xmlStream.Close(); -``` - -## InferXmlSchema - - You can also instruct the **DataSet** to infer its schema from an XML document using the **InferXmlSchema** method of the **DataSet**. **InferXmlSchema** functions the same as do both **ReadXml** with an **XmlReadMode** of **InferSchema** (loads data as well as infers schema), and **ReadXmlSchema** if the document being read contains no inline schema. However, **InferXmlSchema** provides the additional capability of allowing you to specify particular XML namespaces to be ignored when the schema is inferred. **InferXmlSchema** takes two required arguments: the location of the XML document, specified by a file name, a stream, or an **XmlReader**; and a string array of XML namespaces to be ignored by the operation. - - For example, consider the following XML: - -```xml - - +Dim dataSet As DataSet = New DataSet +dataSet.ReadXmlSchema(xmlStream) +xmlStream.Close() +``` + +```csharp +System.IO.StreamReader xmlStream = new System.IO.StreamReader("schema.xsd"); +DataSet dataSet = new DataSet(); +dataSet.ReadXmlSchema(xmlStream); +xmlStream.Close(); +``` + +## InferXmlSchema + + You can also instruct the `DataSet` to infer its schema from an XML document using the `InferXmlSchema` method of the **DataSet**. `InferXmlSchema` functions the same as do both `ReadXml` with an `XmlReadMode` of `InferSchema` (loads data as well as infers schema), and `ReadXmlSchema` if the document being read contains no inline schema. However, `InferXmlSchema` provides the additional capability of allowing you to specify particular XML namespaces to be ignored when the schema is inferred. `InferXmlSchema` takes two required arguments: the location of the XML document, specified by a file name, a stream, or an **XmlReader**; and a string array of XML namespaces to be ignored by the operation. + + For example, consider the following XML: + +```xml + + 1 Beverages Soft drinks and teas - - + + 1 10 0 - - -``` - - Because of the attributes specified for the elements in the preceding XML document, both the **ReadXmlSchema** method and the **ReadXml** method with an **XmlReadMode** of **InferSchema** would create tables for every element in the document: **Categories**, **CategoryID**, **CategoryName**, **Description**, **Products**, **ProductID**, **ReorderLevel**, and **Discontinued**. (For more information, see [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md).) However, a more appropriate structure would be to create only the **Categories** and **Products** tables, and then to create **CategoryID**, **CategoryName**, and **Description** columns in the **Categories** table, and **ProductID**, **ReorderLevel**, and **Discontinued** columns in the **Products** table. To ensure that the inferred schema ignores the attributes specified in the XML elements, use the **InferXmlSchema** method and specify the XML namespace for **officedata** to be ignored, as shown in the following example. - -```vb -Dim dataSet As DataSet = New DataSet -dataSet.InferXmlSchema("input_od.xml", New String() {"urn:schemas-microsoft-com:officedata"}) -``` - -```csharp -DataSet dataSet = new DataSet(); -dataSet.InferXmlSchema("input_od.xml", new string[] "urn:schemas-microsoft-com:officedata"); -``` - + + +``` + + Because of the attributes specified for the elements in the preceding XML document, both the `ReadXmlSchema` method and the `ReadXml` method with an `XmlReadMode` of `InferSchema` would create tables for every element in the document: **Categories**, **CategoryID**, **CategoryName**, **Description**, **Products**, **ProductID**, **ReorderLevel**, and **Discontinued**. (For more information, see [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md).) However, a more appropriate structure would be to create only the `Categories` and `Products` tables, and then to create **CategoryID**, **CategoryName**, and `Description` columns in the `Categories` table, and **ProductID**, **ReorderLevel**, and `Discontinued` columns in the `Products` table. To ensure that the inferred schema ignores the attributes specified in the XML elements, use the `InferXmlSchema` method and specify the XML namespace for `officedata` to be ignored, as shown in the following example. + +```vb +Dim dataSet As DataSet = New DataSet +dataSet.InferXmlSchema("input_od.xml", New String() {"urn:schemas-microsoft-com:officedata"}) +``` + +```csharp +DataSet dataSet = new DataSet(); +dataSet.InferXmlSchema("input_od.xml", new string[] "urn:schemas-microsoft-com:officedata"); +``` + ## See also - [Using XML in a DataSet](using-xml-in-a-dataset.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/managing-dataviews.md b/docs/framework/data/adonet/dataset-datatable-dataview/managing-dataviews.md index 9f39607d199d1..bd7aed6c9047e 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/managing-dataviews.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/managing-dataviews.md @@ -2,119 +2,119 @@ description: "Learn more about: Managing DataViews" title: "Managing DataViews" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 0b67fab5-1722-4d2b-bfc1-247a75f0f1ee --- # Managing DataViews -You can use a to manage view settings for all the tables in a . If you have a control that you want to bind to multiple tables, such as a grid that navigates relationships, a **DataViewManager** is ideal. - - The **DataViewManager** contains a collection of objects that are used to set the view setting of the tables in the . The contains one object for each table in a **DataSet**. You can set the default **ApplyDefaultSort**, **Sort**, **RowFilter**, and **RowStateFilter** properties of the referenced table by using its **DataViewSetting**. You can reference the **DataViewSetting** for a particular table by name or ordinal reference, or by passing a reference to that specific table object. You can access the collection of **DataViewSetting** objects in a **DataViewManager** by using the **DataViewSettings** property. - - The following code example fills a **DataSet** with the SQL Server **Northwind** database tables **Customers**, **Orders**, and **Order Details**, creates the relationships between the tables, uses a **DataViewManager** to set default **DataView** settings, and binds a **DataGrid** to the **DataViewManager**. The example sets the default **DataView** settings for all tables in the **DataSet** to sort by the primary key of the table (**ApplyDefaultSort** = **true**), and then modifies the sort order of the **Customers** table to sort by **CompanyName**. - -```vb -' Assumes connection is a valid SqlConnection to Northwind. -' Create a Connection, DataAdapters, and a DataSet. -Dim custDA As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT CustomerID, CompanyName FROM Customers", connection) -Dim orderDA As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT OrderID, CustomerID FROM Orders", connection) -Dim ordDetDA As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT OrderID, ProductID, Quantity FROM [Order Details]", connection) - -Dim custDS As DataSet = New DataSet() - -' Open the Connection. -connection.Open() - - ' Fill the DataSet with schema information and data. - custDA.MissingSchemaAction = MissingSchemaAction.AddWithKey - orderDA.MissingSchemaAction = MissingSchemaAction.AddWithKey - ordDetDA.MissingSchemaAction = MissingSchemaAction.AddWithKey - - custDA.Fill(custDS, "Customers") - orderDA.Fill(custDS, "Orders") - ordDetDA.Fill(custDS, "OrderDetails") - - ' Close the Connection. - connection.Close() - - ' Create relationships. - custDS.Relations.Add("CustomerOrders", _ - custDS.Tables("Customers").Columns("CustomerID"), _ - custDS.Tables("Orders").Columns("CustomerID")) - - custDS.Relations.Add("OrderDetails", _ - custDS.Tables("Orders").Columns("OrderID"), _ - custDS.Tables("OrderDetails").Columns("OrderID")) - -' Create default DataView settings. -Dim viewManager As DataViewManager = New DataViewManager(custDS) - -Dim viewSetting As DataViewSetting -For Each viewSetting In viewManager.DataViewSettings - viewSetting.ApplyDefaultSort = True -Next - -viewManager.DataViewSettings("Customers").Sort = "CompanyName" - -' Bind to a DataGrid. -Dim grid As System.Windows.Forms.DataGrid = New System.Windows.Forms.DataGrid() -grid.SetDataBinding(viewManager, "Customers") -``` - -```csharp -// Assumes connection is a valid SqlConnection to Northwind. -// Create a Connection, DataAdapters, and a DataSet. -SqlDataAdapter custDA = new SqlDataAdapter( - "SELECT CustomerID, CompanyName FROM Customers", connection); -SqlDataAdapter orderDA = new SqlDataAdapter( - "SELECT OrderID, CustomerID FROM Orders", connection); -SqlDataAdapter ordDetDA = new SqlDataAdapter( - "SELECT OrderID, ProductID, Quantity FROM [Order Details]", connection); - -DataSet custDS = new DataSet(); - -// Open the Connection. -connection.Open(); - - // Fill the DataSet with schema information and data. - custDA.MissingSchemaAction = MissingSchemaAction.AddWithKey; - orderDA.MissingSchemaAction = MissingSchemaAction.AddWithKey; - ordDetDA.MissingSchemaAction = MissingSchemaAction.AddWithKey; - - custDA.Fill(custDS, "Customers"); - orderDA.Fill(custDS, "Orders"); - ordDetDA.Fill(custDS, "OrderDetails"); - - // Close the Connection. - connection.Close(); - - // Create relationships. - custDS.Relations.Add("CustomerOrders", - custDS.Tables["Customers"].Columns["CustomerID"], - custDS.Tables["Orders"].Columns["CustomerID"]); - - custDS.Relations.Add("OrderDetails", - custDS.Tables["Orders"].Columns["OrderID"], - custDS.Tables["OrderDetails"].Columns["OrderID"]); - -// Create default DataView settings. -DataViewManager viewManager = new DataViewManager(custDS); - -foreach (DataViewSetting viewSetting in viewManager.DataViewSettings) - viewSetting.ApplyDefaultSort = true; - -viewManager.DataViewSettings["Customers"].Sort = "CompanyName"; - -// Bind to a DataGrid. -System.Windows.Forms.DataGrid grid = new System.Windows.Forms.DataGrid(); -grid.SetDataBinding(viewManager, "Customers"); -``` - +You can use a to manage view settings for all the tables in a . If you have a control that you want to bind to multiple tables, such as a grid that navigates relationships, a `DataViewManager` is ideal. + + The `DataViewManager` contains a collection of objects that are used to set the view setting of the tables in the . The contains one object for each table in a **DataSet**. You can set the default **ApplyDefaultSort**, **Sort**, **RowFilter**, and `RowStateFilter` properties of the referenced table by using its **DataViewSetting**. You can reference the `DataViewSetting` for a particular table by name or ordinal reference, or by passing a reference to that specific table object. You can access the collection of `DataViewSetting` objects in a `DataViewManager` by using the `DataViewSettings` property. + + The following code example fills a `DataSet` with the SQL Server `Northwind` database tables **Customers**, **Orders**, and **Order Details**, creates the relationships between the tables, uses a `DataViewManager` to set default `DataView` settings, and binds a `DataGrid` to the **DataViewManager**. The example sets the default `DataView` settings for all tables in the `DataSet` to sort by the primary key of the table (**ApplyDefaultSort** = **true**), and then modifies the sort order of the `Customers` table to sort by **CompanyName**. + +```vb +' Assumes connection is a valid SqlConnection to Northwind. +' Create a Connection, DataAdapters, and a DataSet. +Dim custDA As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT CustomerID, CompanyName FROM Customers", connection) +Dim orderDA As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT OrderID, CustomerID FROM Orders", connection) +Dim ordDetDA As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT OrderID, ProductID, Quantity FROM [Order Details]", connection) + +Dim custDS As DataSet = New DataSet() + +' Open the Connection. +connection.Open() + + ' Fill the DataSet with schema information and data. + custDA.MissingSchemaAction = MissingSchemaAction.AddWithKey + orderDA.MissingSchemaAction = MissingSchemaAction.AddWithKey + ordDetDA.MissingSchemaAction = MissingSchemaAction.AddWithKey + + custDA.Fill(custDS, "Customers") + orderDA.Fill(custDS, "Orders") + ordDetDA.Fill(custDS, "OrderDetails") + + ' Close the Connection. + connection.Close() + + ' Create relationships. + custDS.Relations.Add("CustomerOrders", _ + custDS.Tables("Customers").Columns("CustomerID"), _ + custDS.Tables("Orders").Columns("CustomerID")) + + custDS.Relations.Add("OrderDetails", _ + custDS.Tables("Orders").Columns("OrderID"), _ + custDS.Tables("OrderDetails").Columns("OrderID")) + +' Create default DataView settings. +Dim viewManager As DataViewManager = New DataViewManager(custDS) + +Dim viewSetting As DataViewSetting +For Each viewSetting In viewManager.DataViewSettings + viewSetting.ApplyDefaultSort = True +Next + +viewManager.DataViewSettings("Customers").Sort = "CompanyName" + +' Bind to a DataGrid. +Dim grid As System.Windows.Forms.DataGrid = New System.Windows.Forms.DataGrid() +grid.SetDataBinding(viewManager, "Customers") +``` + +```csharp +// Assumes connection is a valid SqlConnection to Northwind. +// Create a Connection, DataAdapters, and a DataSet. +SqlDataAdapter custDA = new SqlDataAdapter( + "SELECT CustomerID, CompanyName FROM Customers", connection); +SqlDataAdapter orderDA = new SqlDataAdapter( + "SELECT OrderID, CustomerID FROM Orders", connection); +SqlDataAdapter ordDetDA = new SqlDataAdapter( + "SELECT OrderID, ProductID, Quantity FROM [Order Details]", connection); + +DataSet custDS = new DataSet(); + +// Open the Connection. +connection.Open(); + + // Fill the DataSet with schema information and data. + custDA.MissingSchemaAction = MissingSchemaAction.AddWithKey; + orderDA.MissingSchemaAction = MissingSchemaAction.AddWithKey; + ordDetDA.MissingSchemaAction = MissingSchemaAction.AddWithKey; + + custDA.Fill(custDS, "Customers"); + orderDA.Fill(custDS, "Orders"); + ordDetDA.Fill(custDS, "OrderDetails"); + + // Close the Connection. + connection.Close(); + + // Create relationships. + custDS.Relations.Add("CustomerOrders", + custDS.Tables["Customers"].Columns["CustomerID"], + custDS.Tables["Orders"].Columns["CustomerID"]); + + custDS.Relations.Add("OrderDetails", + custDS.Tables["Orders"].Columns["OrderID"], + custDS.Tables["OrderDetails"].Columns["OrderID"]); + +// Create default DataView settings. +DataViewManager viewManager = new DataViewManager(custDS); + +foreach (DataViewSetting viewSetting in viewManager.DataViewSettings) + viewSetting.ApplyDefaultSort = true; + +viewManager.DataViewSettings["Customers"].Sort = "CompanyName"; + +// Bind to a DataGrid. +System.Windows.Forms.DataGrid grid = new System.Windows.Forms.DataGrid(); +grid.SetDataBinding(viewManager, "Customers"); +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/manipulating-data-in-a-datatable.md b/docs/framework/data/adonet/dataset-datatable-dataview/manipulating-data-in-a-datatable.md index a2803fbb1dac4..10894d23ff070 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/manipulating-data-in-a-datatable.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/manipulating-data-in-a-datatable.md @@ -6,34 +6,34 @@ ms.assetid: 5cb86d48-a987-4af4-80e0-8cc2c8373d62 --- # Manipulating Data in a DataTable -After creating a in a , you can perform the same activities that you would when using a table in a database. You can add, view, edit, and delete data in the table; you can monitor errors and events; and you can query the data in the table. When modifying data in a **DataTable**, you can also verify whether the changes are accurate, and determine whether to programmatically accept or reject the changes. - -## In This Section - - [Adding Data to a DataTable](adding-data-to-a-datatable.md) - Explains how to create new rows and add them to a table. - - [Viewing Data in a DataTable](viewing-data-in-a-datatable.md) - Describes how to access the data in a row, including original and current versions of the data. - - [The Load Method](the-load-method.md) - Describes the use of the **Load** method to fill a **DataTable** with rows. - - [DataTable Edits](datatable-edits.md) - Explains how to modify the data in a row, including suspending the changes to a row until the proposed changes are verified and accepted. - - [Row States and Row Versions](row-states-and-row-versions.md) - Provides information about the different states of a row. - - [DataRow Deletion](datarow-deletion.md) - Describes how to remove a row from a table. - - [Row Error Information](row-error-information.md) - Explains how to insert error information per row, to help resolve problems with the data within an application. - - [AcceptChanges and RejectChanges](acceptchanges-and-rejectchanges.md) - Explains how to accept or reject the changes made to a row. - +After creating a in a , you can perform the same activities that you would when using a table in a database. You can add, view, edit, and delete data in the table; you can monitor errors and events; and you can query the data in the table. When modifying data in a **DataTable**, you can also verify whether the changes are accurate, and determine whether to programmatically accept or reject the changes. + +## In This Section + + [Adding Data to a DataTable](adding-data-to-a-datatable.md) + Explains how to create new rows and add them to a table. + + [Viewing Data in a DataTable](viewing-data-in-a-datatable.md) + Describes how to access the data in a row, including original and current versions of the data. + + [The Load Method](the-load-method.md) + Describes the use of the `Load` method to fill a `DataTable` with rows. + + [DataTable Edits](datatable-edits.md) + Explains how to modify the data in a row, including suspending the changes to a row until the proposed changes are verified and accepted. + + [Row States and Row Versions](row-states-and-row-versions.md) + Provides information about the different states of a row. + + [DataRow Deletion](datarow-deletion.md) + Describes how to remove a row from a table. + + [Row Error Information](row-error-information.md) + Explains how to insert error information per row, to help resolve problems with the data within an application. + + [AcceptChanges and RejectChanges](acceptchanges-and-rejectchanges.md) + Explains how to accept or reject the changes made to a row. + ## See also - [DataTables](datatables.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/map-implicit-relations-between-nested-schema-elements.md b/docs/framework/data/adonet/dataset-datatable-dataview/map-implicit-relations-between-nested-schema-elements.md index 2df9fe3591afa..609456d0a524a 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/map-implicit-relations-between-nested-schema-elements.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/map-implicit-relations-between-nested-schema-elements.md @@ -6,93 +6,93 @@ ms.assetid: 6b25002a-352e-4d9b-bae3-15129458a355 --- # Map Implicit Relations Between Nested Schema Elements -An XML Schema definition language (XSD) schema can have complex types nested inside one another. In this case, the mapping process applies default mapping and creates the following in the : - -- One table for each of the complex types (parent and child). - -- If no unique constraint exists on the parent, one additional primary key column per table definition named *TableName*_Id where *TableName* is the name of the parent table. - -- A primary key constraint on the parent table identifying the additional column as the primary key (by setting the **IsPrimaryKey** property to **True**). The constraint is named Constraint\# where \# is 1, 2, 3, and so on. For example, the default name for the first constraint is Constraint1. - -- A foreign key constraint on the child table identifying the additional column as the foreign key referring to the primary key of the parent table. The constraint is named *ParentTable_ChildTable* where *ParentTable* is the name of the parent table and *ChildTable* is the name of the child table. - -- A data relation between the parent and child tables. - - The following example shows a schema where **OrderDetail** is a child element of **Order**. - -```xml +An XML Schema definition language (XSD) schema can have complex types nested inside one another. In this case, the mapping process applies default mapping and creates the following in the : + +- One table for each of the complex types (parent and child). + +- If no unique constraint exists on the parent, one additional primary key column per table definition named *TableName*_Id where *TableName* is the name of the parent table. + +- A primary key constraint on the parent table identifying the additional column as the primary key (by setting the `IsPrimaryKey` property to **True**). The constraint is named Constraint\# where \# is 1, 2, 3, and so on. For example, the default name for the first constraint is Constraint1. + +- A foreign key constraint on the child table identifying the additional column as the foreign key referring to the primary key of the parent table. The constraint is named *ParentTable_ChildTable* where *ParentTable* is the name of the parent table and *ChildTable* is the name of the child table. + +- A data relation between the parent and child tables. + + The following example shows a schema where `OrderDetail` is a child element of **Order**. + +```xml - - - - - - - - - - - - - - - - - - - - - - - - -``` - - The XML Schema mapping process creates the following in the **DataSet**: - -- An **Order** and an **OrderDetail** table. - - ```text - Order(OrderNumber, EmpNumber, Order_Id) - OrderDetail(OrderNo, ItemNo, Order_Id) - ``` - -- A unique constraint on the **Order** table. Note that the **IsPrimaryKey** property is set to **True**. - - ```text - ConstraintName: Constraint1 - Type: UniqueConstraint - Table: Order + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + + + + + + + + + + + + + + + + + + + + + + + + +``` + + The XML Schema mapping process creates the following in the **DataSet**: + +- An `Order` and an `OrderDetail` table. + + ```text + Order(OrderNumber, EmpNumber, Order_Id) + OrderDetail(OrderNo, ItemNo, Order_Id) + ``` + +- A unique constraint on the `Order` table. Note that the `IsPrimaryKey` property is set to **True**. + + ```text + ConstraintName: Constraint1 + Type: UniqueConstraint + Table: Order Columns: Order_Id - IsPrimaryKey: True - ``` - -- A foreign key constraint on the **OrderDetail** table. - - ```text - ConstraintName: Order_OrderDetail - Type: ForeignKeyConstraint - Table: OrderDetail + IsPrimaryKey: True + ``` + +- A foreign key constraint on the `OrderDetail` table. + + ```text + ConstraintName: Order_OrderDetail + Type: ForeignKeyConstraint + Table: OrderDetail Columns: Order_Id - RelatedTable: Order + RelatedTable: Order RelatedColumns: Order_Id - ``` - -- A relationship between the **Order** and **OrderDetail** tables. The **Nested** property for this relationship is set to **True** because the **Order** and **OrderDetail** elements are nested in the schema. - - ```text - ParentTable: Order + ``` + +- A relationship between the `Order` and `OrderDetail` tables. The `Nested` property for this relationship is set to `True` because the `Order` and `OrderDetail` elements are nested in the schema. + + ```text + ParentTable: Order ParentColumns: Order_Id - ChildTable: OrderDetail + ChildTable: OrderDetail ChildColumns: Order_Id - ParentKeyConstraint: Constraint1 - ChildKeyConstraint: Order_OrderDetail - RelationName: Order_OrderDetail - Nested: True - ``` - + ParentKeyConstraint: Constraint1 + ChildKeyConstraint: Order_OrderDetail + RelationName: Order_OrderDetail + Nested: True + ``` + ## See also - [Generating DataSet Relations from XML Schema (XSD)](generating-dataset-relations-from-xml-schema-xsd.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/map-key-xml-schema-xsd-constraints-to-dataset-constraints.md b/docs/framework/data/adonet/dataset-datatable-dataview/map-key-xml-schema-xsd-constraints-to-dataset-constraints.md index baed5b67312bf..5418e957d510a 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/map-key-xml-schema-xsd-constraints-to-dataset-constraints.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/map-key-xml-schema-xsd-constraints-to-dataset-constraints.md @@ -6,74 +6,74 @@ ms.assetid: 22664196-f270-4ebc-a169-70e16a83dfa1 --- # Map key XML Schema (XSD) Constraints to DataSet Constraints -In a schema, you can specify a key constraint on an element or attribute using the **key** element. The element or attribute on which a key constraint is specified must have unique values in any schema instance, and cannot have null values. - - The key constraint is similar to the unique constraint, except that the column on which a key constraint is defined cannot have null values. - - The following table outlines the **msdata** attributes that you can specify in the **key** element. - -|Attribute name|Description| -|--------------------|-----------------| -|**msdata:ConstraintName**|If this attribute is specified, its value is used as the constraint name. Otherwise, the **name** attribute provides the value of the constraint name.| -|**msdata:PrimaryKey**|If `PrimaryKey="true"` is present, the **IsPrimaryKey** constraint property is set to **true**, thus making it a primary key. The **AllowDBNull** column property is set to **false**, because primary keys cannot have null values.| - - In converting schema in which a key constraint is specified, the mapping process creates a unique constraint on the table with the **AllowDBNull** column property set to **false** for each column in the constraint. The **IsPrimaryKey** property of the unique constraint is also set to **false** unless you have specified `msdata:PrimaryKey="true"` on the **key** element. This is identical to a unique constraint in the schema in which `PrimaryKey="true"`. - - In the following schema example, the **key** element specifies the key constraint on the **CustomerID** element. - -```xml - - - - - - - - - - - - - - - - - - - - - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + + + + + + + + + + + + + + + + + + + + -``` - - The **key** element specifies that the values of the **CustomerID** child element of the **Customers** element must have unique values and cannot have null values. In translating the XML Schema definition language (XSD) schema, the mapping process creates the following table: - -```text -Customers(CustomerID, CompanyName, Phone) -``` - - The XML Schema mapping also creates a **UniqueConstraint** on the **CustomerID** column, as shown in the following . (For simplicity, only relevant properties are shown.) - -```text - DataSetName: MyDataSet -TableName: customers - ColumnName: CustomerID - AllowDBNull: False - Unique: True - ConstraintName: KeyCustID - Table: customers +``` + + The `key` element specifies that the values of the `CustomerID` child element of the `Customers` element must have unique values and cannot have null values. In translating the XML Schema definition language (XSD) schema, the mapping process creates the following table: + +```text +Customers(CustomerID, CompanyName, Phone) +``` + + The XML Schema mapping also creates a `UniqueConstraint` on the `CustomerID` column, as shown in the following . (For simplicity, only relevant properties are shown.) + +```text + DataSetName: MyDataSet +TableName: customers + ColumnName: CustomerID + AllowDBNull: False + Unique: True + ConstraintName: KeyCustID + Table: customers Columns: CustomerID - IsPrimaryKey: True -``` - - In the **DataSet** that is generated, the **IsPrimaryKey** property of the **UniqueConstraint** is set to **true** because the schema specifies `msdata:PrimaryKey="true"` in the **key** element. - - The value of the **ConstraintName** property of the **UniqueConstraint** in the **DataSet** is the value of the **msdata:ConstraintName** attribute specified in the **key** element in the schema. - + IsPrimaryKey: True +``` + + In the `DataSet` that is generated, the `IsPrimaryKey` property of the `UniqueConstraint` is set to `true` because the schema specifies `msdata:PrimaryKey="true"` in the `key` element. + + The value of the `ConstraintName` property of the `UniqueConstraint` in the `DataSet` is the value of the `msdata:ConstraintName` attribute specified in the `key` element in the schema. + ## See also - [Mapping XML Schema (XSD) Constraints to DataSet Constraints](mapping-xml-schema-xsd-constraints-to-dataset-constraints.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/map-keyref-xml-schema-xsd-constraints-to-dataset-constraints.md b/docs/framework/data/adonet/dataset-datatable-dataview/map-keyref-xml-schema-xsd-constraints-to-dataset-constraints.md index 93cd527da1748..9b88286a421d9 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/map-keyref-xml-schema-xsd-constraints-to-dataset-constraints.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/map-keyref-xml-schema-xsd-constraints-to-dataset-constraints.md @@ -6,105 +6,105 @@ ms.assetid: 5b634fea-cc1e-4f6b-9454-10858105b1c8 --- # Map keyref XML Schema (XSD) Constraints to DataSet Constraints -The **keyref** element allows you to establish links between elements within a document. This is similar to a foreign key relationship in a relational database. If a schema specifies the **keyref** element, the element is converted during the schema mapping process to a corresponding foreign key constraint on the columns in the tables of the . By default, the **keyref** element also generates a relation, with the **ParentTable**, **ChildTable**, **ParentColumn**, and **ChildColumn** properties specified on the relation. - - The following table outlines the **msdata** attributes you can specify in the **keyref** element. - -|Attribute name|Description| -|--------------------|-----------------| -|**msdata:ConstraintOnly**|If **ConstraintOnly="true"** is specified on the **keyref** element in the schema, a constraint is created, but no relation is created. If this attribute is not specified (or is set to **False**), both the constraint and the relation are created in the **DataSet**.| -|**msdata:ConstraintName**|If the **ConstraintName** attribute is specified, its value is used as the name of the constraint. Otherwise, the **name** attribute of the **keyref** element in the schema provides the constraint name in the **DataSet**.| -|**msdata:UpdateRule**|If the **UpdateRule** attribute is specified in the **keyref** element in the schema, its value is assigned to the **UpdateRule** constraint property in the **DataSet**. Otherwise the **UpdateRule** property is set to **Cascade**.| -|**msdata:DeleteRule**|If the **DeleteRule** attribute is specified in the **keyref** element in the schema, its value is assigned to the **DeleteRule** constraint property in the **DataSet**. Otherwise the **DeleteRule** property is set to **Cascade**.| -|**msdata:AcceptRejectRule**|If the **AcceptRejectRule** attribute is specified in the **keyref** element in the schema, its value is assigned to the **AcceptRejectRule** constraint property in the **DataSet**. Otherwise the **AcceptRejectRule** property is set to **None**.| - - The following example contains a schema that specifies the **key** and **keyref** relationships between the **OrderNumber** child element of the **Order** element and the **OrderNo** child element of the **OrderDetail** element. - - In the example, the **OrderNumber** child element of the **OrderDetail** element refers to the **OrderNo** key child element of the **Order** element. - -```xml +The `keyref` element allows you to establish links between elements within a document. This is similar to a foreign key relationship in a relational database. If a schema specifies the `keyref` element, the element is converted during the schema mapping process to a corresponding foreign key constraint on the columns in the tables of the . By default, the `keyref` element also generates a relation, with the **ParentTable**, **ChildTable**, **ParentColumn**, and `ChildColumn` properties specified on the relation. + + The following table outlines the `msdata` attributes you can specify in the `keyref` element. + +|Attribute name|Description| +|--------------------|-----------------| +|**msdata:ConstraintOnly**|If **ConstraintOnly="true"** is specified on the `keyref` element in the schema, a constraint is created, but no relation is created. If this attribute is not specified (or is set to **False**), both the constraint and the relation are created in the **DataSet**.| +|**msdata:ConstraintName**|If the `ConstraintName` attribute is specified, its value is used as the name of the constraint. Otherwise, the `name` attribute of the `keyref` element in the schema provides the constraint name in the **DataSet**.| +|**msdata:UpdateRule**|If the `UpdateRule` attribute is specified in the `keyref` element in the schema, its value is assigned to the `UpdateRule` constraint property in the **DataSet**. Otherwise the `UpdateRule` property is set to **Cascade**.| +|**msdata:DeleteRule**|If the `DeleteRule` attribute is specified in the `keyref` element in the schema, its value is assigned to the `DeleteRule` constraint property in the **DataSet**. Otherwise the `DeleteRule` property is set to **Cascade**.| +|**msdata:AcceptRejectRule**|If the `AcceptRejectRule` attribute is specified in the `keyref` element in the schema, its value is assigned to the `AcceptRejectRule` constraint property in the **DataSet**. Otherwise the `AcceptRejectRule` property is set to **None**.| + + The following example contains a schema that specifies the `key` and `keyref` relationships between the `OrderNumber` child element of the `Order` element and the `OrderNo` child element of the `OrderDetail` element. + + In the example, the `OrderNumber` child element of the `OrderDetail` element refers to the `OrderNo` key child element of the `Order` element. + +```xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -``` - - The XML Schema definition language (XSD) schema mapping process produces the following **DataSet** with two tables: - -```text -OrderDetail(OrderNo, ItemNo) and -Order(OrderNumber, EmpNumber) -``` - - In addition, the **DataSet** defines the following constraints: - -- A unique constraint on the **Order** table. - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + + The XML Schema definition language (XSD) schema mapping process produces the following `DataSet` with two tables: + +```text +OrderDetail(OrderNo, ItemNo) and +Order(OrderNumber, EmpNumber) +``` + + In addition, the `DataSet` defines the following constraints: + +- A unique constraint on the `Order` table. + ```text - Table: Order + Table: Order Columns: OrderNumber - ConstraintName: OrderNumberKey - Type: UniqueConstraint - IsPrimaryKey: False - ``` - -- A relationship between the **Order** and **OrderDetail** tables. The **Nested** property is set to **False** because the two elements are not nested in the schema. - + ConstraintName: OrderNumberKey + Type: UniqueConstraint + IsPrimaryKey: False + ``` + +- A relationship between the `Order` and `OrderDetail` tables. The `Nested` property is set to `False` because the two elements are not nested in the schema. + ```text - ParentTable: Order + ParentTable: Order ParentColumns: OrderNumber - ChildTable: OrderDetail + ChildTable: OrderDetail ChildColumns: OrderNo - ParentKeyConstraint: OrderNumberKey - ChildKeyConstraint: OrderNoRef - RelationName: OrderNoRef - Nested: False - ``` - -- A foreign key constraint on the **OrderDetail** table. - - ```text - ConstraintName: OrderNoRef - Type: ForeignKeyConstraint - Table: OrderDetail + ParentKeyConstraint: OrderNumberKey + ChildKeyConstraint: OrderNoRef + RelationName: OrderNoRef + Nested: False + ``` + +- A foreign key constraint on the `OrderDetail` table. + + ```text + ConstraintName: OrderNoRef + Type: ForeignKeyConstraint + Table: OrderDetail Columns: OrderNo - RelatedTable: Order + RelatedTable: Order RelatedColumns: OrderNumber - ``` - + ``` + ## See also - [Mapping XML Schema (XSD) Constraints to DataSet Constraints](mapping-xml-schema-xsd-constraints-to-dataset-constraints.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/map-relations-specified-for-nested-elements.md b/docs/framework/data/adonet/dataset-datatable-dataview/map-relations-specified-for-nested-elements.md index 968a40a926581..fbba69724e437 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/map-relations-specified-for-nested-elements.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/map-relations-specified-for-nested-elements.md @@ -6,70 +6,70 @@ ms.assetid: 24a2d3e5-4af7-4f9a-ab7a-fe6684c9e4fe --- # Map Relations Specified for Nested Elements -A schema can include an **msdata:Relationship** annotation to explicitly specify the mapping between any two elements in the schema. The two elements specified in **msdata:Relationship** can be nested in the schema, but do not have to be. The mapping process uses **msdata:Relationship** in the schema to generate the primary key/foreign key relationship between the two columns. - - The following example shows an XML Schema in which the **OrderDetail** element is a child element of **Order**. The **msdata:Relationship** identifies this parent-child relationship and specifies that the **OrderNumber** column of the resulting **Order** table is related to the **OrderNo** column of the resulting **OrderDetail** table. - -```xml +A schema can include an **msdata:Relationship** annotation to explicitly specify the mapping between any two elements in the schema. The two elements specified in **msdata:Relationship** can be nested in the schema, but do not have to be. The mapping process uses **msdata:Relationship** in the schema to generate the primary key/foreign key relationship between the two columns. + + The following example shows an XML Schema in which the `OrderDetail` element is a child element of **Order**. The **msdata:Relationship** identifies this parent-child relationship and specifies that the `OrderNumber` column of the resulting `Order` table is related to the `OrderNo` column of the resulting `OrderDetail` table. + +```xml - - - - - - - - - - - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + + + + + + + + + + + - - - - - - - - - - - - - - - - -``` - - The XML Schema mapping process creates the following in the : - -- An **Order** and an **OrderDetail** table. - - ```text - Order(OrderNumber, EmpNumber) - OrderDetail(OrderNo, ItemNo) - ``` - -- A relationship between the **Order** and **OrderDetail** tables. The **Nested** property for this relationship is set to **True** because the **Order** and **OrderDetail** elements are nested in the schema. - - ```text - ParentTable: Order + msdata:childkey="OrderNo"/> + + + + + + + + +
+ + +
+ + + + +``` + + The XML Schema mapping process creates the following in the : + +- An `Order` and an `OrderDetail` table. + + ```text + Order(OrderNumber, EmpNumber) + OrderDetail(OrderNo, ItemNo) + ``` + +- A relationship between the `Order` and `OrderDetail` tables. The `Nested` property for this relationship is set to `True` because the `Order` and `OrderDetail` elements are nested in the schema. + + ```text + ParentTable: Order ParentColumns: OrderNumber - ChildTable: OrderDetail + ChildTable: OrderDetail ChildColumns: OrderNo - RelationName: OrdODRelation - Nested: True - ``` - - The mapping process does not create any constraints. - + RelationName: OrdODRelation + Nested: True + ``` + + The mapping process does not create any constraints. + ## See also - [Generating DataSet Relations from XML Schema (XSD)](generating-dataset-relations-from-xml-schema-xsd.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/map-unique-xml-schema-xsd-constraints-to-dataset-constraints.md b/docs/framework/data/adonet/dataset-datatable-dataview/map-unique-xml-schema-xsd-constraints-to-dataset-constraints.md index d187540826e2a..990b42215aa36 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/map-unique-xml-schema-xsd-constraints-to-dataset-constraints.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/map-unique-xml-schema-xsd-constraints-to-dataset-constraints.md @@ -6,89 +6,89 @@ ms.assetid: 56da90bf-21d3-4d1a-8bb8-de908866b78d --- # Map unique XML Schema (XSD) Constraints to DataSet Constraints -In an XML Schema definition language (XSD) schema, the **unique** element specifies the uniqueness constraint on an element or attribute. In the process of translating an XML Schema into a relational schema, the unique constraint specified on an element or attribute in the XML Schema is mapped to a unique constraint in the in the corresponding that is generated. - - The following table outlines the **msdata** attributes that you can specify in the **unique** element. - -|Attribute name|Description| -|--------------------|-----------------| -|**msdata:ConstraintName**|If this attribute is specified, its value is used as the constraint name. Otherwise, the **name** attribute provides the value of the constraint name.| -|**msdata:PrimaryKey**|If `PrimaryKey="true"` is present in the **unique** element, a unique constraint is created with the **IsPrimaryKey** property set to **true**.| - - The following example shows an XML Schema that uses the **unique** element to specify a uniqueness constraint. - -```xml +In an XML Schema definition language (XSD) schema, the `unique` element specifies the uniqueness constraint on an element or attribute. In the process of translating an XML Schema into a relational schema, the unique constraint specified on an element or attribute in the XML Schema is mapped to a unique constraint in the in the corresponding that is generated. + + The following table outlines the `msdata` attributes that you can specify in the `unique` element. + +|Attribute name|Description| +|--------------------|-----------------| +|**msdata:ConstraintName**|If this attribute is specified, its value is used as the constraint name. Otherwise, the `name` attribute provides the value of the constraint name.| +|**msdata:PrimaryKey**|If `PrimaryKey="true"` is present in the `unique` element, a unique constraint is created with the `IsPrimaryKey` property set to **true**.| + + The following example shows an XML Schema that uses the `unique` element to specify a uniqueness constraint. + +```xml - - - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + + + + minOccurs="0"/> - - - - - - - - - - - - - - -``` - - The **unique** element in the schema specifies that for all **Customers** elements in a document instance, the value of the **CustomerID** child element must be unique. In building the **DataSet**, the mapping process reads this schema and generates the following table: - -```text -Customers (CustomerID, CompanyName, Phone) -``` - - The mapping process also creates a unique constraint on the **CustomerID** column, as shown in the following **DataSet**. (For simplicity, only relevant properties are shown.) - -```text - DataSetName: MyDataSet -TableName: Customers - ColumnName: CustomerID - AllowDBNull: True - Unique: True - ConstraintName: UcustID Type: UniqueConstraint - Table: Customers + minOccurs="0"/> + + + + + + + + + + + + + + +``` + + The `unique` element in the schema specifies that for all `Customers` elements in a document instance, the value of the `CustomerID` child element must be unique. In building the **DataSet**, the mapping process reads this schema and generates the following table: + +```text +Customers (CustomerID, CompanyName, Phone) +``` + + The mapping process also creates a unique constraint on the `CustomerID` column, as shown in the following **DataSet**. (For simplicity, only relevant properties are shown.) + +```text + DataSetName: MyDataSet +TableName: Customers + ColumnName: CustomerID + AllowDBNull: True + Unique: True + ConstraintName: UcustID Type: UniqueConstraint + Table: Customers Columns: CustomerID - IsPrimaryKey: False -``` - - In the **DataSet** that is generated, the **IsPrimaryKey** property is set to **False** for the unique constraint. The **unique** property on the column indicates that the **CustomerID** column values must be unique (but they can be a null reference, as specified by the **AllowDBNull** property of the column). - - If you modify the schema and set the optional **msdata:PrimaryKey** attribute value to **True**, the unique constraint is created on the table. The **AllowDBNull** column property is set to **False**, and the **IsPrimaryKey** property of the constraint set to **True**, thus making the **CustomerID** column a primary key column. - - You can specify a unique constraint on a combination of elements or attributes in the XML Schema. The following example demonstrates how to specify that a combination of **CustomerID** and **CompanyName** values must be unique for all **Customers** in any instance, by adding another **xs:field** element in the schema. - -```xml + IsPrimaryKey: False +``` + + In the `DataSet` that is generated, the `IsPrimaryKey` property is set to `False` for the unique constraint. The `unique` property on the column indicates that the `CustomerID` column values must be unique (but they can be a null reference, as specified by the `AllowDBNull` property of the column). + + If you modify the schema and set the optional `msdata:PrimaryKey` attribute value to **True**, the unique constraint is created on the table. The `AllowDBNull` column property is set to **False**, and the `IsPrimaryKey` property of the constraint set to **True**, thus making the `CustomerID` column a primary key column. + + You can specify a unique constraint on a combination of elements or attributes in the XML Schema. The following example demonstrates how to specify that a combination of `CustomerID` and `CompanyName` values must be unique for all `Customers` in any instance, by adding another **xs:field** element in the schema. + +```xml - -``` - - This is the constraint that is created in the resulting **DataSet**. - -```text -ConstraintName: SomeName - Table: Customers + +``` + + This is the constraint that is created in the resulting **DataSet**. + +```text +ConstraintName: SomeName + Table: Customers Columns: CustomerID CompanyName - IsPrimaryKey: False -``` - + IsPrimaryKey: False +``` + ## See also - [Mapping XML Schema (XSD) Constraints to DataSet Constraints](mapping-xml-schema-xsd-constraints-to-dataset-constraints.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/mapping-xml-schema-xsd-constraints-to-dataset-constraints.md b/docs/framework/data/adonet/dataset-datatable-dataview/mapping-xml-schema-xsd-constraints-to-dataset-constraints.md index 02a970a827052..bcd2edb456914 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/mapping-xml-schema-xsd-constraints-to-dataset-constraints.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/mapping-xml-schema-xsd-constraints-to-dataset-constraints.md @@ -6,41 +6,41 @@ ms.assetid: 3d0d1a4b-9104-434f-ac04-6c01ab5716b5 --- # Mapping XML Schema (XSD) Constraints to DataSet Constraints -The XML Schema definition language (XSD) allows constraints to be specified on the elements and attributes it defines. When mapping an XML Schema to relational schema in a , XML Schema constraints are mapped to appropriate relational constraints on the tables and columns within the **DataSet**. - - This section discusses the mapping of the following XML Schema constraints: - -- The uniqueness constraint specified using the **unique** element. - -- The key constraint specified using the **key** element. - -- The keyref constraint specified using the **keyref** element. - - By using a constraint on an element or attribute, you specify certain restrictions on the values of the element in any instance of the document. For example, a key constraint on a **CustomerID** child element of a **Customer** element in the schema indicates that the values of the **CustomerID** child element must be unique in any document instance, and that null values are not allowed. - - Constraints can also be specified between elements and attributes in a document, in order to establish a relationship within the document. The key and keyref constraints are used in the schema to specify the constraints within the document, resulting in a relationship between document elements and attributes. - - The mapping process converts these schema constraints into appropriate constraints on the tables created within the **DataSet**. - -## In This Section - - [Map unique XML Schema (XSD) Constraints to DataSet Constraints](map-unique-xml-schema-xsd-constraints-to-dataset-constraints.md) - Describes the XML Schema elements used to create unique constraints in a **DataSet**. - - [Map key XML Schema (XSD) Constraints to DataSet Constraints](map-key-xml-schema-xsd-constraints-to-dataset-constraints.md) - Describes the XML Schema elements used to create key constraints (unique constraints where null values are not allowed) in a **DataSet**. - - [Map keyref XML Schema (XSD) Constraints to DataSet Constraints](map-keyref-xml-schema-xsd-constraints-to-dataset-constraints.md) - Describes the XML Schema elements used to create keyref (foreign key) constraints in a **DataSet**. - -## Related Sections - - [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md) - Describes the relational structure, or schema, of a **DataSet** that is created from XSD schema. - - [Generating DataSet Relations from XML Schema (XSD)](generating-dataset-relations-from-xml-schema-xsd.md) - Describes the XML Schema elements used to create relations between table columns in a **DataSet**. - +The XML Schema definition language (XSD) allows constraints to be specified on the elements and attributes it defines. When mapping an XML Schema to relational schema in a , XML Schema constraints are mapped to appropriate relational constraints on the tables and columns within the **DataSet**. + + This section discusses the mapping of the following XML Schema constraints: + +- The uniqueness constraint specified using the `unique` element. + +- The key constraint specified using the `key` element. + +- The keyref constraint specified using the `keyref` element. + + By using a constraint on an element or attribute, you specify certain restrictions on the values of the element in any instance of the document. For example, a key constraint on a `CustomerID` child element of a `Customer` element in the schema indicates that the values of the `CustomerID` child element must be unique in any document instance, and that null values are not allowed. + + Constraints can also be specified between elements and attributes in a document, in order to establish a relationship within the document. The key and keyref constraints are used in the schema to specify the constraints within the document, resulting in a relationship between document elements and attributes. + + The mapping process converts these schema constraints into appropriate constraints on the tables created within the **DataSet**. + +## In This Section + + [Map unique XML Schema (XSD) Constraints to DataSet Constraints](map-unique-xml-schema-xsd-constraints-to-dataset-constraints.md) + Describes the XML Schema elements used to create unique constraints in a **DataSet**. + + [Map key XML Schema (XSD) Constraints to DataSet Constraints](map-key-xml-schema-xsd-constraints-to-dataset-constraints.md) + Describes the XML Schema elements used to create key constraints (unique constraints where null values are not allowed) in a **DataSet**. + + [Map keyref XML Schema (XSD) Constraints to DataSet Constraints](map-keyref-xml-schema-xsd-constraints-to-dataset-constraints.md) + Describes the XML Schema elements used to create keyref (foreign key) constraints in a **DataSet**. + +## Related Sections + + [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md) + Describes the relational structure, or schema, of a `DataSet` that is created from XSD schema. + + [Generating DataSet Relations from XML Schema (XSD)](generating-dataset-relations-from-xml-schema-xsd.md) + Describes the XML Schema elements used to create relations between table columns in a **DataSet**. + ## See also - [ADO.NET Overview](../ado-net-overview.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/modifying-dataviews.md b/docs/framework/data/adonet/dataset-datatable-dataview/modifying-dataviews.md index cb39a5f0fc83e..3ad2eb59b1d2b 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/modifying-dataviews.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/modifying-dataviews.md @@ -2,51 +2,51 @@ description: "Learn more about: Modifying DataViews" title: "Modifying DataViews" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 697a3991-b660-4a5a-8a54-1a2304ff158e --- # Modifying DataViews -You can use the to add, delete, or modify rows of data in the underlying table. The ability to use the **DataView** to modify data in the underlying table is controlled by setting one of three Boolean properties of the **DataView**. These properties are , , and . They are set to **true** by default. - - If **AllowNew** is **true**, you can use the method of the **DataView** to create a new . Note that a new row is not actually added to the underlying until the method of the **DataRowView** is called. If the method of the **DataRowView** is called, the new row is discarded. Note also that you can edit only one **DataRowView** at a time. If you call the **AddNew** or **BeginEdit** method of the **DataRowView** while a pending row exists, **EndEdit** is implicitly called on the pending row. When **EndEdit** is called, the changes are applied to the underlying **DataTable** and can later be committed or rejected using the **AcceptChanges** or **RejectChanges** methods of the **DataTable**, **DataSet**, or **DataRow** object. If **AllowNew** is **false**, an exception is thrown if you call the **AddNew** method of the **DataRowView**. - - If **AllowEdit** is **true**, you can modify the contents of a **DataRow** via the **DataRowView**. You can confirm changes to the underlying row using **DataRowView.EndEdit** or reject the changes using **DataRowView.CancelEdit**. Note that only one row can be edited at a time. If you call the **AddNew** or **BeginEdit** methods of the **DataRowView** while a pending row exists, **EndEdit** is implicitly called on the pending row. When **EndEdit** is called, proposed changes are placed in the **Current** row version of the underlying **DataRow** and can later be committed or rejected using the **AcceptChanges** or **RejectChanges** methods of the **DataTable**, **DataSet**, or **DataRow** object. If **AllowEdit** is **false**, an exception is thrown if you attempt to modify a value in the **DataView**. - - When an existing **DataRowView** is being edited, events of the underlying **DataTable** will still be raised with the proposed changes. Note that if you call **EndEdit** or **CancelEdit** on the underlying **DataRow**, pending changes will be applied or canceled regardless of whether **EndEdit** or **CancelEdit** is called on the **DataRowView**. - - If **AllowDelete** is **true**, you can delete rows from the **DataView** by using the **Delete** method of the **DataView** or **DataRowView** object, and the rows are deleted from the underlying **DataTable**. You can later commit or reject the deletes using **AcceptChanges** or **RejectChanges** respectively. If **AllowDelete** is **false**, an exception is thrown if you call the **Delete** method of the **DataView** or **DataRowView**. - - The following code example disables using the **DataView** to delete rows and adds a new row to the underlying table using the **DataView**. - -```vb -Dim custTable As DataTable = custDS.Tables("Customers") -Dim custView As DataView = custTable.DefaultView -custView.Sort = "CompanyName" - -custView.AllowDelete = False - -Dim newDRV As DataRowView = custView.AddNew() -newDRV("CustomerID") = "ABCDE" -newDRV("CompanyName") = "ABC Products" -newDRV.EndEdit() -``` - -```csharp -DataTable custTable = custDS.Tables["Customers"]; -DataView custView = custTable.DefaultView; -custView.Sort = "CompanyName"; - -custView.AllowDelete = false; - -DataRowView newDRV = custView.AddNew(); -newDRV["CustomerID"] = "ABCDE"; -newDRV["CompanyName"] = "ABC Products"; -newDRV.EndEdit(); -``` - +You can use the to add, delete, or modify rows of data in the underlying table. The ability to use the `DataView` to modify data in the underlying table is controlled by setting one of three Boolean properties of the **DataView**. These properties are , , and . They are set to `true` by default. + + If `AllowNew` is **true**, you can use the method of the `DataView` to create a new . Note that a new row is not actually added to the underlying until the method of the `DataRowView` is called. If the method of the `DataRowView` is called, the new row is discarded. Note also that you can edit only one `DataRowView` at a time. If you call the `AddNew` or `BeginEdit` method of the `DataRowView` while a pending row exists, `EndEdit` is implicitly called on the pending row. When `EndEdit` is called, the changes are applied to the underlying `DataTable` and can later be committed or rejected using the `AcceptChanges` or `RejectChanges` methods of the **DataTable**, **DataSet**, or `DataRow` object. If `AllowNew` is **false**, an exception is thrown if you call the `AddNew` method of the **DataRowView**. + + If `AllowEdit` is **true**, you can modify the contents of a `DataRow` via the **DataRowView**. You can confirm changes to the underlying row using **DataRowView.EndEdit** or reject the changes using **DataRowView.CancelEdit**. Note that only one row can be edited at a time. If you call the `AddNew` or `BeginEdit` methods of the `DataRowView` while a pending row exists, `EndEdit` is implicitly called on the pending row. When `EndEdit` is called, proposed changes are placed in the `Current` row version of the underlying `DataRow` and can later be committed or rejected using the `AcceptChanges` or `RejectChanges` methods of the **DataTable**, **DataSet**, or `DataRow` object. If `AllowEdit` is **false**, an exception is thrown if you attempt to modify a value in the **DataView**. + + When an existing `DataRowView` is being edited, events of the underlying `DataTable` will still be raised with the proposed changes. Note that if you call `EndEdit` or `CancelEdit` on the underlying **DataRow**, pending changes will be applied or canceled regardless of whether `EndEdit` or `CancelEdit` is called on the **DataRowView**. + + If `AllowDelete` is **true**, you can delete rows from the `DataView` by using the `Delete` method of the `DataView` or `DataRowView` object, and the rows are deleted from the underlying **DataTable**. You can later commit or reject the deletes using `AcceptChanges` or `RejectChanges` respectively. If `AllowDelete` is **false**, an exception is thrown if you call the `Delete` method of the `DataView` or **DataRowView**. + + The following code example disables using the `DataView` to delete rows and adds a new row to the underlying table using the **DataView**. + +```vb +Dim custTable As DataTable = custDS.Tables("Customers") +Dim custView As DataView = custTable.DefaultView +custView.Sort = "CompanyName" + +custView.AllowDelete = False + +Dim newDRV As DataRowView = custView.AddNew() +newDRV("CustomerID") = "ABCDE" +newDRV("CompanyName") = "ABC Products" +newDRV.EndEdit() +``` + +```csharp +DataTable custTable = custDS.Tables["Customers"]; +DataView custView = custTable.DefaultView; +custView.Sort = "CompanyName"; + +custView.AllowDelete = false; + +DataRowView newDRV = custView.AddNew(); +newDRV["CustomerID"] = "ABCDE"; +newDRV["CompanyName"] = "ABC Products"; +newDRV.EndEdit(); +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datarelations.md b/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datarelations.md index 4e00fe9e0980b..6867a447c0510 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datarelations.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datarelations.md @@ -2,49 +2,49 @@ description: "Learn more about: Navigating DataRelations" title: "Navigating DataRelations" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: e5e673f4-9b44-45ae-aaea-c504d1cc5d3e --- # Navigating DataRelations -One of the primary functions of a is to allow navigation from one to another within a . This allows you to retrieve all the related objects in one **DataTable** when given a single **DataRow** from a related **DataTable**. For example, after establishing a **DataRelation** between a table of customers and a table of orders, you can retrieve all the order rows for a particular customer row using **GetChildRows**. - - The following code example creates a **DataRelation** between the **Customers** table and the **Orders** table of a **DataSet** and returns all the orders for each customer. - +One of the primary functions of a is to allow navigation from one to another within a . This allows you to retrieve all the related objects in one `DataTable` when given a single `DataRow` from a related **DataTable**. For example, after establishing a `DataRelation` between a table of customers and a table of orders, you can retrieve all the order rows for a particular customer row using **GetChildRows**. + + The following code example creates a `DataRelation` between the `Customers` table and the `Orders` table of a `DataSet` and returns all the orders for each customer. + [!code-csharp[DataWorks Data.DataTableRelation#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/CS/source.cs#1)] - [!code-vb[DataWorks Data.DataTableRelation#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/VB/source.vb#1)] - - The next example builds on the preceding example, relating four tables together and navigating those relationships. As in the previous example, **CustomerID** relates the **Customers** table to the **Orders** table. For each customer in the **Customers** table, all the child rows in the **Orders** table are determined, in order to return the number of orders a particular customer has and their **OrderID** values. - - The expanded example also returns the values from the **OrderDetails** and **Products** tables. The **Orders** table is related to the **OrderDetails** table using **OrderID** to determine, for each customer order, what products and quantities were ordered. Because the **OrderDetails** table only contains the **ProductID** of an ordered product, **OrderDetails** is related to **Products** using **ProductID** in order to return the **ProductName**. In this relation, the **Products** table is the parent and the **Order Details** table is the child. As a result, when iterating through the **OrderDetails** table, **GetParentRow** is called to retrieve the related **ProductName** value. - - Notice that when the **DataRelation** is created for the **Customers** and **Orders** tables, no value is specified for the **createConstraints** flag (the default is **true**). This assumes that all the rows in the **Orders** table have a **CustomerID** value that exists in the parent **Customers** table. If a **CustomerID** exists in the **Orders** table that does not exist in the **Customers** table, a causes an exception to be thrown. - - When the child column might contain values that the parent column does not contain, set the **createConstraints** flag to **false** when adding the **DataRelation**. In the example, the **createConstraints** flag is set to **false** for the **DataRelation** between the **Orders** table and the **OrderDetails** table. This enables the application to return all the records from the **OrderDetails** table and only a subset of records from the **Orders** table without generating a run-time exception. The expanded sample generates output in the following format. - -```output -Customer ID: NORTS - Order ID: 10517 - Order Date: 4/24/1997 12:00:00 AM - Product: Filo Mix - Quantity: 6 - Product: Raclette Courdavault - Quantity: 4 - Product: Outback Lager - Quantity: 6 - Order ID: 11057 - Order Date: 4/29/1998 12:00:00 AM - Product: Outback Lager - Quantity: 3 -``` - - The following code example is an expanded sample where the values from the **OrderDetails** and **Products** tables are returned, with only a subset of the records in the **Orders** table being returned. - + [!code-vb[DataWorks Data.DataTableRelation#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks Data.DataTableRelation/VB/source.vb#1)] + + The next example builds on the preceding example, relating four tables together and navigating those relationships. As in the previous example, `CustomerID` relates the `Customers` table to the `Orders` table. For each customer in the `Customers` table, all the child rows in the `Orders` table are determined, in order to return the number of orders a particular customer has and their `OrderID` values. + + The expanded example also returns the values from the `OrderDetails` and `Products` tables. The `Orders` table is related to the `OrderDetails` table using `OrderID` to determine, for each customer order, what products and quantities were ordered. Because the `OrderDetails` table only contains the `ProductID` of an ordered product, `OrderDetails` is related to `Products` using `ProductID` in order to return the **ProductName**. In this relation, the `Products` table is the parent and the **Order Details** table is the child. As a result, when iterating through the `OrderDetails` table, `GetParentRow` is called to retrieve the related `ProductName` value. + + Notice that when the `DataRelation` is created for the `Customers` and `Orders` tables, no value is specified for the `createConstraints` flag (the default is **true**). This assumes that all the rows in the `Orders` table have a `CustomerID` value that exists in the parent `Customers` table. If a `CustomerID` exists in the `Orders` table that does not exist in the `Customers` table, a causes an exception to be thrown. + + When the child column might contain values that the parent column does not contain, set the `createConstraints` flag to `false` when adding the **DataRelation**. In the example, the `createConstraints` flag is set to `false` for the `DataRelation` between the `Orders` table and the `OrderDetails` table. This enables the application to return all the records from the `OrderDetails` table and only a subset of records from the `Orders` table without generating a run-time exception. The expanded sample generates output in the following format. + +```output +Customer ID: NORTS + Order ID: 10517 + Order Date: 4/24/1997 12:00:00 AM + Product: Filo Mix + Quantity: 6 + Product: Raclette Courdavault + Quantity: 4 + Product: Outback Lager + Quantity: 6 + Order ID: 11057 + Order Date: 4/29/1998 12:00:00 AM + Product: Outback Lager + Quantity: 3 +``` + + The following code example is an expanded sample where the values from the `OrderDetails` and `Products` tables are returned, with only a subset of the records in the `Orders` table being returned. + [!code-csharp[DataWorks Data.DataTableNavigation#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/CS/source.cs#1)] - [!code-vb[DataWorks Data.DataTableNavigation#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/VB/source.vb#1)] - + [!code-vb[DataWorks Data.DataTableNavigation#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks Data.DataTableNavigation/VB/source.vb#1)] + ## See also - [DataSets, DataTables, and DataViews](index.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datatables.md b/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datatables.md index e825ad96bac6b..51ffc525d8c20 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datatables.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/navigating-datatables.md @@ -2,24 +2,24 @@ description: "Learn more about: Navigating DataTables" title: "Navigating DataTables" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 202026a1-ec79-435e-b507-12a77f5011b2 --- # Navigating DataTables -The obtains the contents of one or more objects in the form of one or more read-only, forward-only result sets. - - A may contain multiple result sets if it is created by using the method. When there is more than one result set, the method advances the cursor to the next result set. This is a forward-only process. It is not possible to return to a previous result set. - -## Example +The obtains the contents of one or more objects in the form of one or more read-only, forward-only result sets. + + A may contain multiple result sets if it is created by using the method. When there is more than one result set, the method advances the cursor to the next result set. This is a forward-only process. It is not possible to return to a previous result set. + +## Example + + In the following example, the `TestConstructor` method creates two instances. In order to demonstrate this constructor for the class, the sample creates a new `DataTableReader` based on an array that contains the two **DataTables**, and performs a simple operation, printing the contents from the first few columns to the console window. - In the following example, the `TestConstructor` method creates two instances. In order to demonstrate this constructor for the class, the sample creates a new **DataTableReader** based on an array that contains the two **DataTables**, and performs a simple operation, printing the contents from the first few columns to the console window. - [!code-csharp[DataWorks DataTableReader.NextResult#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/CS/source.cs#1)] - [!code-vb[DataWorks DataTableReader.NextResult#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/VB/source.vb#1)] - + [!code-vb[DataWorks DataTableReader.NextResult#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks DataTableReader.NextResult/VB/source.vb#1)] + ## See also - [DataTableReaders](datatablereaders.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/nesting-datarelations.md b/docs/framework/data/adonet/dataset-datatable-dataview/nesting-datarelations.md index e86e9d638e94a..9707382b39eec 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/nesting-datarelations.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/nesting-datarelations.md @@ -2,131 +2,131 @@ description: "Learn more about: Nesting DataRelations" title: "Nesting DataRelations" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 9530f9c9-dd98-4b93-8cdb-40d7f1e8d0ab --- # Nesting DataRelations -In a relational representation of data, individual tables contain rows that are related to one another using a column or set of columns. In the ADO.NET , the relationship between tables is implemented using a . When you create a **DataRelation**, the parent-child relationships of the columns are managed only through the relation. The tables and columns are separate entities. In the hierarchical representation of data that XML provides, the parent-child relationships are represented by parent elements that contain nested child elements. - - To facilitate the nesting of child objects when a **DataSet** is synchronized with an or written as XML data using **WriteXml**, the **DataRelation** exposes a **Nested** property. Setting the **Nested** property of a **DataRelation** to **true** causes the child rows of the relation to be nested within the parent column when written as XML data or synchronized with an **XmlDataDocument**. The **Nested** property of the **DataRelation** is **false**, by default. - - For example, consider the following **DataSet**. - -```vb -' Assumes connection is a valid SqlConnection. -Dim customerAdapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT CustomerID, CompanyName FROM Customers", connection) -Dim orderAdapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT OrderID, CustomerID, OrderDate FROM Orders", connection) - -connection.Open() - -Dim dataSet As DataSet = New DataSet("CustomerOrders") -customerAdapter.Fill(dataSet, "Customers") -orderAdapter.Fill(dataSet, "Orders") - -connection.Close() - -Dim customerOrders As DataRelation = dataSet.Relations.Add( _ - "CustOrders", dataSet.Tables("Customers").Columns("CustomerID"), _ - dataSet.Tables("Orders").Columns("CustomerID")) -``` - -```csharp -// Assumes connection is a valid SqlConnection. -SqlDataAdapter customerAdapter = new SqlDataAdapter( - "SELECT CustomerID, CompanyName FROM Customers", connection); -SqlDataAdapter orderAdapter = new SqlDataAdapter( - "SELECT OrderID, CustomerID, OrderDate FROM Orders", connection); - -connection.Open(); - -DataSet dataSet = new DataSet("CustomerOrders"); -customerAdapter.Fill(dataSet, "Customers"); -orderAdapter.Fill(dataSet, "Orders"); - -connection.Close(); - -DataRelation customerOrders = dataSet.Relations.Add( - "CustOrders", dataSet.Tables["Customers"].Columns["CustomerID"], - dataSet.Tables["Orders"].Columns["CustomerID"]); -``` - - Because the **Nested** property of the **DataRelation** object is not set to **true** for this **DataSet**, the child objects are not nested within the parent elements when this **DataSet** is represented as XML data. Transforming the XML representation of a **DataSet** that contains related **DataSet**s with non-nested data relations can cause slow performance. We recommend that you nest the data relations. To do this, set the **Nested** property to **true**. Then write code in the XSLT style sheet that uses top-down hierarchical XPath query expressions to locate and transform the data. - - The following code example shows the result from calling **WriteXml** on the **DataSet**. - -```xml - - - ALFKI - Alfreds Futterkiste - - - ANATR - Ana Trujillo Emparedados y helados - - - 10643 - ALFKI - 1997-08-25T00:00:00 - - - 10692 - ALFKI - 1997-10-03T00:00:00 - - - 10308 - ANATR - 1996-09-18T00:00:00 - - -``` - - Note that the **Customers** element and the **Orders** elements are shown as sibling elements. If you wanted the **Orders** elements to show up as children of their respective parent elements, the **Nested** property of the **DataRelation** would need to be set to **true** and you would add the following: - -```vb -customerOrders.Nested = True -``` - -```csharp -customerOrders.Nested = true; -``` - - The following code shows what the resulting output would look like, with the **Orders** elements nested within their respective parent elements. - -```xml - - - ALFKI - - 10643 - ALFKI - 1997-08-25T00:00:00 - - - 10692 - ALFKI - 1997-10-03T00:00:00 - - Alfreds Futterkiste - - - ANATR - - 10308 - ANATR - 1996-09-18T00:00:00 - - Ana Trujillo Emparedados y helados - - -``` - +In a relational representation of data, individual tables contain rows that are related to one another using a column or set of columns. In the ADO.NET , the relationship between tables is implemented using a . When you create a **DataRelation**, the parent-child relationships of the columns are managed only through the relation. The tables and columns are separate entities. In the hierarchical representation of data that XML provides, the parent-child relationships are represented by parent elements that contain nested child elements. + + To facilitate the nesting of child objects when a `DataSet` is synchronized with an or written as XML data using **WriteXml**, the `DataRelation` exposes a `Nested` property. Setting the `Nested` property of a `DataRelation` to `true` causes the child rows of the relation to be nested within the parent column when written as XML data or synchronized with an **XmlDataDocument**. The `Nested` property of the `DataRelation` is **false**, by default. + + For example, consider the following **DataSet**. + +```vb +' Assumes connection is a valid SqlConnection. +Dim customerAdapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT CustomerID, CompanyName FROM Customers", connection) +Dim orderAdapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT OrderID, CustomerID, OrderDate FROM Orders", connection) + +connection.Open() + +Dim dataSet As DataSet = New DataSet("CustomerOrders") +customerAdapter.Fill(dataSet, "Customers") +orderAdapter.Fill(dataSet, "Orders") + +connection.Close() + +Dim customerOrders As DataRelation = dataSet.Relations.Add( _ + "CustOrders", dataSet.Tables("Customers").Columns("CustomerID"), _ + dataSet.Tables("Orders").Columns("CustomerID")) +``` + +```csharp +// Assumes connection is a valid SqlConnection. +SqlDataAdapter customerAdapter = new SqlDataAdapter( + "SELECT CustomerID, CompanyName FROM Customers", connection); +SqlDataAdapter orderAdapter = new SqlDataAdapter( + "SELECT OrderID, CustomerID, OrderDate FROM Orders", connection); + +connection.Open(); + +DataSet dataSet = new DataSet("CustomerOrders"); +customerAdapter.Fill(dataSet, "Customers"); +orderAdapter.Fill(dataSet, "Orders"); + +connection.Close(); + +DataRelation customerOrders = dataSet.Relations.Add( + "CustOrders", dataSet.Tables["Customers"].Columns["CustomerID"], + dataSet.Tables["Orders"].Columns["CustomerID"]); +``` + + Because the `Nested` property of the `DataRelation` object is not set to `true` for this **DataSet**, the child objects are not nested within the parent elements when this `DataSet` is represented as XML data. Transforming the XML representation of a `DataSet` that contains related **DataSet**s with non-nested data relations can cause slow performance. We recommend that you nest the data relations. To do this, set the `Nested` property to **true**. Then write code in the XSLT style sheet that uses top-down hierarchical XPath query expressions to locate and transform the data. + + The following code example shows the result from calling `WriteXml` on the **DataSet**. + +```xml + + + ALFKI + Alfreds Futterkiste + + + ANATR + Ana Trujillo Emparedados y helados + + + 10643 + ALFKI + 1997-08-25T00:00:00 + + + 10692 + ALFKI + 1997-10-03T00:00:00 + + + 10308 + ANATR + 1996-09-18T00:00:00 + + +``` + + Note that the `Customers` element and the `Orders` elements are shown as sibling elements. If you wanted the `Orders` elements to show up as children of their respective parent elements, the `Nested` property of the `DataRelation` would need to be set to `true` and you would add the following: + +```vb +customerOrders.Nested = True +``` + +```csharp +customerOrders.Nested = true; +``` + + The following code shows what the resulting output would look like, with the `Orders` elements nested within their respective parent elements. + +```xml + + + ALFKI + + 10643 + ALFKI + 1997-08-25T00:00:00 + + + 10692 + ALFKI + 1997-10-03T00:00:00 + + Alfreds Futterkiste + + + ANATR + + 10308 + ANATR + 1996-09-18T00:00:00 + + Ana Trujillo Emparedados y helados + + +``` + ## See also - [Using XML in a DataSet](using-xml-in-a-dataset.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/performing-an-xpath-query-on-a-dataset.md b/docs/framework/data/adonet/dataset-datatable-dataview/performing-an-xpath-query-on-a-dataset.md index 6d3d58d84406b..92c1dfae1ad2f 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/performing-an-xpath-query-on-a-dataset.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/performing-an-xpath-query-on-a-dataset.md @@ -2,101 +2,101 @@ description: "Learn more about: Performing an XPath Query on a DataSet" title: "Performing an XPath Query on a DataSet" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 7e828566-fffe-4d38-abb2-4d68fd73f663 --- # Performing an XPath Query on a DataSet -The relationship between a synchronized and allows you to make use of XML services, such as the XML Path Language (XPath) query, that access the **XmlDataDocument** and can perform certain functionality more conveniently than accessing the **DataSet** directly. For example, rather than using the **Select** method of a to navigate relationships to other tables in a **DataSet**, you can perform an XPath query on an **XmlDataDocument** that is synchronized with the **DataSet**, to get a list of XML elements in the form of an . The nodes in the **XmlNodeList**, cast as nodes, can then be passed to the **GetRowFromElement** method of the **XmlDataDocument**, to return matching references to the rows of the table in the synchronized **DataSet**. - - For example, the following code sample performs a "grandchild" XPath query. The **DataSet** is filled with three tables: **Customers**, **Orders**, and **OrderDetails**. In the sample, a parent-child relation is first created between the **Customers** and **Orders** tables, and between the **Orders** and **OrderDetails** tables. An XPath query is then performed to return an **XmlNodeList** of **Customers** nodes where a grandchild **OrderDetails** node has a **ProductID** node with the value of 43. In essence, the sample is using the XPath query to determine which customers have ordered the product that has the **ProductID** of 43. - -```vb -' Assumes that connection is a valid SqlConnection. -connection.Open() -Dim dataSet As DataSet = New DataSet("CustomerOrders") -Dim customerAdapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT * FROM Customers", connection) -customerAdapter.Fill(dataSet, "Customers") - -Dim orderAdapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT * FROM Orders", connection) -orderAdapter.Fill(dataSet, "Orders") - -Dim detailAdapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT * FROM [Order Details]", connection) -detailAdapter.Fill(dataSet, "OrderDetails") - -connection.Close() - -dataSet.Relations.Add("CustOrders", _ -dataSet.Tables("Customers").Columns("CustomerID"), _ -dataSet.Tables("Orders").Columns("CustomerID")).Nested = true - -dataSet.Relations.Add("OrderDetail", _ - dataSet.Tables("Orders").Columns("OrderID"), _ -dataSet.Tables("OrderDetails").Columns("OrderID"), false).Nested = true - +The relationship between a synchronized and allows you to make use of XML services, such as the XML Path Language (XPath) query, that access the `XmlDataDocument` and can perform certain functionality more conveniently than accessing the `DataSet` directly. For example, rather than using the `Select` method of a to navigate relationships to other tables in a **DataSet**, you can perform an XPath query on an `XmlDataDocument` that is synchronized with the **DataSet**, to get a list of XML elements in the form of an . The nodes in the **XmlNodeList**, cast as nodes, can then be passed to the `GetRowFromElement` method of the **XmlDataDocument**, to return matching references to the rows of the table in the synchronized **DataSet**. + + For example, the following code sample performs a "grandchild" XPath query. The `DataSet` is filled with three tables: **Customers**, **Orders**, and **OrderDetails**. In the sample, a parent-child relation is first created between the `Customers` and `Orders` tables, and between the `Orders` and `OrderDetails` tables. An XPath query is then performed to return an `XmlNodeList` of `Customers` nodes where a grandchild `OrderDetails` node has a `ProductID` node with the value of 43. In essence, the sample is using the XPath query to determine which customers have ordered the product that has the `ProductID` of 43. + +```vb +' Assumes that connection is a valid SqlConnection. +connection.Open() +Dim dataSet As DataSet = New DataSet("CustomerOrders") +Dim customerAdapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT * FROM Customers", connection) +customerAdapter.Fill(dataSet, "Customers") + +Dim orderAdapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT * FROM Orders", connection) +orderAdapter.Fill(dataSet, "Orders") + +Dim detailAdapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT * FROM [Order Details]", connection) +detailAdapter.Fill(dataSet, "OrderDetails") + +connection.Close() + +dataSet.Relations.Add("CustOrders", _ +dataSet.Tables("Customers").Columns("CustomerID"), _ +dataSet.Tables("Orders").Columns("CustomerID")).Nested = true + +dataSet.Relations.Add("OrderDetail", _ + dataSet.Tables("Orders").Columns("OrderID"), _ +dataSet.Tables("OrderDetails").Columns("OrderID"), false).Nested = true + Dim xmlDoc As XmlDataDocument = New XmlDataDocument(dataSet) - -Dim nodeList As XmlNodeList = xmlDoc.DocumentElement.SelectNodes( _ - "descendant::Customers[*/OrderDetails/ProductID=43]") - -Dim dataRow As DataRow -Dim xmlNode As XmlNode - -For Each xmlNode In nodeList - dataRow = xmlDoc.GetRowFromElement(CType(xmlNode, XmlElement)) - - If Not dataRow Is Nothing then Console.WriteLine(xmlRow(0).ToString()) -Next -``` - -```csharp -// Assumes that connection is a valid SqlConnection. -connection.Open(); - -DataSet dataSet = new DataSet("CustomerOrders"); - -SqlDataAdapter customerAdapter = new SqlDataAdapter( - "SELECT * FROM Customers", connection); -customerAdapter.Fill(dataSet, "Customers"); - -SqlDataAdapter orderAdapter = new SqlDataAdapter( - "SELECT * FROM Orders", connection); -orderAdapter.Fill(dataSet, "Orders"); - -SqlDataAdapter detailAdapter = new SqlDataAdapter( - "SELECT * FROM [Order Details]", connection); -detailAdapter.Fill(dataSet, "OrderDetails"); - -connection.Close(); - -dataSet.Relations.Add("CustOrders", - dataSet.Tables["Customers"].Columns["CustomerID"], - dataSet.Tables["Orders"].Columns["CustomerID"]).Nested = true; - -dataSet.Relations.Add("OrderDetail", - dataSet.Tables["Orders"].Columns["OrderID"], + +Dim nodeList As XmlNodeList = xmlDoc.DocumentElement.SelectNodes( _ + "descendant::Customers[*/OrderDetails/ProductID=43]") + +Dim dataRow As DataRow +Dim xmlNode As XmlNode + +For Each xmlNode In nodeList + dataRow = xmlDoc.GetRowFromElement(CType(xmlNode, XmlElement)) + + If Not dataRow Is Nothing then Console.WriteLine(xmlRow(0).ToString()) +Next +``` + +```csharp +// Assumes that connection is a valid SqlConnection. +connection.Open(); + +DataSet dataSet = new DataSet("CustomerOrders"); + +SqlDataAdapter customerAdapter = new SqlDataAdapter( + "SELECT * FROM Customers", connection); +customerAdapter.Fill(dataSet, "Customers"); + +SqlDataAdapter orderAdapter = new SqlDataAdapter( + "SELECT * FROM Orders", connection); +orderAdapter.Fill(dataSet, "Orders"); + +SqlDataAdapter detailAdapter = new SqlDataAdapter( + "SELECT * FROM [Order Details]", connection); +detailAdapter.Fill(dataSet, "OrderDetails"); + +connection.Close(); + +dataSet.Relations.Add("CustOrders", + dataSet.Tables["Customers"].Columns["CustomerID"], + dataSet.Tables["Orders"].Columns["CustomerID"]).Nested = true; + +dataSet.Relations.Add("OrderDetail", + dataSet.Tables["Orders"].Columns["OrderID"], dataSet.Tables["OrderDetails"].Columns["OrderID"], - false).Nested = true; - + false).Nested = true; + XmlDataDocument xmlDoc = new XmlDataDocument(dataSet); - -XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes( - "descendant::Customers[*/OrderDetails/ProductID=43]"); - -DataRow dataRow; -foreach (XmlNode xmlNode in nodeList) -{ - dataRow = xmlDoc.GetRowFromElement((XmlElement)xmlNode); - if (dataRow != null) - Console.WriteLine(dataRow[0]); -} -``` - + +XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes( + "descendant::Customers[*/OrderDetails/ProductID=43]"); + +DataRow dataRow; +foreach (XmlNode xmlNode in nodeList) +{ + dataRow = xmlDoc.GetRowFromElement((XmlElement)xmlNode); + if (dataRow != null) + Console.WriteLine(dataRow[0]); +} +``` + ## See also - [DataSet and XmlDataDocument Synchronization](dataset-and-xmldatadocument-synchronization.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/row-error-information.md b/docs/framework/data/adonet/dataset-datatable-dataview/row-error-information.md index adf92405e8603..2071baf1f6d4a 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/row-error-information.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/row-error-information.md @@ -2,77 +2,77 @@ description: "Learn more about: Row Error Information" title: "Row Error Information" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 8b1f9070-d032-48c7-b030-bd8fbb2ca59a --- # Row Error Information -To avoid having to respond to row errors while editing values in a , you can add the error information to the row for later use. The object provides a property on each row for this purpose. Adding data to the **RowError** property of a **DataRow** sets the property of the **DataRow** to **true**. If the **DataRow** is part of a **DataTable**, and **DataRow.HasErrors** is **true**, the **DataTable.HasErrors** property is also **true**. This applies as well to the **DataSet** to which the **DataTable** belongs. When testing for errors, you can check the **HasErrors** property to determine if error information has been added to any rows. If **HasErrors** is **true**, you can use the method of the **DataTable** to return and examine only the rows with errors, as shown in the following example. - -```vb -Dim workTable As DataTable = New DataTable("Customers") -workTable.Columns.Add("CustID", Type.GetType("System.Int32")) -workTable.Columns.Add("Total", Type.GetType("System.Double")) - -AddHandler workTable.RowChanged, New DataRowChangeEventHandler(AddressOf OnRowChanged) - -Dim i As Int32 - -For i = 0 To 10 - workTable.Rows.Add(New Object() {i , i *100}) -Next - -If workTable.HasErrors Then - Console.WriteLine("Errors in Table " & workTable.TableName) - - Dim myRow As DataRow - - For Each myRow In workTable.GetErrors() - Console.WriteLine("CustID = " & myRow("CustID").ToString()) - Console.WriteLine(" Error = " & myRow.RowError & vbCrLf) - Next -End If - -Private Shared Sub OnRowChanged( _ - sender As Object, args As DataRowChangeEventArgs) - ' Check for zero values. - If CDbl(args.Row("Total")) = 0 Then args.Row.RowError = _ - "Total cannot be 0." -End Sub -``` - -```csharp -DataTable workTable = new DataTable("Customers"); -workTable.Columns.Add("CustID", typeof(Int32)); -workTable.Columns.Add("Total", typeof(Double)); - -workTable.RowChanged += new DataRowChangeEventHandler(OnRowChanged); - -for (int i = 0; i < 10; i++) - workTable.Rows.Add(new Object[] {i, i*100}); - -if (workTable.HasErrors) -{ - Console.WriteLine("Errors in Table " + workTable.TableName); - - foreach (DataRow myRow in workTable.GetErrors()) - { - Console.WriteLine("CustID = " + myRow["CustID"]); - Console.WriteLine(" Error = " + myRow.RowError + "\n"); - } -} - -protected static void OnRowChanged( - Object sender, DataRowChangeEventArgs args) -{ - // Check for zero values. - if (args.Row["Total"].Equals(0D)) - args.Row.RowError = "Total cannot be 0."; -} -``` - +To avoid having to respond to row errors while editing values in a , you can add the error information to the row for later use. The object provides a property on each row for this purpose. Adding data to the `RowError` property of a `DataRow` sets the property of the `DataRow` to **true**. If the `DataRow` is part of a **DataTable**, and **DataRow.HasErrors** is **true**, the **DataTable.HasErrors** property is also **true**. This applies as well to the `DataSet` to which the `DataTable` belongs. When testing for errors, you can check the `HasErrors` property to determine if error information has been added to any rows. If `HasErrors` is **true**, you can use the method of the `DataTable` to return and examine only the rows with errors, as shown in the following example. + +```vb +Dim workTable As DataTable = New DataTable("Customers") +workTable.Columns.Add("CustID", Type.GetType("System.Int32")) +workTable.Columns.Add("Total", Type.GetType("System.Double")) + +AddHandler workTable.RowChanged, New DataRowChangeEventHandler(AddressOf OnRowChanged) + +Dim i As Int32 + +For i = 0 To 10 + workTable.Rows.Add(New Object() {i , i *100}) +Next + +If workTable.HasErrors Then + Console.WriteLine("Errors in Table " & workTable.TableName) + + Dim myRow As DataRow + + For Each myRow In workTable.GetErrors() + Console.WriteLine("CustID = " & myRow("CustID").ToString()) + Console.WriteLine(" Error = " & myRow.RowError & vbCrLf) + Next +End If + +Private Shared Sub OnRowChanged( _ + sender As Object, args As DataRowChangeEventArgs) + ' Check for zero values. + If CDbl(args.Row("Total")) = 0 Then args.Row.RowError = _ + "Total cannot be 0." +End Sub +``` + +```csharp +DataTable workTable = new DataTable("Customers"); +workTable.Columns.Add("CustID", typeof(Int32)); +workTable.Columns.Add("Total", typeof(Double)); + +workTable.RowChanged += new DataRowChangeEventHandler(OnRowChanged); + +for (int i = 0; i < 10; i++) + workTable.Rows.Add(new Object[] {i, i*100}); + +if (workTable.HasErrors) +{ + Console.WriteLine("Errors in Table " + workTable.TableName); + + foreach (DataRow myRow in workTable.GetErrors()) + { + Console.WriteLine("CustID = " + myRow["CustID"]); + Console.WriteLine(" Error = " + myRow.RowError + "\n"); + } +} + +protected static void OnRowChanged( + Object sender, DataRowChangeEventArgs args) +{ + // Check for zero values. + if (args.Row["Total"].Equals(0D)) + args.Row.RowError = "Total cannot be 0."; +} +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/sorting-and-filtering-data.md b/docs/framework/data/adonet/dataset-datatable-dataview/sorting-and-filtering-data.md index 54d1859846a7a..60e3900c63dcd 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/sorting-and-filtering-data.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/sorting-and-filtering-data.md @@ -2,56 +2,56 @@ description: "Learn more about: Sorting and Filtering Data" title: "Sorting and Filtering Data" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: fdd9c753-39df-48cd-9822-2781afe76200 --- # Sorting and Filtering Data -The provides several ways of sorting and filtering data in a : - -- You can use the property to specify single or multiple column sort orders and include ASC (ascending) and DESC (descending) parameters. - -- You can use the property to automatically create a sort order, in ascending order, based on the primary key column or columns of the table. only applies when the **Sort** property is a null reference or an empty string, and when the table has a primary key defined. - -- You can use the property to specify subsets of rows based on their column values. For details about valid expressions for the **RowFilter** property, see the reference information for the property of the class. - - If you want to return the results of a particular query on the data, as opposed to providing a dynamic view of a subset of the data, use the or methods of the **DataView** to achieve best performance rather than setting the **RowFilter** property. Setting the **RowFilter** property rebuilds the index for the data, adding overhead to your application and decreasing performance. The **RowFilter** property is best used in a data-bound application where a bound control displays filtered results. The **Find** and **FindRows** methods leverage the current index without requiring the index to be rebuilt. For more information about the **Find** and **FindRows** methods, see [Finding Rows](finding-rows.md). - -- You can use the property to specify which row versions to view. The **DataView** implicitly manages which row version to expose depending upon the **RowState** of the underlying row. For example, if the **RowStateFilter** is set to **DataViewRowState.Deleted**, the **DataView** exposes the **Original** row version of all **Deleted** rows because there is no **Current** row version. You can determine which row version of a row is being exposed by using the **RowVersion** property of the **DataRowView**. - - The following table shows the options for **DataViewRowState**. - - |DataViewRowState options|Description| - |------------------------------|-----------------| - |**CurrentRows**|The **Current** row version of all **Unchanged**, **Added**, and **Modified** rows. This is the default.| - |**Added**|The **Current** row version of all **Added** rows.| - |**Deleted**|The **Original** row version of all **Deleted** rows.| - |**ModifiedCurrent**|The **Current** row version of all **Modified** rows.| - |**ModifiedOriginal**|The **Original** row version of all **Modified** rows.| - |**None**|No rows.| - |**OriginalRows**|The **Original** row version of all **Unchanged**, **Modified**, and **Deleted** rows.| - |**Unchanged**|The **Current** row version of all **Unchanged** rows.| - - For more information about row states and row versions, see [Row States and Row Versions](row-states-and-row-versions.md). - - The following code example creates a view that shows all the products where the number of units in stock is less than or equal to the reorder level, sorted first by supplier ID and then by product name. - -```vb -Dim prodView As DataView = New DataView(prodDS.Tables("Products"), _ - "UnitsInStock <= ReorderLevel", _ - "SupplierID, ProductName", _ - DataViewRowState.CurrentRows) -``` - -```csharp -DataView prodView = new DataView(prodDS.Tables["Products"], - "UnitsInStock <= ReorderLevel", - "SupplierID, ProductName", - DataViewRowState.CurrentRows); -``` - +The provides several ways of sorting and filtering data in a : + +- You can use the property to specify single or multiple column sort orders and include ASC (ascending) and DESC (descending) parameters. + +- You can use the property to automatically create a sort order, in ascending order, based on the primary key column or columns of the table. only applies when the `Sort` property is a null reference or an empty string, and when the table has a primary key defined. + +- You can use the property to specify subsets of rows based on their column values. For details about valid expressions for the `RowFilter` property, see the reference information for the property of the class. + + If you want to return the results of a particular query on the data, as opposed to providing a dynamic view of a subset of the data, use the or methods of the `DataView` to achieve best performance rather than setting the `RowFilter` property. Setting the `RowFilter` property rebuilds the index for the data, adding overhead to your application and decreasing performance. The `RowFilter` property is best used in a data-bound application where a bound control displays filtered results. The `Find` and `FindRows` methods leverage the current index without requiring the index to be rebuilt. For more information about the `Find` and `FindRows` methods, see [Finding Rows](finding-rows.md). + +- You can use the property to specify which row versions to view. The `DataView` implicitly manages which row version to expose depending upon the `RowState` of the underlying row. For example, if the `RowStateFilter` is set to **DataViewRowState.Deleted**, the `DataView` exposes the `Original` row version of all `Deleted` rows because there is no `Current` row version. You can determine which row version of a row is being exposed by using the `RowVersion` property of the **DataRowView**. + + The following table shows the options for **DataViewRowState**. + + |DataViewRowState options|Description| + |------------------------------|-----------------| + |**CurrentRows**|The `Current` row version of all **Unchanged**, **Added**, and `Modified` rows. This is the default.| + |**Added**|The `Current` row version of all `Added` rows.| + |**Deleted**|The `Original` row version of all `Deleted` rows.| + |**ModifiedCurrent**|The `Current` row version of all `Modified` rows.| + |**ModifiedOriginal**|The `Original` row version of all `Modified` rows.| + |**None**|No rows.| + |**OriginalRows**|The `Original` row version of all **Unchanged**, **Modified**, and `Deleted` rows.| + |**Unchanged**|The `Current` row version of all `Unchanged` rows.| + + For more information about row states and row versions, see [Row States and Row Versions](row-states-and-row-versions.md). + + The following code example creates a view that shows all the products where the number of units in stock is less than or equal to the reorder level, sorted first by supplier ID and then by product name. + +```vb +Dim prodView As DataView = New DataView(prodDS.Tables("Products"), _ + "UnitsInStock <= ReorderLevel", _ + "SupplierID, ProductName", _ + DataViewRowState.CurrentRows) +``` + +```csharp +DataView prodView = new DataView(prodDS.Tables["Products"], + "UnitsInStock <= ReorderLevel", + "SupplierID, ProductName", + DataViewRowState.CurrentRows); +``` + ## See also - diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/specify-relations-between-elements-with-no-nesting.md b/docs/framework/data/adonet/dataset-datatable-dataview/specify-relations-between-elements-with-no-nesting.md index d862538e07d82..f0b42ab5aeebe 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/specify-relations-between-elements-with-no-nesting.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/specify-relations-between-elements-with-no-nesting.md @@ -6,60 +6,60 @@ ms.assetid: e31325da-7691-4d33-acf4-99fccca67006 --- # Specify Relations Between Elements with No Nesting -When elements are not nested, no implicit relations are created. You can, however, explicitly specify relations between elements that are not nested by using the **msdata:Relationship** annotation. - - The following example shows an XML Schema in which the **msdata:Relationship** annotation is specified between the **Order** and **OrderDetail** elements, which are not nested. The **msdata:Relationship** annotation is specified as the child element of the **Schema** element. - -```xml +When elements are not nested, no implicit relations are created. You can, however, explicitly specify relations between elements that are not nested by using the **msdata:Relationship** annotation. + + The following example shows an XML Schema in which the **msdata:Relationship** annotation is specified between the `Order` and `OrderDetail` elements, which are not nested. The **msdata:Relationship** annotation is specified as the child element of the `Schema` element. + +```xml - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + - - - -``` - - The XML Schema definition language (XSD) schema mapping process creates a with **Order** and **OrderDetail** tables and a relationship specified between these two tables, as shown below. - -```text -RelationName: OrdOrderDetailRelation -ParentTable: Order + msdata:childkey="OrderNo"/> + + + +``` + + The XML Schema definition language (XSD) schema mapping process creates a with `Order` and `OrderDetail` tables and a relationship specified between these two tables, as shown below. + +```text +RelationName: OrdOrderDetailRelation +ParentTable: Order ParentColumns: OrderNumber -ChildTable: OrderDetail +ChildTable: OrderDetail ChildColumns: OrderNo -Nested: False -``` - +Nested: False +``` + ## See also - [Generating DataSet Relations from XML Schema (XSD)](generating-dataset-relations-from-xml-schema-xsd.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/summary-of-the-dataset-schema-inference-process.md b/docs/framework/data/adonet/dataset-datatable-dataview/summary-of-the-dataset-schema-inference-process.md index 3454d12475073..376833abf57f9 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/summary-of-the-dataset-schema-inference-process.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/summary-of-the-dataset-schema-inference-process.md @@ -6,26 +6,26 @@ ms.assetid: fd0891c8-d068-4e30-a76f-7c375f078bf7 --- # Summary of the DataSet Schema Inference Process -The inference process first determines, from the XML document, which elements will be inferred as tables. From the remaining XML, the inference process determines the columns for those tables. For nested tables, the inference process generates nested and objects. - - The following is a brief summary of inference rules: - -- Elements that have attributes are inferred as tables. - -- Elements that have child elements are inferred as tables. - -- Elements that repeat are inferred as a single table. - -- If the document, or root, element has no attributes, and no child elements that would be inferred as columns, it is inferred as a . Otherwise, the document element is inferred as a table. - -- Attributes are inferred as columns. - -- Elements that have no attributes or child elements, and that do not repeat, are inferred as columns. - -- For elements that are inferred as nested tables within other elements that are also inferred as tables, a nested **DataRelation** is created between the two tables. A new, primary key column named **TableName_Id** is added to both tables and used by the **DataRelation**. A **ForeignKeyConstraint** is created between the two tables using the **TableName_Id** column. - -- For elements that are inferred as tables and that contain text but have no child elements, a new column named **TableName_Text** is created for the text of each of the elements. If an element is inferred as a table and has text, but also has child elements, the text is ignored. - +The inference process first determines, from the XML document, which elements will be inferred as tables. From the remaining XML, the inference process determines the columns for those tables. For nested tables, the inference process generates nested and objects. + + The following is a brief summary of inference rules: + +- Elements that have attributes are inferred as tables. + +- Elements that have child elements are inferred as tables. + +- Elements that repeat are inferred as a single table. + +- If the document, or root, element has no attributes, and no child elements that would be inferred as columns, it is inferred as a . Otherwise, the document element is inferred as a table. + +- Attributes are inferred as columns. + +- Elements that have no attributes or child elements, and that do not repeat, are inferred as columns. + +- For elements that are inferred as nested tables within other elements that are also inferred as tables, a nested `DataRelation` is created between the two tables. A new, primary key column named `TableName_Id` is added to both tables and used by the **DataRelation**. A `ForeignKeyConstraint` is created between the two tables using the `TableName_Id` column. + +- For elements that are inferred as tables and that contain text but have no child elements, a new column named `TableName_Text` is created for the text of each of the elements. If an element is inferred as a table and has text, but also has child elements, the text is ignored. + ## See also - [Inferring DataSet Relational Structure from XML](inferring-dataset-relational-structure-from-xml.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/synchronizing-a-dataset-with-an-xmldatadocument.md b/docs/framework/data/adonet/dataset-datatable-dataview/synchronizing-a-dataset-with-an-xmldatadocument.md index 44b744bf3a567..4b95a1b6c115f 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/synchronizing-a-dataset-with-an-xmldatadocument.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/synchronizing-a-dataset-with-an-xmldatadocument.md @@ -2,231 +2,231 @@ description: "Learn more about: Synchronizing a DataSet with an XmlDataDocument" title: "Synchronizing a DataSet with an XmlDataDocument" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: fbc96fa9-b5d1-4f97-b099-c89b0e14ce2c --- -# Synchronizing a DataSet with an XmlDataDocument - -This section demonstrates one step in the processing of a purchase order, using a strongly typed synchronized with an . The examples that follow create a **DataSet** with a minimized schema that matches only a portion of the source XML document. The examples use an **XmlDataDocument** to preserve the fidelity of the source XML document, enabling the **DataSet** to be used to expose a subset of the XML document. - - The following XML document contains all the information pertaining to a purchase order: customer information, items ordered, shipping information, and so on. - -```xml - - - - CHOPS - - 10966 - - 10966 - 37 - 26 - 8 - 0 - - - 10966 - 56 - 38 - 12 - 0.15 - - - 10966 - 62 - 49.3 - 12 - 0.15 - - CHOPS - 4 - 1998-03-20T00:00:00.0000000 - 1998-04-17T00:00:00.0000000 - 1998-04-08T00:00:00.0000000 - 1 - 27.19 - Chop-suey Chinese - Hauptstr. 31 - Bern - 3012 - Switzerland - - Chop-suey Chinese - Yang Wang - Owner -
Hauptstr. 29
- Bern - 3012 - Switzerland - 0452-076545 -
- - 1 - Speedy Express - (503) 555-0100 - - - 2 - United Package - (503) 555-0101 - - - 3 - Federal Shipping - (503) 555-0102 - - - 37 - Gravad lax - 12 - 500 g pkgs. - 11 - 50 - 25 - - - 56 - Gnocchi di nonna Alice - 24 - 250 g pkgs. - 21 - 10 - 30 - - - 62 - Tarte au sucre - 48 pies - 17 - 0 - 0 - -
-``` - - One step in processing the purchase order information contained in the preceding XML document is for the order to be filled from the company's current inventory. The employee responsible for filling the order from the company's warehouse does not need to see the entire contents of the purchase order; they only need to see the product information for the order. To expose only the product information from the XML document, create a strongly typed **DataSet** with a schema, written as XML Schema definition language (XSD) schema, that maps to the products and quantities ordered. For more information about strongly typed **DataSet** objects, see [Typed DataSets](typed-datasets.md). - - The following code shows the schema from which the strongly typed **DataSet** is generated for this sample. - -```xml - +# Synchronize a DataSet with an XmlDataDocument + +This section demonstrates one step in the processing of a purchase order, using a strongly typed synchronized with an . The examples that follow create a `DataSet` with a minimized schema that matches only a portion of the source XML document. The examples use an `XmlDataDocument` to preserve the fidelity of the source XML document, enabling the `DataSet` to be used to expose a subset of the XML document. + + The following XML document contains all the information pertaining to a purchase order: customer information, items ordered, shipping information, and so on. + +```xml + + + + CHOPS + + 10966 + + 10966 + 37 + 26 + 8 + 0 + + + 10966 + 56 + 38 + 12 + 0.15 + + + 10966 + 62 + 49.3 + 12 + 0.15 + + CHOPS + 4 + 1998-03-20T00:00:00.0000000 + 1998-04-17T00:00:00.0000000 + 1998-04-08T00:00:00.0000000 + 1 + 27.19 + Chop-suey Chinese + Hauptstr. 31 + Bern + 3012 + Switzerland + + Chop-suey Chinese + Yang Wang + Owner +
Hauptstr. 29
+ Bern + 3012 + Switzerland + 0452-076545 +
+ + 1 + Speedy Express + (503) 555-0100 + + + 2 + United Package + (503) 555-0101 + + + 3 + Federal Shipping + (503) 555-0102 + + + 37 + Gravad lax + 12 - 500 g pkgs. + 11 + 50 + 25 + + + 56 + Gnocchi di nonna Alice + 24 - 250 g pkgs. + 21 + 10 + 30 + + + 62 + Tarte au sucre + 48 pies + 17 + 0 + 0 + +
+``` + + One step in processing the purchase order information contained in the preceding XML document is for the order to be filled from the company's current inventory. The employee responsible for filling the order from the company's warehouse does not need to see the entire contents of the purchase order; they only need to see the product information for the order. To expose only the product information from the XML document, create a strongly typed `DataSet` with a schema, written as XML Schema definition language (XSD) schema, that maps to the products and quantities ordered. For more information about strongly typed `DataSet` objects, see [Typed DataSets](typed-datasets.md). + + The following code shows the schema from which the strongly typed `DataSet` is generated for this sample. + +```xml + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -``` - - Notice that only information from the **OrderDetails** and **Products** elements of the original XML document are included in the schema for the **DataSet**. Synchronizing the **DataSet** with an **XmlDataDocument** ensures that the elements not included in the **DataSet** will persist with the XML document. - - With the strongly typed **DataSet** generated from the XML Schema (with a namespace of **Northwind.FillOrder**), a portion of the original XML document can be exposed by synchronizing the **DataSet** with the **XmlDataDocument** loaded from the source XML document. Notice that the **DataSet** generated from the schema contains structure but no data. The data is filled in when you load the XML into the **XmlDataDocument**. If you attempt to load an **XmlDataDocument** that has been synchronized with a **DataSet** that already contains data, an exception will be thrown. - - After the **DataSet** (and the **XmlDataDocument**) has been updated, the **XmlDataDocument** can then write out the modified XML document with the elements ignored by the **DataSet** still intact, as shown below. In the purchase order scenario, after the order items have been filled, the modified XML document can then be passed on to the next step in the order process, perhaps to the company's shipping department. - -```vb -Imports System -Imports System.Data -Imports System.Xml -Imports Northwind.FillOrder - -Public class Sample - Public Shared Sub Main() - - Dim orderDS As OrderDetail = New OrderDetail - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + + Notice that only information from the `OrderDetails` and `Products` elements of the original XML document is included in the schema for the **DataSet**. Synchronizing the `DataSet` with an `XmlDataDocument` ensures that the elements not included in the `DataSet` will persist with the XML document. + + With the strongly typed `DataSet` generated from the XML Schema (with a namespace of **Northwind.FillOrder**), a portion of the original XML document can be exposed by synchronizing the `DataSet` with the `XmlDataDocument` loaded from the source XML document. The `DataSet` generated from the schema contains structure but no data. The data is filled in when you load the XML into the **XmlDataDocument**. If you attempt to load an `XmlDataDocument` that has been synchronized with a `DataSet` that already contains data, an exception is thrown. + + After the `DataSet` (and the **XmlDataDocument**) has been updated, the `XmlDataDocument` can then write out the modified XML document with the elements ignored by the `DataSet` still intact, as shown below. In the purchase order scenario, after the order items have been filled, the modified XML document can then be passed on to the next step in the order process, perhaps to the company's shipping department. + +```vb +Imports System +Imports System.Data +Imports System.Xml +Imports Northwind.FillOrder + +Public class Sample + Public Shared Sub Main() + + Dim orderDS As OrderDetail = New OrderDetail + Dim xmlDocument As XmlDataDocument = New XmlDataDocument(orderDS) - - xmlDocument.Load("Order.xml") - - Dim orderItem As OrderDetail.LineItem - Dim product As OrderDetail.Product - - For Each orderItem In orderDS.LineItems - product = orderItem.Product - - ' Remove quantity from the current stock. - product.UnitsInStock = CType(product.UnitsInStock - orderItem.Quantity, Short) - - ' If the remaining stock is less than the reorder level, order more. - If ((product.UnitsInStock + product.UnitsOnOrder) < product.ReorderLevel) Then - product.UnitsOnOrder = CType(product.UnitsOnOrder + product.ReorderLevel, Short) - End If - Next - - xmlDocument.Save("Order_out.xml") - End Sub -End Class -``` - -```csharp -using System; -using System.Data; -using System.Xml; -using Northwind.FillOrder; - -public class Sample -{ - public static void Main() - { + + xmlDocument.Load("Order.xml") + + Dim orderItem As OrderDetail.LineItem + Dim product As OrderDetail.Product + + For Each orderItem In orderDS.LineItems + product = orderItem.Product + + ' Remove quantity from the current stock. + product.UnitsInStock = CType(product.UnitsInStock - orderItem.Quantity, Short) + + ' If the remaining stock is less than the reorder level, order more. + If ((product.UnitsInStock + product.UnitsOnOrder) < product.ReorderLevel) Then + product.UnitsOnOrder = CType(product.UnitsOnOrder + product.ReorderLevel, Short) + End If + Next + + xmlDocument.Save("Order_out.xml") + End Sub +End Class +``` + +```csharp +using System; +using System.Data; +using System.Xml; +using Northwind.FillOrder; + +public class Sample +{ + public static void Main() + { OrderDetail orderDS = new OrderDetail(); - + XmlDataDocument xmlDocument = new XmlDataDocument(orderDS); - - xmlDocument.Load("Order.xml"); - - foreach (OrderDetail.LineItem orderItem in orderDS.LineItems) - { - OrderDetail.Product product = orderItem.Product; - - // Remove quantity from the current stock. - product.UnitsInStock = (short)(product.UnitsInStock - orderItem.Quantity); - - // If the remaining stock is less than the reorder level, order more. - if ((product.UnitsInStock + product.UnitsOnOrder) < product.ReorderLevel) - product.UnitsOnOrder = (short)(product.UnitsOnOrder + product.ReorderLevel); - } - - xmlDocument.Save("Order_out.xml"); - } -} -``` - + + xmlDocument.Load("Order.xml"); + + foreach (OrderDetail.LineItem orderItem in orderDS.LineItems) + { + OrderDetail.Product product = orderItem.Product; + + // Remove quantity from the current stock. + product.UnitsInStock = (short)(product.UnitsInStock - orderItem.Quantity); + + // If the remaining stock is less than the reorder level, order more. + if ((product.UnitsInStock + product.UnitsOnOrder) < product.ReorderLevel) + product.UnitsOnOrder = (short)(product.UnitsOnOrder + product.ReorderLevel); + } + + xmlDocument.Save("Order_out.xml"); + } +} +``` + ## See also - [DataSet and XmlDataDocument Synchronization](dataset-and-xmldatadocument-synchronization.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/the-load-method.md b/docs/framework/data/adonet/dataset-datatable-dataview/the-load-method.md index 2097adbdb54f2..574f1c102577f 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/the-load-method.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/the-load-method.md @@ -8,19 +8,19 @@ ms.custom: sfi-ropc-nochange --- # The Load method -You can use the method to load a with rows from a data source. This is an overloaded method which, in its simplest form, accepts a single parameter, a **DataReader**. In this form, it simply loads the **DataTable** with rows. Optionally, you can specify the **LoadOption** parameter to control how data is added to the **DataTable**. +You can use the method to load a with rows from a data source. This is an overloaded method which, in its simplest form, accepts a single parameter, a **DataReader**. In this form, it simply loads the `DataTable` with rows. Optionally, you can specify the `LoadOption` parameter to control how data is added to the **DataTable**. - The **LoadOption** parameter is particularly useful in cases where the **DataTable** already contains rows of data, because it describes how incoming data from the data source will be combined with the data already in the table. For example, **PreserveCurrentValues** (the default) specifies that in cases where a row is marked as **Added** in the **DataTable**, the **Original** value or each column is set to the contents of the matching row from the data source. The **Current** value will retain the values assigned when the row was added, and the **RowState** of the row will be set to **Changed**. + The `LoadOption` parameter is particularly useful in cases where the `DataTable` already contains rows of data, because it describes how incoming data from the data source will be combined with the data already in the table. For example, `PreserveCurrentValues` (the default) specifies that in cases where a row is marked as `Added` in the **DataTable**, the `Original` value or each column is set to the contents of the matching row from the data source. The `Current` value will retain the values assigned when the row was added, and the `RowState` of the row will be set to **Changed**. The following table gives a short description of the enumeration values. |LoadOption value|Description| |----------------------|-----------------| -|**OverwriteRow**|If incoming rows have the same **PrimaryKey** value as a row already in the **DataTable**, the **Original** and **Current** values of each column are replaced with the values in the incoming row, and the **RowState** property is set to **Unchanged**.

Rows from the data source that do not already exist in the **DataTable** are added with a **RowState** value of **Unchanged**.

This option in effect refreshes the contents of the **DataTable** so that it matches the contents of the data source.| -|**PreserveCurrentValues (default)**|If incoming rows have the same **PrimaryKey** value as a row already in the **DataTable**, the **Original** value is set to the contents of the incoming row, and the **Current** value is not changed.

If the **RowState** is **Added** or **Modified**, it is set to **Modified**.

If the **RowState** was **Deleted**, it remains **Deleted**.

Rows from the data source that do not already exist in the **DataTable** are added, and the **RowState** is set to **Unchanged**.| -|**UpdateCurrentValues**|If incoming rows have the same **PrimaryKey** value as the row already in the **DataTable**, the **Current** value is copied to the **Original** value, and the **Current** value is then set to the contents of the incoming row.

If the **RowState** in the **DataTable** was **Added**, the **RowState** remains **Added**. For rows marked as **Modified** or **Deleted**, the **RowState** is **Modified**.

Rows from the data source that do not already exist in the **DataTable** are added, and the **RowState** is set to **Added**.| +|**OverwriteRow**|If incoming rows have the same `PrimaryKey` value as a row already in the **DataTable**, the `Original` and `Current` values of each column are replaced with the values in the incoming row, and the `RowState` property is set to **Unchanged**.

Rows from the data source that do not already exist in the `DataTable` are added with a `RowState` value of **Unchanged**.

This option in effect refreshes the contents of the `DataTable` so that it matches the contents of the data source.| +|**PreserveCurrentValues (default)**|If incoming rows have the same `PrimaryKey` value as a row already in the **DataTable**, the `Original` value is set to the contents of the incoming row, and the `Current` value is not changed.

If the `RowState` is `Added` or **Modified**, it is set to **Modified**.

If the `RowState` was **Deleted**, it remains **Deleted**.

Rows from the data source that do not already exist in the `DataTable` are added, and the `RowState` is set to **Unchanged**.| +|**UpdateCurrentValues**|If incoming rows have the same `PrimaryKey` value as the row already in the **DataTable**, the `Current` value is copied to the `Original` value, and the `Current` value is then set to the contents of the incoming row.

If the `RowState` in the `DataTable` was **Added**, the `RowState` remains **Added**. For rows marked as `Modified` or **Deleted**, the `RowState` is **Modified**.

Rows from the data source that do not already exist in the `DataTable` are added, and the `RowState` is set to **Added**.| - The following sample uses the **Load** method to display a list of birthdays for the employees in the **Northwind** database. + The following sample uses the `Load` method to display a list of birthdays for the employees in the `Northwind` database. ```vb Private Sub LoadBirthdays(ByVal connectionString As String) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/typed-datasets.md b/docs/framework/data/adonet/dataset-datatable-dataview/typed-datasets.md index 9e5a5f70b528b..1e9e8131d5fef 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/typed-datasets.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/typed-datasets.md @@ -6,20 +6,20 @@ ms.assetid: 033d2548-cf24-4c05-8179-67d8b009c048 --- # Typed DataSets -Along with late bound access to values through weakly typed variables, the provides access to data through a strongly typed metaphor. Tables and columns that are part of the **DataSet** can be accessed using user-friendly names and strongly typed variables. - - A typed **DataSet** is a class that derives from a **DataSet**. As such, it inherits all the methods, events, and properties of a **DataSet**. Additionally, a typed **DataSet** provides strongly typed methods, events, and properties. This means you can access tables and columns by name, instead of using collection-based methods. Aside from the improved readability of the code, a typed **DataSet** also allows the Visual Studio .NET code editor to automatically complete lines as you type. - - Additionally, the strongly typed **DataSet** provides access to values as the correct type at compile time. With a strongly typed **DataSet**, type mismatch errors are caught when the code is compiled rather than at run time. - -## In This Section - - [Generating Strongly Typed DataSets](generating-strongly-typed-datasets.md) - Describes how to create and use a strongly typed **DataSet**. - - [Annotating Typed DataSets](annotating-typed-datasets.md) - Describes how to annotate the XML Schema definition language (XSD) schema used to generate a strongly typed **DataSet**, to give **DataSet** elements friendly names without altering the underlying schema. - +Along with late bound access to values through weakly typed variables, the provides access to data through a strongly typed metaphor. Tables and columns that are part of the `DataSet` can be accessed using user-friendly names and strongly typed variables. + + A typed `DataSet` is a class that derives from a **DataSet**. As such, it inherits all the methods, events, and properties of a **DataSet**. Additionally, a typed `DataSet` provides strongly typed methods, events, and properties. This means you can access tables and columns by name, instead of using collection-based methods. Aside from the improved readability of the code, a typed `DataSet` also allows the Visual Studio .NET code editor to automatically complete lines as you type. + + Additionally, the strongly typed `DataSet` provides access to values as the correct type at compile time. With a strongly typed **DataSet**, type mismatch errors are caught when the code is compiled rather than at run time. + +## In This Section + + [Generating Strongly Typed DataSets](generating-strongly-typed-datasets.md) + Describes how to create and use a strongly typed **DataSet**. + + [Annotating Typed DataSets](annotating-typed-datasets.md) + Describes how to annotate the XML Schema definition language (XSD) schema used to generate a strongly typed **DataSet**, to give `DataSet` elements friendly names without altering the underlying schema. + ## See also - [DataSets, DataTables, and DataViews](index.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/viewing-data-in-a-datatable.md b/docs/framework/data/adonet/dataset-datatable-dataview/viewing-data-in-a-datatable.md index 6198873e6589f..9a884814a7295 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/viewing-data-in-a-datatable.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/viewing-data-in-a-datatable.md @@ -10,14 +10,14 @@ ms.assetid: 1d26e0fb-f6e0-4afa-9a9c-b8d55b8f20dc # Viewing Data in a DataTable -You can access the contents of a by using the **Rows** and **Columns** collections of the **DataTable**. You can also use the method to return subsets of the data in a **DataTable** according to criteria including search criteria, sort order, and row state. Additionally, you can use the method of the **DataRowCollection** when searching for a particular row using a primary key value. +You can access the contents of a by using the `Rows` and `Columns` collections of the **DataTable**. You can also use the method to return subsets of the data in a `DataTable` according to criteria including search criteria, sort order, and row state. Additionally, you can use the method of the `DataRowCollection` when searching for a particular row using a primary key value. -The **Select** method of the **DataTable** object returns a set of objects that match the specified criteria. **Select** takes optional arguments of a filter expression, sort expression, and **DataViewRowState**. The filter expression identifies which rows to return based on **DataColumn** values, such as `LastName = 'Smith'`. The sort expression follows standard SQL conventions for ordering columns, for example `LastName ASC, FirstName ASC`. For rules about writing expressions, see the property of the **DataColumn** class. +The `Select` method of the `DataTable` object returns a set of objects that match the specified criteria. `Select` takes optional arguments of a filter expression, sort expression, and **DataViewRowState**. The filter expression identifies which rows to return based on `DataColumn` values, such as `LastName = 'Smith'`. The sort expression follows standard SQL conventions for ordering columns, for example `LastName ASC, FirstName ASC`. For rules about writing expressions, see the property of the `DataColumn` class. > [!TIP] -> If you are performing a number of calls to the **Select** method of a **DataTable**, you can increase performance by first creating a for the **DataTable**. Creating the **DataView** indexes the rows of the table. The **Select** method then uses that index, significantly reducing the time to generate the query result. For information about creating a **DataView** for a **DataTable**, see [DataViews](dataviews.md). +> If you are performing a number of calls to the `Select` method of a **DataTable**, you can increase performance by first creating a for the **DataTable**. Creating the `DataView` indexes the rows of the table. The `Select` method then uses that index, significantly reducing the time to generate the query result. For information about creating a `DataView` for a **DataTable**, see [DataViews](dataviews.md). -The **Select** method determines which version of the rows to view or manipulate based on a . The following table describes the possible **DataViewRowState** enumeration values. +The `Select` method determines which version of the rows to view or manipulate based on a . The following table describes the possible `DataViewRowState` enumeration values. |DataViewRowState value|Description| |----------------------------|-----------------| @@ -30,7 +30,7 @@ The **Select** method determines which version of the rows to view or manipulate |**OriginalRows**|Original rows, including unchanged and deleted rows.| |**Unchanged**|An unchanged row.| -In the following example, the **DataSet** object is filtered so that you are only working with rows whose **DataViewRowState** is set to **CurrentRows**. +In the following example, the `DataSet` object is filtered so that you are only working with rows whose `DataViewRowState` is set to **CurrentRows**. ```vb Dim column As DataColumn @@ -83,7 +83,7 @@ else } ``` -The **Select** method can be used to return rows with differing **RowState** values or field values. The following example returns a **DataRow** array that references all rows that have been deleted, and returns another **DataRow** array that references all rows, ordered by **CustLName**, where the **CustID** column is greater than 5. For information about how to view the information in the **Deleted** row, see [Row States and Row Versions](row-states-and-row-versions.md). +The `Select` method can be used to return rows with differing `RowState` values or field values. The following example returns a `DataRow` array that references all rows that have been deleted, and returns another `DataRow` array that references all rows, ordered by **CustLName**, where the `CustID` column is greater than 5. For information about how to view the information in the `Deleted` row, see [Row States and Row Versions](row-states-and-row-versions.md). ```vb ' Retrieve all deleted rows. diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/writing-dataset-contents-as-xml-data.md b/docs/framework/data/adonet/dataset-datatable-dataview/writing-dataset-contents-as-xml-data.md index f6ac182f9c74a..20505666d4547 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/writing-dataset-contents-as-xml-data.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/writing-dataset-contents-as-xml-data.md @@ -2,74 +2,74 @@ description: "Learn more about: Writing DataSet Contents as XML Data" title: "Writing DataSet Contents as XML Data" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: fd15f8a5-3b4c-46d0-a561-4559ab2a4705 --- # Writing DataSet Contents as XML Data -In ADO.NET you can write an XML representation of a , with or without its schema. If schema information is included inline with the XML, it is written using the XML Schema definition language (XSD). The schema contains the table definitions of the as well as the relation and constraint definitions. - - When a is written as XML data, the rows in the are written in their current versions. However, the can also be written as a DiffGram so that both the current and the original values of the rows will be included. - - The XML representation of the can be written to a file, a stream, an **XmlWriter**, or a string. These choices provide great flexibility for how you transport the XML representation of the . To obtain the XML representation of the as a string, use the **GetXml** method as shown in the following example. - -```vb -Dim xmlDS As String = custDS.GetXml() -``` - -```csharp -string xmlDS = custDS.GetXml(); -``` - - **GetXml** returns the XML representation of the without schema information. To write the schema information from the (as XML Schema) to a string, use **GetXmlSchema**. - - To write a to a file, stream, or **XmlWriter**, use the **WriteXml** method. The first parameter you pass to **WriteXml** is the destination of the XML output. For example, pass a string containing a file name, a **System.IO.TextWriter** object, and so on. You can pass an optional second parameter of an **XmlWriteMode** to specify how the XML output is to be written. - - The following table shows the options for **XmlWriteMode**. - -|XmlWriteMode option|Description| -|-------------------------|-----------------| -|**IgnoreSchema**|Writes the current contents of the as XML data, without an XML Schema. This is the default.| -|**WriteSchema**|Writes the current contents of the as XML data with the relational structure as inline XML Schema.| -|**DiffGram**|Writes the entire as a DiffGram, including original and current values. For more information, see [DiffGrams](diffgrams.md).| - - When writing an XML representation of a that contains **DataRelation** objects, you will most likely want the resulting XML to have the child rows of each relation nested within their related parent elements. To accomplish this, set the **Nested** property of the **DataRelation** to **true** when you add the **DataRelation** to the . For more information, see [Nesting DataRelations](nesting-datarelations.md). - +In ADO.NET you can write an XML representation of a , with or without its schema. If schema information is included inline with the XML, it is written using the XML Schema definition language (XSD). The schema contains the table definitions of the as well as the relation and constraint definitions. + + When a is written as XML data, the rows in the are written in their current versions. However, the can also be written as a DiffGram so that both the current and the original values of the rows will be included. + + The XML representation of the can be written to a file, a stream, an **XmlWriter**, or a string. These choices provide great flexibility for how you transport the XML representation of the . To obtain the XML representation of the as a string, use the `GetXml` method as shown in the following example. + +```vb +Dim xmlDS As String = custDS.GetXml() +``` + +```csharp +string xmlDS = custDS.GetXml(); +``` + + `GetXml` returns the XML representation of the without schema information. To write the schema information from the (as XML Schema) to a string, use **GetXmlSchema**. + + To write a to a file, stream, or **XmlWriter**, use the `WriteXml` method. The first parameter you pass to `WriteXml` is the destination of the XML output. For example, pass a string containing a file name, a **System.IO.TextWriter** object, and so on. You can pass an optional second parameter of an `XmlWriteMode` to specify how the XML output is to be written. + + The following table shows the options for **XmlWriteMode**. + +|XmlWriteMode option|Description| +|-------------------------|-----------------| +|**IgnoreSchema**|Writes the current contents of the as XML data, without an XML Schema. This is the default.| +|**WriteSchema**|Writes the current contents of the as XML data with the relational structure as inline XML Schema.| +|**DiffGram**|Writes the entire as a DiffGram, including original and current values. For more information, see [DiffGrams](diffgrams.md).| + + When writing an XML representation of a that contains `DataRelation` objects, you will most likely want the resulting XML to have the child rows of each relation nested within their related parent elements. To accomplish this, set the `Nested` property of the `DataRelation` to `true` when you add the `DataRelation` to the . For more information, see [Nesting DataRelations](nesting-datarelations.md). + The following are two examples of how to write the XML representation of a to a file. The first example passes the file name for the resulting XML as a string to **WriteXml**. The second example passes a **System.IO.StreamWriter** object. - -```vb -custDS.WriteXml("Customers.xml", XmlWriteMode.WriteSchema) -``` - -```csharp -custDS.WriteXml("Customers.xml", XmlWriteMode.WriteSchema); -``` - -```vb -Dim xmlSW As System.IO.StreamWriter = New System.IO.StreamWriter("Customers.xml") -custDS.WriteXml(xmlSW, XmlWriteMode.WriteSchema) -xmlSW.Close() -``` - -```csharp -System.IO.StreamWriter xmlSW = new System.IO.StreamWriter("Customers.xml"); -custDS.WriteXml(xmlSW, XmlWriteMode.WriteSchema); -xmlSW.Close(); -``` - -## Mapping Columns to XML Elements, Attributes, and Text - - You can specify how a column of a table is represented in XML using the **ColumnMapping** property of the **DataColumn** object. The following table shows the different **MappingType** values for the **ColumnMapping** property of a table column, and the resulting XML. - -|MappingType value|Description| -|-----------------------|-----------------| -|**Element**|This is the default. The column is written as an XML element where the ColumnName is the name of the element and the contents of the column are written as the text of the element. For example:

`Column Contents`| -|**Attribute**|The column is written as an XML attribute of the XML element for the current row where the ColumnName is the name of the attribute and the contents of the column are written as the value of the attribute. For example:

``| -|**SimpleContent**|The contents of the column are written as text in the XML element for the current row. For example:

`Column Contents`

Note that **SimpleContent** cannot be set for a column of a table that has **Element** columns or nested relations.| -|**Hidden**|The column is not written in the XML output.| - + +```vb +custDS.WriteXml("Customers.xml", XmlWriteMode.WriteSchema) +``` + +```csharp +custDS.WriteXml("Customers.xml", XmlWriteMode.WriteSchema); +``` + +```vb +Dim xmlSW As System.IO.StreamWriter = New System.IO.StreamWriter("Customers.xml") +custDS.WriteXml(xmlSW, XmlWriteMode.WriteSchema) +xmlSW.Close() +``` + +```csharp +System.IO.StreamWriter xmlSW = new System.IO.StreamWriter("Customers.xml"); +custDS.WriteXml(xmlSW, XmlWriteMode.WriteSchema); +xmlSW.Close(); +``` + +## Mapping Columns to XML Elements, Attributes, and Text + + You can specify how a column of a table is represented in XML using the `ColumnMapping` property of the `DataColumn` object. The following table shows the different `MappingType` values for the `ColumnMapping` property of a table column, and the resulting XML. + +|MappingType value|Description| +|-----------------------|-----------------| +|**Element**|This is the default. The column is written as an XML element where the ColumnName is the name of the element and the contents of the column are written as the text of the element. For example:

`Column Contents`| +|**Attribute**|The column is written as an XML attribute of the XML element for the current row where the ColumnName is the name of the attribute and the contents of the column are written as the value of the attribute. For example:

``| +|**SimpleContent**|The contents of the column are written as text in the XML element for the current row. For example:

`Column Contents`

Note that `SimpleContent` cannot be set for a column of a table that has `Element` columns or nested relations.| +|**Hidden**|The column is not written in the XML output.| + ## See also - [Using XML in a DataSet](using-xml-in-a-dataset.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/writing-dataset-schema-information-as-xsd.md b/docs/framework/data/adonet/dataset-datatable-dataview/writing-dataset-schema-information-as-xsd.md index 6445b312b82ba..002db885808f0 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/writing-dataset-schema-information-as-xsd.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/writing-dataset-schema-information-as-xsd.md @@ -2,49 +2,49 @@ description: "Learn more about: Writing DataSet Schema Information as XSD" title: "Writing DataSet Schema Information as XSD" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 4e530831-695e-49ff-8f0b-e5b0c526b8eb --- # Writing DataSet Schema Information as XSD -You can write the schema of a as XML Schema definition language (XSD) schema, so that you can transport it, with or without related data, in an XML document. XML Schema can be written to a file, a stream, an , or a string; it is useful for generating a strongly typed **DataSet**. For more information about strongly typed **DataSet** objects, see [Typed DataSets](typed-datasets.md). - - You can specify how a column of a table is represented in XML Schema using the **ColumnMapping** property of the object. For more information, see "Mapping Columns to XML Elements, Attributes, and Text" in [Writing DataSet Contents as XML Data](writing-dataset-contents-as-xml-data.md). - - To write the schema of a **DataSet** as XML Schema, to a file, stream, or **XmlWriter**, use the **WriteXmlSchema** method of the **DataSet**. **WriteXmlSchema** takes one parameter that specifies the destination of the resulting XML Schema. The following code examples demonstrate how to write the XML Schema of a **DataSet** to a file by passing a string containing a file name and a object. - -```vb -dataSet.WriteXmlSchema("Customers.xsd") -``` - -```csharp -dataSet.WriteXmlSchema("Customers.xsd"); -``` - -```vb -Dim writer As System.IO.StreamWriter = New System.IO.StreamWriter("Customers.xsd") -dataSet.WriteXmlSchema(writer) -writer.Close() -``` - -```csharp -System.IO.StreamWriter writer = new System.IO.StreamWriter("Customers.xsd"); -dataSet.WriteXmlSchema(writer); -writer.Close(); -``` - - To obtain the schema of a **DataSet** and write it as an XML Schema string, use the **GetXmlSchema** method, as shown in the following example. - -```vb -Dim schemaString As String = dataSet.GetXmlSchema() -``` - -```csharp -string schemaString = dataSet.GetXmlSchema(); -``` - +You can write the schema of a as XML Schema definition language (XSD) schema, so that you can transport it, with or without related data, in an XML document. XML Schema can be written to a file, a stream, an , or a string; it is useful for generating a strongly typed **DataSet**. For more information about strongly typed `DataSet` objects, see [Typed DataSets](typed-datasets.md). + + You can specify how a column of a table is represented in XML Schema using the `ColumnMapping` property of the object. For more information, see "Mapping Columns to XML Elements, Attributes, and Text" in [Writing DataSet Contents as XML Data](writing-dataset-contents-as-xml-data.md). + + To write the schema of a `DataSet` as XML Schema, to a file, stream, or **XmlWriter**, use the `WriteXmlSchema` method of the **DataSet**. `WriteXmlSchema` takes one parameter that specifies the destination of the resulting XML Schema. The following code examples demonstrate how to write the XML Schema of a `DataSet` to a file by passing a string containing a file name and a object. + +```vb +dataSet.WriteXmlSchema("Customers.xsd") +``` + +```csharp +dataSet.WriteXmlSchema("Customers.xsd"); +``` + +```vb +Dim writer As System.IO.StreamWriter = New System.IO.StreamWriter("Customers.xsd") +dataSet.WriteXmlSchema(writer) +writer.Close() +``` + +```csharp +System.IO.StreamWriter writer = new System.IO.StreamWriter("Customers.xsd"); +dataSet.WriteXmlSchema(writer); +writer.Close(); +``` + + To obtain the schema of a `DataSet` and write it as an XML Schema string, use the `GetXmlSchema` method, as shown in the following example. + +```vb +Dim schemaString As String = dataSet.GetXmlSchema() +``` + +```csharp +string schemaString = dataSet.GetXmlSchema(); +``` + ## See also - [Using XML in a DataSet](using-xml-in-a-dataset.md) diff --git a/docs/framework/data/adonet/dataset-datatable-dataview/xml-schema-constraints-and-relationships.md b/docs/framework/data/adonet/dataset-datatable-dataview/xml-schema-constraints-and-relationships.md index 0353207f3552a..1ae63a7676dbf 100644 --- a/docs/framework/data/adonet/dataset-datatable-dataview/xml-schema-constraints-and-relationships.md +++ b/docs/framework/data/adonet/dataset-datatable-dataview/xml-schema-constraints-and-relationships.md @@ -6,183 +6,183 @@ ms.assetid: 165bc2bc-60a1-40e0-9b89-7c68ef979079 --- # XML Schema Constraints and Relationships -In an XML Schema definition language (XSD) schema, you can specify constraints (unique, key, and keyref constraints) and relationships (using the **msdata:Relationship** annotation). This topic explains how the constraints and relationships specified in an XML Schema are interpreted to generate the . - - In general, in an XML Schema, you specify the **msdata:Relationship** annotation if you want to generate only relationships in the **DataSet**. For more information, see [Generating DataSet Relations from XML Schema (XSD)](generating-dataset-relations-from-xml-schema-xsd.md). You specify constraints (unique, key, and keyref) if you want to generate constraints in the **DataSet**. Note that the key and keyref constraints are also used to generate relationships, as explained later in this topic. - -## Generating a Relationship from key and keyref Constraints - - Instead of specifying the **msdata:Relationship** annotation, you can specify key and keyref constraints, which are used during the XML Schema mapping process to generate not only the constraints but also the relationship in the **DataSet**. However, if you specify `msdata:ConstraintOnly="true"` in the **keyref** element, the **DataSet** will include only the constraints and will not include the relationship. - - The following example shows an XML Schema that includes **Order** and **OrderDetail** elements, which are not nested. The schema also specifies key and keyref constraints. - -```xml +In an XML Schema definition language (XSD) schema, you can specify constraints (unique, key, and keyref constraints) and relationships (using the **msdata:Relationship** annotation). This topic explains how the constraints and relationships specified in an XML Schema are interpreted to generate the . + + In general, in an XML Schema, you specify the **msdata:Relationship** annotation if you want to generate only relationships in the **DataSet**. For more information, see [Generating DataSet Relations from XML Schema (XSD)](generating-dataset-relations-from-xml-schema-xsd.md). You specify constraints (unique, key, and keyref) if you want to generate constraints in the **DataSet**. Note that the key and keyref constraints are also used to generate relationships, as explained later in this topic. + +## Generating a Relationship from key and keyref Constraints + + Instead of specifying the **msdata:Relationship** annotation, you can specify key and keyref constraints, which are used during the XML Schema mapping process to generate not only the constraints but also the relationship in the **DataSet**. However, if you specify `msdata:ConstraintOnly="true"` in the `keyref` element, the `DataSet` will include only the constraints and will not include the relationship. + + The following example shows an XML Schema that includes `Order` and `OrderDetail` elements, which are not nested. The schema also specifies key and keyref constraints. + +```xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -``` - - The **DataSet** that is generated during the XML Schema mapping process includes the **Order** and **OrderDetail** tables. In addition, the **DataSet** includes relationships and constraints. The following example shows these relationships and constraints. Note that the schema does not specify the **msdata:Relationship** annotation; instead, the key and keyref constraints are used to generate the relation. - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + + The `DataSet` that is generated during the XML Schema mapping process includes the `Order` and `OrderDetail` tables. In addition, the `DataSet` includes relationships and constraints. The following example shows these relationships and constraints. Note that the schema does not specify the **msdata:Relationship** annotation; instead, the key and keyref constraints are used to generate the relation. + ```text -....ConstraintName: OrderNumberKey -....Type: UniqueConstraint -....Table: Order -....Columns: OrderNumber -....IsPrimaryKey: False - -....ConstraintName: OrderNoRef -....Type: ForeignKeyConstraint -....Table: OrderDetail -....Columns: OrderNo -....RelatedTable: Order -....RelatedColumns: OrderNumber - -..RelationName: OrderNoRef -..ParentTable: Order -..ParentColumns: OrderNumber -..ChildTable: OrderDetail -..ChildColumns: OrderNo -..ParentKeyConstraint: OrderNumberKey -..ChildKeyConstraint: OrderNoRef -..Nested: False -``` - - In the previous schema example, the **Order** and **OrderDetail** elements are not nested. In the following schema example, these elements are nested. However, no **msdata:Relationship** annotation is specified; therefore, an implicit relation is assumed. For more information, see [Map Implicit Relations Between Nested Schema Elements](map-implicit-relations-between-nested-schema-elements.md). The schema also specifies key and keyref constraints. - -```xml +....ConstraintName: OrderNumberKey +....Type: UniqueConstraint +....Table: Order +....Columns: OrderNumber +....IsPrimaryKey: False + +....ConstraintName: OrderNoRef +....Type: ForeignKeyConstraint +....Table: OrderDetail +....Columns: OrderNo +....RelatedTable: Order +....RelatedColumns: OrderNumber + +..RelationName: OrderNoRef +..ParentTable: Order +..ParentColumns: OrderNumber +..ChildTable: OrderDetail +..ChildColumns: OrderNo +..ParentKeyConstraint: OrderNumberKey +..ChildKeyConstraint: OrderNoRef +..Nested: False +``` + + In the previous schema example, the `Order` and `OrderDetail` elements are not nested. In the following schema example, these elements are nested. However, no **msdata:Relationship** annotation is specified; therefore, an implicit relation is assumed. For more information, see [Map Implicit Relations Between Nested Schema Elements](map-implicit-relations-between-nested-schema-elements.md). The schema also specifies key and keyref constraints. + +```xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -``` - - The **DataSet** resulting from the XML Schema mapping process includes two tables: - -```text -Order(OrderNumber, EmpNumber, Order_Id) -OrderDetail(OrderNumber, ItemNumber, Order_Id) -``` - - The **DataSet** also includes the two relationships (one based on the **msdata:relationship** annotation and the other based on the key and keyref constraints) and various constraints. The following example shows the relations and constraints. - + xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + + The `DataSet` resulting from the XML Schema mapping process includes two tables: + +```text +Order(OrderNumber, EmpNumber, Order_Id) +OrderDetail(OrderNumber, ItemNumber, Order_Id) +``` + + The `DataSet` also includes the two relationships (one based on the **msdata:relationship** annotation and the other based on the key and keyref constraints) and various constraints. The following example shows the relations and constraints. + ```text -..RelationName: Order_OrderDetail -..ParentTable: Order -..ParentColumns: Order_Id -..ChildTable: OrderDetail -..ChildColumns: Order_Id -..ParentKeyConstraint: Constraint1 -..ChildKeyConstraint: Order_OrderDetail -..Nested: True - -..RelationName: OrderNoRef -..ParentTable: Order -..ParentColumns: OrderNumber -..ChildTable: OrderDetail -..ChildColumns: OrderNo -..ParentKeyConstraint: OrderNumberKey -..ChildKeyConstraint: OrderNoRef -..Nested: False - -..ConstraintName: OrderNumberKey -..Type: UniqueConstraint -..Table: Order -..Columns: OrderNumber -..IsPrimaryKey: False - -..ConstraintName: Constraint1 -..Type: UniqueConstraint -..Table: Order -..Columns: Order_Id -..IsPrimaryKey: True - -..ConstraintName: Order_OrderDetail -..Type: ForeignKeyConstraint -..Table: OrderDetail -..Columns: Order_Id -..RelatedTable: Order -..RelatedColumns: Order_Id - -..ConstraintName: OrderNoRef -..Type: ForeignKeyConstraint -..Table: OrderDetail -..Columns: OrderNo -..RelatedTable: Order -..RelatedColumns: OrderNumber -``` - - If a keyref constraint referring to a nested table contains the **msdata:IsNested="true"** annotation, the **DataSet** will create a single nested relationship that is based on the keyref constraint and the related unique/key constraint. - +..RelationName: Order_OrderDetail +..ParentTable: Order +..ParentColumns: Order_Id +..ChildTable: OrderDetail +..ChildColumns: Order_Id +..ParentKeyConstraint: Constraint1 +..ChildKeyConstraint: Order_OrderDetail +..Nested: True + +..RelationName: OrderNoRef +..ParentTable: Order +..ParentColumns: OrderNumber +..ChildTable: OrderDetail +..ChildColumns: OrderNo +..ParentKeyConstraint: OrderNumberKey +..ChildKeyConstraint: OrderNoRef +..Nested: False + +..ConstraintName: OrderNumberKey +..Type: UniqueConstraint +..Table: Order +..Columns: OrderNumber +..IsPrimaryKey: False + +..ConstraintName: Constraint1 +..Type: UniqueConstraint +..Table: Order +..Columns: Order_Id +..IsPrimaryKey: True + +..ConstraintName: Order_OrderDetail +..Type: ForeignKeyConstraint +..Table: OrderDetail +..Columns: Order_Id +..RelatedTable: Order +..RelatedColumns: Order_Id + +..ConstraintName: OrderNoRef +..Type: ForeignKeyConstraint +..Table: OrderDetail +..Columns: OrderNo +..RelatedTable: Order +..RelatedColumns: OrderNumber +``` + + If a keyref constraint referring to a nested table contains the **msdata:IsNested="true"** annotation, the `DataSet` will create a single nested relationship that is based on the keyref constraint and the related unique/key constraint. + ## See also - [Deriving DataSet Relational Structure from XML Schema (XSD)](deriving-dataset-relational-structure-from-xml-schema-xsd.md) diff --git a/docs/framework/data/adonet/establishing-the-connection.md b/docs/framework/data/adonet/establishing-the-connection.md index d6e69674a233a..cab7d4bf87ff6 100644 --- a/docs/framework/data/adonet/establishing-the-connection.md +++ b/docs/framework/data/adonet/establishing-the-connection.md @@ -54,18 +54,18 @@ using (SqlConnection connection = new SqlConnection(connectionString)) ## Connect to an OLE DB Data Source - The .NET Framework Data Provider for OLE DB provides connectivity to data sources exposed using OLE DB (through SQLOLEDB, the OLE DB Provider for SQL Server), using the **OleDbConnection** object. + The .NET Framework Data Provider for OLE DB provides connectivity to data sources exposed using OLE DB (through SQLOLEDB, the OLE DB Provider for SQL Server), using the `OleDbConnection` object. For the .NET Framework Data Provider for OLE DB, the connection string format is identical to the connection string format used in ADO, with the following exceptions: -- The **Provider** keyword is required. +- The `Provider` keyword is required. - The **URL**, **Remote Provider**, and **Remote Server** keywords are not supported. For more information about OLE DB connection strings, see the article. You can also use the to create connection strings at run time. > [!NOTE] -> The **OleDbConnection** object does not support setting or retrieving dynamic properties specific to an OLE DB provider. Only properties that can be passed in the connection string for the OLE DB provider are supported. +> The `OleDbConnection` object does not support setting or retrieving dynamic properties specific to an OLE DB provider. Only properties that can be passed in the connection string for the OLE DB provider are supported. The following code example demonstrates how to create and open a connection to an OLE DB data source. @@ -89,13 +89,13 @@ using (OleDbConnection connection = ## Do Not Use Universal Data Link Files - It is possible to supply connection information for an **OleDbConnection** in a Universal Data Link (UDL) file; however you should avoid doing so. UDL files are not encrypted, and expose connection string information in clear text. Because a UDL file is an external file-based resource to your application, it cannot be secured using the .NET Framework. + It is possible to supply connection information for an `OleDbConnection` in a Universal Data Link (UDL) file; however you should avoid doing so. UDL files are not encrypted, and expose connection string information in clear text. Because a UDL file is an external file-based resource to your application, it cannot be secured using the .NET Framework. ## Connect to an ODBC Data Source - The .NET Framework Data Provider for ODBC provides connectivity to data sources exposed using ODBC using the **OdbcConnection** object. + The .NET Framework Data Provider for ODBC provides connectivity to data sources exposed using ODBC using the `OdbcConnection` object. - For the .NET Framework Data Provider for ODBC, the connection string format is designed to match the ODBC connection string format as closely as possible. You may also supply an ODBC data source name (DSN). For more detail on the **OdbcConnection** , see the . + For the .NET Framework Data Provider for ODBC, the connection string format is designed to match the ODBC connection string format as closely as possible. You may also supply an ODBC data source name (DSN). For more detail on the `OdbcConnection` , see the . The following code example demonstrates how to create and open a connection to an ODBC data source. @@ -119,7 +119,7 @@ using (OdbcConnection connection = ## Connect to an Oracle Data Source - The .NET Framework Data Provider for Oracle provides connectivity to Oracle data sources using the **OracleConnection** object. + The .NET Framework Data Provider for Oracle provides connectivity to Oracle data sources using the `OracleConnection` object. For the .NET Framework Data Provider for Oracle, the connection string format is designed to match the OLE DB Provider for Oracle (MSDAORA) connection string format as closely as possible. For more detail on the **OracleConnection**, see the . diff --git a/docs/framework/data/adonet/generating-commands-with-commandbuilders.md b/docs/framework/data/adonet/generating-commands-with-commandbuilders.md index 720a276048483..46ca339e6085f 100644 --- a/docs/framework/data/adonet/generating-commands-with-commandbuilders.md +++ b/docs/framework/data/adonet/generating-commands-with-commandbuilders.md @@ -2,119 +2,119 @@ description: "Learn more about: Generating Commands with CommandBuilders" title: "Generating Commands with CommandBuilders" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 6e3fb8b5-373b-4f9e-ab03-a22693df8e91 --- # Generating Commands with CommandBuilders -When the `SelectCommand` property is dynamically specified at run time, such as through a query tool that takes a textual command from the user, you may not be able to specify the appropriate `InsertCommand`, `UpdateCommand`, or `DeleteCommand` at design time. If your maps to or is generated from a single database table, you can take advantage of the object to automatically generate the `DeleteCommand`, `InsertCommand`, and `UpdateCommand` of the . - - As a minimum requirement, you must set the `SelectCommand` property in order for automatic command generation to work. The table schema retrieved by the `SelectCommand` property determines the syntax of the automatically generated INSERT, UPDATE, and DELETE statements. - - The must execute the `SelectCommand` in order to return the metadata necessary to construct the INSERT, UPDATE, and DELETE SQL commands. As a result, an extra trip to the data source is necessary, and this can hinder performance. To achieve optimal performance, specify your commands explicitly rather than using the . - - The `SelectCommand` must also return at least one primary key or unique column. If none are present, an `InvalidOperation` exception is generated, and the commands are not generated. - - When associated with a `DataAdapter`, the automatically generates the `InsertCommand`, `UpdateCommand`, and `DeleteCommand` properties of the `DataAdapter` if they are null references. If a `Command` already exists for a property, the existing `Command` is used. - - Database views that are created by joining two or more tables together are not considered a single database table. In this instance you cannot use the to automatically generate commands; you must specify your commands explicitly. For information about explicitly setting commands to resolve updates to a `DataSet` back to the data source, see [Updating Data Sources with DataAdapters](updating-data-sources-with-dataadapters.md). - - You might want to map output parameters back to the updated row of a `DataSet`. One common task would be retrieving the value of an automatically generated identity field or time stamp from the data source. The will not map output parameters to columns in an updated row by default. In this instance you must specify your command explicitly. For an example of mapping an automatically generated identity field back to a column of an inserted row, see [Retrieving Identity or Autonumber Values](retrieving-identity-or-autonumber-values.md). - -## Rules for Automatically Generated Commands - - The following table shows the rules for how automatically generated commands are generated. - -|Command|Rule| -|-------------|----------| -|`InsertCommand`|Inserts a row at the data source for all rows in the table with a of . Inserts values for all columns that are updateable (but not columns such as identities, expressions, or timestamps).| -|`UpdateCommand`|Updates rows at the data source for all rows in the table with a `RowState` of . Updates the values of all columns except for columns that are not updateable, such as identities or expressions. Updates all rows where the column values at the data source match the primary key column values of the row, and where the remaining columns at the data source match the original values of the row. For more information, see "Optimistic Concurrency Model for Updates and Deletes," later in this topic.| -|`DeleteCommand`|Deletes rows at the data source for all rows in the table with a `RowState` of . Deletes all rows where the column values match the primary key column values of the row, and where the remaining columns at the data source match the original values of the row. For more information, see "Optimistic Concurrency Model for Updates and Deletes," later in this topic.| - -## Optimistic Concurrency Model for Updates and Deletes - - The logic for generating commands automatically for UPDATE and DELETE statements is based on *optimistic concurrency*--that is, records are not locked for editing and can be modified by other users or processes at any time. Because a record could have been modified after it was returned from the SELECT statement, but before the UPDATE or DELETE statement is issued, the automatically generated UPDATE or DELETE statement contains a WHERE clause, specifying that a row is only updated if it contains all original values and has not been deleted from the data source. This is done to avoid overwriting new data. Where an automatically generated update attempts to update a row that has been deleted or that does not contain the original values found in the , the command does not affect any records, and a is thrown. - - If you want the UPDATE or DELETE to complete regardless of original values, you must explicitly set the `UpdateCommand` for the `DataAdapter` and not rely on automatic command generation. - -## Limitations of Automatic Command Generation Logic - - The following limitations apply to automatic command generation. - -### Unrelated Tables Only - - The automatic command generation logic generates INSERT, UPDATE, or DELETE statements for stand-alone tables without taking into account any relationships to other tables at the data source. As a result, you may encounter a failure when calling `Update` to submit changes for a column that participates in a foreign key constraint in the database. To avoid this exception, do not use the for updating columns involved in a foreign key constraint; instead, explicitly specify the statements used to perform the operation. - -### Table and Column Names - - Automatic command generation logic may fail if column names or table names contain any special characters, such as spaces, periods, quotation marks, or other nonalphanumeric characters, even if delimited by brackets. Depending on the provider, setting the QuotePrefix and QuoteSuffix parameters may allow the generation logic to process spaces, but it cannot escape special characters. Fully qualified table names in the form of *catalog.schema.table* are supported. - -## Using the CommandBuilder to Automatically Generate an SQL Statement - - To automatically generate SQL statements for a `DataAdapter`, first set the `SelectCommand` property of the `DataAdapter`, then create a `CommandBuilder` object, and specify as an argument the `DataAdapter` for which the `CommandBuilder` will automatically generate SQL statements. - -```vb +When the `SelectCommand` property is dynamically specified at run time, such as through a query tool that takes a textual command from the user, you may not be able to specify the appropriate `InsertCommand`, `UpdateCommand`, or `DeleteCommand` at design time. If your maps to or is generated from a single database table, you can take advantage of the object to automatically generate the `DeleteCommand`, `InsertCommand`, and `UpdateCommand` of the . + + As a minimum requirement, you must set the `SelectCommand` property in order for automatic command generation to work. The table schema retrieved by the `SelectCommand` property determines the syntax of the automatically generated INSERT, UPDATE, and DELETE statements. + + The must execute the `SelectCommand` in order to return the metadata necessary to construct the INSERT, UPDATE, and DELETE SQL commands. As a result, an extra trip to the data source is necessary, and this can hinder performance. To achieve optimal performance, specify your commands explicitly rather than using the . + + The `SelectCommand` must also return at least one primary key or unique column. If none are present, an `InvalidOperation` exception is generated, and the commands are not generated. + + When associated with a `DataAdapter`, the automatically generates the `InsertCommand`, `UpdateCommand`, and `DeleteCommand` properties of the `DataAdapter` if they are null references. If a `Command` already exists for a property, the existing `Command` is used. + + Database views that are created by joining two or more tables together are not considered a single database table. In this instance you cannot use the to automatically generate commands; you must specify your commands explicitly. For information about explicitly setting commands to resolve updates to a `DataSet` back to the data source, see [Updating Data Sources with DataAdapters](updating-data-sources-with-dataadapters.md). + + You might want to map output parameters back to the updated row of a `DataSet`. One common task would be retrieving the value of an automatically generated identity field or time stamp from the data source. The will not map output parameters to columns in an updated row by default. In this instance you must specify your command explicitly. For an example of mapping an automatically generated identity field back to a column of an inserted row, see [Retrieving Identity or Autonumber Values](retrieving-identity-or-autonumber-values.md). + +## Rules for Automatically Generated Commands + + The following table shows the rules for how automatically generated commands are generated. + +|Command|Rule| +|-------------|----------| +|`InsertCommand`|Inserts a row at the data source for all rows in the table with a of . Inserts values for all columns that are updateable (but not columns such as identities, expressions, or timestamps).| +|`UpdateCommand`|Updates rows at the data source for all rows in the table with a `RowState` of . Updates the values of all columns except for columns that are not updateable, such as identities or expressions. Updates all rows where the column values at the data source match the primary key column values of the row, and where the remaining columns at the data source match the original values of the row. For more information, see "Optimistic Concurrency Model for Updates and Deletes," later in this topic.| +|`DeleteCommand`|Deletes rows at the data source for all rows in the table with a `RowState` of . Deletes all rows where the column values match the primary key column values of the row, and where the remaining columns at the data source match the original values of the row. For more information, see "Optimistic Concurrency Model for Updates and Deletes," later in this topic.| + +## Optimistic Concurrency Model for Updates and Deletes + + The logic for generating commands automatically for UPDATE and DELETE statements is based on *optimistic concurrency*--that is, records are not locked for editing and can be modified by other users or processes at any time. Because a record could have been modified after it was returned from the SELECT statement, but before the UPDATE or DELETE statement is issued, the automatically generated UPDATE or DELETE statement contains a WHERE clause, specifying that a row is only updated if it contains all original values and has not been deleted from the data source. This is done to avoid overwriting new data. Where an automatically generated update attempts to update a row that has been deleted or that does not contain the original values found in the , the command does not affect any records, and a is thrown. + + If you want the UPDATE or DELETE to complete regardless of original values, you must explicitly set the `UpdateCommand` for the `DataAdapter` and not rely on automatic command generation. + +## Limitations of Automatic Command Generation Logic + + The following limitations apply to automatic command generation. + +### Unrelated Tables Only + + The automatic command generation logic generates INSERT, UPDATE, or DELETE statements for stand-alone tables without taking into account any relationships to other tables at the data source. As a result, you may encounter a failure when calling `Update` to submit changes for a column that participates in a foreign key constraint in the database. To avoid this exception, do not use the for updating columns involved in a foreign key constraint; instead, explicitly specify the statements used to perform the operation. + +### Table and Column Names + + Automatic command generation logic may fail if column names or table names contain any special characters, such as spaces, periods, quotation marks, or other nonalphanumeric characters, even if delimited by brackets. Depending on the provider, setting the QuotePrefix and QuoteSuffix parameters may allow the generation logic to process spaces, but it cannot escape special characters. Fully qualified table names in the form of *catalog.schema.table* are supported. + +## Using the CommandBuilder to Automatically Generate an SQL Statement + + To automatically generate SQL statements for a `DataAdapter`, first set the `SelectCommand` property of the `DataAdapter`, then create a `CommandBuilder` object, and specify as an argument the `DataAdapter` for which the `CommandBuilder` will automatically generate SQL statements. + +```vb ' Assumes that connection is a valid SqlConnection object -' inside of a Using block. -Dim adapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT * FROM dbo.Customers", connection) -Dim builder As SqlCommandBuilder = New SqlCommandBuilder(adapter) -builder.QuotePrefix = "[" -builder.QuoteSuffix = "]" -``` - -```csharp -// Assumes that connection is a valid SqlConnection object -// inside of a using block. -SqlDataAdapter adapter = new SqlDataAdapter( - "SELECT * FROM dbo.Customers", connection); -SqlCommandBuilder builder = new SqlCommandBuilder(adapter); -builder.QuotePrefix = "["; -builder.QuoteSuffix = "]"; -``` - -## Modifying the SelectCommand - - If you modify the `CommandText` of the `SelectCommand` after the INSERT, UPDATE, or DELETE commands have been automatically generated, an exception may occur. If the modified `SelectCommand.CommandText` contains schema information that is inconsistent with the `SelectCommand.CommandText` used when the insert, update, or delete commands were automatically generated, future calls to the `DataAdapter.Update` method may attempt to access columns that no longer exist in the current table referenced by the `SelectCommand`, and an exception will be thrown. - - You can refresh the schema information used by the `CommandBuilder` to automatically generate commands by calling the `RefreshSchema` method of the `CommandBuilder`. - - If you want to know what command was automatically generated, you can obtain a reference to the automatically generated commands by using the `GetInsertCommand`, `GetUpdateCommand`, and `GetDeleteCommand` methods of the `CommandBuilder` object and checking the `CommandText` property of the associated command. - - The following code example writes to the console the update command that was automatically generated. - +' inside of a Using block. +Dim adapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT * FROM dbo.Customers", connection) +Dim builder As SqlCommandBuilder = New SqlCommandBuilder(adapter) +builder.QuotePrefix = "[" +builder.QuoteSuffix = "]" +``` + +```csharp +// Assumes that connection is a valid SqlConnection object +// inside of a using block. +SqlDataAdapter adapter = new SqlDataAdapter( + "SELECT * FROM dbo.Customers", connection); +SqlCommandBuilder builder = new SqlCommandBuilder(adapter); +builder.QuotePrefix = "["; +builder.QuoteSuffix = "]"; +``` + +## Modifying the SelectCommand + + If you modify the `CommandText` of the `SelectCommand` after the INSERT, UPDATE, or DELETE commands have been automatically generated, an exception may occur. If the modified `SelectCommand.CommandText` contains schema information that is inconsistent with the `SelectCommand.CommandText` used when the insert, update, or delete commands were automatically generated, future calls to the `DataAdapter.Update` method may attempt to access columns that no longer exist in the current table referenced by the `SelectCommand`, and an exception will be thrown. + + You can refresh the schema information used by the `CommandBuilder` to automatically generate commands by calling the `RefreshSchema` method of the `CommandBuilder`. + + If you want to know what command was automatically generated, you can obtain a reference to the automatically generated commands by using the `GetInsertCommand`, `GetUpdateCommand`, and `GetDeleteCommand` methods of the `CommandBuilder` object and checking the `CommandText` property of the associated command. + + The following code example writes to the console the update command that was automatically generated. + ```vb -Console.WriteLine(builder.GetUpdateCommand().CommandText) +Console.WriteLine(builder.GetUpdateCommand().CommandText) ``` ```csharp Console.WriteLine(builder.GetUpdateCommand().CommandText); ``` - - The following example recreates the `Customers` table in the `custDS` dataset. The **RefreshSchema** method is called to refresh the automatically generated commands with this new column information. - -```vb -' Assumes an open SqlConnection and SqlDataAdapter inside of a Using block. -adapter.SelectCommand.CommandText = _ - "SELECT CustomerID, ContactName FROM dbo.Customers" -builder.RefreshSchema() - -custDS.Tables.Remove(custDS.Tables("Customers")) -adapter.Fill(custDS, "Customers") -``` - -```csharp -// Assumes an open SqlConnection and SqlDataAdapter inside of a using block. + + The following example recreates the `Customers` table in the `custDS` dataset. The `RefreshSchema` method is called to refresh the automatically generated commands with this new column information. + +```vb +' Assumes an open SqlConnection and SqlDataAdapter inside of a Using block. +adapter.SelectCommand.CommandText = _ + "SELECT CustomerID, ContactName FROM dbo.Customers" +builder.RefreshSchema() + +custDS.Tables.Remove(custDS.Tables("Customers")) +adapter.Fill(custDS, "Customers") +``` + +```csharp +// Assumes an open SqlConnection and SqlDataAdapter inside of a using block. adapter.SelectCommand.CommandText = - "SELECT CustomerID, ContactName FROM dbo.Customers"; -builder.RefreshSchema(); - -custDS.Tables.Remove(custDS.Tables["Customers"]); -adapter.Fill(custDS, "Customers"); -``` - + "SELECT CustomerID, ContactName FROM dbo.Customers"; +builder.RefreshSchema(); + +custDS.Tables.Remove(custDS.Tables["Customers"]); +adapter.Fill(custDS, "Customers"); +``` + ## See also - [Commands and Parameters](commands-and-parameters.md) diff --git a/docs/framework/data/adonet/getschema-and-schema-collections.md b/docs/framework/data/adonet/getschema-and-schema-collections.md index 6b30bc664ea91..5a047de2d0e40 100644 --- a/docs/framework/data/adonet/getschema-and-schema-collections.md +++ b/docs/framework/data/adonet/getschema-and-schema-collections.md @@ -8,17 +8,17 @@ dev_langs: --- # GetSchema and Schema Collections -The **Connection** classes in each of the .NET Framework managed providers implement a **GetSchema** method that's used to retrieve schema information about the database that is currently connected. The schema information returned from the **GetSchema** method comes in the form of a . The **GetSchema** method is an overloaded method that provides optional parameters for specifying the schema collection to return, and for restricting the amount of information returned. +The `Connection` classes in each of the .NET Framework managed providers implement a `GetSchema` method that's used to retrieve schema information about the database that is currently connected. The schema information returned from the `GetSchema` method comes in the form of a . The `GetSchema` method is an overloaded method that provides optional parameters for specifying the schema collection to return, and for restricting the amount of information returned. ## Specifying the Schema Collections - The first optional parameter of the **GetSchema** method is the collection name which is specified as a string. There are two types of schema collections: common schema collections that are common to all providers, and specific schema collections which are specific to each provider. + The first optional parameter of the `GetSchema` method is the collection name which is specified as a string. There are two types of schema collections: common schema collections that are common to all providers, and specific schema collections which are specific to each provider. - You can query a .NET Framework managed provider to determine the list of supported schema collections by calling the **GetSchema** method with no arguments, or with the schema collection name "MetaDataCollections". This will return a with a list of the supported schema collections, the number of restrictions that they each support, and the number of identifier parts that they use. + You can query a .NET Framework managed provider to determine the list of supported schema collections by calling the `GetSchema` method with no arguments, or with the schema collection name "MetaDataCollections". This will return a with a list of the supported schema collections, the number of restrictions that they each support, and the number of identifier parts that they use. ### Retrieving Schema Collections Example - The following examples demonstrate how to use the method of the .NET Framework Data Provider for the SQL Server class to retrieve schema information about all of the tables contained in the **AdventureWorks** sample database: + The following examples demonstrate how to use the method of the .NET Framework Data Provider for the SQL Server class to retrieve schema information about all of the tables contained in the `AdventureWorks` sample database: ```vb Imports System.Data.SqlClient diff --git a/docs/framework/data/adonet/modifying-data-with-stored-procedures.md b/docs/framework/data/adonet/modifying-data-with-stored-procedures.md index dd2d39b97e457..2963d58b578ee 100644 --- a/docs/framework/data/adonet/modifying-data-with-stored-procedures.md +++ b/docs/framework/data/adonet/modifying-data-with-stored-procedures.md @@ -2,40 +2,40 @@ description: "Learn more about: Modifying Data with Stored Procedures" title: "Modifying Data with Stored Procedures" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 7d8e9a46-1af6-4a02-bf61-969d77ae07e0 --- # Modifying Data with Stored Procedures -Stored procedures can accept data as input parameters and can return data as output parameters, result sets, or return values. The sample below illustrates how ADO.NET sends and receives input parameters, output parameters, and return values. The example inserts a new record into a table where the primary key column is an identity column in a SQL Server database. - +Stored procedures can accept data as input parameters and can return data as output parameters, result sets, or return values. The sample below illustrates how ADO.NET sends and receives input parameters, output parameters, and return values. The example inserts a new record into a table where the primary key column is an identity column in a SQL Server database. + > [!NOTE] -> If you are using SQL Server stored procedures to edit or delete data using a , make sure that you do not use SET NOCOUNT ON in the stored procedure definition. This causes the rows affected count returned to be zero, which the `DataAdapter` interprets as a concurrency conflict. In this event, a will be thrown. - -## Example +> If you are using SQL Server stored procedures to edit or delete data using a , make sure that you do not use SET NOCOUNT ON in the stored procedure definition. This causes the rows affected count returned to be zero, which the `DataAdapter` interprets as a concurrency conflict. In this event, a will be thrown. + +## Example + + The sample uses the following stored procedure to insert a new category into the `Northwind` **Categories** table. The stored procedure takes the value in the `CategoryName` column as an input parameter and uses the SCOPE_IDENTITY() function to retrieve the new value of the identity field, **CategoryID**, and return it in an output parameter. The RETURN statement uses the @@ROWCOUNT function to return the number of rows inserted. - The sample uses the following stored procedure to insert a new category into the **Northwind** **Categories** table. The stored procedure takes the value in the **CategoryName** column as an input parameter and uses the SCOPE_IDENTITY() function to retrieve the new value of the identity field, **CategoryID**, and return it in an output parameter. The RETURN statement uses the @@ROWCOUNT function to return the number of rows inserted. - ```sql -CREATE PROCEDURE dbo.InsertCategory - @CategoryName nvarchar(15), - @Identity int OUT -AS -INSERT INTO Categories (CategoryName) VALUES(@CategoryName) -SET @Identity = SCOPE_IDENTITY() -RETURN @@ROWCOUNT -``` - - The following code example uses the `InsertCategory` stored procedure shown above as the source for the of the . The `@Identity` output parameter will be reflected in the after the record has been inserted into the database when the `Update` method of the is called. The code also retrieves the return value. - +CREATE PROCEDURE dbo.InsertCategory + @CategoryName nvarchar(15), + @Identity int OUT +AS +INSERT INTO Categories (CategoryName) VALUES(@CategoryName) +SET @Identity = SCOPE_IDENTITY() +RETURN @@ROWCOUNT +``` + + The following code example uses the `InsertCategory` stored procedure shown above as the source for the of the . The `@Identity` output parameter will be reflected in the after the record has been inserted into the database when the `Update` method of the is called. The code also retrieves the return value. + > [!NOTE] -> When using the , you must specify parameters with a of **ReturnValue** before the other parameters. - +> When using the , you must specify parameters with a of `ReturnValue` before the other parameters. + [!code-csharp[DataWorks SqlClient.SprocIdentityReturn#1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/CS/source.cs#1)] - [!code-vb[DataWorks SqlClient.SprocIdentityReturn#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/VB/source.vb#1)] - + [!code-vb[DataWorks SqlClient.SprocIdentityReturn#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.SprocIdentityReturn/VB/source.vb#1)] + ## See also - [Retrieving and Modifying Data in ADO.NET](retrieving-and-modifying-data.md) diff --git a/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md b/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md index 2398fd0cb1aa2..63936d65b4328 100644 --- a/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md +++ b/docs/framework/data/adonet/obtaining-a-dbproviderfactory.md @@ -15,7 +15,7 @@ The process of obtaining a involves ## Registering DbProviderFactories - Each .NET Framework data provider that supports a factory-based class registers configuration information in the **DbProviderFactories** section of the **machine.config** file on the local computer. The following configuration file fragment shows the syntax and format for . + Each .NET Framework data provider that supports a factory-based class registers configuration information in the `DbProviderFactories` section of the **machine.config** file on the local computer. The following configuration file fragment shows the syntax and format for . ```xml @@ -30,18 +30,18 @@ The process of obtaining a involves ``` - The **invariant** attribute identifies the underlying data provider. This three-part naming syntax is also used when creating a new factory and for identifying the provider in an application configuration file so that the provider name, along with its associated connection string, can be retrieved at run time. + The `invariant` attribute identifies the underlying data provider. This three-part naming syntax is also used when creating a new factory and for identifying the provider in an application configuration file so that the provider name, along with its associated connection string, can be retrieved at run time. ## Retrieving Provider Information - You can retrieve information about all of the data providers installed on the local computer by using the method. It returns a named **DbProviderFactories** that contains the columns described in the following table. + You can retrieve information about all of the data providers installed on the local computer by using the method. It returns a named `DbProviderFactories` that contains the columns described in the following table. | Column ordinal | Column name | Example output | Description | |----------------|-----------------|--------------------------------------------|-------------------------------------------| -| 0 | **Name** | SqlClient Data Provider | Readable name for the data provider | -| 1 | **Description** | .Net Framework Data Provider for SqlServer | Readable description of the data provider | -| 2 | **InvariantName** | System.Data.SqlClient | Name that can be used programmatically to refer to the data provider| -| 3 | **AssemblyQualifiedName** | System.Data.SqlClient.SqlClientFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 | Fully qualified name of the factory class, which contains enough information to instantiate the object | +| 0 | `Name` | SqlClient Data Provider | Readable name for the data provider | +| 1 | `Description` | .Net Framework Data Provider for SqlServer | Readable description of the data provider | +| 2 | `InvariantName` | System.Data.SqlClient | Name that can be used programmatically to refer to the data provider| +| 3 | `AssemblyQualifiedName` | System.Data.SqlClient.SqlClientFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 | Fully qualified name of the factory class, which contains enough information to instantiate the object | This `DataTable` can be used to enable a user to select a at run time. The selected `DataRow` can then be passed to the method to create a strongly typed . A selected can be passed to the `GetFactory` method to create the desired `DbProviderFactory` object. @@ -56,7 +56,7 @@ The process of obtaining a involves The design pattern used for working with factories entails storing provider and connection string information in an application configuration file, such as **app.config** for a Windows application, and **web.config** for an ASP.NET application. - The following configuration file fragment demonstrates how to save two named connection strings: "NorthwindSQL" for a connection to the Northwind database in SQL Server, and "NorthwindAccess" for a connection to the Northwind database in Access/Jet. The **invariant** name is used for the **providerName** attribute. + The following configuration file fragment demonstrates how to save two named connection strings: "NorthwindSQL" for a connection to the Northwind database in SQL Server, and "NorthwindAccess" for a connection to the Northwind database in Access/Jet. The `invariant` name is used for the `providerName` attribute. ```xml diff --git a/docs/framework/data/adonet/obtaining-a-single-value-from-a-database.md b/docs/framework/data/adonet/obtaining-a-single-value-from-a-database.md index b6bbdb6d6086f..ddebca2b07389 100644 --- a/docs/framework/data/adonet/obtaining-a-single-value-from-a-database.md +++ b/docs/framework/data/adonet/obtaining-a-single-value-from-a-database.md @@ -2,20 +2,20 @@ title: "Obtaining a Single Value from a Database" description: Learn how to return a single value in ADO.NET. This example code returns the identity column value for an inserted record. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: b38526cd-a62a-48cb-822a-e91dfa68e02d --- # Obtaining a Single Value from a Database -You may need to return database information that is simply a single value rather than in the form of a table or data stream. For example, you may want to return the result of an aggregate function such as COUNT(\*), SUM(Price), or AVG(Quantity). The **Command** object provides the capability to return single values using the **ExecuteScalar** method. The **ExecuteScalar** method returns, as a scalar value, the value of the first column of the first row of the result set. - - The following code example inserts a new value in the database using a . The method is used to return the identity column value for the inserted record. - +You may need to return database information that is simply a single value rather than in the form of a table or data stream. For example, you may want to return the result of an aggregate function such as COUNT(\*), SUM(Price), or AVG(Quantity). The `Command` object provides the capability to return single values using the `ExecuteScalar` method. The `ExecuteScalar` method returns, as a scalar value, the value of the first column of the first row of the result set. + + The following code example inserts a new value in the database using a . The method is used to return the identity column value for the inserted record. + [!code-csharp[DataWorks SqlCommand.ExecuteScalar#1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/CS/source.cs#1)] - [!code-vb[DataWorks SqlCommand.ExecuteScalar#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/VB/source.vb#1)] - + [!code-vb[DataWorks SqlCommand.ExecuteScalar#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlCommand.ExecuteScalar/VB/source.vb#1)] + ## See also - [Commands and Parameters](commands-and-parameters.md) diff --git a/docs/framework/data/adonet/optimistic-concurrency.md b/docs/framework/data/adonet/optimistic-concurrency.md index 7dd9e592af0a5..2a2ab47c6dafe 100644 --- a/docs/framework/data/adonet/optimistic-concurrency.md +++ b/docs/framework/data/adonet/optimistic-concurrency.md @@ -2,209 +2,209 @@ description: "Learn more about: Optimistic Concurrency" title: "Optimistic Concurrency" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: e380edac-da67-4276-80a5-b64decae4947 --- # Optimistic Concurrency -In a multiuser environment, there are two models for updating data in a database: optimistic concurrency and pessimistic concurrency. The object is designed to encourage the use of optimistic concurrency for long-running activities, such as remoting data and interacting with data. - - Pessimistic concurrency involves locking rows at the data source to prevent other users from modifying data in a way that affects the current user. In a pessimistic model, when a user performs an action that causes a lock to be applied, other users cannot perform actions that would conflict with the lock until the lock owner releases it. This model is primarily used in environments where there is heavy contention for data, so that the cost of protecting data with locks is less than the cost of rolling back transactions if concurrency conflicts occur. - - Therefore, in a pessimistic concurrency model, a user who updates a row establishes a lock. Until the user has finished the update and released the lock, no one else can change that row. For this reason, pessimistic concurrency is best implemented when lock times will be short, as in programmatic processing of records. Pessimistic concurrency is not a scalable option when users are interacting with data and causing records to be locked for relatively large periods of time. - +In a multiuser environment, there are two models for updating data in a database: optimistic concurrency and pessimistic concurrency. The object is designed to encourage the use of optimistic concurrency for long-running activities, such as remoting data and interacting with data. + + Pessimistic concurrency involves locking rows at the data source to prevent other users from modifying data in a way that affects the current user. In a pessimistic model, when a user performs an action that causes a lock to be applied, other users cannot perform actions that would conflict with the lock until the lock owner releases it. This model is primarily used in environments where there is heavy contention for data, so that the cost of protecting data with locks is less than the cost of rolling back transactions if concurrency conflicts occur. + + Therefore, in a pessimistic concurrency model, a user who updates a row establishes a lock. Until the user has finished the update and released the lock, no one else can change that row. For this reason, pessimistic concurrency is best implemented when lock times will be short, as in programmatic processing of records. Pessimistic concurrency is not a scalable option when users are interacting with data and causing records to be locked for relatively large periods of time. + > [!NOTE] -> If you need to update multiple rows in the same operation, then creating a transaction is a more scalable option than using pessimistic locking. - - By contrast, users who use optimistic concurrency do not lock a row when reading it. When a user wants to update a row, the application must determine whether another user has changed the row since it was read. Optimistic concurrency is generally used in environments with a low contention for data. Optimistic concurrency improves performance because no locking of records is required, and locking of records requires additional server resources. Also, in order to maintain record locks, a persistent connection to the database server is required. Because this is not the case in an optimistic concurrency model, connections to the server are free to serve a larger number of clients in less time. - - In an optimistic concurrency model, a violation is considered to have occurred if, after a user receives a value from the database, another user modifies the value before the first user has attempted to modify it. How the server resolves a concurrency violation is best shown by first describing the following example. - - The following tables follow an example of optimistic concurrency. - - At 1:00 p.m., User1 reads a row from the database with the following values: - - **CustID LastName FirstName** - - 101 Smith Bob - -|Column name|Original value|Current value|Value in database| -|-----------------|--------------------|-------------------|-----------------------| -|CustID|101|101|101| -|LastName|Smith|Smith|Smith| -|FirstName|Bob|Bob|Bob| - - At 1:01 p.m., User2 reads the same row. - - At 1:03 p.m., User2 changes **FirstName** from "Bob" to "Robert" and updates the database. - -|Column name|Original value|Current value|Value in database| -|-----------------|--------------------|-------------------|-----------------------| -|CustID|101|101|101| -|LastName|Smith|Smith|Smith| -|FirstName|Bob|Robert|Bob| - - The update succeeds because the values in the database at the time of update match the original values that User2 has. - - At 1:05 p.m., User1 changes "Bob"'s first name to "James" and tries to update the row. - -|Column name|Original value|Current value|Value in database| -|-----------------|--------------------|-------------------|-----------------------| -|CustID|101|101|101| -|LastName|Smith|Smith|Smith| -|FirstName|Bob|James|Robert| - - At this point, User1 encounters an optimistic concurrency violation because the value in the database ("Robert") no longer matches the original value that User1 was expecting ("Bob"). The concurrency violation simply lets you know that the update failed. The decision now needs to be made whether to overwrite the changes supplied by User2 with the changes supplied by User1, or to cancel the changes by User1. - -## Testing for Optimistic Concurrency Violations - - There are several techniques for testing for an optimistic concurrency violation. One involves including a timestamp column in the table. Databases commonly provide timestamp functionality that can be used to identify the date and time when the record was last updated. Using this technique, a timestamp column is included in the table definition. Whenever the record is updated, the timestamp is updated to reflect the current date and time. In a test for optimistic concurrency violations, the timestamp column is returned with any query of the contents of the table. When an update is attempted, the timestamp value in the database is compared to the original timestamp value contained in the modified row. If they match, the update is performed and the timestamp column is updated with the current time to reflect the update. If they do not match, an optimistic concurrency violation has occurred. - - Another technique for testing for an optimistic concurrency violation is to verify that all the original column values in a row still match those found in the database. For example, consider the following query: - +> If you need to update multiple rows in the same operation, then creating a transaction is a more scalable option than using pessimistic locking. + + By contrast, users who use optimistic concurrency do not lock a row when reading it. When a user wants to update a row, the application must determine whether another user has changed the row since it was read. Optimistic concurrency is generally used in environments with a low contention for data. Optimistic concurrency improves performance because no locking of records is required, and locking of records requires additional server resources. Also, in order to maintain record locks, a persistent connection to the database server is required. Because this is not the case in an optimistic concurrency model, connections to the server are free to serve a larger number of clients in less time. + + In an optimistic concurrency model, a violation is considered to have occurred if, after a user receives a value from the database, another user modifies the value before the first user has attempted to modify it. How the server resolves a concurrency violation is best shown by first describing the following example. + + The following tables follow an example of optimistic concurrency. + + At 1:00 p.m., User1 reads a row from the database with the following values: + + **CustID LastName FirstName** + + 101 Smith Bob + +|Column name|Original value|Current value|Value in database| +|-----------------|--------------------|-------------------|-----------------------| +|CustID|101|101|101| +|LastName|Smith|Smith|Smith| +|FirstName|Bob|Bob|Bob| + + At 1:01 p.m., User2 reads the same row. + + At 1:03 p.m., User2 changes `FirstName` from "Bob" to "Robert" and updates the database. + +|Column name|Original value|Current value|Value in database| +|-----------------|--------------------|-------------------|-----------------------| +|CustID|101|101|101| +|LastName|Smith|Smith|Smith| +|FirstName|Bob|Robert|Bob| + + The update succeeds because the values in the database at the time of update match the original values that User2 has. + + At 1:05 p.m., User1 changes "Bob"'s first name to "James" and tries to update the row. + +|Column name|Original value|Current value|Value in database| +|-----------------|--------------------|-------------------|-----------------------| +|CustID|101|101|101| +|LastName|Smith|Smith|Smith| +|FirstName|Bob|James|Robert| + + At this point, User1 encounters an optimistic concurrency violation because the value in the database ("Robert") no longer matches the original value that User1 was expecting ("Bob"). The concurrency violation simply lets you know that the update failed. The decision now needs to be made whether to overwrite the changes supplied by User2 with the changes supplied by User1, or to cancel the changes by User1. + +## Testing for Optimistic Concurrency Violations + + There are several techniques for testing for an optimistic concurrency violation. One involves including a timestamp column in the table. Databases commonly provide timestamp functionality that can be used to identify the date and time when the record was last updated. Using this technique, a timestamp column is included in the table definition. Whenever the record is updated, the timestamp is updated to reflect the current date and time. In a test for optimistic concurrency violations, the timestamp column is returned with any query of the contents of the table. When an update is attempted, the timestamp value in the database is compared to the original timestamp value contained in the modified row. If they match, the update is performed and the timestamp column is updated with the current time to reflect the update. If they do not match, an optimistic concurrency violation has occurred. + + Another technique for testing for an optimistic concurrency violation is to verify that all the original column values in a row still match those found in the database. For example, consider the following query: + ```sql -SELECT Col1, Col2, Col3 FROM Table1 -``` - - To test for an optimistic concurrency violation when updating a row in **Table1**, you would issue the following UPDATE statement: - +SELECT Col1, Col2, Col3 FROM Table1 +``` + + To test for an optimistic concurrency violation when updating a row in **Table1**, you would issue the following UPDATE statement: + ```sql -UPDATE Table1 Set Col1 = @NewCol1Value, - Set Col2 = @NewCol2Value, - Set Col3 = @NewCol3Value -WHERE Col1 = @OldCol1Value AND - Col2 = @OldCol2Value AND - Col3 = @OldCol3Value -``` - - As long as the original values match the values in the database, the update is performed. If a value has been modified, the update will not modify the row because the WHERE clause will not find a match. - - Note that it is recommended to always return a unique primary key value in your query. Otherwise, the preceding UPDATE statement may update more than one row, which might not be your intent. - - If a column at your data source allows nulls, you may need to extend your WHERE clause to check for a matching null reference in your local table and at the data source. For example, the following UPDATE statement verifies that a null reference in the local row still matches a null reference at the data source, or that the value in the local row still matches the value at the data source. - +UPDATE Table1 Set Col1 = @NewCol1Value, + Set Col2 = @NewCol2Value, + Set Col3 = @NewCol3Value +WHERE Col1 = @OldCol1Value AND + Col2 = @OldCol2Value AND + Col3 = @OldCol3Value +``` + + As long as the original values match the values in the database, the update is performed. If a value has been modified, the update will not modify the row because the WHERE clause will not find a match. + + Note that it is recommended to always return a unique primary key value in your query. Otherwise, the preceding UPDATE statement may update more than one row, which might not be your intent. + + If a column at your data source allows nulls, you may need to extend your WHERE clause to check for a matching null reference in your local table and at the data source. For example, the following UPDATE statement verifies that a null reference in the local row still matches a null reference at the data source, or that the value in the local row still matches the value at the data source. + ```sql -UPDATE Table1 Set Col1 = @NewVal1 - WHERE (@OldVal1 IS NULL AND Col1 IS NULL) OR Col1 = @OldVal1 -``` - - You may also choose to apply less restrictive criteria when using an optimistic concurrency model. For example, using only the primary key columns in the WHERE clause causes the data to be overwritten regardless of whether the other columns have been updated since the last query. You can also apply a WHERE clause only to specific columns, resulting in data being overwritten unless particular fields have been updated since they were last queried. - -### The DataAdapter.RowUpdated Event - - The **RowUpdated** event of the object can be used in conjunction with the techniques described earlier, to provide notification to your application of optimistic concurrency violations. **RowUpdated** occurs after each attempt to update a **Modified** row from a **DataSet**. This enables you to add special handling code, including processing when an exception occurs, adding custom error information, adding retry logic, and so on. The object returns a **RecordsAffected** property containing the number of rows affected by a particular update command for a modified row in a table. By setting the update command to test for optimistic concurrency, the **RecordsAffected** property will, as a result, return a value of 0 when an optimistic concurrency violation has occurred, because no records were updated. If this is the case, an exception is thrown. The **RowUpdated** event enables you to handle this occurrence and avoid the exception by setting an appropriate **RowUpdatedEventArgs.Status** value, such as **UpdateStatus.SkipCurrentRow**. For more information about the **RowUpdated** event, see [Handling DataAdapter Events](handling-dataadapter-events.md). - - Optionally, you can set **DataAdapter.ContinueUpdateOnError** to **true**, before calling **Update**, and respond to the error information stored in the **RowError** property of a particular row when the **Update** is completed. For more information, see [Row Error Information](./dataset-datatable-dataview/row-error-information.md). - -## Optimistic Concurrency Example - - The following is a simple example that sets the **UpdateCommand** of a **DataAdapter** to test for optimistic concurrency, and then uses the **RowUpdated** event to test for optimistic concurrency violations. When an optimistic concurrency violation is encountered, the application sets the **RowError** of the row that the update was issued for to reflect an optimistic concurrency violation. - - Note that the parameter values passed to the WHERE clause of the UPDATE command are mapped to the **Original** values of their respective columns. - -```vb -' Assumes connection is a valid SqlConnection. -Dim adapter As SqlDataAdapter = New SqlDataAdapter( _ - "SELECT CustomerID, CompanyName FROM Customers ORDER BY CustomerID", _ - connection) - -' The Update command checks for optimistic concurrency violations -' in the WHERE clause. -adapter.UpdateCommand = New SqlCommand("UPDATE Customers " & - "(CustomerID, CompanyName) VALUES(@CustomerID, @CompanyName) " & _ - "WHERE CustomerID = @oldCustomerID AND CompanyName = " & - "@oldCompanyName", connection) -adapter.UpdateCommand.Parameters.Add( _ - "@CustomerID", SqlDbType.NChar, 5, "CustomerID") -adapter.UpdateCommand.Parameters.Add( _ - "@CompanyName", SqlDbType.NVarChar, 30, "CompanyName") - -' Pass the original values to the WHERE clause parameters. -Dim parameter As SqlParameter = adapter.UpdateCommand.Parameters.Add( _ - "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID") -parameter.SourceVersion = DataRowVersion.Original -parameter = adapter.UpdateCommand.Parameters.Add( _ - "@oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName") -parameter.SourceVersion = DataRowVersion.Original - -' Add the RowUpdated event handler. -AddHandler adapter.RowUpdated, New SqlRowUpdatedEventHandler( _ - AddressOf OnRowUpdated) - -Dim dataSet As DataSet = New DataSet() -adapter.Fill(dataSet, "Customers") - -' Modify the DataSet contents. -adapter.Update(dataSet, "Customers") - -Dim dataRow As DataRow - -For Each dataRow In dataSet.Tables("Customers").Rows +UPDATE Table1 Set Col1 = @NewVal1 + WHERE (@OldVal1 IS NULL AND Col1 IS NULL) OR Col1 = @OldVal1 +``` + + You may also choose to apply less restrictive criteria when using an optimistic concurrency model. For example, using only the primary key columns in the WHERE clause causes the data to be overwritten regardless of whether the other columns have been updated since the last query. You can also apply a WHERE clause only to specific columns, resulting in data being overwritten unless particular fields have been updated since they were last queried. + +### The DataAdapter.RowUpdated Event + + The `RowUpdated` event of the object can be used in conjunction with the techniques described earlier, to provide notification to your application of optimistic concurrency violations. `RowUpdated` occurs after each attempt to update a `Modified` row from a **DataSet**. This enables you to add special handling code, including processing when an exception occurs, adding custom error information, adding retry logic, and so on. The object returns a `RecordsAffected` property containing the number of rows affected by a particular update command for a modified row in a table. By setting the update command to test for optimistic concurrency, the `RecordsAffected` property will, as a result, return a value of 0 when an optimistic concurrency violation has occurred, because no records were updated. If this is the case, an exception is thrown. The `RowUpdated` event enables you to handle this occurrence and avoid the exception by setting an appropriate **RowUpdatedEventArgs.Status** value, such as **UpdateStatus.SkipCurrentRow**. For more information about the `RowUpdated` event, see [Handling DataAdapter Events](handling-dataadapter-events.md). + + Optionally, you can set **DataAdapter.ContinueUpdateOnError** to **true**, before calling **Update**, and respond to the error information stored in the `RowError` property of a particular row when the `Update` is completed. For more information, see [Row Error Information](./dataset-datatable-dataview/row-error-information.md). + +## Optimistic Concurrency Example + + The following is a simple example that sets the `UpdateCommand` of a `DataAdapter` to test for optimistic concurrency, and then uses the `RowUpdated` event to test for optimistic concurrency violations. When an optimistic concurrency violation is encountered, the application sets the `RowError` of the row that the update was issued for to reflect an optimistic concurrency violation. + + Note that the parameter values passed to the WHERE clause of the UPDATE command are mapped to the `Original` values of their respective columns. + +```vb +' Assumes connection is a valid SqlConnection. +Dim adapter As SqlDataAdapter = New SqlDataAdapter( _ + "SELECT CustomerID, CompanyName FROM Customers ORDER BY CustomerID", _ + connection) + +' The Update command checks for optimistic concurrency violations +' in the WHERE clause. +adapter.UpdateCommand = New SqlCommand("UPDATE Customers " & + "(CustomerID, CompanyName) VALUES(@CustomerID, @CompanyName) " & _ + "WHERE CustomerID = @oldCustomerID AND CompanyName = " & + "@oldCompanyName", connection) +adapter.UpdateCommand.Parameters.Add( _ + "@CustomerID", SqlDbType.NChar, 5, "CustomerID") +adapter.UpdateCommand.Parameters.Add( _ + "@CompanyName", SqlDbType.NVarChar, 30, "CompanyName") + +' Pass the original values to the WHERE clause parameters. +Dim parameter As SqlParameter = adapter.UpdateCommand.Parameters.Add( _ + "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID") +parameter.SourceVersion = DataRowVersion.Original +parameter = adapter.UpdateCommand.Parameters.Add( _ + "@oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName") +parameter.SourceVersion = DataRowVersion.Original + +' Add the RowUpdated event handler. +AddHandler adapter.RowUpdated, New SqlRowUpdatedEventHandler( _ + AddressOf OnRowUpdated) + +Dim dataSet As DataSet = New DataSet() +adapter.Fill(dataSet, "Customers") + +' Modify the DataSet contents. +adapter.Update(dataSet, "Customers") + +Dim dataRow As DataRow + +For Each dataRow In dataSet.Tables("Customers").Rows If dataRow.HasErrors Then - Console.WriteLine(dataRow (0) & vbCrLf & dataRow.RowError) - End If -Next - -Private Shared Sub OnRowUpdated( _ - sender As object, args As SqlRowUpdatedEventArgs) - If args.RecordsAffected = 0 - args.Row.RowError = "Optimistic Concurrency Violation!" - args.Status = UpdateStatus.SkipCurrentRow - End If -End Sub -``` - -```csharp -// Assumes connection is a valid SqlConnection. -SqlDataAdapter adapter = new SqlDataAdapter( - "SELECT CustomerID, CompanyName FROM Customers ORDER BY CustomerID", - connection); - -// The Update command checks for optimistic concurrency violations -// in the WHERE clause. -adapter.UpdateCommand = new SqlCommand("UPDATE Customers Set CustomerID = @CustomerID, CompanyName = @CompanyName " + - "WHERE CustomerID = @oldCustomerID AND CompanyName = @oldCompanyName", connection); -adapter.UpdateCommand.Parameters.Add( - "@CustomerID", SqlDbType.NChar, 5, "CustomerID"); -adapter.UpdateCommand.Parameters.Add( - "@CompanyName", SqlDbType.NVarChar, 30, "CompanyName"); - -// Pass the original values to the WHERE clause parameters. -SqlParameter parameter = adapter.UpdateCommand.Parameters.Add( - "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID"); -parameter.SourceVersion = DataRowVersion.Original; -parameter = adapter.UpdateCommand.Parameters.Add( - "@oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName"); -parameter.SourceVersion = DataRowVersion.Original; - -// Add the RowUpdated event handler. -adapter.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated); - -DataSet dataSet = new DataSet(); -adapter.Fill(dataSet, "Customers"); - -// Modify the DataSet contents. - -adapter.Update(dataSet, "Customers"); - -foreach (DataRow dataRow in dataSet.Tables["Customers"].Rows) -{ - if (dataRow.HasErrors) - Console.WriteLine(dataRow [0] + "\n" + dataRow.RowError); -} - -protected static void OnRowUpdated(object sender, SqlRowUpdatedEventArgs args) -{ + Console.WriteLine(dataRow (0) & vbCrLf & dataRow.RowError) + End If +Next + +Private Shared Sub OnRowUpdated( _ + sender As object, args As SqlRowUpdatedEventArgs) + If args.RecordsAffected = 0 + args.Row.RowError = "Optimistic Concurrency Violation!" + args.Status = UpdateStatus.SkipCurrentRow + End If +End Sub +``` + +```csharp +// Assumes connection is a valid SqlConnection. +SqlDataAdapter adapter = new SqlDataAdapter( + "SELECT CustomerID, CompanyName FROM Customers ORDER BY CustomerID", + connection); + +// The Update command checks for optimistic concurrency violations +// in the WHERE clause. +adapter.UpdateCommand = new SqlCommand("UPDATE Customers Set CustomerID = @CustomerID, CompanyName = @CompanyName " + + "WHERE CustomerID = @oldCustomerID AND CompanyName = @oldCompanyName", connection); +adapter.UpdateCommand.Parameters.Add( + "@CustomerID", SqlDbType.NChar, 5, "CustomerID"); +adapter.UpdateCommand.Parameters.Add( + "@CompanyName", SqlDbType.NVarChar, 30, "CompanyName"); + +// Pass the original values to the WHERE clause parameters. +SqlParameter parameter = adapter.UpdateCommand.Parameters.Add( + "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID"); +parameter.SourceVersion = DataRowVersion.Original; +parameter = adapter.UpdateCommand.Parameters.Add( + "@oldCompanyName", SqlDbType.NVarChar, 30, "CompanyName"); +parameter.SourceVersion = DataRowVersion.Original; + +// Add the RowUpdated event handler. +adapter.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated); + +DataSet dataSet = new DataSet(); +adapter.Fill(dataSet, "Customers"); + +// Modify the DataSet contents. + +adapter.Update(dataSet, "Customers"); + +foreach (DataRow dataRow in dataSet.Tables["Customers"].Rows) +{ + if (dataRow.HasErrors) + Console.WriteLine(dataRow [0] + "\n" + dataRow.RowError); +} + +protected static void OnRowUpdated(object sender, SqlRowUpdatedEventArgs args) +{ if (args.RecordsAffected == 0) - { - args.Row.RowError = "Optimistic Concurrency Violation Encountered"; - args.Status = UpdateStatus.SkipCurrentRow; - } -} -``` - + { + args.Row.RowError = "Optimistic Concurrency Violation Encountered"; + args.Status = UpdateStatus.SkipCurrentRow; + } +} +``` + ## See also - [Retrieving and Modifying Data in ADO.NET](retrieving-and-modifying-data.md) diff --git a/docs/framework/data/adonet/oracle-data-type-mappings.md b/docs/framework/data/adonet/oracle-data-type-mappings.md index e4222cc67e835..7022b08777b01 100644 --- a/docs/framework/data/adonet/oracle-data-type-mappings.md +++ b/docs/framework/data/adonet/oracle-data-type-mappings.md @@ -6,64 +6,64 @@ ms.assetid: ec34ae21-bbbb-4adb-b672-83865e2a8451 --- # Oracle Data Type Mappings -The following table lists Oracle data types and their mappings to the . - -|Oracle data type|.NET Framework data type returned by OracleDataReader.GetValue|OracleClient data type returned by OracleDataReader.GetOracleValue|Remarks| -|----------------------|--------------------------------------------------------------------|------------------------------------------------------------------------|-------------| -|**BFILE**|**Byte[]**||| -|**BLOB**|**Byte[]**||| -|**CHAR**|**String**||| -|**CLOB**|**String**||| -|**DATE**|**DateTime**||| -|**FLOAT**|**Decimal**||This data type is an alias for the **NUMBER** data type, and is designed so that the returns a **System.Decimal** or instead of a floating-point value. Using the .NET Framework data type can cause an overflow.| -|**INTEGER**|**Decimal**||This data type is an alias for the **NUMBER(38)** data type, and is designed so that the returns a **System.Decimal** or instead of an integer value. Using the .NET Framework data type can cause an overflow.| -|**INTERVAL YEAR TO MONTH**|**Int32**||| -|**INTERVAL DAY TO SECOND**|**TimeSpan**||| -|**LONG**|**String**||| -|**LONG RAW**|**Byte[]**||| -|**NCHAR**|**String**||| -|**NCLOB**|**String**||| -|**NUMBER**|**Decimal**||Using the .NET Framework data type can cause an overflow.| -|**NVARCHAR2**|**String**||| -|**RAW**|**Byte[]**||| -|**REF CURSOR**|||The Oracle **REF CURSOR** data type is not supported by the object.| -|**ROWID**|**String**||| -|**TIMESTAMP**|**DateTime**||| -|**TIMESTAMP WITH LOCAL TIME ZONE**|**DateTime**||| -|**TIMESTAMP WITH TIME ZONE**|**DateTime**||| -|**UNSIGNED INTEGER**|**Number**||This data type is an alias for the **NUMBER(38)** data type, and is designed so that the returns a **System.Decimal** or instead of an unsigned integer value. Using the .NET Framework data type can cause an overflow.| -|**VARCHAR2**|**String**||| - - The following table lists Oracle data types and the .NET Framework data types (**System.Data.DbType** and ) to use when binding them as parameters. - -|Oracle data type|DbType enumeration to bind as a parameter|OracleType enumeration to bind as a parameter|Remarks| -|----------------------|-----------------------------------------------|---------------------------------------------------|-------------| -|**BFILE**||**BFile**|Oracle only allows binding a **BFILE** as a **BFILE** parameter. The .NET Data Provider for Oracle does not automatically construct one for you if you attempt to bind a non-**BFILE** value, such as **byte[]** or .| -|**BLOB**||**Blob**|Oracle only allows binding a **BLOB** as a **BLOB** parameter. The .NET Data Provider for Oracle does not automatically construct one for you if you attempt to bind a non-**BLOB** value, such as **byte[]** or .| -|**CHAR**|**AnsiStringFixedLength**|**Char**|| -|**CLOB**||**Clob**|Oracle only allows binding a **CLOB** as a **CLOB** parameter. The .NET Data Provider for Oracle does not automatically construct one for you if you attempt to bind a non-**CLOB** value, such as **System.String** or .| -|**DATE**|**DateTime**|**DateTime**|| -|**FLOAT**|**Single, Double, Decimal**|**Float, Double, Number**| determines the **System.Data.DBType** and .| -|**INTEGER**|**SByte, Int16, Int32, Int64, Decimal**|**SByte, Int16, Int32, Number**| determines the **System.Data.DBType** and .| -|**INTERVAL YEAR TO MONTH**|**Int32**|**IntervalYearToMonth**| is only available when using both Oracle 9i client and server software.| -|**INTERVAL DAY TO SECOND**|**Object**|**IntervalDayToSecond**| is only available when using both Oracle 9i client and server software.| -|**LONG**|**AnsiString**|**LongVarChar**|| -|**LONG RAW**|**Binary**|**LongRaw**|| -|**NCHAR**|**StringFixedLength**|**NChar**|| -|**NCLOB**||**NClob**|Oracle only allows binding a **NCLOB** as a **NCLOB** parameter. The .NET Data Provider for Oracle does not automatically construct one for you if you attempt to bind a non-**NCLOB** value, such as **System.String** or .| -|**NUMBER**|**VarNumeric**|**Number**|| -|**NVARCHAR2**|**String**|**NVarChar**|| -|**RAW**|**Binary**|**Raw**|| -|**REF CURSOR**||**Cursor**|For more information, see [Oracle REF CURSORs](oracle-ref-cursors.md).| -|**ROWID**|**AnsiString**|**Rowid**|| -|**TIMESTAMP**|**DateTime**|**Timestamp**| is only available when using both Oracle 9i client and server software.| -|**TIMESTAMP WITH LOCAL TIME ZONE**|**DateTime**|**TimestampLocal**| is only available when using both Oracle 9i client and server software.| -|**TIMESTAMP WITH TIME ZONE**|**DateTime**|**TimestampWithTz**| is only available when using both Oracle 9i client and server software.| -|**UNSIGNED INTEGER**|**Byte, UInt16, UInt32, UInt64, Decimal**|**Byte, UInt16, Uint32, Number**| determines the **System.Data.DBType** and .| -|**VARCHAR2**|**AnsiString**|**VarChar**|| - - The **InputOutput**, **Output**, and **ReturnValue** **ParameterDirection** values used by the property of the object are .NET Framework data types, unless the input value is an Oracle data type (for example, or ). This does not apply to **REF CURSOR**, **BFILE**, or **LOB** data types. - +The following table lists Oracle data types and their mappings to the . + +|Oracle data type|.NET Framework data type returned by OracleDataReader.GetValue|OracleClient data type returned by OracleDataReader.GetOracleValue|Remarks| +|----------------------|--------------------------------------------------------------------|------------------------------------------------------------------------|-------------| +|**BFILE**|**Byte[]**||| +|**BLOB**|**Byte[]**||| +|**CHAR**|**String**||| +|**CLOB**|**String**||| +|**DATE**|**DateTime**||| +|**FLOAT**|**Decimal**||This data type is an alias for the `NUMBER` data type, and is designed so that the returns a **System.Decimal** or instead of a floating-point value. Using the .NET Framework data type can cause an overflow.| +|**INTEGER**|**Decimal**||This data type is an alias for the **NUMBER(38)** data type, and is designed so that the returns a **System.Decimal** or instead of an integer value. Using the .NET Framework data type can cause an overflow.| +|**INTERVAL YEAR TO MONTH**|**Int32**||| +|**INTERVAL DAY TO SECOND**|**TimeSpan**||| +|**LONG**|**String**||| +|**LONG RAW**|**Byte[]**||| +|**NCHAR**|**String**||| +|**NCLOB**|**String**||| +|**NUMBER**|**Decimal**||Using the .NET Framework data type can cause an overflow.| +|**NVARCHAR2**|**String**||| +|**RAW**|**Byte[]**||| +|**REF CURSOR**|||The Oracle **REF CURSOR** data type is not supported by the object.| +|**ROWID**|**String**||| +|**TIMESTAMP**|**DateTime**||| +|**TIMESTAMP WITH LOCAL TIME ZONE**|**DateTime**||| +|**TIMESTAMP WITH TIME ZONE**|**DateTime**||| +|**UNSIGNED INTEGER**|**Number**||This data type is an alias for the **NUMBER(38)** data type, and is designed so that the returns a **System.Decimal** or instead of an unsigned integer value. Using the .NET Framework data type can cause an overflow.| +|**VARCHAR2**|**String**||| + + The following table lists Oracle data types and the .NET Framework data types (**System.Data.DbType** and ) to use when binding them as parameters. + +|Oracle data type|DbType enumeration to bind as a parameter|OracleType enumeration to bind as a parameter|Remarks| +|----------------------|-----------------------------------------------|---------------------------------------------------|-------------| +|**BFILE**||**BFile**|Oracle only allows binding a `BFILE` as a `BFILE` parameter. The .NET Data Provider for Oracle does not automatically construct one for you if you attempt to bind a non-**BFILE** value, such as `byte[]` or .| +|**BLOB**||**Blob**|Oracle only allows binding a `BLOB` as a `BLOB` parameter. The .NET Data Provider for Oracle does not automatically construct one for you if you attempt to bind a non-**BLOB** value, such as `byte[]` or .| +|**CHAR**|**AnsiStringFixedLength**|**Char**|| +|**CLOB**||**Clob**|Oracle only allows binding a `CLOB` as a `CLOB` parameter. The .NET Data Provider for Oracle does not automatically construct one for you if you attempt to bind a non-**CLOB** value, such as **System.String** or .| +|**DATE**|**DateTime**|**DateTime**|| +|**FLOAT**|**Single, Double, Decimal**|**Float, Double, Number**| determines the **System.Data.DBType** and .| +|**INTEGER**|**SByte, Int16, Int32, Int64, Decimal**|**SByte, Int16, Int32, Number**| determines the **System.Data.DBType** and .| +|**INTERVAL YEAR TO MONTH**|**Int32**|**IntervalYearToMonth**| is only available when using both Oracle 9i client and server software.| +|**INTERVAL DAY TO SECOND**|**Object**|**IntervalDayToSecond**| is only available when using both Oracle 9i client and server software.| +|**LONG**|**AnsiString**|**LongVarChar**|| +|**LONG RAW**|**Binary**|**LongRaw**|| +|**NCHAR**|**StringFixedLength**|**NChar**|| +|**NCLOB**||**NClob**|Oracle only allows binding a `NCLOB` as a `NCLOB` parameter. The .NET Data Provider for Oracle does not automatically construct one for you if you attempt to bind a non-**NCLOB** value, such as **System.String** or .| +|**NUMBER**|**VarNumeric**|**Number**|| +|**NVARCHAR2**|**String**|**NVarChar**|| +|**RAW**|**Binary**|**Raw**|| +|**REF CURSOR**||**Cursor**|For more information, see [Oracle REF CURSORs](oracle-ref-cursors.md).| +|**ROWID**|**AnsiString**|**Rowid**|| +|**TIMESTAMP**|**DateTime**|**Timestamp**| is only available when using both Oracle 9i client and server software.| +|**TIMESTAMP WITH LOCAL TIME ZONE**|**DateTime**|**TimestampLocal**| is only available when using both Oracle 9i client and server software.| +|**TIMESTAMP WITH TIME ZONE**|**DateTime**|**TimestampWithTz**| is only available when using both Oracle 9i client and server software.| +|**UNSIGNED INTEGER**|**Byte, UInt16, UInt32, UInt64, Decimal**|**Byte, UInt16, Uint32, Number**| determines the **System.Data.DBType** and .| +|**VARCHAR2**|**AnsiString**|**VarChar**|| + + The **InputOutput**, **Output**, and `ReturnValue` **ParameterDirection** values used by the property of the object are .NET Framework data types, unless the input value is an Oracle data type (for example, or ). This does not apply to **REF CURSOR**, **BFILE**, or `LOB` data types. + ## See also - [Oracle and ADO.NET](oracle-and-adonet.md) diff --git a/docs/framework/data/adonet/oracle-lobs.md b/docs/framework/data/adonet/oracle-lobs.md index 3475848380ca5..9c88b6f9f0a67 100644 --- a/docs/framework/data/adonet/oracle-lobs.md +++ b/docs/framework/data/adonet/oracle-lobs.md @@ -6,245 +6,245 @@ ms.assetid: 272e8e1e-a31f-475a-8c2a-ae8e1286bdab --- # Oracle LOBs -The .NET Framework Data Provider for Oracle includes the class, which is used to work with Oracle **LOB** data types. - - An **OracleLob** may be one of these data types: - -|Data type|Description| -|---------------|-----------------| -|**Blob**|An Oracle **BLOB** data type that contains binary data with a maximum size of 4 gigabytes. This maps to an **Array** of type **Byte**.| -|**Clob**|An Oracle **CLOB** data type that contains character data, based on the default character set on the server, with a maximum size of 4 gigabytes. This maps to **String**.| -|**NClob**|An Oracle **NCLOB** data type that contains character data, based on the national character set on the server with a maximum size of 4 gigabytes. This maps to **String**.| - - An **OracleLob** differs from an in that the data is stored on the server instead of in a physical file in the operating system. It can also be a read-write object, unlike an **OracleBFile**, which is always read-only. - -## Creating, Retrieving, and Writing to a LOB - - The following C# example demonstrates how you can create LOBs in an Oracle table, and then retrieve and write to them in the form of **OracleLob** objects. The example demonstrates using the object and the **OracleLob** **Read** and **Write** methods. The example uses Oracle **BLOB**, **CLOB**, and **NCLOB** data types. - -```csharp -using System; +The .NET Framework Data Provider for Oracle includes the class, which is used to work with Oracle `LOB` data types. + + An `OracleLob` may be one of these data types: + +|Data type|Description| +|---------------|-----------------| +|**Blob**|An Oracle `BLOB` data type that contains binary data with a maximum size of 4 gigabytes. This maps to an `Array` of type **Byte**.| +|**Clob**|An Oracle `CLOB` data type that contains character data, based on the default character set on the server, with a maximum size of 4 gigabytes. This maps to **String**.| +|**NClob**|An Oracle `NCLOB` data type that contains character data, based on the national character set on the server with a maximum size of 4 gigabytes. This maps to **String**.| + + An `OracleLob` differs from an in that the data is stored on the server instead of in a physical file in the operating system. It can also be a read-write object, unlike an **OracleBFile**, which is always read-only. + +## Creating, Retrieving, and Writing to a LOB + + The following C# example demonstrates how you can create LOBs in an Oracle table, and then retrieve and write to them in the form of `OracleLob` objects. The example demonstrates using the object and the `OracleLob` **Read** and `Write` methods. The example uses Oracle **BLOB**, **CLOB**, and `NCLOB` data types. + +```csharp +using System; using System.IO; using System.Text; using System.Data; -using System.Data.OracleClient; - -// LobExample -public class LobExample -{ - public static int Main(string[] args) - { - //Create a connection. - OracleConnection conn = new OracleConnection( - "Data Source=Oracle8i;Integrated Security=yes"); - using(conn) - { - //Open a connection. - conn.Open(); - OracleCommand cmd = conn.CreateCommand(); - - //Create the table and schema. - CreateTable(cmd); - - //Read example. - ReadLobExample(cmd); - - //Write example - WriteLobExample(cmd); - } - - return 1; - } - - // ReadLobExample - public static void ReadLobExample(OracleCommand cmd) - { - int actual = 0; - - // Table Schema: - // "CREATE TABLE tablewithlobs (a int, b BLOB, c CLOB, d NCLOB)"; - // "INSERT INTO tablewithlobs values (1, 'AA', 'AAA', N'AAAA')"; - // Select some data. - cmd.CommandText = "SELECT * FROM tablewithlobs"; - OracleDataReader reader = cmd.ExecuteReader(); - using(reader) - { - //Obtain the first row of data. - reader.Read(); - - //Obtain the LOBs (all 3 varieties). - OracleLob blob = reader.GetOracleLob(1); - OracleLob clob = reader.GetOracleLob(2); - OracleLob nclob = reader.GetOracleLob(3); - - //Example - Reading binary data (in chunks). - byte[] buffer = new byte[100]; - while((actual = blob.Read(buffer, 0, buffer.Length)) >0) +using System.Data.OracleClient; + +// LobExample +public class LobExample +{ + public static int Main(string[] args) + { + //Create a connection. + OracleConnection conn = new OracleConnection( + "Data Source=Oracle8i;Integrated Security=yes"); + using(conn) + { + //Open a connection. + conn.Open(); + OracleCommand cmd = conn.CreateCommand(); + + //Create the table and schema. + CreateTable(cmd); + + //Read example. + ReadLobExample(cmd); + + //Write example + WriteLobExample(cmd); + } + + return 1; + } + + // ReadLobExample + public static void ReadLobExample(OracleCommand cmd) + { + int actual = 0; + + // Table Schema: + // "CREATE TABLE tablewithlobs (a int, b BLOB, c CLOB, d NCLOB)"; + // "INSERT INTO tablewithlobs values (1, 'AA', 'AAA', N'AAAA')"; + // Select some data. + cmd.CommandText = "SELECT * FROM tablewithlobs"; + OracleDataReader reader = cmd.ExecuteReader(); + using(reader) + { + //Obtain the first row of data. + reader.Read(); + + //Obtain the LOBs (all 3 varieties). + OracleLob blob = reader.GetOracleLob(1); + OracleLob clob = reader.GetOracleLob(2); + OracleLob nclob = reader.GetOracleLob(3); + + //Example - Reading binary data (in chunks). + byte[] buffer = new byte[100]; + while((actual = blob.Read(buffer, 0, buffer.Length)) >0) Console.WriteLine(blob.LobType + ".Read(" + buffer + ", " + - buffer.Length + ") => " + actual); - - // Example - Reading CLOB/NCLOB data (in chunks). + buffer.Length + ") => " + actual); + + // Example - Reading CLOB/NCLOB data (in chunks). // Note: You can read character data as raw Unicode bytes - // (using OracleLob.Read as in the above example). + // (using OracleLob.Read as in the above example). // However, because the OracleLob object inherits directly // from the .NET stream object, // all the existing classes that manipulate streams can // also be used. For example, the // .NET StreamReader makes it easier to convert the raw bytes - // into actual characters. + // into actual characters. StreamReader streamreader = - new StreamReader(clob, Encoding.Unicode); - char[] cbuffer = new char[100]; + new StreamReader(clob, Encoding.Unicode); + char[] cbuffer = new char[100]; while((actual = streamreader.Read(cbuffer, - 0, cbuffer.Length)) >0) - Console.WriteLine(clob.LobType + ".Read( + 0, cbuffer.Length)) >0) + Console.WriteLine(clob.LobType + ".Read( " + new string(cbuffer, 0, actual) + ", " + - cbuffer.Length + ") => " + actual); - - // Example - Reading data (all at once). + cbuffer.Length + ") => " + actual); + + // Example - Reading data (all at once). // You could use StreamReader.ReadToEnd to obtain - // all the string data, or simply + // all the string data, or simply // call OracleLob.Value to obtain a contiguous allocation - // of all the data. - Console.WriteLine(nclob.LobType + ".Value => " + nclob.Value); - } - } - - // WriteLobExample - public static void WriteLobExample(OracleCommand cmd) - { - //Note: Updating LOB data requires a transaction. - cmd.Transaction = cmd.Connection.BeginTransaction(); - - // Select some data. - // Table Schema: - // "CREATE TABLE tablewithlobs (a int, b BLOB, c CLOB, d NCLOB)"; - // "INSERT INTO tablewithlobs values (1, 'AA', 'AAA', N'AAAA')"; - cmd.CommandText = "SELECT * FROM tablewithlobs FOR UPDATE"; - OracleDataReader reader = cmd.ExecuteReader(); - using(reader) - { - // Obtain the first row of data. - reader.Read(); - - // Obtain a LOB. - OracleLob blob = reader.GetOracleLob(1/*0:based ordinal*/); - + // of all the data. + Console.WriteLine(nclob.LobType + ".Value => " + nclob.Value); + } + } + + // WriteLobExample + public static void WriteLobExample(OracleCommand cmd) + { + //Note: Updating LOB data requires a transaction. + cmd.Transaction = cmd.Connection.BeginTransaction(); + + // Select some data. + // Table Schema: + // "CREATE TABLE tablewithlobs (a int, b BLOB, c CLOB, d NCLOB)"; + // "INSERT INTO tablewithlobs values (1, 'AA', 'AAA', N'AAAA')"; + cmd.CommandText = "SELECT * FROM tablewithlobs FOR UPDATE"; + OracleDataReader reader = cmd.ExecuteReader(); + using(reader) + { + // Obtain the first row of data. + reader.Read(); + + // Obtain a LOB. + OracleLob blob = reader.GetOracleLob(1/*0:based ordinal*/); + // Perform any desired operations on the LOB - // (read, position, and so on). - - // Example - Writing binary data (directly to the backend). - // To write, you can use any of the stream classes, or write + // (read, position, and so on). + + // Example - Writing binary data (directly to the backend). + // To write, you can use any of the stream classes, or write // raw binary data using // the OracleLob write method. Writing character vs. binary - // is the same; + // is the same; // however note that character is always in terms of - // Unicode byte counts - // (for example, even number of bytes - 2 bytes for every - // Unicode character). - byte[] buffer = new byte[100]; - buffer[0] = 0xCC; - buffer[1] = 0xDD; - blob.Write(buffer, 0, 2); - blob.Position = 0; - Console.WriteLine(blob.LobType + ".Write( - " + buffer + ", 0, 2) => " + blob.Value); - + // Unicode byte counts + // (for example, even number of bytes - 2 bytes for every + // Unicode character). + byte[] buffer = new byte[100]; + buffer[0] = 0xCC; + buffer[1] = 0xDD; + blob.Write(buffer, 0, 2); + blob.Position = 0; + Console.WriteLine(blob.LobType + ".Write( + " + buffer + ", 0, 2) => " + blob.Value); + // Example - Obtaining a temp LOB and copying data - // into it from another LOB. - OracleLob templob = CreateTempLob(cmd, blob.LobType); - long actual = blob.CopyTo(templob); - Console.WriteLine(blob.LobType + ".CopyTo( - " + templob.Value + ") => " + actual); - - // Commit the transaction now that everything succeeded. + // into it from another LOB. + OracleLob templob = CreateTempLob(cmd, blob.LobType); + long actual = blob.CopyTo(templob); + Console.WriteLine(blob.LobType + ".CopyTo( + " + templob.Value + ") => " + actual); + + // Commit the transaction now that everything succeeded. // Note: On error, Transaction.Dispose is called - // (from the using statement) - // and will automatically roll back the pending transaction. - cmd.Transaction.Commit(); - } - } - - // CreateTempLob - public static OracleLob CreateTempLob( - OracleCommand cmd, OracleType lobtype) - { - //Oracle server syntax to obtain a temporary LOB. - cmd.CommandText = "DECLARE A " + lobtype + "; "+ - "BEGIN "+ - "DBMS_LOB.CREATETEMPORARY(A, FALSE); "+ - ":LOC := A; "+ - "END;"; - - //Bind the LOB as an output parameter. - OracleParameter p = cmd.Parameters.Add("LOC", lobtype); - p.Direction = ParameterDirection.Output; - - //Execute (to receive the output temporary LOB). - cmd.ExecuteNonQuery(); - - //Return the temporary LOB. - return (OracleLob)p.Value; - } - - // CreateTable - public static void CreateTable(OracleCommand cmd) - { - // Table Schema: - // "CREATE TABLE tablewithlobs (a int, b BLOB, c CLOB, d NCLOB)"; - // "INSERT INTO tablewithlobs VALUES (1, 'AA', 'AAA', N'AAAA')"; - try - { - cmd.CommandText = "DROP TABLE tablewithlobs"; - cmd.ExecuteNonQuery(); - } - catch(Exception) - { - } - + // (from the using statement) + // and will automatically roll back the pending transaction. + cmd.Transaction.Commit(); + } + } + + // CreateTempLob + public static OracleLob CreateTempLob( + OracleCommand cmd, OracleType lobtype) + { + //Oracle server syntax to obtain a temporary LOB. + cmd.CommandText = "DECLARE A " + lobtype + "; "+ + "BEGIN "+ + "DBMS_LOB.CREATETEMPORARY(A, FALSE); "+ + ":LOC := A; "+ + "END;"; + + //Bind the LOB as an output parameter. + OracleParameter p = cmd.Parameters.Add("LOC", lobtype); + p.Direction = ParameterDirection.Output; + + //Execute (to receive the output temporary LOB). + cmd.ExecuteNonQuery(); + + //Return the temporary LOB. + return (OracleLob)p.Value; + } + + // CreateTable + public static void CreateTable(OracleCommand cmd) + { + // Table Schema: + // "CREATE TABLE tablewithlobs (a int, b BLOB, c CLOB, d NCLOB)"; + // "INSERT INTO tablewithlobs VALUES (1, 'AA', 'AAA', N'AAAA')"; + try + { + cmd.CommandText = "DROP TABLE tablewithlobs"; + cmd.ExecuteNonQuery(); + } + catch(Exception) + { + } + cmd.CommandText = - "CREATE TABLE tablewithlobs (a int, b BLOB, c CLOB, d NCLOB)"; - cmd.ExecuteNonQuery(); + "CREATE TABLE tablewithlobs (a int, b BLOB, c CLOB, d NCLOB)"; + cmd.ExecuteNonQuery(); cmd.CommandText = - "INSERT INTO tablewithlobs VALUES (1, 'AA', 'AAA', N'AAAA')"; - cmd.ExecuteNonQuery(); - } -} -``` - -## Creating a Temporary LOB - - The following C# example demonstrates how to create a temporary LOB. - -```csharp -OracleConnection conn = new OracleConnection( - "server=test8172; integrated security=yes;"); -conn.Open(); - -OracleTransaction tx = conn.BeginTransaction(); - -OracleCommand cmd = conn.CreateCommand(); -cmd.Transaction = tx; + "INSERT INTO tablewithlobs VALUES (1, 'AA', 'AAA', N'AAAA')"; + cmd.ExecuteNonQuery(); + } +} +``` + +## Creating a Temporary LOB + + The following C# example demonstrates how to create a temporary LOB. + +```csharp +OracleConnection conn = new OracleConnection( + "server=test8172; integrated security=yes;"); +conn.Open(); + +OracleTransaction tx = conn.BeginTransaction(); + +OracleCommand cmd = conn.CreateCommand(); +cmd.Transaction = tx; cmd.CommandText = - "declare xx blob; begin dbms_lob.createtemporary( - xx, false, 0); :tempblob := xx; end;"; -cmd.Parameters.Add(new OracleParameter("tempblob", - OracleType.Blob)).Direction = ParameterDirection.Output; -cmd.ExecuteNonQuery(); -OracleLob tempLob = (OracleLob)cmd.Parameters[0].Value; -tempLob.BeginBatch(OracleLobOpenMode.ReadWrite); -tempLob.Write(tempbuff,0,tempbuff.Length); -tempLob.EndBatch(); -cmd.Parameters.Clear(); -cmd.CommandText = "myTable.myProc"; + "declare xx blob; begin dbms_lob.createtemporary( + xx, false, 0); :tempblob := xx; end;"; +cmd.Parameters.Add(new OracleParameter("tempblob", + OracleType.Blob)).Direction = ParameterDirection.Output; +cmd.ExecuteNonQuery(); +OracleLob tempLob = (OracleLob)cmd.Parameters[0].Value; +tempLob.BeginBatch(OracleLobOpenMode.ReadWrite); +tempLob.Write(tempbuff,0,tempbuff.Length); +tempLob.EndBatch(); +cmd.Parameters.Clear(); +cmd.CommandText = "myTable.myProc"; cmd.CommandType = CommandType.StoredProcedure; -cmd.Parameters.Add(new OracleParameter( - "ImportDoc", OracleType.Blob)).Value = tempLob; -cmd.ExecuteNonQuery(); - -tx.Commit(); -``` - +cmd.Parameters.Add(new OracleParameter( + "ImportDoc", OracleType.Blob)).Value = tempLob; +cmd.ExecuteNonQuery(); + +tx.Commit(); +``` + ## See also - [Oracle and ADO.NET](oracle-and-adonet.md) diff --git a/docs/framework/data/adonet/oracle-ref-cursors.md b/docs/framework/data/adonet/oracle-ref-cursors.md index 938a8e0a4357f..d027b6eb8a7d3 100644 --- a/docs/framework/data/adonet/oracle-ref-cursors.md +++ b/docs/framework/data/adonet/oracle-ref-cursors.md @@ -6,39 +6,39 @@ ms.assetid: c6b25b8b-0bdd-41b2-9c7c-661f070c2247 --- # Oracle REF CURSORs -The .NET Framework Data Provider for Oracle supports the Oracle **REF CURSOR** data type. When using the data provider to work with Oracle REF CURSORs, you should consider the following behaviors. - +The .NET Framework Data Provider for Oracle supports the Oracle **REF CURSOR** data type. When using the data provider to work with Oracle REF CURSORs, you should consider the following behaviors. + > [!NOTE] -> Some behaviors differ from those of the Microsoft OLE DB Provider for Oracle (MSDAORA). - -- For performance reasons, the Data Provider for Oracle does not automatically bind **REF CURSOR** data types, as MSDAORA does, unless you explicitly specify them. - -- The data provider does not support any ODBC escape sequences, including the {resultset} escape used to specify REF CURSOR parameters. - -- To execute a stored procedure that returns REF CURSORs, you must define the parameters in the with an of **Cursor** and a of **Output**. The data provider supports binding REF CURSORs as output parameters only. The provider does not support REF CURSORs as input parameters. - -- Obtaining an from the parameter value is not supported. The values are of type after command execution. - -- The only **CommandBehavior** enumeration value that works with REF CURSORs (for example, when calling ) is **CloseConnection**; all others are ignored. - -- The order of REF CURSORs in the **OracleDataReader** depends on the order of the parameters in the **OracleParameterCollection**. The property is ignored. - -- The PL/SQL **TABLE** data type is not supported. However, REF CURSORs are more efficient. If you must use a **TABLE** data type, use the OLE DB .NET Data Provider with MSDAORA. - -## In This Section - - [REF CURSOR Examples](ref-cursor-examples.md) - Contains three examples that demonstrate using REF CURSORs. - - [REF CURSOR Parameters in an OracleDataReader](ref-cursor-parameters-in-an-oracledatareader.md) - Demonstrates how to execute a PL/SQL stored procedure that returns a REF CURSOR parameter, and reads the value as an **OracleDataReader**. - - [Retrieving Data from Multiple REF CURSORs Using an OracleDataReader](retrieving-data-from-multiple-ref-cursors.md) - Demonstrates how to execute a PL/SQL stored procedure that returns two REF CURSOR parameters, and reads the values using an **OracleDataReader**. - - [Filling a DataSet Using One or More REF CURSORs](filling-a-dataset-using-one-or-more-ref-cursors.md) - Demonstrates how to execute a PL/SQL stored procedure that returns two REF CURSOR parameters, and fills a with the rows that are returned. - +> Some behaviors differ from those of the Microsoft OLE DB Provider for Oracle (MSDAORA). + +- For performance reasons, the Data Provider for Oracle does not automatically bind **REF CURSOR** data types, as MSDAORA does, unless you explicitly specify them. + +- The data provider does not support any ODBC escape sequences, including the {resultset} escape used to specify REF CURSOR parameters. + +- To execute a stored procedure that returns REF CURSORs, you must define the parameters in the with an of `Cursor` and a of **Output**. The data provider supports binding REF CURSORs as output parameters only. The provider does not support REF CURSORs as input parameters. + +- Obtaining an from the parameter value is not supported. The values are of type after command execution. + +- The only `CommandBehavior` enumeration value that works with REF CURSORs (for example, when calling ) is **CloseConnection**; all others are ignored. + +- The order of REF CURSORs in the `OracleDataReader` depends on the order of the parameters in the **OracleParameterCollection**. The property is ignored. + +- The PL/SQL `TABLE` data type is not supported. However, REF CURSORs are more efficient. If you must use a `TABLE` data type, use the OLE DB .NET Data Provider with MSDAORA. + +## In This Section + + [REF CURSOR Examples](ref-cursor-examples.md) + Contains three examples that demonstrate using REF CURSORs. + + [REF CURSOR Parameters in an OracleDataReader](ref-cursor-parameters-in-an-oracledatareader.md) + Demonstrates how to execute a PL/SQL stored procedure that returns a REF CURSOR parameter, and reads the value as an **OracleDataReader**. + + [Retrieving Data from Multiple REF CURSORs Using an OracleDataReader](retrieving-data-from-multiple-ref-cursors.md) + Demonstrates how to execute a PL/SQL stored procedure that returns two REF CURSOR parameters, and reads the values using an **OracleDataReader**. + + [Filling a DataSet Using One or More REF CURSORs](filling-a-dataset-using-one-or-more-ref-cursors.md) + Demonstrates how to execute a PL/SQL stored procedure that returns two REF CURSOR parameters, and fills a with the rows that are returned. + ## See also - [Oracle and ADO.NET](oracle-and-adonet.md) diff --git a/docs/framework/data/adonet/oracletypes.md b/docs/framework/data/adonet/oracletypes.md index 8e2a72fb35f1b..943dcc10814d6 100644 --- a/docs/framework/data/adonet/oracletypes.md +++ b/docs/framework/data/adonet/oracletypes.md @@ -44,7 +44,7 @@ public void Setup(string connectionString) ## Retrieve data from the Oracle table - This example uses an **OracleDataReader** to access the data, and uses several **OracleType** structures to display the data. + This example uses an `OracleDataReader` to access the data, and uses several `OracleType` structures to display the data. ```csharp public void ReadOracleTypesExample(string connectionString) diff --git a/docs/framework/data/adonet/paging-through-a-query-result.md b/docs/framework/data/adonet/paging-through-a-query-result.md index cc39d97584e4e..c03ffcb8fb9e4 100644 --- a/docs/framework/data/adonet/paging-through-a-query-result.md +++ b/docs/framework/data/adonet/paging-through-a-query-result.md @@ -2,123 +2,123 @@ description: "Learn more about: Paging Through a Query Result" title: "Paging Through a Query Result" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: fa360c46-e5f8-411e-a711-46997771133d --- # Paging Through a Query Result -Paging through a query result is the process of returning the results of a query in smaller subsets of data, or pages. This is a common practice for displaying results to a user in small, easy-to-manage chunks. - - The **DataAdapter** provides a facility for returning only a page of data, through overloads of the **Fill** method. However, this might not be the best choice for paging through large query results because, although the **DataAdapter** fills the target or with only the requested records, the resources to return the entire query are still used. To return a page of data from a data source without using the resources to return the entire query, specify additional criteria for your query that reduce the rows returned to only those required. - - To use the **Fill** method to return a page of data, specify a **startRecord** parameter, for the first record in the page of data, and a **maxRecords** parameter, for the number of records in the page of data. - - The following code example shows how to use the **Fill** method to return the first page of a query result where the page size is five records. - -```vb -Dim currentIndex As Integer = 0 -Dim pageSize As Integer = 5 - -Dim orderSQL As String = "SELECT * FROM dbo.Orders ORDER BY OrderID" -' Assumes that connection is a valid SqlConnection object. -Dim adapter As SqlDataAdapter = _ - New SqlDataAdapter(orderSQL, connection) - -Dim dataSet As DataSet = New DataSet() -adapter.Fill(dataSet, currentIndex, pageSize, "Orders") -``` - -```csharp -int currentIndex = 0; -int pageSize = 5; - -string orderSQL = "SELECT * FROM Orders ORDER BY OrderID"; -// Assumes that connection is a valid SqlConnection object. -SqlDataAdapter adapter = new SqlDataAdapter(orderSQL, connection); - -DataSet dataSet = new DataSet(); -adapter.Fill(dataSet, currentIndex, pageSize, "Orders"); -``` - - In the previous example, the **DataSet** is only filled with five records, but the entire **Orders** table is returned. To fill the **DataSet** with those same five records, but only return five records, use the TOP and WHERE clauses in your SQL statement, as in the following code example. - -```vb -Dim pageSize As Integer = 5 - -Dim orderSQL As String = "SELECT TOP " & pageSize & _ - " * FROM Orders ORDER BY OrderID" -Dim adapter As SqlDataAdapter = _ - New SqlDataAdapter(orderSQL, connection) - -Dim dataSet As DataSet = New DataSet() +Paging through a query result is the process of returning the results of a query in smaller subsets of data, or pages. This is a common practice for displaying results to a user in small, easy-to-manage chunks. + + The `DataAdapter` provides a facility for returning only a page of data, through overloads of the `Fill` method. However, this might not be the best choice for paging through large query results because, although the `DataAdapter` fills the target or with only the requested records, the resources to return the entire query are still used. To return a page of data from a data source without using the resources to return the entire query, specify additional criteria for your query that reduce the rows returned to only those required. + + To use the `Fill` method to return a page of data, specify a `startRecord` parameter, for the first record in the page of data, and a `maxRecords` parameter, for the number of records in the page of data. + + The following code example shows how to use the `Fill` method to return the first page of a query result where the page size is five records. + +```vb +Dim currentIndex As Integer = 0 +Dim pageSize As Integer = 5 + +Dim orderSQL As String = "SELECT * FROM dbo.Orders ORDER BY OrderID" +' Assumes that connection is a valid SqlConnection object. +Dim adapter As SqlDataAdapter = _ + New SqlDataAdapter(orderSQL, connection) + +Dim dataSet As DataSet = New DataSet() +adapter.Fill(dataSet, currentIndex, pageSize, "Orders") +``` + +```csharp +int currentIndex = 0; +int pageSize = 5; + +string orderSQL = "SELECT * FROM Orders ORDER BY OrderID"; +// Assumes that connection is a valid SqlConnection object. +SqlDataAdapter adapter = new SqlDataAdapter(orderSQL, connection); + +DataSet dataSet = new DataSet(); +adapter.Fill(dataSet, currentIndex, pageSize, "Orders"); +``` + + In the previous example, the `DataSet` is only filled with five records, but the entire `Orders` table is returned. To fill the `DataSet` with those same five records, but only return five records, use the TOP and WHERE clauses in your SQL statement, as in the following code example. + +```vb +Dim pageSize As Integer = 5 + +Dim orderSQL As String = "SELECT TOP " & pageSize & _ + " * FROM Orders ORDER BY OrderID" +Dim adapter As SqlDataAdapter = _ + New SqlDataAdapter(orderSQL, connection) + +Dim dataSet As DataSet = New DataSet() adapter.Fill(dataSet, "Orders") -``` - -```csharp -int pageSize = 5; - +``` + +```csharp +int pageSize = 5; + string orderSQL = "SELECT TOP " + pageSize + - " * FROM Orders ORDER BY OrderID"; -SqlDataAdapter adapter = new SqlDataAdapter(orderSQL, connection); - -DataSet dataSet = new DataSet(); -adapter.Fill(dataSet, "Orders"); -``` - - Note that, when paging through the query results in this way, you must preserve the unique identifier that orders the rows, in order to pass the unique ID to the command to return the next page of records, as shown in the following code example. - -```vb -Dim lastRecord As String = _ - dataSet.Tables("Orders").Rows(pageSize - 1)("OrderID").ToString() -``` - -```csharp + " * FROM Orders ORDER BY OrderID"; +SqlDataAdapter adapter = new SqlDataAdapter(orderSQL, connection); + +DataSet dataSet = new DataSet(); +adapter.Fill(dataSet, "Orders"); +``` + + Note that, when paging through the query results in this way, you must preserve the unique identifier that orders the rows, in order to pass the unique ID to the command to return the next page of records, as shown in the following code example. + +```vb +Dim lastRecord As String = _ + dataSet.Tables("Orders").Rows(pageSize - 1)("OrderID").ToString() +``` + +```csharp string lastRecord = - dataSet.Tables["Orders"].Rows[pageSize - 1]["OrderID"].ToString(); -``` - - To return the next page of records using the overload of the **Fill** method that takes the **startRecord** and **maxRecords** parameters, increment the current record index by the page size and fill the table. Remember that the database server returns the entire query results even though only one page of records is added to the **DataSet**. In the following code example, the table rows are cleared before they are filled with the next page of data. You might want to preserve a certain number of returned rows in a local cache to reduce trips to the database server. - -```vb -currentIndex = currentIndex + pageSize - -dataSet.Tables("Orders").Rows.Clear() - -adapter.Fill(dataSet, currentIndex, pageSize, "Orders") -``` - -```csharp -currentIndex += pageSize; - -dataSet.Tables["Orders"].Rows.Clear(); - -adapter.Fill(dataSet, currentIndex, pageSize, "Orders"); -``` - - To return the next page of records without having the database server return the entire query, specify restrictive criteria to the SELECT statement. Because the preceding example preserved the last record returned, you can use it in the WHERE clause to specify a starting point for the query, as shown in the following code example. - -```vb -orderSQL = "SELECT TOP " & pageSize & _ - " * FROM Orders WHERE OrderID > " & lastRecord & " ORDER BY OrderID" -adapter.SelectCommand.CommandText = orderSQL - -dataSet.Tables("Orders").Rows.Clear() - -adapter.Fill(dataSet, "Orders") -``` - -```csharp + dataSet.Tables["Orders"].Rows[pageSize - 1]["OrderID"].ToString(); +``` + + To return the next page of records using the overload of the `Fill` method that takes the `startRecord` and `maxRecords` parameters, increment the current record index by the page size and fill the table. Remember that the database server returns the entire query results even though only one page of records is added to the **DataSet**. In the following code example, the table rows are cleared before they are filled with the next page of data. You might want to preserve a certain number of returned rows in a local cache to reduce trips to the database server. + +```vb +currentIndex = currentIndex + pageSize + +dataSet.Tables("Orders").Rows.Clear() + +adapter.Fill(dataSet, currentIndex, pageSize, "Orders") +``` + +```csharp +currentIndex += pageSize; + +dataSet.Tables["Orders"].Rows.Clear(); + +adapter.Fill(dataSet, currentIndex, pageSize, "Orders"); +``` + + To return the next page of records without having the database server return the entire query, specify restrictive criteria to the SELECT statement. Because the preceding example preserved the last record returned, you can use it in the WHERE clause to specify a starting point for the query, as shown in the following code example. + +```vb +orderSQL = "SELECT TOP " & pageSize & _ + " * FROM Orders WHERE OrderID > " & lastRecord & " ORDER BY OrderID" +adapter.SelectCommand.CommandText = orderSQL + +dataSet.Tables("Orders").Rows.Clear() + +adapter.Fill(dataSet, "Orders") +``` + +```csharp orderSQL = "SELECT TOP " + pageSize + - " * FROM Orders WHERE OrderID > " + lastRecord + " ORDER BY OrderID"; -adapter.SelectCommand.CommandText = orderSQL; - -dataSet.Tables["Orders"].Rows.Clear(); - -adapter.Fill(dataSet, "Orders"); -``` - + " * FROM Orders WHERE OrderID > " + lastRecord + " ORDER BY OrderID"; +adapter.SelectCommand.CommandText = orderSQL; + +dataSet.Tables["Orders"].Rows.Clear(); + +adapter.Fill(dataSet, "Orders"); +``` + ## See also - [DataAdapters and DataReaders](dataadapters-and-datareaders.md) diff --git a/docs/framework/data/adonet/performance-counters.md b/docs/framework/data/adonet/performance-counters.md index af8e5e804e2b2..13d6401cf5079 100644 --- a/docs/framework/data/adonet/performance-counters.md +++ b/docs/framework/data/adonet/performance-counters.md @@ -33,7 +33,7 @@ ADO.NET 2.0 introduced expanded support for performance counters that includes s ### Connection Pool Groups and Connection Pools -When using Windows Authentication (integrated security), you must monitor both the `NumberOfActiveConnectionPoolGroups` and `NumberOfActiveConnectionPools` performance counters. The reason is that connection pool groups map to unique connection strings. When integrated security is used, connection pools map to connection strings and additionally create separate pools for individual Windows identities. For example, if Fred and Julie, each within the same AppDomain, both use the connection string `"Data Source=MySqlServer;Integrated Security=true"`, a connection pool group is created for the connection string, and two additional pools are created, one for Fred and one for Julie. If John and Martha use a connection string with an identical SQL Server login, `"Data Source=MySqlServer;User Id=lowPrivUser;Password=[PLACEHOLDER]"`, then only a single pool is created for the **lowPrivUser** identity. +When using Windows Authentication (integrated security), you must monitor both the `NumberOfActiveConnectionPoolGroups` and `NumberOfActiveConnectionPools` performance counters. The reason is that connection pool groups map to unique connection strings. When integrated security is used, connection pools map to connection strings and additionally create separate pools for individual Windows identities. For example, if Fred and Julie, each within the same AppDomain, both use the connection string `"Data Source=MySqlServer;Integrated Security=true"`, a connection pool group is created for the connection string, and two additional pools are created, one for Fred and one for Julie. If John and Martha use a connection string with an identical SQL Server login, `"Data Source=MySqlServer;User Id=lowPrivUser;Password=[PLACEHOLDER]"`, then only a single pool is created for the `lowPrivUser` identity. [!INCLUDE [managed-identities](../../../includes/managed-identities.md)] @@ -55,7 +55,7 @@ When using Windows Authentication (integrated security), you must monitor both t The following console application shows how to retrieve performance counter values in your application. Connections must be open and active for information to be returned for all of the ADO.NET performance counters. > [!NOTE] -> This example uses the sample **AdventureWorks** database included with SQL Server. The connection strings provided in the sample code assume that the database is installed and available on the local computer with an instance name of SqlExpress, and that you have created SQL Server logins that match those supplied in the connection strings. You may need to enable SQL Server logins if your server is configured using the default security settings which allow only Windows Authentication. Modify the connection strings as necessary to suit your environment. +> This example uses the sample `AdventureWorks` database included with SQL Server. The connection strings provided in the sample code assume that the database is installed and available on the local computer with an instance name of SqlExpress, and that you have created SQL Server logins that match those supplied in the connection strings. You may need to enable SQL Server logins if your server is configured using the default security settings which allow only Windows Authentication. Modify the connection strings as necessary to suit your environment. ### Example diff --git a/docs/framework/data/adonet/performing-batch-operations-using-dataadapters.md b/docs/framework/data/adonet/performing-batch-operations-using-dataadapters.md index 302ce5ae10086..7077460db8bbc 100644 --- a/docs/framework/data/adonet/performing-batch-operations-using-dataadapters.md +++ b/docs/framework/data/adonet/performing-batch-operations-using-dataadapters.md @@ -21,7 +21,7 @@ Batch support in ADO.NET allows a to group When batch updates are enabled, the property value of the DataAdapter's `UpdateCommand`, `InsertCommand`, and `DeleteCommand` should be set to or . When performing a batch update, the command's property value of or is invalid. - The following procedure demonstrates the use of the `UpdateBatchSize` property. The procedure takes two arguments, a object that has columns representing the **ProductCategoryID** and **Name** fields in the **Production.ProductCategory** table, and an integer representing the batch size (the number of rows in the batch). The code creates a new object, setting its , , and properties. The code assumes that the object has modified rows. It sets the `UpdateBatchSize` property and executes the update. + The following procedure demonstrates the use of the `UpdateBatchSize` property. The procedure takes two arguments, a object that has columns representing the `ProductCategoryID` and `Name` fields in the **Production.ProductCategory** table, and an integer representing the batch size (the number of rows in the batch). The code creates a new object, setting its , , and properties. The code assumes that the object has modified rows. It sets the `UpdateBatchSize` property and executes the update. ```vb Public Sub BatchUpdate( _ @@ -124,7 +124,7 @@ public static void BatchUpdate(DataTable dataTable,Int32 batchSize) ## Handling Batch Update-Related Events and Errors - The **DataAdapter** has two update-related events: **RowUpdating** and **RowUpdated**. In previous versions of ADO.NET, when batch processing is disabled, each of these events is generated once for each row processed. **RowUpdating** is generated before the update occurs, and **RowUpdated** is generated after the database update has been completed. + The `DataAdapter` has two update-related events: `RowUpdating` and **RowUpdated**. In previous versions of ADO.NET, when batch processing is disabled, each of these events is generated once for each row processed. `RowUpdating` is generated before the update occurs, and `RowUpdated` is generated after the database update has been completed. ### Event Behavior Changes with Batch Updates diff --git a/docs/framework/data/adonet/performing-catalog-operations.md b/docs/framework/data/adonet/performing-catalog-operations.md index da533fbe135eb..c92c71c6cec6f 100644 --- a/docs/framework/data/adonet/performing-catalog-operations.md +++ b/docs/framework/data/adonet/performing-catalog-operations.md @@ -2,45 +2,45 @@ description: "Learn more about: Performing Catalog Operations" title: "Performing Catalog Operations" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: e60f542f-6271-495b-a9e4-48553481c2a3 --- # Performing Catalog Operations -To execute a command to modify a database or catalog, such as the CREATE TABLE or CREATE PROCEDURE statement, create a **Command** object using the appropriate SQL statements and a **Connection** object. Execute the command with the **ExecuteNonQuery** method of the **Command** object. - - The following code example creates a stored procedure in a Microsoft SQL Server database. - -```vb -' Assumes connection is a valid SqlConnection. -Dim queryString As String = "CREATE PROCEDURE InsertCategory " & _ - "@CategoryName nchar(15), " & _ - "@Identity int OUT " & _ - "AS " & _ - "INSERT INTO Categories (CategoryName) VALUES(@CategoryName) " & _ - "SET @Identity = @@Identity " & _ - "RETURN @@ROWCOUNT" - -Dim command As SqlCommand = New SqlCommand(queryString, connection) -command.ExecuteNonQuery() -``` - -```csharp -// Assumes connection is a valid SqlConnection. +To execute a command to modify a database or catalog, such as the CREATE TABLE or CREATE PROCEDURE statement, create a `Command` object using the appropriate SQL statements and a `Connection` object. Execute the command with the `ExecuteNonQuery` method of the `Command` object. + + The following code example creates a stored procedure in a Microsoft SQL Server database. + +```vb +' Assumes connection is a valid SqlConnection. +Dim queryString As String = "CREATE PROCEDURE InsertCategory " & _ + "@CategoryName nchar(15), " & _ + "@Identity int OUT " & _ + "AS " & _ + "INSERT INTO Categories (CategoryName) VALUES(@CategoryName) " & _ + "SET @Identity = @@Identity " & _ + "RETURN @@ROWCOUNT" + +Dim command As SqlCommand = New SqlCommand(queryString, connection) +command.ExecuteNonQuery() +``` + +```csharp +// Assumes connection is a valid SqlConnection. string queryString = "CREATE PROCEDURE InsertCategory " + - "@CategoryName nchar(15), " + - "@Identity int OUT " + + "@CategoryName nchar(15), " + + "@Identity int OUT " + "AS " + "INSERT INTO Categories (CategoryName) VALUES(@CategoryName) " + - "SET @Identity = @@Identity " + - "RETURN @@ROWCOUNT"; - -SqlCommand command = new SqlCommand(queryString, connection); -command.ExecuteNonQuery(); -``` - + "SET @Identity = @@Identity " + + "RETURN @@ROWCOUNT"; + +SqlCommand command = new SqlCommand(queryString, connection); +command.ExecuteNonQuery(); +``` + ## See also - [Using Commands to Modify Data](using-commands-to-modify-data.md) diff --git a/docs/framework/data/adonet/protecting-connection-information.md b/docs/framework/data/adonet/protecting-connection-information.md index 11298b81d6b80..250e8598b437b 100644 --- a/docs/framework/data/adonet/protecting-connection-information.md +++ b/docs/framework/data/adonet/protecting-connection-information.md @@ -42,7 +42,7 @@ The default value for `Persist Security Info` is false; we recommend using this ## Encrypt Configuration Files - You can also store connection strings in configuration files, which eliminates the need to embed them in your application's code. Configuration files are standard XML files for which .NET Framework has defined a common set of elements. Connection strings in configuration files are typically stored inside the **\** element in the **app.config** for a Windows application, or the **web.config** file for an ASP.NET application. For more information on the basics of storing, retrieving and encrypting connection strings from configuration files, see [Connection Strings and Configuration Files](connection-strings-and-configuration-files.md). + You can also store connection strings in configuration files, which eliminates the need to embed them in your application's code. Configuration files are standard XML files for which .NET Framework has defined a common set of elements. Connection strings in configuration files are typically stored inside the `` element in the **app.config** for a Windows application, or the **web.config** file for an ASP.NET application. For more information on the basics of storing, retrieving and encrypting connection strings from configuration files, see [Connection Strings and Configuration Files](connection-strings-and-configuration-files.md). ## See also diff --git a/docs/framework/data/adonet/retrieving-and-modifying-data.md b/docs/framework/data/adonet/retrieving-and-modifying-data.md index 1da62f27b94c3..eaf225d7cf09b 100644 --- a/docs/framework/data/adonet/retrieving-and-modifying-data.md +++ b/docs/framework/data/adonet/retrieving-and-modifying-data.md @@ -6,55 +6,55 @@ ms.assetid: 722e7f87-3691-46c6-87e8-7d159722d675 --- # Retrieving and Modifying Data in ADO.NET -A primary function of any database application is connecting to a data source and retrieving the data that it contains. The .NET Framework data providers of ADO.NET serve as a bridge between an application and a data source, allowing you to execute commands as well as to retrieve data by using a **DataReader** or a **DataAdapter**. A key function of any database application is the ability to update the data that is stored in the database. In ADO.NET, updating data involves using the **DataAdapter** and , and **Command** objects; and it may also involve using transactions. - -## In This Section - - [Connecting to a Data Source](connecting-to-a-data-source.md) - Describes how to establish a connection to a data source and how to work with connection events. - - [Connection Strings](connection-strings.md) - Contains topics describing various aspects of using connection strings, including connection string keywords, security info, and storing and retrieving them. - - [Connection Pooling](connection-pooling.md) - Describes connection pooling for the .NET Framework data providers. - - [Commands and Parameters](commands-and-parameters.md) - Contains topics describing how to create commands and command builders, configure parameters, and how to execute commands to retrieve and modify data. - - [DataAdapters and DataReaders](dataadapters-and-datareaders.md) - Contains topics describing DataReaders, DataAdapters, parameters, handling DataAdapter events and performing batch operations. - - [Transactions and Concurrency](transactions-and-concurrency.md) - Contains topics describing how to perform local transactions, distributed transactions, and work with optimistic concurrency. - - [Retrieving Identity or Autonumber Values](retrieving-identity-or-autonumber-values.md) - Provides an example of mapping the values generated for an **identity** column in a SQL Server table or for an **Autonumber** field in a Microsoft Access table, to a column of an inserted row in a table. Discusses merging identity values in a `DataTable`. - - [Retrieving Binary Data](retrieving-binary-data.md) - Describes how to retrieve binary data or large data structures using `CommandBehavior`.`SequentialAccess` to modify the default behavior of a `DataReader`. - - [Modifying Data with Stored Procedures](modifying-data-with-stored-procedures.md) - Describes how to use stored procedure input parameters and output parameters to insert a row in a database, returning a new identity value. - - [Retrieving Database Schema Information](retrieving-database-schema-information.md) - Describes how to obtain available databases or catalogs, tables and views in a database, constraints that exist for tables, and other schema information from a data source. - - [DbProviderFactories](dbproviderfactories.md) - Describes the provider factory model and demonstrates how to use the base classes in the `System.Data.Common` namespace. - - [Data Tracing in ADO.NET](data-tracing.md) - Describes how ADO.NET provides built-in data tracing functionality. - - [Performance Counters](performance-counters.md) - Describes performance counters available for `SqlClient` and `OracleClient`. - - [Asynchronous Programming](asynchronous-programming.md) - Describes ADO.NET support for asynchronous programming. - - [SqlClient Streaming Support](sqlclient-streaming-support.md) - Discusses how to write applications that stream data from SQL Server without having it fully loaded in memory. - +A primary function of any database application is connecting to a data source and retrieving the data that it contains. The .NET Framework data providers of ADO.NET serve as a bridge between an application and a data source, allowing you to execute commands as well as to retrieve data by using a `DataReader` or a **DataAdapter**. A key function of any database application is the ability to update the data that is stored in the database. In ADO.NET, updating data involves using the `DataAdapter` and , and `Command` objects; and it may also involve using transactions. + +## In This Section + + [Connecting to a Data Source](connecting-to-a-data-source.md) + Describes how to establish a connection to a data source and how to work with connection events. + + [Connection Strings](connection-strings.md) + Contains topics describing various aspects of using connection strings, including connection string keywords, security info, and storing and retrieving them. + + [Connection Pooling](connection-pooling.md) + Describes connection pooling for the .NET Framework data providers. + + [Commands and Parameters](commands-and-parameters.md) + Contains topics describing how to create commands and command builders, configure parameters, and how to execute commands to retrieve and modify data. + + [DataAdapters and DataReaders](dataadapters-and-datareaders.md) + Contains topics describing DataReaders, DataAdapters, parameters, handling DataAdapter events and performing batch operations. + + [Transactions and Concurrency](transactions-and-concurrency.md) + Contains topics describing how to perform local transactions, distributed transactions, and work with optimistic concurrency. + + [Retrieving Identity or Autonumber Values](retrieving-identity-or-autonumber-values.md) + Provides an example of mapping the values generated for an `identity` column in a SQL Server table or for an `Autonumber` field in a Microsoft Access table, to a column of an inserted row in a table. Discusses merging identity values in a `DataTable`. + + [Retrieving Binary Data](retrieving-binary-data.md) + Describes how to retrieve binary data or large data structures using `CommandBehavior`.`SequentialAccess` to modify the default behavior of a `DataReader`. + + [Modifying Data with Stored Procedures](modifying-data-with-stored-procedures.md) + Describes how to use stored procedure input parameters and output parameters to insert a row in a database, returning a new identity value. + + [Retrieving Database Schema Information](retrieving-database-schema-information.md) + Describes how to obtain available databases or catalogs, tables and views in a database, constraints that exist for tables, and other schema information from a data source. + + [DbProviderFactories](dbproviderfactories.md) + Describes the provider factory model and demonstrates how to use the base classes in the `System.Data.Common` namespace. + + [Data Tracing in ADO.NET](data-tracing.md) + Describes how ADO.NET provides built-in data tracing functionality. + + [Performance Counters](performance-counters.md) + Describes performance counters available for `SqlClient` and `OracleClient`. + + [Asynchronous Programming](asynchronous-programming.md) + Describes ADO.NET support for asynchronous programming. + + [SqlClient Streaming Support](sqlclient-streaming-support.md) + Discusses how to write applications that stream data from SQL Server without having it fully loaded in memory. + ## See also - [Data Type Mappings in ADO.NET](data-type-mappings-in-ado-net.md) diff --git a/docs/framework/data/adonet/retrieving-binary-data.md b/docs/framework/data/adonet/retrieving-binary-data.md index a0e1ac1cd0013..2796db3d16452 100644 --- a/docs/framework/data/adonet/retrieving-binary-data.md +++ b/docs/framework/data/adonet/retrieving-binary-data.md @@ -2,154 +2,154 @@ description: "Learn more about: Retrieving Binary Data" title: "Retrieving Binary Data" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 56c5a9e3-31f1-482f-bce0-ff1c41a658d0 --- # Retrieving Binary Data -By default, the **DataReader** loads incoming data as a row as soon as an entire row of data is available. Binary large objects (BLOBs) need different treatment, however, because they can contain gigabytes of data that cannot be contained in a single row. The **Command.ExecuteReader** method has an overload that will take a argument to modify the default behavior of the **DataReader**. You can pass to the **ExecuteReader** method to modify the default behavior of the **DataReader** so that instead of loading rows of data, it will load data sequentially as it is received. This is ideal for loading BLOBs or other large data structures. Note that this behavior may depend on your data source. For example, returning a BLOB from Microsoft Access will load the entire BLOB being loaded into memory, rather than sequentially as it is received. - - When setting the **DataReader** to use **SequentialAccess**, it is important to note the sequence in which you access the fields returned. The default behavior of the **DataReader**, which loads an entire row as soon as it is available, allows you to access the fields returned in any order until the next row is read. When using **SequentialAccess** however, you must access the fields returned by the **DataReader** in order. For example, if your query returns three columns, the third of which is a BLOB, you must return the values of the first and second fields before accessing the BLOB data in the third field. If you access the third field before the first or second fields, the first and second field values are no longer available. This is because **SequentialAccess** has modified the **DataReader** to return data in sequence and the data is not available after the **DataReader** has read past it. - - When accessing the data in the BLOB field, use the **GetBytes** or **GetChars** typed accessors of the **DataReader**, which fill an array with data. You can also use **GetString** for character data; however. to conserve system resources you might not want to load an entire BLOB value into a single string variable. You can instead specify a specific buffer size of data to be returned, and a starting location for the first byte or character to be read from the returned data. **GetBytes** and **GetChars** will return a `long` value, which represents the number of bytes or characters returned. If you pass a null array to **GetBytes** or **GetChars**, the long value returned will be the total number of bytes or characters in the BLOB. You can optionally specify an index in the array as a starting position for the data being read. - -## Example - - The following example returns the publisher ID and logo from the **pubs** sample database in Microsoft SQL Server. The publisher ID (`pub_id`) is a character field, and the logo is an image, which is a BLOB. Because the **logo** field is a bitmap, the example returns binary data using **GetBytes**. Notice that the publisher ID is accessed for the current row of data before the logo, because the fields must be accessed sequentially. - -```vb -' Assumes that connection is a valid SqlConnection object. -Dim command As SqlCommand = New SqlCommand( _ - "SELECT pub_id, logo FROM pub_info", connection) - -' Writes the BLOB to a file (*.bmp). +By default, the `DataReader` loads incoming data as a row as soon as an entire row of data is available. Binary large objects (BLOBs) need different treatment, however, because they can contain gigabytes of data that cannot be contained in a single row. The **Command.ExecuteReader** method has an overload that will take a argument to modify the default behavior of the **DataReader**. You can pass to the `ExecuteReader` method to modify the default behavior of the `DataReader` so that instead of loading rows of data, it will load data sequentially as it is received. This is ideal for loading BLOBs or other large data structures. Note that this behavior may depend on your data source. For example, returning a BLOB from Microsoft Access will load the entire BLOB being loaded into memory, rather than sequentially as it is received. + + When setting the `DataReader` to use **SequentialAccess**, it is important to note the sequence in which you access the fields returned. The default behavior of the **DataReader**, which loads an entire row as soon as it is available, allows you to access the fields returned in any order until the next row is read. When using `SequentialAccess` however, you must access the fields returned by the `DataReader` in order. For example, if your query returns three columns, the third of which is a BLOB, you must return the values of the first and second fields before accessing the BLOB data in the third field. If you access the third field before the first or second fields, the first and second field values are no longer available. This is because `SequentialAccess` has modified the `DataReader` to return data in sequence and the data is not available after the `DataReader` has read past it. + + When accessing the data in the BLOB field, use the `GetBytes` or `GetChars` typed accessors of the **DataReader**, which fill an array with data. You can also use `GetString` for character data; however. to conserve system resources you might not want to load an entire BLOB value into a single string variable. You can instead specify a specific buffer size of data to be returned, and a starting location for the first byte or character to be read from the returned data. `GetBytes` and `GetChars` will return a `long` value, which represents the number of bytes or characters returned. If you pass a null array to `GetBytes` or **GetChars**, the long value returned will be the total number of bytes or characters in the BLOB. You can optionally specify an index in the array as a starting position for the data being read. + +## Example + + The following example returns the publisher ID and logo from the `pubs` sample database in Microsoft SQL Server. The publisher ID (`pub_id`) is a character field, and the logo is an image, which is a BLOB. Because the `logo` field is a bitmap, the example returns binary data using **GetBytes**. Notice that the publisher ID is accessed for the current row of data before the logo, because the fields must be accessed sequentially. + +```vb +' Assumes that connection is a valid SqlConnection object. +Dim command As SqlCommand = New SqlCommand( _ + "SELECT pub_id, logo FROM pub_info", connection) + +' Writes the BLOB to a file (*.bmp). Dim stream As FileStream -' Streams the binary data to the FileStream object. +' Streams the binary data to the FileStream object. Dim writer As BinaryWriter -' The size of the BLOB buffer. +' The size of the BLOB buffer. Dim bufferSize As Integer = 100 -' The BLOB byte() buffer to be filled by GetBytes. +' The BLOB byte() buffer to be filled by GetBytes. Dim outByte(bufferSize - 1) As Byte -' The bytes returned from GetBytes. +' The bytes returned from GetBytes. Dim retval As Long -' The starting position in the BLOB output. +' The starting position in the BLOB output. Dim startIndex As Long = 0 - -' The publisher id to use in the file name. + +' The publisher id to use in the file name. Dim pubID As String = "" - -' Open the connection and read data into the DataReader. -connection.Open() -Dim reader As SqlDataReader = command.ExecuteReader(CommandBehavior.SequentialAccess) - -Do While reader.Read() - ' Get the publisher id, which must occur before getting the logo. - pubID = reader.GetString(0) - - ' Create a file to hold the output. - stream = New FileStream( _ - "logo" & pubID & ".bmp", FileMode.OpenOrCreate, FileAccess.Write) - writer = New BinaryWriter(stream) - - ' Reset the starting byte for a new BLOB. - startIndex = 0 - - ' Read bytes into outByte() and retain the number of bytes returned. - retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize) - - ' Continue while there are bytes beyond the size of the buffer. - Do While retval = bufferSize - writer.Write(outByte) - writer.Flush() - - ' Reposition start index to end of the last buffer and fill buffer. - startIndex += bufferSize - retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize) - Loop - - ' Write the remaining buffer. - writer.Write(outByte, 0 , retval - 1) - writer.Flush() - - ' Close the output file. - writer.Close() - stream.Close() -Loop - -' Close the reader and the connection. -reader.Close() -connection.Close() -``` - -```csharp -// Assumes that connection is a valid SqlConnection object. -SqlCommand command = new SqlCommand( - "SELECT pub_id, logo FROM pub_info", connection); - -// Writes the BLOB to a file (*.bmp). + +' Open the connection and read data into the DataReader. +connection.Open() +Dim reader As SqlDataReader = command.ExecuteReader(CommandBehavior.SequentialAccess) + +Do While reader.Read() + ' Get the publisher id, which must occur before getting the logo. + pubID = reader.GetString(0) + + ' Create a file to hold the output. + stream = New FileStream( _ + "logo" & pubID & ".bmp", FileMode.OpenOrCreate, FileAccess.Write) + writer = New BinaryWriter(stream) + + ' Reset the starting byte for a new BLOB. + startIndex = 0 + + ' Read bytes into outByte() and retain the number of bytes returned. + retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize) + + ' Continue while there are bytes beyond the size of the buffer. + Do While retval = bufferSize + writer.Write(outByte) + writer.Flush() + + ' Reposition start index to end of the last buffer and fill buffer. + startIndex += bufferSize + retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize) + Loop + + ' Write the remaining buffer. + writer.Write(outByte, 0 , retval - 1) + writer.Flush() + + ' Close the output file. + writer.Close() + stream.Close() +Loop + +' Close the reader and the connection. +reader.Close() +connection.Close() +``` + +```csharp +// Assumes that connection is a valid SqlConnection object. +SqlCommand command = new SqlCommand( + "SELECT pub_id, logo FROM pub_info", connection); + +// Writes the BLOB to a file (*.bmp). FileStream stream; -// Streams the BLOB to the FileStream object. +// Streams the BLOB to the FileStream object. BinaryWriter writer; - -// Size of the BLOB buffer. + +// Size of the BLOB buffer. int bufferSize = 100; -// The BLOB byte[] buffer to be filled by GetBytes. +// The BLOB byte[] buffer to be filled by GetBytes. byte[] outByte = new byte[bufferSize]; -// The bytes returned from GetBytes. +// The bytes returned from GetBytes. long retval; -// The starting position in the BLOB output. +// The starting position in the BLOB output. long startIndex = 0; - -// The publisher id to use in the file name. + +// The publisher id to use in the file name. string pubID = ""; - -// Open the connection and read data into the DataReader. -connection.Open(); -SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess); - -while (reader.Read()) -{ - // Get the publisher id, which must occur before getting the logo. + +// Open the connection and read data into the DataReader. +connection.Open(); +SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess); + +while (reader.Read()) +{ + // Get the publisher id, which must occur before getting the logo. pubID = reader.GetString(0); - - // Create a file to hold the output. - stream = new FileStream( - "logo" + pubID + ".bmp", FileMode.OpenOrCreate, FileAccess.Write); - writer = new BinaryWriter(stream); - - // Reset the starting byte for the new BLOB. - startIndex = 0; - - // Read bytes into outByte[] and retain the number of bytes returned. - retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize); - - // Continue while there are bytes beyond the size of the buffer. - while (retval == bufferSize) - { - writer.Write(outByte); - writer.Flush(); - - // Reposition start index to end of last buffer and fill buffer. - startIndex += bufferSize; - retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize); - } - - // Write the remaining buffer. - writer.Write(outByte, 0, (int)retval); - writer.Flush(); - - // Close the output file. - writer.Close(); - stream.Close(); -} - -// Close the reader and the connection. -reader.Close(); -connection.Close(); -``` - + + // Create a file to hold the output. + stream = new FileStream( + "logo" + pubID + ".bmp", FileMode.OpenOrCreate, FileAccess.Write); + writer = new BinaryWriter(stream); + + // Reset the starting byte for the new BLOB. + startIndex = 0; + + // Read bytes into outByte[] and retain the number of bytes returned. + retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize); + + // Continue while there are bytes beyond the size of the buffer. + while (retval == bufferSize) + { + writer.Write(outByte); + writer.Flush(); + + // Reposition start index to end of last buffer and fill buffer. + startIndex += bufferSize; + retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize); + } + + // Write the remaining buffer. + writer.Write(outByte, 0, (int)retval); + writer.Flush(); + + // Close the output file. + writer.Close(); + stream.Close(); +} + +// Close the reader and the connection. +reader.Close(); +connection.Close(); +``` + ## See also - [SQL Server Binary and Large-Value Data](./sql/sql-server-binary-and-large-value-data.md) diff --git a/docs/framework/data/adonet/retrieving-data-using-a-datareader.md b/docs/framework/data/adonet/retrieving-data-using-a-datareader.md index ceaa4fa7fed0a..165b523a2c9ed 100644 --- a/docs/framework/data/adonet/retrieving-data-using-a-datareader.md +++ b/docs/framework/data/adonet/retrieving-data-using-a-datareader.md @@ -2,66 +2,66 @@ title: "Retrieving Data Using a DataReader" description: Learn how to retrieve data using a DataReader in ADO.NET with this sample code. DataReader provides an unbuffered stream of data. ms.date: "10/29/2018" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 97afc121-fb8b-465b-bab3-6d844420badb --- # Retrieve data using a DataReader -To retrieve data using a **DataReader**, create an instance of the **Command** object, and then create a **DataReader** by calling **Command.ExecuteReader** to retrieve rows from a data source. The **DataReader** provides an unbuffered stream of data that allows procedural logic to efficiently process results from a data source sequentially. The **DataReader** is a good choice when you're retrieving large amounts of data because the data is not cached in memory. +To retrieve data using a **DataReader**, create an instance of the `Command` object, and then create a `DataReader` by calling **Command.ExecuteReader** to retrieve rows from a data source. The `DataReader` provides an unbuffered stream of data that allows procedural logic to efficiently process results from a data source sequentially. The `DataReader` is a good choice when you're retrieving large amounts of data because the data is not cached in memory. -The following example illustrates using a **DataReader**, where `reader` represents a valid DataReader and `command` represents a valid Command object. +The following example illustrates using a **DataReader**, where `reader` represents a valid DataReader and `command` represents a valid Command object. ```csharp -reader = command.ExecuteReader(); +reader = command.ExecuteReader(); ``` ```vb reader = command.ExecuteReader() -``` +``` + +Use the **DataReader.Read** method to obtain a row from the query results. You can access each column of the returned row by passing the name or ordinal number of the column to the **DataReader**. However, for best performance, the `DataReader` provides a series of methods that allow you to access column values in their native data types (**GetDateTime**, **GetDouble**, **GetGuid**, **GetInt32**, and so on). For a list of typed accessor methods for data provider-specific **DataReaders**, see and . Using the typed accessor methods when you know the underlying data type reduces the amount of type conversion required when retrieving the column value. + + The following example iterates through a `DataReader` object and returns two columns from each row. -Use the **DataReader.Read** method to obtain a row from the query results. You can access each column of the returned row by passing the name or ordinal number of the column to the **DataReader**. However, for best performance, the **DataReader** provides a series of methods that allow you to access column values in their native data types (**GetDateTime**, **GetDouble**, **GetGuid**, **GetInt32**, and so on). For a list of typed accessor methods for data provider-specific **DataReaders**, see and . Using the typed accessor methods when you know the underlying data type reduces the amount of type conversion required when retrieving the column value. - - The following example iterates through a **DataReader** object and returns two columns from each row. - [!code-csharp[DataWorks SqlClient.HasRows#1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/CS/source.cs#1)] - [!code-vb[DataWorks SqlClient.HasRows#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/VB/source.vb#1)] - -## Closing the DataReader - - Always call the **Close** method when you have finished using the **DataReader** object. - - If your **Command** contains output parameters or return values, those values are not available until the **DataReader** is closed. - - While a **DataReader** is open, the **Connection** is in use exclusively by that **DataReader**. You cannot execute any commands for the **Connection**, including creating another **DataReader**, until the original **DataReader** is closed. - + [!code-vb[DataWorks SqlClient.HasRows#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.HasRows/VB/source.vb#1)] + +## Closing the DataReader + + Always call the `Close` method when you have finished using the `DataReader` object. + + If your `Command` contains output parameters or return values, those values are not available until the `DataReader` is closed. + + While a `DataReader` is open, the `Connection` is in use exclusively by that **DataReader**. You cannot execute any commands for the **Connection**, including creating another **DataReader**, until the original `DataReader` is closed. + > [!NOTE] -> Do not call **Close** or **Dispose** on a **Connection**, a **DataReader**, or any other managed object in the **Finalize** method of your class. In a finalizer, only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a **Finalize** method in your class definition. For more information, see [Garbage Collection](../../../standard/garbage-collection/index.md). - -## Retrieving multiple result sets using NextResult +> Do not call `Close` or `Dispose` on a **Connection**, a **DataReader**, or any other managed object in the `Finalize` method of your class. In a finalizer, only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](../../../standard/garbage-collection/index.md). + +## Retrieving multiple result sets using NextResult + + If the `DataReader` returns multiple result sets, call the `NextResult` method to iterate through the result sets sequentially. The following example shows the processing the results of two SELECT statements using the method. - If the **DataReader** returns multiple result sets, call the **NextResult** method to iterate through the result sets sequentially. The following example shows the processing the results of two SELECT statements using the method. - [!code-csharp[DataWorks SqlClient.NextResult#1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/CS/source.cs#1)] - [!code-vb[DataWorks SqlClient.NextResult#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/VB/source.vb#1)] - -## Getting schema information from the DataReader + [!code-vb[DataWorks SqlClient.NextResult#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.NextResult/VB/source.vb#1)] + +## Getting schema information from the DataReader + + While a `DataReader` is open, you can retrieve schema information about the current result set using the `GetSchemaTable` method. `GetSchemaTable` returns a object populated with rows and columns that contain the schema information for the current result set. The `DataTable` contains one row for each column of the result set. Each column of the schema table maps to a property of the columns returned in the rows of the result set, where the `ColumnName` is the name of the property and the value of the column is the value of the property. The following example writes out the schema information for **DataReader**. - While a **DataReader** is open, you can retrieve schema information about the current result set using the **GetSchemaTable** method. **GetSchemaTable** returns a object populated with rows and columns that contain the schema information for the current result set. The **DataTable** contains one row for each column of the result set. Each column of the schema table maps to a property of the columns returned in the rows of the result set, where the **ColumnName** is the name of the property and the value of the column is the value of the property. The following example writes out the schema information for **DataReader**. - [!code-csharp[DataWorks SqlClient.GetSchemaTable#1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlClient.GetSchemaTable/CS/source.cs#1)] - [!code-vb[DataWorks SqlClient.GetSchemaTable#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.GetSchemaTable/VB/source.vb#1)] - -## Working with OLE DB chapters - - Hierarchical rowsets, or chapters (OLE DB type **DBTYPE_HCHAPTER**, ADO type **adChapter**), can be retrieved using the . When a query that includes a chapter is returned as a **DataReader**, the chapter is returned as a column in that **DataReader** and is exposed as a **DataReader** object. - - The ADO.NET **DataSet** can also be used to represent hierarchical rowsets by using parent-child relationships between tables. For more information, see [DataSets, DataTables, and DataViews](./dataset-datatable-dataview/index.md). - - The following code example uses the MSDataShape Provider to generate a chapter column of orders for each customer in a list of customers. - -```vb + [!code-vb[DataWorks SqlClient.GetSchemaTable#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlClient.GetSchemaTable/VB/source.vb#1)] + +## Working with OLE DB chapters + + Hierarchical rowsets, or chapters (OLE DB type **DBTYPE_HCHAPTER**, ADO type **adChapter**), can be retrieved using the . When a query that includes a chapter is returned as a **DataReader**, the chapter is returned as a column in that `DataReader` and is exposed as a `DataReader` object. + + The ADO.NET `DataSet` can also be used to represent hierarchical rowsets by using parent-child relationships between tables. For more information, see [DataSets, DataTables, and DataViews](./dataset-datatable-dataview/index.md). + + The following code example uses the MSDataShape Provider to generate a chapter column of orders for each customer in a list of customers. + +```vb Using connection As OleDbConnection = New OleDbConnection( "Provider=MSDataShape;Data Provider=SQLOLEDB;" & "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind") @@ -77,26 +77,26 @@ Using connection As OleDbConnection = New OleDbConnection( Do While custReader.Read() Console.WriteLine("Orders for " & custReader.GetString(1)) - ' custReader.GetString(1) = CompanyName + ' custReader.GetString(1) = CompanyName Using orderReader As OleDbDataReader = custReader.GetValue(2) - ' custReader.GetValue(2) = Orders chapter as DataReader + ' custReader.GetValue(2) = Orders chapter as DataReader Do While orderReader.Read() Console.WriteLine(vbTab & orderReader.GetInt32(1)) - ' orderReader.GetInt32(1) = OrderID + ' orderReader.GetInt32(1) = OrderID Loop orderReader.Close() End Using Loop - ' Make sure to always close readers and connections. + ' Make sure to always close readers and connections. custReader.Close() End Using End Using End Using -``` - -```csharp +``` + +```csharp using (OleDbConnection connection = new OleDbConnection( "Provider=MSDataShape;Data Provider=SQLOLEDB;" + "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind")) @@ -114,44 +114,44 @@ using (OleDbConnection connection = new OleDbConnection( while (custReader.Read()) { Console.WriteLine("Orders for " + custReader.GetString(1)); - // custReader.GetString(1) = CompanyName + // custReader.GetString(1) = CompanyName using (OleDbDataReader orderReader = (OleDbDataReader)custReader.GetValue(2)) { - // custReader.GetValue(2) = Orders chapter as DataReader + // custReader.GetValue(2) = Orders chapter as DataReader while (orderReader.Read()) Console.WriteLine("\t" + orderReader.GetInt32(1)); - // orderReader.GetInt32(1) = OrderID + // orderReader.GetInt32(1) = OrderID orderReader.Close(); } } - // Make sure to always close readers and connections. + // Make sure to always close readers and connections. custReader.Close(); } } } -``` - -## Returning results with Oracle REF CURSORs - - The .NET Framework Data Provider for Oracle supports the use of Oracle REF CURSORs to return a query result. An Oracle REF CURSOR is returned as an . - - You can retrieve an object that represents an Oracle REF CURSOR by using the method. You can also specify an that returns one or more Oracle REF CURSORs as the **SelectCommand** for an used to fill a . - - To access a REF CURSOR returned from an Oracle data source, create an for your query and add an output parameter that references the REF CURSOR to the collection of your . The name of the parameter must match the name of the REF CURSOR parameter in your query. Set the type of the parameter to . The method of your returns an for the REF CURSOR. - - If your returns multiple REF CURSORS, add multiple output parameters. You can access the different REF CURSORs by calling the method. The call to returns an referencing the first REF CURSOR. You can then call the method to access subsequent REF CURSORs. Although the parameters in your collection match the REF CURSOR output parameters by name, the accesses them in the order in which they were added to the collection. - - For example, consider the following Oracle package and package body. - +``` + +## Returning results with Oracle REF CURSORs + + The .NET Framework Data Provider for Oracle supports the use of Oracle REF CURSORs to return a query result. An Oracle REF CURSOR is returned as an . + + You can retrieve an object that represents an Oracle REF CURSOR by using the method. You can also specify an that returns one or more Oracle REF CURSORs as the `SelectCommand` for an used to fill a . + + To access a REF CURSOR returned from an Oracle data source, create an for your query and add an output parameter that references the REF CURSOR to the collection of your . The name of the parameter must match the name of the REF CURSOR parameter in your query. Set the type of the parameter to . The method of your returns an for the REF CURSOR. + + If your returns multiple REF CURSORS, add multiple output parameters. You can access the different REF CURSORs by calling the method. The call to returns an referencing the first REF CURSOR. You can then call the method to access subsequent REF CURSORs. Although the parameters in your collection match the REF CURSOR output parameters by name, the accesses them in the order in which they were added to the collection. + + For example, consider the following Oracle package and package body. + ```sql CREATE OR REPLACE PACKAGE CURSPKG AS TYPE T_CURSOR IS REF CURSOR; PROCEDURE OPEN_TWO_CURSORS (EMPCURSOR OUT T_CURSOR, DEPTCURSOR OUT T_CURSOR); -END CURSPKG; - +END CURSPKG; + CREATE OR REPLACE PACKAGE BODY CURSPKG AS PROCEDURE OPEN_TWO_CURSORS (EMPCURSOR OUT T_CURSOR, DEPTCURSOR OUT T_CURSOR) @@ -161,103 +161,103 @@ CREATE OR REPLACE PACKAGE BODY CURSPKG AS OPEN DEPTCURSOR FOR SELECT * FROM DEMO.DEPARTMENT; END OPEN_TWO_CURSORS; END CURSPKG; -``` - - The following code creates an that returns the REF CURSORs from the previous Oracle package by adding two parameters of type to the collection. - -```vb -Dim cursCmd As OracleCommand = New OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn) -cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output -cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output -``` - -```csharp -OracleCommand cursCmd = new OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn); -cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output; -cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output; -``` - - The following code returns the results of the previous command using the and methods of the . The REF CURSOR parameters are returned in order. - -```vb -oraConn.Open() - -Dim cursCmd As OracleCommand = New OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn) -cursCmd.CommandType = CommandType.StoredProcedure -cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output -cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output - -Dim reader As OracleDataReader = cursCmd.ExecuteReader() - -Console.WriteLine(vbCrLf & "Emp ID" & vbTab & "Name") - -Do While reader.Read() - Console.WriteLine("{0}" & vbTab & "{1}, {2}", reader.GetOracleNumber(0), reader.GetString(1), reader.GetString(2)) -Loop - -reader.NextResult() - -Console.WriteLine(vbCrLf & "Dept ID" & vbTab & "Name") - -Do While reader.Read() - Console.WriteLine("{0}" & vbTab & "{1}", reader.GetOracleNumber(0), reader.GetString(1)) -Loop -' Make sure to always close readers and connections. -reader.Close() -oraConn.Close() -``` - -```csharp -oraConn.Open(); - -OracleCommand cursCmd = new OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn); -cursCmd.CommandType = CommandType.StoredProcedure; -cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output; -cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output; - -OracleDataReader reader = cursCmd.ExecuteReader(); - -Console.WriteLine("\nEmp ID\tName"); - -while (reader.Read()) - Console.WriteLine("{0}\t{1}, {2}", reader.GetOracleNumber(0), reader.GetString(1), reader.GetString(2)); - -reader.NextResult(); - -Console.WriteLine("\nDept ID\tName"); - -while (reader.Read()) - Console.WriteLine("{0}\t{1}", reader.GetOracleNumber(0), reader.GetString(1)); -// Make sure to always close readers and connections. -reader.Close(); -oraConn.Close(); -``` - - The following example uses the previous command to populate a with the results of the Oracle package. - -```vb -Dim ds As DataSet = New DataSet() - -Dim adapter As OracleDataAdapter = New OracleDataAdapter(cursCmd) -adapter.TableMappings.Add("Table", "Employees") -adapter.TableMappings.Add("Table1", "Departments") - -adapter.Fill(ds) -``` - -```csharp -DataSet ds = new DataSet(); - -OracleDataAdapter adapter = new OracleDataAdapter(cursCmd); -adapter.TableMappings.Add("Table", "Employees"); -adapter.TableMappings.Add("Table1", "Departments"); - -adapter.Fill(ds); +``` + + The following code creates an that returns the REF CURSORs from the previous Oracle package by adding two parameters of type to the collection. + +```vb +Dim cursCmd As OracleCommand = New OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn) +cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output +cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output +``` + +```csharp +OracleCommand cursCmd = new OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn); +cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output; +cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output; +``` + + The following code returns the results of the previous command using the and methods of the . The REF CURSOR parameters are returned in order. + +```vb +oraConn.Open() + +Dim cursCmd As OracleCommand = New OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn) +cursCmd.CommandType = CommandType.StoredProcedure +cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output +cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output + +Dim reader As OracleDataReader = cursCmd.ExecuteReader() + +Console.WriteLine(vbCrLf & "Emp ID" & vbTab & "Name") + +Do While reader.Read() + Console.WriteLine("{0}" & vbTab & "{1}, {2}", reader.GetOracleNumber(0), reader.GetString(1), reader.GetString(2)) +Loop + +reader.NextResult() + +Console.WriteLine(vbCrLf & "Dept ID" & vbTab & "Name") + +Do While reader.Read() + Console.WriteLine("{0}" & vbTab & "{1}", reader.GetOracleNumber(0), reader.GetString(1)) +Loop +' Make sure to always close readers and connections. +reader.Close() +oraConn.Close() +``` + +```csharp +oraConn.Open(); + +OracleCommand cursCmd = new OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn); +cursCmd.CommandType = CommandType.StoredProcedure; +cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output; +cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output; + +OracleDataReader reader = cursCmd.ExecuteReader(); + +Console.WriteLine("\nEmp ID\tName"); + +while (reader.Read()) + Console.WriteLine("{0}\t{1}, {2}", reader.GetOracleNumber(0), reader.GetString(1), reader.GetString(2)); + +reader.NextResult(); + +Console.WriteLine("\nDept ID\tName"); + +while (reader.Read()) + Console.WriteLine("{0}\t{1}", reader.GetOracleNumber(0), reader.GetString(1)); +// Make sure to always close readers and connections. +reader.Close(); +oraConn.Close(); +``` + + The following example uses the previous command to populate a with the results of the Oracle package. + +```vb +Dim ds As DataSet = New DataSet() + +Dim adapter As OracleDataAdapter = New OracleDataAdapter(cursCmd) +adapter.TableMappings.Add("Table", "Employees") +adapter.TableMappings.Add("Table1", "Departments") + +adapter.Fill(ds) +``` + +```csharp +DataSet ds = new DataSet(); + +OracleDataAdapter adapter = new OracleDataAdapter(cursCmd); +adapter.TableMappings.Add("Table", "Employees"); +adapter.TableMappings.Add("Table1", "Departments"); + +adapter.Fill(ds); ``` > [!NOTE] -> To avoid an **OverflowException**, we recommend that you also handle any conversion from the Oracle NUMBER type to a valid .NET Framework type before storing the value in a . You can use the event to determine if an **OverflowException** has occurred. For more information on the event, see [Handling DataAdapter Events](handling-dataadapter-events.md). - +> To avoid an **OverflowException**, we recommend that you also handle any conversion from the Oracle NUMBER type to a valid .NET Framework type before storing the value in a . You can use the event to determine if an `OverflowException` has occurred. For more information on the event, see [Handling DataAdapter Events](handling-dataadapter-events.md). + ## See also - [DataAdapters and DataReaders](dataadapters-and-datareaders.md) diff --git a/docs/framework/data/adonet/retrieving-database-schema-information.md b/docs/framework/data/adonet/retrieving-database-schema-information.md index f2f5c025e6f07..87ee2722bc3fd 100644 --- a/docs/framework/data/adonet/retrieving-database-schema-information.md +++ b/docs/framework/data/adonet/retrieving-database-schema-information.md @@ -6,69 +6,69 @@ ms.assetid: 79038d52-f122-4fd4-9bfb-aaa22d6a114b --- # Retrieving Database Schema Information -Obtaining schema information from a database is accomplished with the process of schema discovery. Schema discovery allows applications to request that managed providers find and return information about the database schema, also known as *metadata*, of a given database. Different database schema elements such as tables, columns, and stored-procedures are exposed through schema collections. Each schema collection contains a variety of schema information specific to the provider being used. - - Each of the .NET Framework managed providers implement the **GetSchema** method in the **Connection** class, and the schema information that is returned from the **GetSchema** method comes in the form of a . The **GetSchema** method is an overloaded method that provides optional parameters for specifying the schema collection to return, and restricting the amount of information returned. - - The .NET Framework Data Providers for OLE DB, ODBC, Oracle, and SqlClient provide a **GetSchemaTable** method that returns a DataTable describing the column metadata of the **DataReader**. - - The .NET Framework Data Provider for OLE DB also exposes schema information by using the method of the object. As arguments, **GetOleDbSchemaTable** takes an that identifies the schema information to return, and an array of restrictions on those returned columns. **GetOleDbSchemaTable** returns a populated with the requested schema information. - -## In This Section - - [GetSchema and Schema Collections](getschema-and-schema-collections.md) - Describes the **GetSchema** method and how it can be used to retrieve and restrict schema information from a database. - - Schema Restrictions - Describes schema restrictions that can be used with **GetSchema**. - - [Common Schema Collections](common-schema-collections.md) - Describes all of the common schema collections supported by all of the .NET Framework managed providers. - - [SQL Server Schema Collections](sql-server-schema-collections.md) - Describes the schema collection supported by the .NET Framework provider for SQL Server. - - [Oracle Schema Collections](oracle-schema-collections.md) - Describes the schema collection supported by the .NET Framework provider for Oracle. - - [ODBC Schema Collections](odbc-schema-collections.md) - Describes the schema collections for ODBC drivers. - - [OLE DB Schema Collections](ole-db-schema-collections.md) - Describes the schema collections for OLE DB providers. - -## Reference - - - Describes the **GetSchema** method of the class. - - - Describes the **GetSchema** method of the class. - - - Describes the **GetSchema** method of the class. - - - Describes the **GetSchema** method of the class. - - - Describes the **GetSchema** method of the class. - - - Describes the **GetSchemaTable** method of the class. - - - Describes the **GetSchemaTable** method of the class. - - - Describes the **GetSchemaTable** method of the class. - - - Describes the **GetSchemaTable** method of the class. - - - Describes the **GetSchemaTable** method of the class. - +Obtaining schema information from a database is accomplished with the process of schema discovery. Schema discovery allows applications to request that managed providers find and return information about the database schema, also known as *metadata*, of a given database. Different database schema elements such as tables, columns, and stored-procedures are exposed through schema collections. Each schema collection contains a variety of schema information specific to the provider being used. + + Each of the .NET Framework managed providers implement the `GetSchema` method in the `Connection` class, and the schema information that is returned from the `GetSchema` method comes in the form of a . The `GetSchema` method is an overloaded method that provides optional parameters for specifying the schema collection to return, and restricting the amount of information returned. + + The .NET Framework Data Providers for OLE DB, ODBC, Oracle, and SqlClient provide a `GetSchemaTable` method that returns a DataTable describing the column metadata of the **DataReader**. + + The .NET Framework Data Provider for OLE DB also exposes schema information by using the method of the object. As arguments, `GetOleDbSchemaTable` takes an that identifies the schema information to return, and an array of restrictions on those returned columns. `GetOleDbSchemaTable` returns a populated with the requested schema information. + +## In This Section + + [GetSchema and Schema Collections](getschema-and-schema-collections.md) + Describes the `GetSchema` method and how it can be used to retrieve and restrict schema information from a database. + + Schema Restrictions + Describes schema restrictions that can be used with **GetSchema**. + + [Common Schema Collections](common-schema-collections.md) + Describes all of the common schema collections supported by all of the .NET Framework managed providers. + + [SQL Server Schema Collections](sql-server-schema-collections.md) + Describes the schema collection supported by the .NET Framework provider for SQL Server. + + [Oracle Schema Collections](oracle-schema-collections.md) + Describes the schema collection supported by the .NET Framework provider for Oracle. + + [ODBC Schema Collections](odbc-schema-collections.md) + Describes the schema collections for ODBC drivers. + + [OLE DB Schema Collections](ole-db-schema-collections.md) + Describes the schema collections for OLE DB providers. + +## Reference + + + Describes the `GetSchema` method of the class. + + + Describes the `GetSchema` method of the class. + + + Describes the `GetSchema` method of the class. + + + Describes the `GetSchema` method of the class. + + + Describes the `GetSchema` method of the class. + + + Describes the `GetSchemaTable` method of the class. + + + Describes the `GetSchemaTable` method of the class. + + + Describes the `GetSchemaTable` method of the class. + + + Describes the `GetSchemaTable` method of the class. + + + Describes the `GetSchemaTable` method of the class. + ## See also - [Retrieving and Modifying Data in ADO.NET](retrieving-and-modifying-data.md) diff --git a/docs/framework/data/adonet/retrieving-identity-or-autonumber-values.md b/docs/framework/data/adonet/retrieving-identity-or-autonumber-values.md index 7ad1201712beb..74b6443bce623 100644 --- a/docs/framework/data/adonet/retrieving-identity-or-autonumber-values.md +++ b/docs/framework/data/adonet/retrieving-identity-or-autonumber-values.md @@ -30,7 +30,7 @@ When working with Microsoft SQL Server, you can create a stored procedure with a |@@IDENTITY|Contains the last identity value generated in any table in the current session. @@IDENTITY can be affected by triggers and may not return the identity value that you expect.| |IDENT_CURRENT|Returns the last identity value generated for a specific table in any session and any scope.| - The following stored procedure demonstrates how to insert a row into the **Categories** table and use an output parameter to return the new identity value generated by the Transact-SQL SCOPE_IDENTITY() function. + The following stored procedure demonstrates how to insert a row into the `Categories` table and use an output parameter to return the new identity value generated by the Transact-SQL SCOPE_IDENTITY() function. ```sql CREATE PROCEDURE dbo.InsertCategory @@ -41,7 +41,7 @@ INSERT INTO Categories (CategoryName) VALUES(@CategoryName) SET @Identity = SCOPE_IDENTITY() ``` -The stored procedure can then be specified as the source of the of a object. The property of the must be set to . The identity output is retrieved by creating a that has a of . When the `InsertCommand` is processed, the auto-incremented identity value is returned and placed in the **CategoryID** column of the current row if you set the property of the insert command to `UpdateRowSource.OutputParameters` or to `UpdateRowSource.Both`. +The stored procedure can then be specified as the source of the of a object. The property of the must be set to . The identity output is retrieved by creating a that has a of . When the `InsertCommand` is processed, the auto-incremented identity value is returned and placed in the `CategoryID` column of the current row if you set the property of the insert command to `UpdateRowSource.OutputParameters` or to `UpdateRowSource.Both`. If your insert command executes a batch that includes both an INSERT statement and a SELECT statement that returns the new identity value, then you can retrieve the new value by setting the `UpdatedRowSource` property of the insert command to `UpdateRowSource.FirstReturnedRecord`. @@ -50,7 +50,7 @@ If your insert command executes a batch that includes both an INSERT statement a ## Merging New Identity Values -A common scenario is to call the `GetChanges` method of a `DataTable` to create a copy that contains only changed rows, and to use the new copy when calling the `Update` method of a `DataAdapter`. This is especially useful when you need to marshal the changed rows to a separate component that performs the update. Following the update, the copy can contain new identity values that must then be merged back into the original `DataTable`. The new identity values are likely to be different from the original values in the `DataTable`. To accomplish the merge, the original values of the **AutoIncrement** columns in the copy must be preserved, in order to be able to locate and update existing rows in the original `DataTable`, rather than appending new rows containing the new identity values. However, by default those original values are lost after a call to the `Update` method of a `DataAdapter`, because `AcceptChanges` is implicitly called for each updated `DataRow`. +A common scenario is to call the `GetChanges` method of a `DataTable` to create a copy that contains only changed rows, and to use the new copy when calling the `Update` method of a `DataAdapter`. This is especially useful when you need to marshal the changed rows to a separate component that performs the update. Following the update, the copy can contain new identity values that must then be merged back into the original `DataTable`. The new identity values are likely to be different from the original values in the `DataTable`. To accomplish the merge, the original values of the `AutoIncrement` columns in the copy must be preserved, in order to be able to locate and update existing rows in the original `DataTable`, rather than appending new rows containing the new identity values. However, by default those original values are lost after a call to the `Update` method of a `DataAdapter`, because `AcceptChanges` is implicitly called for each updated `DataRow`. There are two ways to preserve the original values of a `DataColumn` in a `DataRow` during a `DataAdapter` update: @@ -98,12 +98,12 @@ This section includes a sample that shows how to retrieve `Autonumber` values fr ### Example -Instead of adding schema information using `MissingSchemaAction.AddWithKey`, this example configures a `DataTable` with the correct schema prior to calling the to fill the `DataTable`. In this case, the **CategoryID** column is configured to decrement the value assigned each inserted row starting from zero, by setting to `true`, to 0, and to -1. The code then adds two new rows and uses `GetChanges` to add the changed rows to a new `DataTable` that is passed to the `Update` method. +Instead of adding schema information using `MissingSchemaAction.AddWithKey`, this example configures a `DataTable` with the correct schema prior to calling the to fill the `DataTable`. In this case, the `CategoryID` column is configured to decrement the value assigned each inserted row starting from zero, by setting to `true`, to 0, and to -1. The code then adds two new rows and uses `GetChanges` to add the changed rows to a new `DataTable` that is passed to the `Update` method. [!code-csharp[DataWorks OleDb.JetAutonumberMerge#1](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/source.cs#1)] [!code-vb[DataWorks OleDb.JetAutonumberMerge#1](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/VB/source.vb#1)] -The `RowUpdated` event handler uses the same open as the `Update` statement of the `OleDbDataAdapter`. It checks the `StatementType` of the for inserted rows. For each inserted row a new is created to execute the SELECT @@IDENTITY statement on the connection, returning the new `Autonumber` value, which is placed in the **CategoryID** column of the `DataRow`. The `Status` property is then set to `UpdateStatus.SkipCurrentRow` to suppress the hidden call to `AcceptChanges`. In the main body of the procedure, the `Merge` method is called to merge the two `DataTable` objects, and finally `AcceptChanges` is called. +The `RowUpdated` event handler uses the same open as the `Update` statement of the `OleDbDataAdapter`. It checks the `StatementType` of the for inserted rows. For each inserted row a new is created to execute the SELECT @@IDENTITY statement on the connection, returning the new `Autonumber` value, which is placed in the `CategoryID` column of the `DataRow`. The `Status` property is then set to `UpdateStatus.SkipCurrentRow` to suppress the hidden call to `AcceptChanges`. In the main body of the procedure, the `Merge` method is called to merge the two `DataTable` objects, and finally `AcceptChanges` is called. [!code-csharp[DataWorks OleDb.JetAutonumberMerge#2](../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/CS/source.cs#2)] [!code-vb[DataWorks OleDb.JetAutonumberMerge#2](../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks OleDb.JetAutonumberMerge/VB/source.vb#2)] diff --git a/docs/framework/data/adonet/schema-restrictions.md b/docs/framework/data/adonet/schema-restrictions.md index cd848f804dec5..13ba343717d12 100644 --- a/docs/framework/data/adonet/schema-restrictions.md +++ b/docs/framework/data/adonet/schema-restrictions.md @@ -21,7 +21,7 @@ The second optional parameter of the `GetSchema` method is the restrictions that ## Specifying Restriction Values - To use one of the restrictions of the "Tables" schema collection, simply create an array of strings with four elements, then place a value in the element that matches the restriction number. For example, to restrict the tables returned by the **GetSchema** method to only those tables in the "Sales" schema, set the second element of the array to "Sales" before passing it to the **GetSchema** method. + To use one of the restrictions of the "Tables" schema collection, simply create an array of strings with four elements, then place a value in the element that matches the restriction number. For example, to restrict the tables returned by the `GetSchema` method to only those tables in the "Sales" schema, set the second element of the array to "Sales" before passing it to the `GetSchema` method. > [!NOTE] > The restrictions collections for `SqlClient` and `OracleClient` have an additional `ParameterName` column. The restriction default column is still there for backwards compatibility, but is currently ignored. Parameterized queries rather than string replacement should be used to minimize the risk of an SQL injection attack when specifying restriction values. @@ -29,11 +29,11 @@ The second optional parameter of the `GetSchema` method is the restrictions that > [!NOTE] > The number of elements in the array must be less than or equal to the number of restrictions supported for the specified schema collection else an will be thrown. There can be fewer than the maximum number of restrictions. The missing restrictions are assumed to be null (unrestricted). - You can query a .NET Framework managed provider to determine the list of supported restrictions by calling the **GetSchema** method with the name of the restrictions schema collection, which is "Restrictions". This will return a with a list of the collection names, the restriction names, the default restriction values, and the restriction numbers. + You can query a .NET Framework managed provider to determine the list of supported restrictions by calling the `GetSchema` method with the name of the restrictions schema collection, which is "Restrictions". This will return a with a list of the collection names, the restriction names, the default restriction values, and the restriction numbers. ### Example - The following examples demonstrate how to use the method of the .NET Framework Data Provider for the SQL Server class to retrieve schema information about all of the tables contained in the **AdventureWorks** sample database, and to restrict the information returned to only those tables in the "Sales" schema: + The following examples demonstrate how to use the method of the .NET Framework Data Provider for the SQL Server class to retrieve schema information about all of the tables contained in the `AdventureWorks` sample database, and to restrict the information returned to only those tables in the "Sales" schema: ```vb Imports System.Data.SqlClient diff --git a/docs/framework/data/adonet/side-by-side-execution.md b/docs/framework/data/adonet/side-by-side-execution.md index e9acd0b77e9f8..0fb3afae7edbf 100644 --- a/docs/framework/data/adonet/side-by-side-execution.md +++ b/docs/framework/data/adonet/side-by-side-execution.md @@ -6,49 +6,49 @@ ms.assetid: 9f9ba96d-9f89-4f65-bb2f-6860879f4393 --- # Side-by-Side Execution in ADO.NET -Side-by-side execution in the .NET Framework is the ability to execute an application on a computer that has multiple versions of the .NET Framework installed, exclusively using the version for which the application was compiled. For detailed information about configuring side-by-side execution, see [Side-by-Side Execution](../../deployment/side-by-side-execution.md). - - An application compiled by using one version of the .NET Framework can run on a different version of the .NET Framework. However, we recommend that you compile a version of the application for each installed version of the .NET Framework, and run them separately. In either scenario, you should be aware of changes in ADO.NET between releases that can affect the forward compatibility or backward compatibility of your application. - -## Forward Compatibility and Backward Compatibility - - Forward compatibility means that an application can be compiled with an earlier version of the .NET Framework, but will still run successfully on a later version of the .NET Framework. ADO.NET code written for the .NET Framework version 1.1 is forward compatible with later versions. - - Backward compatibility means that an application is compiled for a newer version of the .NET Framework, but continues to run on earlier versions of the .NET Framework without any loss of functionality. Of course, this will not be the case for features introduced in a new version of the .NET Framework. - -## The .NET Framework Data Provider for ODBC +Side-by-side execution in the .NET Framework is the ability to execute an application on a computer that has multiple versions of the .NET Framework installed, exclusively using the version for which the application was compiled. For detailed information about configuring side-by-side execution, see [Side-by-Side Execution](../../deployment/side-by-side-execution.md). + + An application compiled by using one version of the .NET Framework can run on a different version of the .NET Framework. However, we recommend that you compile a version of the application for each installed version of the .NET Framework, and run them separately. In either scenario, you should be aware of changes in ADO.NET between releases that can affect the forward compatibility or backward compatibility of your application. + +## Forward Compatibility and Backward Compatibility + + Forward compatibility means that an application can be compiled with an earlier version of the .NET Framework, but will still run successfully on a later version of the .NET Framework. ADO.NET code written for the .NET Framework version 1.1 is forward compatible with later versions. + + Backward compatibility means that an application is compiled for a newer version of the .NET Framework, but continues to run on earlier versions of the .NET Framework without any loss of functionality. Of course, this will not be the case for features introduced in a new version of the .NET Framework. + +## The .NET Framework Data Provider for ODBC Starting with version 1.1, the .NET Framework Data Provider for ODBC () is included as a part of the .NET Framework. - - If you have an application developed for the .NET Framework version 1.0 that uses the ODBC data provider to connect to your data source, and you want to run that application on the .NET Framework version 1.1 or a later version, you must update the namespace for the ODBC data provider to **System.Data.Odbc**. You then must recompile it for the newer version of the .NET Framework. - - If you have an application developed for the .NET Framework version 2.0 or later that uses the ODBC data provider to connect to your data source, and you want to run that application on .NET Framework version 1.0, you must download the ODBC data provider and install it on the .NET Framework version 1.0 system. You then must change the namespace for the ODBC data provider to **Microsoft.Data.Odbc**, and recompile the application for .NET Framework version 1.0. - -## The .NET Framework Data Provider for Oracle + + If you have an application developed for the .NET Framework version 1.0 that uses the ODBC data provider to connect to your data source, and you want to run that application on the .NET Framework version 1.1 or a later version, you must update the namespace for the ODBC data provider to **System.Data.Odbc**. You then must recompile it for the newer version of the .NET Framework. + + If you have an application developed for the .NET Framework version 2.0 or later that uses the ODBC data provider to connect to your data source, and you want to run that application on .NET Framework version 1.0, you must download the ODBC data provider and install it on the .NET Framework version 1.0 system. You then must change the namespace for the ODBC data provider to **Microsoft.Data.Odbc**, and recompile the application for .NET Framework version 1.0. + +## The .NET Framework Data Provider for Oracle Starting with version 1.1, the .NET Framework Data Provider for Oracle () is included as a part of the .NET Framework. - - If you have an application developed for the .NET Framework version 2.0 or later that uses the data provider to connect to your data source, and you want to run that application on .NET Framework version 1.0, you must download the data provider and install it on the .NET Framework version 1.0 system. - + + If you have an application developed for the .NET Framework version 2.0 or later that uses the data provider to connect to your data source, and you want to run that application on .NET Framework version 1.0, you must download the data provider and install it on the .NET Framework version 1.0 system. + ## Code Access Security - - Starting with .NET Framework version 2.0, all of the .NET Framework data providers can be used in partially trusted zones. In addition, a new security feature was added to the .NET Framework data providers in .NET Framework version 1.1. This feature enables you to restrict what connection strings can be used in a particular security zone. You can also disable the use of blank passwords for a particular security zone. For more information, see [Code Access Security and ADO.NET](code-access-security.md). - - Because each installation of .NET Framework has a separate Security.config file, there are no compatibility issues with security settings. However, if your application depends on the additional security capabilities of ADO.NET included in .NET Framework version 1.1 and later, you will not be able to distribute it to a version 1.0 system. - + + Starting with .NET Framework version 2.0, all of the .NET Framework data providers can be used in partially trusted zones. In addition, a new security feature was added to the .NET Framework data providers in .NET Framework version 1.1. This feature enables you to restrict what connection strings can be used in a particular security zone. You can also disable the use of blank passwords for a particular security zone. For more information, see [Code Access Security and ADO.NET](code-access-security.md). + + Because each installation of .NET Framework has a separate Security.config file, there are no compatibility issues with security settings. However, if your application depends on the additional security capabilities of ADO.NET included in .NET Framework version 1.1 and later, you will not be able to distribute it to a version 1.0 system. + ## SqlCommand Execution - -In .NET Framework version 1.1 and later, only executes a command in the context of the **sp_executesql** stored procedure if the command contains parameters, which provides a performance benefit. As a result, if a command affecting the state of the connection is included in a non-parameterized command, it modifies the state of the connection for all subsequent commands executed while the connection is open. - + +In .NET Framework version 1.1 and later, only executes a command in the context of the `sp_executesql` stored procedure if the command contains parameters, which provides a performance benefit. As a result, if a command affecting the state of the connection is included in a non-parameterized command, it modifies the state of the connection for all subsequent commands executed while the connection is open. + Consider the following batch of commands executed in a call to . ```sql -SET NOCOUNT ON; -SELECT * FROM dbo.Customers; -``` - +SET NOCOUNT ON; +SELECT * FROM dbo.Customers; +``` + `NOCOUNT` will remain `ON` for any subsequent commands executed while the connection is open. - + ## See also - [ADO.NET Overview](ado-net-overview.md) diff --git a/docs/framework/data/adonet/sql-server-schema-collections.md b/docs/framework/data/adonet/sql-server-schema-collections.md index dd648042c5545..afe5ad428ab6e 100644 --- a/docs/framework/data/adonet/sql-server-schema-collections.md +++ b/docs/framework/data/adonet/sql-server-schema-collections.md @@ -6,255 +6,255 @@ ms.assetid: c6403cc3-d78b-4f85-bab1-ada7a3446ec5 --- # SQL Server Schema Collections -The Microsoft .NET Framework Data Provider for SQL Server supports additional schema collections in addition to the common schema collections. The schema collections vary slightly by the version of SQL Server you are using. To determine the list of supported schema collections, call the **GetSchema** method with no arguments, or with the schema collection name "MetaDataCollections". This will return a with a list of the supported schema collections, the number of restrictions that they each support, and the number of identifier parts that they use. - -## Databases - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|database_name|String|Name of the database.| -|dbid|Int16|Database ID.| -|create_date|DateTime|Creation Date of the database.| - -## Foreign Keys - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|CONSTRAINT_CATALOG|String|Catalog the constraint belongs to.| -|CONSTRAINT_SCHEMA|String|Schema that contains the constraint.| -|CONSTRAINT_NAME|String|Name.| -|TABLE_CATALOG|String|Table Name constraint is part of.| -|TABLE_SCHEMA|String|Schema that contains the table.| -|TABLE_NAME|String|Table Name| -|CONSTRAINT_TYPE|String|Type of constraint. Only "FOREIGN KEY" is allowed.| -|IS_DEFERRABLE|String|Specifies whether the constraint is deferrable. Returns NO.| -|INITIALLY_DEFERRED|String|Specifies whether the constraint is initially deferrable. Returns NO.| - -## Indexes - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|constraint_catalog|String|Catalog that index belongs to.| -|constraint_schema|String|Schema that contains the index.| -|constraint_name|String|Name of the index.| -|table_catalog|String|Table name the index is associated with.| -|table_schema|String|Schema that contains the table the index is associated with.| -|table_name|String|Table Name.| -|index_name|String|Index Name.| - -### Indexes (SQL Server 2008) - - Beginning with the .NET Framework version 3.5 SP1 and SQL Server 2008, the following columns have been added to the Indexes schema collection to support new spatial types, filestream and sparse columns. These columns are not supported in earlier versions of the .NET Framework and SQL Server. - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|type_desc|String|The type of the index will be one of the following:

- HEAP
- CLUSTERED
- NONCLUSTERED
- XML
- SPATIAL| - -## IndexColumns - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|constraint_catalog|String|Catalog that index belongs to.| -|constraint_schema|String|Schema that contains the index.| -|constraint_name|String|Name of the index.| -|table_catalog|String|Table name the index is associated with.| -|table_schema|String|Schema that contains the table the index is associated with.| -|table_name|String|Table Name.| -|column_name|String|Column name the index is associated with.| -|ordinal_position|Int32|Column ordinal position.| -|KeyType|Byte|The type of object.| -|index_name|String|Index Name.| - -## Procedures - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|SPECIFIC_CATALOG|String|Specific name for the catalog.| -|SPECIFIC_SCHEMA|String|Specific name of the schema.| -|SPECIFIC_NAME|String|Specific name of the catalog.| -|ROUTINE_CATALOG|String|Catalog the stored procedure belongs to.| -|ROUTINE_SCHEMA|String|Schema that contains the stored procedure.| -|ROUTINE_NAME|String|Name of the stored procedure.| -|ROUTINE_TYPE|String|Returns PROCEDURE for stored procedures and FUNCTION for functions.| -|CREATED|DateTime|Time the procedure was created.| -|LAST_ALTERED|DateTime|The last time the procedure was modified.| - -## Procedure Parameters - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|SPECIFIC_CATALOG|String|Catalog name of the procedure for which this is a parameter.| -|SPECIFIC_SCHEMA|String|Schema that contains the procedure for which this parameter is part of.| -|SPECIFIC_NAME|String|Name of the procedure for which this parameter is a part of.| -|ORDINAL_POSITION|Int32|Ordinal position of the parameter starting at 1. For the return value of a procedure, this is a 0.| -|PARAMETER_MODE|String|Returns IN if an input parameter, OUT if an output parameter, and INOUT if an input/output parameter.| -|IS_RESULT|String|Returns YES if indicates result of the procedure that is a function. Otherwise, returns NO.| -|AS_LOCATOR|String|Returns YES if declared as locator. Otherwise, returns NO.| -|PARAMETER_NAME|String|Name of the parameter. NULL if this corresponds to the return value of a function.| -|DATA_TYPE|String|System-supplied data type.| -|CHARACTER_MAXIMUM_LENGTH|Int32|Maximum length in characters for binary or character data types. Otherwise, returns NULL.| -|CHARACTER_OCTET_LENGTH|Int32|Maximum length, in bytes, for binary or character data types. Otherwise, returns NULL.| -|COLLATION_CATALOG|String|Catalog name of the collation of the parameter. If not one of the character types, returns NULL.| -|COLLATION_SCHEMA|String|Always returns NULL.| -|COLLATION_NAME|String|Name of the collation of the parameter. If not one of the character types, returns NULL.| -|CHARACTER_SET_CATALOG|String|Catalog name of the character set of the parameter. If not one of the character types, returns NULL.| -|CHARACTER_SET_SCHEMA|String|Always returns NULL.| -|CHARACTER_SET_NAME|String|Name of the character set of the parameter. If not one of the character types, returns NULL.| -|NUMERIC_PRECISION|Byte|Precision of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, returns NULL.| -|NUMERIC_PRECISION_RADIX|Int16|Precision radix of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, returns NULL.| -|NUMERIC_SCALE|Int32|Scale of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, returns NULL.| -|DATETIME_PRECISION|Int16|Precision in fractional seconds if the parameter type is datetime or smalldatetime. Otherwise, returns NULL.| -|INTERVAL_TYPE|String|NULL. Reserved for future use by SQL Server.| -|INTERVAL_PRECISION|Int16|NULL. Reserved for future use by SQL Server.| - -## Tables - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|TABLE_CATALOG|String|Catalog of the table.| -|TABLE_SCHEMA|String|Schema that contains the table.| -|TABLE_NAME|String|Table name.| -|TABLE_TYPE|String|Type of table. Can be VIEW or BASE TABLE.| - -## Columns - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|TABLE_CATALOG|String|Catalog of the table.| -|TABLE_SCHEMA|String|Schema that contains the table.| -|TABLE_NAME|String|Table name.| -|COLUMN_NAME|String|Column name.| -|ORDINAL_POSITION|Int32|Column identification number.| -|COLUMN_DEFAULT|String|Default value of the column| -|IS_NULLABLE|String|Nullability of the column. If this column allows NULL, this column returns YES. Otherwise, No is returned.| -|DATA_TYPE|String|System-supplied data type.| -|CHARACTER_MAXIMUM_LENGTH|Int32 – Sql8, Int16 – Sql7|Maximum length, in characters, for binary data, character data, or text and image data. Otherwise, NULL is returned.| -|CHARACTER_OCTET_LENGTH|Int32 – SQL8, Int16 – Sql7|Maximum length, in bytes, for binary data, character data, or text and image data. Otherwise, NULL is returned.| -|NUMERIC_PRECISION|Unsigned Byte|Precision of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| -|NUMERIC_PRECISION_RADIX|Int16|Precision radix of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| -|NUMERIC_SCALE|Int32|Scale of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| -|DATETIME_PRECISION|Int16|Subtype code for datetime and SQL-92 interval data types. For other data types, NULL is returned.| -|CHARACTER_SET_CATALOG|String|Returns master, indicating the database in which the character set is located, if the column is character data or text data type. Otherwise, NULL is returned.| -|CHARACTER_SET_SCHEMA|String|Always returns NULL.| -|CHARACTER_SET_NAME|String|Returns the unique name for the character set if this column is character data or text data type. Otherwise, NULL is returned.| -|COLLATION_CATALOG|String|Returns master, indicating the database in which the collation is defined, if the column is character data or text data type. Otherwise, this column is NULL.| - -### Columns (SQL Server 2008) - - Beginning with the .NET Framework version 3.5 SP1 and SQL Server 2008, the following columns have been added to the Columns schema collection to support new spatial types, filestream and sparse columns. These columns are not supported in earlier versions of the .NET Framework and SQL Server. - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|IS_FILESTREAM|String|YES if the column has FILESTREAM attribute.

NO if the column does not have FILESTREAM attribute.| -|IS_SPARSE|String|YES if the column is a sparse column.

NO if the column is not a sparse column.| -|IS_COLUMN_SET|String|YES if the column is a column set column.

NO if the column is not a column set column.| - -### AllColumns (SQL Server 2008) - - Beginning with the .NET Framework version 3.5 SP1 and SQL Server 2008, the AllColumns schema collection has been added to support sparse columns. AllColumns is not supported in earlier versions of the .NET Framework and SQL Server. - - AllColumns has the same restrictions and resulting DataTable schema as the Columns schema collection. The only difference is that AllColumns includes column set columns that are not included in the Columns schema collection. The following table describes these columns. - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|TABLE_CATALOG|String|Catalog of the table.| -|TABLE_SCHEMA|String|Schema that contains the table.| -|TABLE_NAME|String|Table name.| -|COLUMN_NAME|String|Column name.| -|ORDINAL_POSITION|Int32|Column identification number.| -|COLUMN_DEFAULT|String|Default value of the column| -|IS_NULLABLE|String|Nullability of the column. If this column allows NULL, this column returns YES. Otherwise, NO is returned.| -|DATA_TYPE|String|System-supplied data type.| -|CHARACTER_MAXIMUM_LENGTH|Int32|Maximum length, in characters, for binary data, character data, or text and image data. Otherwise, NULL is returned.| -|CHARACTER_OCTET_LENGTH|Int32|Maximum length, in bytes, for binary data, character data, or text and image data. Otherwise, NULL is returned.| -|NUMERIC_PRECISION|Unsigned Byte|Precision of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| -|NUMERIC_PRECISION_RADIX|Int16|Precision radix of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| -|NUMERIC_SCALE|Int32|Scale of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| -|DATETIME_PRECISION|Int16|Subtype code for datetime and SQL-92 interval data types. For other data types, NULL is returned.| -|CHARACTER_SET_CATALOG|String|Returns master, indicating the database in which the character set is located, if the column is character data or text data type. Otherwise, NULL is returned.| -|CHARACTER_SET_SCHEMA|String|Always returns NULL.| -|CHARACTER_SET_NAME|String|Returns the unique name for the character set if this column is character data or text data type. Otherwise, NULL is returned.| -|COLLATION_CATALOG|String|Returns master, indicating the database in which the collation is defined, if the column is character data or text data type. Otherwise, this column is NULL.| -|IS_FILESTREAM|String|YES if the column has FILESTREAM attribute.

NO if the column does not have FILESTREAM attribute.| -|IS_SPARSE|String|YES if the column is a sparse column.

NO if the column is not a sparse column.| -|IS_COLUMN_SET|String|YES if the column is a column set column.

NO if the column is not a column set column.| - -### ColumnSetColumns (SQL Server 2008) - - Beginning with the .NET Framework version 3.5 SP1 and SQL Server 2008, the ColumnSetColumns schema collection has been added to support sparse columns. ColumnSetColumns is not supported in earlier versions of the .NET Framework and SQL Server. The ColumnSetColumns schema collection returns the schema for all of the columns in a column set. The following table describes these columns. - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|TABLE_CATALOG|String|Catalog of the table.| -|TABLE_SCHEMA|String|Schema that contains the table.| -|TABLE_NAME|String|Table name.| -|COLUMN_NAME|String|Column name.| -|ORDINAL_POSITION|Int32|Column identification number.| -|COLUMN_DEFAULT|String|Default value of the column| -|IS_NULLABLE|String|Nullability of the column. If this column allows NULL, this column returns YES. Otherwise, NO is returned.| -|DATA_TYPE|String|System-supplied data type.| -|CHARACTER_MAXIMUM_LENGTH|Int32|Maximum length, in characters, for binary data, character data, or text and image data. Otherwise, NULL is returned.| -|CHARACTER_OCTET_LENGTH|Int32|Maximum length, in bytes, for binary data, character data, or text and image data. Otherwise, NULL is returned.| -|NUMERIC_PRECISION|Unsigned Byte|Precision of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| -|NUMERIC_PRECISION_RADIX|Int16|Precision radix of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| -|NUMERIC_SCALE|Int32|Scale of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| -|DATETIME_PRECISION|Int16|Subtype code for datetime and SQL-92 interval data types. For other data types, NULL is returned.| -|CHARACTER_SET_CATALOG|String|Returns master, indicating the database in which the character set is located, if the column is character data or text data type. Otherwise, NULL is returned.| -|CHARACTER_SET_SCHEMA|String|Always returns NULL.| -|CHARACTER_SET_NAME|String|Returns the unique name for the character set if this column is character data or text data type. Otherwise, NULL is returned.| -|COLLATION_CATALOG|String|Returns master, indicating the database in which the collation is defined, if the column is character data or text data type. Otherwise, this column is NULL.| -|IS_FILESTREAM|String|YES if the column has FILESTREAM attribute.

NO if the column does not have FILESTREAM attribute.| -|IS_SPARSE|String|YES if the column is a sparse column.

NO if the column is not a sparse column.| -|IS_COLUMN_SET|String|YES if the column is a column set column.

NO if the column is not a column set column.| - -## Users - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|uid|Int16|User ID, unique in this database. 1 is the database owner.| -|user_name|String|Username or group name, unique in this database.| -|createdate|DateTime|Date the account was added.| -|updatedate|DateTime|Date the account was last changed.| - -## Views - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|TABLE_CATALOG|String|Catalog of the view.| -|TABLE_SCHEMA|String|Schema that contains the view.| -|TABLE_NAME|String|View name.| -|CHECK_OPTION|String|Type of WITH CHECK OPTION. Is CASCADE if the original view was created using the WITH CHECK OPTION. Otherwise, NONE is returned.| -|IS_UPDATABLE|String|Specifies whether the view is updatable. Always returns NO.| - -## ViewColumns - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|VIEW_CATALOG|String|Catalog of the view.| -|VIEW_SCHEMA|String|Schema that contains the view.| -|VIEW_NAME|String|View name.| -|TABLE_CATALOG|String|Catalog of the table that is associated with this view.| -|TABLE_SCHEMA|String|Schema that contains the table that is associated with this view.| -|TABLE_NAME|String|Name of the table that is associated with the view. Base Table.| -|COLUMN_NAME|String|Column name.| - -## UserDefinedTypes - -|ColumnName|DataType|Description| -|----------------|--------------|-----------------| -|assembly_name|String|The name of the file for the assembly.| -|udt_name|String|The class name for the assembly.| -|version_major|Object|Major Version Number.| -|version_minor|Object|Minor Version Number.| -|version_build|Object|Build Number.| -|version_revision|Object|Revision Number.| -|culture_info|Object|The culture information associated with this UDT.| -|public_key|Object|The public key used by this Assembly.| -|is_fixed_length|Boolean|Specifies whether length of type is always same as max_length.| -|max_length|Int16|Maximum length of type in bytes.| -|Create_Date|DateTime|The date the assembly was created/registered.| -|Permission_set_desc|String|The friendly name for the permission-set/security-level for the assembly.| - +The Microsoft .NET Framework Data Provider for SQL Server supports additional schema collections in addition to the common schema collections. The schema collections vary slightly by the version of SQL Server you are using. To determine the list of supported schema collections, call the `GetSchema` method with no arguments, or with the schema collection name "MetaDataCollections". This will return a with a list of the supported schema collections, the number of restrictions that they each support, and the number of identifier parts that they use. + +## Databases + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|database_name|String|Name of the database.| +|dbid|Int16|Database ID.| +|create_date|DateTime|Creation Date of the database.| + +## Foreign Keys + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|CONSTRAINT_CATALOG|String|Catalog the constraint belongs to.| +|CONSTRAINT_SCHEMA|String|Schema that contains the constraint.| +|CONSTRAINT_NAME|String|Name.| +|TABLE_CATALOG|String|Table Name constraint is part of.| +|TABLE_SCHEMA|String|Schema that contains the table.| +|TABLE_NAME|String|Table Name| +|CONSTRAINT_TYPE|String|Type of constraint. Only "FOREIGN KEY" is allowed.| +|IS_DEFERRABLE|String|Specifies whether the constraint is deferrable. Returns NO.| +|INITIALLY_DEFERRED|String|Specifies whether the constraint is initially deferrable. Returns NO.| + +## Indexes + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|constraint_catalog|String|Catalog that index belongs to.| +|constraint_schema|String|Schema that contains the index.| +|constraint_name|String|Name of the index.| +|table_catalog|String|Table name the index is associated with.| +|table_schema|String|Schema that contains the table the index is associated with.| +|table_name|String|Table Name.| +|index_name|String|Index Name.| + +### Indexes (SQL Server 2008) + + Beginning with the .NET Framework version 3.5 SP1 and SQL Server 2008, the following columns have been added to the Indexes schema collection to support new spatial types, filestream and sparse columns. These columns are not supported in earlier versions of the .NET Framework and SQL Server. + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|type_desc|String|The type of the index will be one of the following:

- HEAP
- CLUSTERED
- NONCLUSTERED
- XML
- SPATIAL| + +## IndexColumns + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|constraint_catalog|String|Catalog that index belongs to.| +|constraint_schema|String|Schema that contains the index.| +|constraint_name|String|Name of the index.| +|table_catalog|String|Table name the index is associated with.| +|table_schema|String|Schema that contains the table the index is associated with.| +|table_name|String|Table Name.| +|column_name|String|Column name the index is associated with.| +|ordinal_position|Int32|Column ordinal position.| +|KeyType|Byte|The type of object.| +|index_name|String|Index Name.| + +## Procedures + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|SPECIFIC_CATALOG|String|Specific name for the catalog.| +|SPECIFIC_SCHEMA|String|Specific name of the schema.| +|SPECIFIC_NAME|String|Specific name of the catalog.| +|ROUTINE_CATALOG|String|Catalog the stored procedure belongs to.| +|ROUTINE_SCHEMA|String|Schema that contains the stored procedure.| +|ROUTINE_NAME|String|Name of the stored procedure.| +|ROUTINE_TYPE|String|Returns PROCEDURE for stored procedures and FUNCTION for functions.| +|CREATED|DateTime|Time the procedure was created.| +|LAST_ALTERED|DateTime|The last time the procedure was modified.| + +## Procedure Parameters + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|SPECIFIC_CATALOG|String|Catalog name of the procedure for which this is a parameter.| +|SPECIFIC_SCHEMA|String|Schema that contains the procedure for which this parameter is part of.| +|SPECIFIC_NAME|String|Name of the procedure for which this parameter is a part of.| +|ORDINAL_POSITION|Int32|Ordinal position of the parameter starting at 1. For the return value of a procedure, this is a 0.| +|PARAMETER_MODE|String|Returns IN if an input parameter, OUT if an output parameter, and INOUT if an input/output parameter.| +|IS_RESULT|String|Returns YES if indicates result of the procedure that is a function. Otherwise, returns NO.| +|AS_LOCATOR|String|Returns YES if declared as locator. Otherwise, returns NO.| +|PARAMETER_NAME|String|Name of the parameter. NULL if this corresponds to the return value of a function.| +|DATA_TYPE|String|System-supplied data type.| +|CHARACTER_MAXIMUM_LENGTH|Int32|Maximum length in characters for binary or character data types. Otherwise, returns NULL.| +|CHARACTER_OCTET_LENGTH|Int32|Maximum length, in bytes, for binary or character data types. Otherwise, returns NULL.| +|COLLATION_CATALOG|String|Catalog name of the collation of the parameter. If not one of the character types, returns NULL.| +|COLLATION_SCHEMA|String|Always returns NULL.| +|COLLATION_NAME|String|Name of the collation of the parameter. If not one of the character types, returns NULL.| +|CHARACTER_SET_CATALOG|String|Catalog name of the character set of the parameter. If not one of the character types, returns NULL.| +|CHARACTER_SET_SCHEMA|String|Always returns NULL.| +|CHARACTER_SET_NAME|String|Name of the character set of the parameter. If not one of the character types, returns NULL.| +|NUMERIC_PRECISION|Byte|Precision of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, returns NULL.| +|NUMERIC_PRECISION_RADIX|Int16|Precision radix of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, returns NULL.| +|NUMERIC_SCALE|Int32|Scale of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, returns NULL.| +|DATETIME_PRECISION|Int16|Precision in fractional seconds if the parameter type is datetime or smalldatetime. Otherwise, returns NULL.| +|INTERVAL_TYPE|String|NULL. Reserved for future use by SQL Server.| +|INTERVAL_PRECISION|Int16|NULL. Reserved for future use by SQL Server.| + +## Tables + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|TABLE_CATALOG|String|Catalog of the table.| +|TABLE_SCHEMA|String|Schema that contains the table.| +|TABLE_NAME|String|Table name.| +|TABLE_TYPE|String|Type of table. Can be VIEW or BASE TABLE.| + +## Columns + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|TABLE_CATALOG|String|Catalog of the table.| +|TABLE_SCHEMA|String|Schema that contains the table.| +|TABLE_NAME|String|Table name.| +|COLUMN_NAME|String|Column name.| +|ORDINAL_POSITION|Int32|Column identification number.| +|COLUMN_DEFAULT|String|Default value of the column| +|IS_NULLABLE|String|Nullability of the column. If this column allows NULL, this column returns YES. Otherwise, No is returned.| +|DATA_TYPE|String|System-supplied data type.| +|CHARACTER_MAXIMUM_LENGTH|Int32 – Sql8, Int16 – Sql7|Maximum length, in characters, for binary data, character data, or text and image data. Otherwise, NULL is returned.| +|CHARACTER_OCTET_LENGTH|Int32 – SQL8, Int16 – Sql7|Maximum length, in bytes, for binary data, character data, or text and image data. Otherwise, NULL is returned.| +|NUMERIC_PRECISION|Unsigned Byte|Precision of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| +|NUMERIC_PRECISION_RADIX|Int16|Precision radix of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| +|NUMERIC_SCALE|Int32|Scale of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| +|DATETIME_PRECISION|Int16|Subtype code for datetime and SQL-92 interval data types. For other data types, NULL is returned.| +|CHARACTER_SET_CATALOG|String|Returns master, indicating the database in which the character set is located, if the column is character data or text data type. Otherwise, NULL is returned.| +|CHARACTER_SET_SCHEMA|String|Always returns NULL.| +|CHARACTER_SET_NAME|String|Returns the unique name for the character set if this column is character data or text data type. Otherwise, NULL is returned.| +|COLLATION_CATALOG|String|Returns master, indicating the database in which the collation is defined, if the column is character data or text data type. Otherwise, this column is NULL.| + +### Columns (SQL Server 2008) + + Beginning with the .NET Framework version 3.5 SP1 and SQL Server 2008, the following columns have been added to the Columns schema collection to support new spatial types, filestream and sparse columns. These columns are not supported in earlier versions of the .NET Framework and SQL Server. + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|IS_FILESTREAM|String|YES if the column has FILESTREAM attribute.

NO if the column does not have FILESTREAM attribute.| +|IS_SPARSE|String|YES if the column is a sparse column.

NO if the column is not a sparse column.| +|IS_COLUMN_SET|String|YES if the column is a column set column.

NO if the column is not a column set column.| + +### AllColumns (SQL Server 2008) + + Beginning with the .NET Framework version 3.5 SP1 and SQL Server 2008, the AllColumns schema collection has been added to support sparse columns. AllColumns is not supported in earlier versions of the .NET Framework and SQL Server. + + AllColumns has the same restrictions and resulting DataTable schema as the Columns schema collection. The only difference is that AllColumns includes column set columns that are not included in the Columns schema collection. The following table describes these columns. + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|TABLE_CATALOG|String|Catalog of the table.| +|TABLE_SCHEMA|String|Schema that contains the table.| +|TABLE_NAME|String|Table name.| +|COLUMN_NAME|String|Column name.| +|ORDINAL_POSITION|Int32|Column identification number.| +|COLUMN_DEFAULT|String|Default value of the column| +|IS_NULLABLE|String|Nullability of the column. If this column allows NULL, this column returns YES. Otherwise, NO is returned.| +|DATA_TYPE|String|System-supplied data type.| +|CHARACTER_MAXIMUM_LENGTH|Int32|Maximum length, in characters, for binary data, character data, or text and image data. Otherwise, NULL is returned.| +|CHARACTER_OCTET_LENGTH|Int32|Maximum length, in bytes, for binary data, character data, or text and image data. Otherwise, NULL is returned.| +|NUMERIC_PRECISION|Unsigned Byte|Precision of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| +|NUMERIC_PRECISION_RADIX|Int16|Precision radix of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| +|NUMERIC_SCALE|Int32|Scale of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| +|DATETIME_PRECISION|Int16|Subtype code for datetime and SQL-92 interval data types. For other data types, NULL is returned.| +|CHARACTER_SET_CATALOG|String|Returns master, indicating the database in which the character set is located, if the column is character data or text data type. Otherwise, NULL is returned.| +|CHARACTER_SET_SCHEMA|String|Always returns NULL.| +|CHARACTER_SET_NAME|String|Returns the unique name for the character set if this column is character data or text data type. Otherwise, NULL is returned.| +|COLLATION_CATALOG|String|Returns master, indicating the database in which the collation is defined, if the column is character data or text data type. Otherwise, this column is NULL.| +|IS_FILESTREAM|String|YES if the column has FILESTREAM attribute.

NO if the column does not have FILESTREAM attribute.| +|IS_SPARSE|String|YES if the column is a sparse column.

NO if the column is not a sparse column.| +|IS_COLUMN_SET|String|YES if the column is a column set column.

NO if the column is not a column set column.| + +### ColumnSetColumns (SQL Server 2008) + + Beginning with the .NET Framework version 3.5 SP1 and SQL Server 2008, the ColumnSetColumns schema collection has been added to support sparse columns. ColumnSetColumns is not supported in earlier versions of the .NET Framework and SQL Server. The ColumnSetColumns schema collection returns the schema for all of the columns in a column set. The following table describes these columns. + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|TABLE_CATALOG|String|Catalog of the table.| +|TABLE_SCHEMA|String|Schema that contains the table.| +|TABLE_NAME|String|Table name.| +|COLUMN_NAME|String|Column name.| +|ORDINAL_POSITION|Int32|Column identification number.| +|COLUMN_DEFAULT|String|Default value of the column| +|IS_NULLABLE|String|Nullability of the column. If this column allows NULL, this column returns YES. Otherwise, NO is returned.| +|DATA_TYPE|String|System-supplied data type.| +|CHARACTER_MAXIMUM_LENGTH|Int32|Maximum length, in characters, for binary data, character data, or text and image data. Otherwise, NULL is returned.| +|CHARACTER_OCTET_LENGTH|Int32|Maximum length, in bytes, for binary data, character data, or text and image data. Otherwise, NULL is returned.| +|NUMERIC_PRECISION|Unsigned Byte|Precision of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| +|NUMERIC_PRECISION_RADIX|Int16|Precision radix of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| +|NUMERIC_SCALE|Int32|Scale of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.| +|DATETIME_PRECISION|Int16|Subtype code for datetime and SQL-92 interval data types. For other data types, NULL is returned.| +|CHARACTER_SET_CATALOG|String|Returns master, indicating the database in which the character set is located, if the column is character data or text data type. Otherwise, NULL is returned.| +|CHARACTER_SET_SCHEMA|String|Always returns NULL.| +|CHARACTER_SET_NAME|String|Returns the unique name for the character set if this column is character data or text data type. Otherwise, NULL is returned.| +|COLLATION_CATALOG|String|Returns master, indicating the database in which the collation is defined, if the column is character data or text data type. Otherwise, this column is NULL.| +|IS_FILESTREAM|String|YES if the column has FILESTREAM attribute.

NO if the column does not have FILESTREAM attribute.| +|IS_SPARSE|String|YES if the column is a sparse column.

NO if the column is not a sparse column.| +|IS_COLUMN_SET|String|YES if the column is a column set column.

NO if the column is not a column set column.| + +## Users + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|uid|Int16|User ID, unique in this database. 1 is the database owner.| +|user_name|String|Username or group name, unique in this database.| +|createdate|DateTime|Date the account was added.| +|updatedate|DateTime|Date the account was last changed.| + +## Views + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|TABLE_CATALOG|String|Catalog of the view.| +|TABLE_SCHEMA|String|Schema that contains the view.| +|TABLE_NAME|String|View name.| +|CHECK_OPTION|String|Type of WITH CHECK OPTION. Is CASCADE if the original view was created using the WITH CHECK OPTION. Otherwise, NONE is returned.| +|IS_UPDATABLE|String|Specifies whether the view is updatable. Always returns NO.| + +## ViewColumns + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|VIEW_CATALOG|String|Catalog of the view.| +|VIEW_SCHEMA|String|Schema that contains the view.| +|VIEW_NAME|String|View name.| +|TABLE_CATALOG|String|Catalog of the table that is associated with this view.| +|TABLE_SCHEMA|String|Schema that contains the table that is associated with this view.| +|TABLE_NAME|String|Name of the table that is associated with the view. Base Table.| +|COLUMN_NAME|String|Column name.| + +## UserDefinedTypes + +|ColumnName|DataType|Description| +|----------------|--------------|-----------------| +|assembly_name|String|The name of the file for the assembly.| +|udt_name|String|The class name for the assembly.| +|version_major|Object|Major Version Number.| +|version_minor|Object|Minor Version Number.| +|version_build|Object|Build Number.| +|version_revision|Object|Revision Number.| +|culture_info|Object|The culture information associated with this UDT.| +|public_key|Object|The public key used by this Assembly.| +|is_fixed_length|Boolean|Specifies whether length of type is always same as max_length.| +|max_length|Int16|Maximum length of type in bytes.| +|Create_Date|DateTime|The date the assembly was created/registered.| +|Permission_set_desc|String|The friendly name for the permission-set/security-level for the assembly.| + ## See also - [Retrieving Database Schema Information](retrieving-database-schema-information.md) diff --git a/docs/framework/data/adonet/sql/bulk-copy-example-setup.md b/docs/framework/data/adonet/sql/bulk-copy-example-setup.md index 97bf71d8d7e2f..18b72555a77b5 100644 --- a/docs/framework/data/adonet/sql/bulk-copy-example-setup.md +++ b/docs/framework/data/adonet/sql/bulk-copy-example-setup.md @@ -6,78 +6,78 @@ ms.assetid: d4dde6ac-b8b6-4593-965a-635c8fb2dadb --- # Bulk Copy Example Setup -The class can be used to write data only to SQL Server tables. The code samples shown in this topic use the SQL Server sample database, **AdventureWorks**. To avoid altering the existing tables code samples write data to tables that you must create first. - - The **BulkCopyDemoMatchingColumns** and **BulkCopyDemoDifferentColumns** tables are both based on the **AdventureWorks** **Production.Products** table. In code samples that use these tables, data is added from the **Production.Products** table to one of these sample tables. The **BulkCopyDemoDifferentColumns** table is used when the sample illustrates how to map columns from the source data to the destination table; **BulkCopyDemoMatchingColumns** is used for most other samples. - - A few of the code samples demonstrate how to use one class to write to multiple tables. For these samples, the **BulkCopyDemoOrderHeader** and **BulkCopyDemoOrderDetail** tables are used as the destination tables. These tables are based on the **Sales.SalesOrderHeader** and **Sales.SalesOrderDetail** tables in **AdventureWorks**. - +The class can be used to write data only to SQL Server tables. The code samples shown in this topic use the SQL Server sample database, **AdventureWorks**. To avoid altering the existing tables code samples write data to tables that you must create first. + + The `BulkCopyDemoMatchingColumns` and `BulkCopyDemoDifferentColumns` tables are both based on the `AdventureWorks` **Production.Products** table. In code samples that use these tables, data is added from the **Production.Products** table to one of these sample tables. The `BulkCopyDemoDifferentColumns` table is used when the sample illustrates how to map columns from the source data to the destination table; `BulkCopyDemoMatchingColumns` is used for most other samples. + + A few of the code samples demonstrate how to use one class to write to multiple tables. For these samples, the `BulkCopyDemoOrderHeader` and `BulkCopyDemoOrderDetail` tables are used as the destination tables. These tables are based on the **Sales.SalesOrderHeader** and **Sales.SalesOrderDetail** tables in **AdventureWorks**. + > [!NOTE] -> The **SqlBulkCopy** code samples are provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - -## Table Setup +> The `SqlBulkCopy` code samples are provided to demonstrate the syntax for using `SqlBulkCopy` only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. + +## Table Setup + + To create the tables necessary for the code samples to run correctly, you must run the following Transact-SQL statements in a SQL Server database. - To create the tables necessary for the code samples to run correctly, you must run the following Transact-SQL statements in a SQL Server database. - ```sql -USE AdventureWorks - +USE AdventureWorks + IF EXISTS (SELECT * FROM dbo.sysobjects - WHERE id = object_id(N'[dbo].[BulkCopyDemoMatchingColumns]') - AND OBJECTPROPERTY(id, N'IsUserTable') = 1) - DROP TABLE [dbo].[BulkCopyDemoMatchingColumns] - -CREATE TABLE [dbo].[BulkCopyDemoMatchingColumns]([ProductID] [int] IDENTITY(1,1) NOT NULL, - [Name] [nvarchar](50) NOT NULL, - [ProductNumber] [nvarchar](25) NOT NULL, - CONSTRAINT [PK_ProductID] PRIMARY KEY CLUSTERED -( - [ProductID] ASC -) ON [PRIMARY]) ON [PRIMARY] - + WHERE id = object_id(N'[dbo].[BulkCopyDemoMatchingColumns]') + AND OBJECTPROPERTY(id, N'IsUserTable') = 1) + DROP TABLE [dbo].[BulkCopyDemoMatchingColumns] + +CREATE TABLE [dbo].[BulkCopyDemoMatchingColumns]([ProductID] [int] IDENTITY(1,1) NOT NULL, + [Name] [nvarchar](50) NOT NULL, + [ProductNumber] [nvarchar](25) NOT NULL, + CONSTRAINT [PK_ProductID] PRIMARY KEY CLUSTERED +( + [ProductID] ASC +) ON [PRIMARY]) ON [PRIMARY] + IF EXISTS (SELECT * FROM dbo.sysobjects - WHERE id = object_id(N'[dbo].[BulkCopyDemoDifferentColumns]') - AND OBJECTPROPERTY(id, N'IsUserTable') = 1) - DROP TABLE [dbo].[BulkCopyDemoDifferentColumns] - -CREATE TABLE [dbo].[BulkCopyDemoDifferentColumns]([ProdID] [int] IDENTITY(1,1) NOT NULL, - [ProdNum] [nvarchar](25) NOT NULL, - [ProdName] [nvarchar](50) NOT NULL, - CONSTRAINT [PK_ProdID] PRIMARY KEY CLUSTERED -( - [ProdID] ASC -) ON [PRIMARY]) ON [PRIMARY] - + WHERE id = object_id(N'[dbo].[BulkCopyDemoDifferentColumns]') + AND OBJECTPROPERTY(id, N'IsUserTable') = 1) + DROP TABLE [dbo].[BulkCopyDemoDifferentColumns] + +CREATE TABLE [dbo].[BulkCopyDemoDifferentColumns]([ProdID] [int] IDENTITY(1,1) NOT NULL, + [ProdNum] [nvarchar](25) NOT NULL, + [ProdName] [nvarchar](50) NOT NULL, + CONSTRAINT [PK_ProdID] PRIMARY KEY CLUSTERED +( + [ProdID] ASC +) ON [PRIMARY]) ON [PRIMARY] + IF EXISTS (SELECT * FROM dbo.sysobjects - WHERE id = object_id(N'[dbo].[BulkCopyDemoOrderHeader]') - AND OBJECTPROPERTY(id, N'IsUserTable') = 1) - DROP TABLE [dbo].[BulkCopyDemoOrderHeader] - -CREATE TABLE [dbo].[BulkCopyDemoOrderHeader]([SalesOrderID] [int] IDENTITY(1,1) NOT NULL, - [OrderDate] [datetime] NOT NULL, - [AccountNumber] [nvarchar](15) NULL, - CONSTRAINT [PK_SalesOrderID] PRIMARY KEY CLUSTERED -( - [SalesOrderID] ASC -) ON [PRIMARY]) ON [PRIMARY] - + WHERE id = object_id(N'[dbo].[BulkCopyDemoOrderHeader]') + AND OBJECTPROPERTY(id, N'IsUserTable') = 1) + DROP TABLE [dbo].[BulkCopyDemoOrderHeader] + +CREATE TABLE [dbo].[BulkCopyDemoOrderHeader]([SalesOrderID] [int] IDENTITY(1,1) NOT NULL, + [OrderDate] [datetime] NOT NULL, + [AccountNumber] [nvarchar](15) NULL, + CONSTRAINT [PK_SalesOrderID] PRIMARY KEY CLUSTERED +( + [SalesOrderID] ASC +) ON [PRIMARY]) ON [PRIMARY] + IF EXISTS (SELECT * FROM dbo.sysobjects - WHERE id = object_id(N'[dbo].[BulkCopyDemoOrderDetail]') - AND OBJECTPROPERTY(id, N'IsUserTable') = 1) - DROP TABLE [dbo].[BulkCopyDemoOrderDetail] - -CREATE TABLE [dbo].[BulkCopyDemoOrderDetail]([SalesOrderID] [int] NOT NULL, - [SalesOrderDetailID] [int] NOT NULL, - [OrderQty] [smallint] NOT NULL, - [ProductID] [int] NOT NULL, - [UnitPrice] [money] NOT NULL, - CONSTRAINT [PK_LineNumber] PRIMARY KEY CLUSTERED -( - [SalesOrderID] ASC, - [SalesOrderDetailID] ASC -) ON [PRIMARY]) ON [PRIMARY] -``` - + WHERE id = object_id(N'[dbo].[BulkCopyDemoOrderDetail]') + AND OBJECTPROPERTY(id, N'IsUserTable') = 1) + DROP TABLE [dbo].[BulkCopyDemoOrderDetail] + +CREATE TABLE [dbo].[BulkCopyDemoOrderDetail]([SalesOrderID] [int] NOT NULL, + [SalesOrderDetailID] [int] NOT NULL, + [OrderQty] [smallint] NOT NULL, + [ProductID] [int] NOT NULL, + [UnitPrice] [money] NOT NULL, + CONSTRAINT [PK_LineNumber] PRIMARY KEY CLUSTERED +( + [SalesOrderID] ASC, + [SalesOrderDetailID] ASC +) ON [PRIMARY]) ON [PRIMARY] +``` + ## See also - [Bulk Copy Operations in SQL Server](bulk-copy-operations-in-sql-server.md) diff --git a/docs/framework/data/adonet/sql/bulk-copy-operations-in-sql-server.md b/docs/framework/data/adonet/sql/bulk-copy-operations-in-sql-server.md index 936a87484bc1b..6d40313641e73 100644 --- a/docs/framework/data/adonet/sql/bulk-copy-operations-in-sql-server.md +++ b/docs/framework/data/adonet/sql/bulk-copy-operations-in-sql-server.md @@ -1,40 +1,40 @@ --- title: "Bulk Copy Operations in SQL Server" -description: Learn to use the SqlBulkCopy class to write managed code solutions that bulk copy large files into tables or views in SQL Server databases. +description: Learn to use the SqlBulkCopy class to write managed code solutions that bulk copy large files into tables or views in SQL Server databases. ms.date: "03/30/2017" ms.assetid: 83a7a0d2-8018-4354-97b9-0b1d99f8342b --- # Bulk Copy Operations in SQL Server -Microsoft SQL Server includes a popular command-line utility named **bcp** for quickly bulk copying large files into tables or views in SQL Server databases. The class allows you to write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example) but offers a significant performance advantage over them. - - The class can be used to write data only to SQL Server tables. But the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a instance or read with a instance. - - Using the class, you can perform: - -- A single bulk copy operation - -- Multiple bulk copy operations - -- A bulk copy operation within a transaction - +Microsoft SQL Server includes a popular command-line utility named `bcp` for quickly bulk copying large files into tables or views in SQL Server databases. The class allows you to write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example) but offers a significant performance advantage over them. + + The class can be used to write data only to SQL Server tables. But the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a instance or read with a instance. + + Using the class, you can perform: + +- A single bulk copy operation + +- Multiple bulk copy operations + +- A bulk copy operation within a transaction + > [!NOTE] -> When using .NET Framework version 1.1 or earlier (which does not support the class), you can execute the SQL Server Transact-SQL **BULK INSERT** statement using the object. - -## In This Section - - [Bulk Copy Example Setup](bulk-copy-example-setup.md) - Describes the tables used in the bulk copy examples and provides SQL scripts for creating the tables in the AdventureWorks database. - - [Single Bulk Copy Operations](single-bulk-copy-operations.md) - Describes how to do a single bulk copy of data into an instance of SQL Server using the class, and how to perform the bulk copy operation using Transact-SQL statements and the class. - - [Multiple Bulk Copy Operations](multiple-bulk-copy-operations.md) - Describes how to do multiple bulk copy operations of data into an instance of SQL Server using the class. - - [Transaction and Bulk Copy Operations](transaction-and-bulk-copy-operations.md) - Describes how to perform a bulk copy operation within a transaction, including how to commit or rollback the transaction. - +> When using .NET Framework version 1.1 or earlier (which does not support the class), you can execute the SQL Server Transact-SQL **BULK INSERT** statement using the object. + +## In This Section + + [Bulk Copy Example Setup](bulk-copy-example-setup.md) + Describes the tables used in the bulk copy examples and provides SQL scripts for creating the tables in the AdventureWorks database. + + [Single Bulk Copy Operations](single-bulk-copy-operations.md) + Describes how to do a single bulk copy of data into an instance of SQL Server using the class, and how to perform the bulk copy operation using Transact-SQL statements and the class. + + [Multiple Bulk Copy Operations](multiple-bulk-copy-operations.md) + Describes how to do multiple bulk copy operations of data into an instance of SQL Server using the class. + + [Transaction and Bulk Copy Operations](transaction-and-bulk-copy-operations.md) + Describes how to perform a bulk copy operation within a transaction, including how to commit or rollback the transaction. + ## See also - [SQL Server and ADO.NET](index.md) diff --git a/docs/framework/data/adonet/sql/clr-stored-procedures.md b/docs/framework/data/adonet/sql/clr-stored-procedures.md index 36a4dda2a7bc7..7e2f1692cd8c6 100644 --- a/docs/framework/data/adonet/sql/clr-stored-procedures.md +++ b/docs/framework/data/adonet/sql/clr-stored-procedures.md @@ -6,21 +6,21 @@ ms.assetid: fd7eea9b-218a-4988-8c9a-8abcc6031c66 --- # CLR Stored Procedures -Stored procedures are routines that cannot be used in scalar expressions. They can return tabular results and messages to the client, invoke data definition language (DDL) and data manipulation language (DML) statements, and return output parameters. - +Stored procedures are routines that cannot be used in scalar expressions. They can return tabular results and messages to the client, invoke data definition language (DDL) and data manipulation language (DML) statements, and return output parameters. + > [!NOTE] -> Microsoft Visual Basic does not support output parameters in the same way that Microsoft Visual C# does. You must specify to pass the parameter by reference and apply the \ attribute to represent an output parameter, as in the following: - +> Microsoft Visual Basic does not support output parameters in the same way that Microsoft Visual C# does. You must specify to pass the parameter by reference and apply the `` attribute to represent an output parameter, as in the following: + ```vb -Public Shared Sub ExecuteToClient( ByRef number As Integer) +Public Shared Sub ExecuteToClient( ByRef number As Integer) ``` - + For more detailed information, see the version of [SQL Server documentation](/sql) for the version of SQL Server you're using. - + **SQL Server documentation** -1. [CLR Stored Procedures](/previous-versions/sql/sql-server-2008/ms131094(v=sql.100)) - +1. [CLR Stored Procedures](/previous-versions/sql/sql-server-2008/ms131094(v=sql.100)) + ## See also - [Creating SQL Server 2005 Objects In Managed Code](/previous-versions/visualstudio/visual-studio-2008/6s0s2at1(v=vs.90)) diff --git a/docs/framework/data/adonet/sql/database-mirroring-in-sql-server.md b/docs/framework/data/adonet/sql/database-mirroring-in-sql-server.md index 03fa65b86dae2..2629889cc79aa 100644 --- a/docs/framework/data/adonet/sql/database-mirroring-in-sql-server.md +++ b/docs/framework/data/adonet/sql/database-mirroring-in-sql-server.md @@ -38,7 +38,7 @@ Database mirroring in SQL Server allows you to keep a copy, or mirror, of a SQL In the event of a failover, you can retrieve the name of the server to which the current connection is actually connected by using the property of a object. The following code fragment retrieves the name of the active server, assuming that the connection variable references an open . - When a failover event occurs and the connection is switched to the mirror server, the **DataSource** property is updated to reflect the mirror name. + When a failover event occurs and the connection is switched to the mirror server, the `DataSource` property is updated to reflect the mirror name. ```vb Dim activeServer As String = connection.DataSource @@ -50,7 +50,7 @@ string activeServer = connection.DataSource; ## SqlClient Mirroring Behavior - The client always tries to connect to the current principal server. If it fails, it tries the failover partner. If the mirror database has already been switched to the principal role on the partner server, the connection succeeds and the new principal-mirror mapping is sent to the client and cached for the lifetime of the calling . It is not stored in persistent storage and is not available for subsequent connections in a different **AppDomain** or process. However, it is available for subsequent connections within the same **AppDomain**. Note that another **AppDomain** or process running on the same or a different computer always has its pool of connections, and those connections are not reset. In that case, if the primary database goes down, each process or **AppDomain** fails once, and the pool is automatically cleared. + The client always tries to connect to the current principal server. If it fails, it tries the failover partner. If the mirror database has already been switched to the principal role on the partner server, the connection succeeds and the new principal-mirror mapping is sent to the client and cached for the lifetime of the calling . It is not stored in persistent storage and is not available for subsequent connections in a different `AppDomain` or process. However, it is available for subsequent connections within the same **AppDomain**. Note that another `AppDomain` or process running on the same or a different computer always has its pool of connections, and those connections are not reset. In that case, if the primary database goes down, each process or `AppDomain` fails once, and the pool is automatically cleared. > [!NOTE] > Mirroring support on the server is configured on a per-database basis. If data manipulation operations are executed against other databases not included in the principal/mirror set, either by using multipart names or by changing the current database, the changes to these other databases do not propagate in the event of failure. No error is generated when data is modified in a database that is not mirrored. The developer must evaluate the possible impact of such operations. diff --git a/docs/framework/data/adonet/sql/enabling-multiple-active-result-sets.md b/docs/framework/data/adonet/sql/enabling-multiple-active-result-sets.md index 84a369151c71f..7e8560f5ae75e 100644 --- a/docs/framework/data/adonet/sql/enabling-multiple-active-result-sets.md +++ b/docs/framework/data/adonet/sql/enabling-multiple-active-result-sets.md @@ -16,7 +16,7 @@ Multiple Active Result Sets (MARS) is a feature that works with SQL Server to al ## Enabling and Disabling MARS in the Connection String > [!NOTE] -> The following connection strings use the sample **AdventureWorks** database included with SQL Server. The connection strings provided assume that the database is installed on a server named MSSQL1. Modify the connection string as necessary for your environment. +> The following connection strings use the sample `AdventureWorks` database included with SQL Server. The connection strings provided assume that the database is installed on a server named MSSQL1. Modify the connection string as necessary for your environment. The MARS feature is disabled by default. It can be enabled by adding the `"MultipleActiveResultSets=True"` keyword pair to your connection string. "True" is the only valid value for enabling MARS. The following example demonstrates how to connect to an instance of SQL Server and how to specify that MARS should be enabled. @@ -46,7 +46,7 @@ string connectionString = "..." + ### MARS Session Cache - When a connection is opened with MARS enabled, a logical session is created, which adds additional overhead. To minimize overhead and enhance performance, **SqlClient** caches the MARS session within a connection. The cache contains at most 10 MARS sessions. This value is not user adjustable. If the session limit is reached, a new session is created—an error is not generated. The cache and sessions contained in it are per-connection; they are not shared across connections. When a session is released, it is returned to the pool unless the pool's upper limit has been reached. If the cache pool is full, the session is closed. MARS sessions do not expire. They are only cleaned up when the connection object is disposed. The MARS session cache is not preloaded. It is loaded as the application requires more sessions. + When a connection is opened with MARS enabled, a logical session is created, which adds additional overhead. To minimize overhead and enhance performance, `SqlClient` caches the MARS session within a connection. The cache contains at most 10 MARS sessions. This value is not user adjustable. If the session limit is reached, a new session is created—an error is not generated. The cache and sessions contained in it are per-connection; they are not shared across connections. When a session is released, it is returned to the pool unless the pool's upper limit has been reached. If the cache pool is full, the session is closed. MARS sessions do not expire. They are only cleaned up when the connection object is disposed. The MARS session cache is not preloaded. It is loaded as the application requires more sessions. ### Thread Safety diff --git a/docs/framework/data/adonet/sql/linq/sql-clr-type-mismatches.md b/docs/framework/data/adonet/sql/linq/sql-clr-type-mismatches.md index 9a24edb806a97..b5971673587dc 100644 --- a/docs/framework/data/adonet/sql/linq/sql-clr-type-mismatches.md +++ b/docs/framework/data/adonet/sql/linq/sql-clr-type-mismatches.md @@ -44,7 +44,7 @@ The following types do not have reasonable counterparts. - **Timestamp**. Unlike the CLR type, the SQL Server `TIMESTAMP` type represents an 8-byte number generated by the database that is unique for each update and is not based on the difference between values. - - **Money** and **SmallMoney**. These types can be mapped to but are basically different types and are treated as such by server-based functions and conversions. + - `Money` and **SmallMoney**. These types can be mapped to but are basically different types and are treated as such by server-based functions and conversions. ### Multiple Mappings diff --git a/docs/framework/data/adonet/sql/manipulating-data.md b/docs/framework/data/adonet/sql/manipulating-data.md index cc44a1922e7ab..d817967864f17 100644 --- a/docs/framework/data/adonet/sql/manipulating-data.md +++ b/docs/framework/data/adonet/sql/manipulating-data.md @@ -8,7 +8,7 @@ dev_langs: --- # Manipulate data -Before the introduction of Multiple Active Result Sets (MARS), developers had to use either multiple connections or server-side cursors to solve certain scenarios. In addition, when multiple connections were used in a transactional situation, bound connections (with **sp_getbindtoken** and **sp_bindsession**) were required. The following scenarios show how to use a MARS-enabled connection instead of multiple connections. +Before the introduction of Multiple Active Result Sets (MARS), developers had to use either multiple connections or server-side cursors to solve certain scenarios. In addition, when multiple connections were used in a transactional situation, bound connections (with `sp_getbindtoken` and **sp_bindsession**) were required. The following scenarios show how to use a MARS-enabled connection instead of multiple connections. ## Use Multiple Commands with MARS @@ -16,10 +16,10 @@ Before the introduction of Multiple Active Result Sets (MARS), developers had to ### Example - The example opens a single connection to the **AdventureWorks** database. Using a object, a is created. As the reader is used, a second is opened, using data from the first as input to the WHERE clause for the second reader. + The example opens a single connection to the `AdventureWorks` database. Using a object, a is created. As the reader is used, a second is opened, using data from the first as input to the WHERE clause for the second reader. > [!NOTE] -> The following example uses the sample **AdventureWorks** database included with SQL Server. The connection string provided in the sample code assumes that the database is installed and available on the local computer. Modify the connection string as necessary for your environment. +> The following example uses the sample `AdventureWorks` database included with SQL Server. The connection string provided in the sample code assumes that the database is installed and available on the local computer. Modify the connection string as necessary for your environment. ```vb Option Strict On @@ -162,14 +162,14 @@ static void Main() ## Read and Update Data with MARS - MARS allows a connection to be used for both read operations and data manipulation language (DML) operations with more than one pending operation. This feature eliminates the need for an application to deal with connection-busy errors. In addition, MARS can replace the use of server-side cursors, which generally consume more resources. Finally, because multiple operations can operate on a single connection, they can share the same transaction context, eliminating the need to use **sp_getbindtoken** and **sp_bindsession** system stored procedures. + MARS allows a connection to be used for both read operations and data manipulation language (DML) operations with more than one pending operation. This feature eliminates the need for an application to deal with connection-busy errors. In addition, MARS can replace the use of server-side cursors, which generally consume more resources. Finally, because multiple operations can operate on a single connection, they can share the same transaction context, eliminating the need to use `sp_getbindtoken` and `sp_bindsession` system stored procedures. ### Example - The following Console application demonstrates how to use two objects with three objects and a single object with MARS enabled. The first command object retrieves a list of vendors whose credit rating is 5. The second command object uses the vendor ID provided from a to load the second with all of the products for the particular vendor. Each product record is visited by the second . A calculation is performed to determine what the new **OnOrderQty** should be. The third command object is then used to update the **ProductVendor** table with the new value. This entire process takes place within a single transaction, which is rolled back at the end. + The following Console application demonstrates how to use two objects with three objects and a single object with MARS enabled. The first command object retrieves a list of vendors whose credit rating is 5. The second command object uses the vendor ID provided from a to load the second with all of the products for the particular vendor. Each product record is visited by the second . A calculation is performed to determine what the new `OnOrderQty` should be. The third command object is then used to update the `ProductVendor` table with the new value. This entire process takes place within a single transaction, which is rolled back at the end. > [!NOTE] -> The following example uses the sample **AdventureWorks** database included with SQL Server. The connection string provided in the sample code assumes that the database is installed and available on the local computer. Modify the connection string as necessary for your environment. +> The following example uses the sample `AdventureWorks` database included with SQL Server. The connection string provided in the sample code assumes that the database is installed and available on the local computer. Modify the connection string as necessary for your environment. ```vb Option Strict On diff --git a/docs/framework/data/adonet/sql/multiple-bulk-copy-operations.md b/docs/framework/data/adonet/sql/multiple-bulk-copy-operations.md index 04aa6e1386157..c91dd5671f99f 100644 --- a/docs/framework/data/adonet/sql/multiple-bulk-copy-operations.md +++ b/docs/framework/data/adonet/sql/multiple-bulk-copy-operations.md @@ -2,26 +2,26 @@ description: "Learn more about: Multiple Bulk Copy Operations" title: "Multiple Bulk Copy Operations" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 5ad12f94-7459-4a93-a421-4160d1a90715 --- # Multiple Bulk Copy Operations -You can perform multiple bulk copy operations using a single instance of a class. If the operation parameters change between copies (for example, the name of the destination table), you must update them prior to any subsequent calls to any of the **WriteToServer** methods, as demonstrated in the following example. Unless explicitly changed, all property values remain the same as they were on the previous bulk copy operation for a given instance. - +You can perform multiple bulk copy operations using a single instance of a class. If the operation parameters change between copies (for example, the name of the destination table), you must update them prior to any subsequent calls to any of the `WriteToServer` methods, as demonstrated in the following example. Unless explicitly changed, all property values remain the same as they were on the previous bulk copy operation for a given instance. + > [!NOTE] -> Performing multiple bulk copy operations using the same instance of is usually more efficient than using a separate instance for each operation. - - If you perform several bulk copy operations using the same object, there are no restrictions on whether source or target information is equal or different in each operation. However, you must ensure that column association information is properly set each time you write to the server. - +> Performing multiple bulk copy operations using the same instance of is usually more efficient than using a separate instance for each operation. + + If you perform several bulk copy operations using the same object, there are no restrictions on whether source or target information is equal or different in each operation. However, you must ensure that column association information is properly set each time you write to the server. + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](bulk-copy-example-setup.md). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](bulk-copy-example-setup.md). This code is provided to demonstrate the syntax for using `SqlBulkCopy` only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. + [!code-csharp[DataWorks SqlBulkCopy.ColumnMappingOrdersDetails#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/CS/source.cs#1)] - [!code-vb[DataWorks SqlBulkCopy.ColumnMappingOrdersDetails#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/VB/source.vb#1)] - + [!code-vb[DataWorks SqlBulkCopy.ColumnMappingOrdersDetails#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.ColumnMappingOrdersDetails/VB/source.vb#1)] + ## See also - [Bulk Copy Operations in SQL Server](bulk-copy-operations-in-sql-server.md) diff --git a/docs/framework/data/adonet/sql/provider-statistics-for-sql-server.md b/docs/framework/data/adonet/sql/provider-statistics-for-sql-server.md index d1dc3f3143f89..cdd08a7e715ef 100644 --- a/docs/framework/data/adonet/sql/provider-statistics-for-sql-server.md +++ b/docs/framework/data/adonet/sql/provider-statistics-for-sql-server.md @@ -18,7 +18,7 @@ All statistical values gathered are on a per-connection basis. ## Statistical Values Available - Currently there are 18 different items available from the Microsoft SQL Server provider. The number of items available can be accessed via the **Count** property of the interface reference returned by . All of the counters for provider statistics use the common language runtime type (**long** in C# and Visual Basic), which is 64 bits wide. The maximum value of the **int64** data type, as defined by the **int64.MaxValue** field, is ((2^63)-1)). When the values for the counters reach this maximum value, they should no longer be considered accurate. This means that **int64.MaxValue**-1((2^63)-2) is effectively the greatest valid value for any statistic. + Currently there are 18 different items available from the Microsoft SQL Server provider. The number of items available can be accessed via the `Count` property of the interface reference returned by . All of the counters for provider statistics use the common language runtime type (**long** in C# and Visual Basic), which is 64 bits wide. The maximum value of the **int64** data type, as defined by the **int64.MaxValue** field, is ((2^63)-1)). When the values for the counters reach this maximum value, they should no longer be considered accurate. This means that **int64.MaxValue**-1((2^63)-2) is effectively the greatest valid value for any statistic. > [!NOTE] > A dictionary is used for returning provider statistics because the number, names and order of the returned statistics may change in the future. Applications should not rely on a specific value being found in the dictionary, but should instead check whether the value is there and branch accordingly. @@ -51,7 +51,7 @@ All statistical values gathered are on a per-connection basis. The following console application shows how to enable statistics on a connection, retrieve four individual statistic values, and write them out to the console window. > [!NOTE] -> The following example uses the sample **AdventureWorks** database included with SQL Server. The connection string provided in the sample code assumes the database is installed and available on the local computer. Modify the connection string as necessary for your environment. +> The following example uses the sample `AdventureWorks` database included with SQL Server. The connection string provided in the sample code assumes the database is installed and available on the local computer. Modify the connection string as necessary for your environment. ```vb Option Strict On @@ -206,7 +206,7 @@ namespace CS_Stats_Console_GetValue The following console application shows how to enable statistics on a connection, retrieve all available statistic values using the enumerator, and write them to the console window. > [!NOTE] -> The following example uses the sample **AdventureWorks** database included with SQL Server. The connection string provided in the sample code assumes the database is installed and available on the local computer. Modify the connection string as necessary for your environment. +> The following example uses the sample `AdventureWorks` database included with SQL Server. The connection string provided in the sample code assumes the database is installed and available on the local computer. Modify the connection string as necessary for your environment. ```vb Option Strict On diff --git a/docs/framework/data/adonet/sql/single-bulk-copy-operations.md b/docs/framework/data/adonet/sql/single-bulk-copy-operations.md index 941dbbec01e7e..51770e9569882 100644 --- a/docs/framework/data/adonet/sql/single-bulk-copy-operations.md +++ b/docs/framework/data/adonet/sql/single-bulk-copy-operations.md @@ -12,7 +12,7 @@ ms.custom: sfi-ropc-nochange The simplest approach to performing a SQL Server bulk copy operation is to perform a single operation against a database. By default, a bulk copy operation is performed as an isolated operation: the copy operation occurs in a non-transacted way, with no opportunity for rolling it back. > [!NOTE] -> If you need to roll back all or part of the bulk copy when an error occurs, you can either use a -managed transaction, or perform the bulk copy operation within an existing transaction. **SqlBulkCopy** will also work with if the connection is enlisted (implicitly or explicitly) into a **System.Transactions** transaction. +> If you need to roll back all or part of the bulk copy when an error occurs, you can either use a -managed transaction, or perform the bulk copy operation within an existing transaction. `SqlBulkCopy` will also work with if the connection is enlisted (implicitly or explicitly) into a **System.Transactions** transaction. > > For more information, see [Transaction and Bulk Copy Operations](transaction-and-bulk-copy-operations.md). @@ -20,27 +20,27 @@ The general steps for performing a bulk copy operation are as follows: 1. Connect to the source server and obtain the data to be copied. Data can also come from other sources, if it can be retrieved from an or object. -2. Connect to the destination server (unless you want **SqlBulkCopy** to establish a connection for you). +2. Connect to the destination server (unless you want `SqlBulkCopy` to establish a connection for you). 3. Create a object, setting any necessary properties. -4. Set the **DestinationTableName** property to indicate the target table for the bulk insert operation. +4. Set the `DestinationTableName` property to indicate the target table for the bulk insert operation. -5. Call one of the **WriteToServer** methods. +5. Call one of the `WriteToServer` methods. -6. Optionally, update properties and call **WriteToServer** again as necessary. +6. Optionally, update properties and call `WriteToServer` again as necessary. 7. Call , or wrap the bulk copy operations within a `Using` statement. > [!CAUTION] -> We recommend that the source and target column data types match. If the data types do not match, **SqlBulkCopy** attempts to convert each source value to the target data type, using the rules employed by . Conversions can affect performance, and also can result in unexpected errors. For example, a `Double` data type can be converted to a `Decimal` data type most of the time, but not always. +> We recommend that the source and target column data types match. If the data types do not match, `SqlBulkCopy` attempts to convert each source value to the target data type, using the rules employed by . Conversions can affect performance, and also can result in unexpected errors. For example, a `Double` data type can be converted to a `Decimal` data type most of the time, but not always. ## Example -The following console application demonstrates how to load data using the class. In this example, a is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database. +The following console application demonstrates how to load data using the class. In this example, a is used to copy data from the **Production.Product** table in the SQL Server `AdventureWorks` database to a similar table in the same database. > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](bulk-copy-example-setup.md). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](bulk-copy-example-setup.md). This code is provided to demonstrate the syntax for using `SqlBulkCopy` only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data. [!code-csharp[DataWorks BulkCopy.Single#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/CS/source.cs#1)] [!code-vb[DataWorks BulkCopy.Single#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks BulkCopy.Single/VB/source.vb#1)] diff --git a/docs/framework/data/adonet/sql/snapshot-isolation-in-sql-server.md b/docs/framework/data/adonet/sql/snapshot-isolation-in-sql-server.md index 46f29c82f6a04..4a4c79e553f04 100644 --- a/docs/framework/data/adonet/sql/snapshot-isolation-in-sql-server.md +++ b/docs/framework/data/adonet/sql/snapshot-isolation-in-sql-server.md @@ -2,149 +2,149 @@ title: "Snapshot Isolation in SQL Server" description: Read an overview of snapshot isolation and row versioning in SQL Server, and learn how to manage concurrency with isolation levels. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 43ae5dd3-50f5-43a8-8d01-e37a61664176 --- # Snapshot Isolation in SQL Server -Snapshot isolation enhances concurrency for OLTP applications. - -## Understanding Snapshot Isolation and Row Versioning +Snapshot isolation enhances concurrency for OLTP applications. + +## Understanding Snapshot Isolation and Row Versioning + + Once snapshot isolation is enabled, updated row versions for each transaction must be maintained. Prior to SQL Server 2019, these versions were stored in **tempdb**. SQL Server 2019 introduces a new feature, Accelerated Database Recovery (ADR) which requires its own set of row versions. So, as of SQL Server 2019, if ADR is not enabled, row versions are kept in `tempdb` as always. If ADR is enabled, then all row versions, both related to snapshot isolation and ADR, are kept in ADR's Persistent Version Store (PVS), which is located in the user database in a filegroup which the user specifies. A unique transaction sequence number identifies each transaction, and these unique numbers are recorded for each row version. The transaction works with the most recent row versions having a sequence number before the sequence number of the transaction. Newer row versions created after the transaction has begun are ignored by the transaction. + + The term "snapshot" reflects the fact that all queries in the transaction see the same version, or snapshot, of the database, based on the state of the database at the moment in time when the transaction begins. No locks are acquired on the underlying data rows or data pages in a snapshot transaction, which permits other transactions to execute without being blocked by a prior uncompleted transaction. Transactions that modify data do not block transactions that read data, and transactions that read data do not block transactions that write data, as they normally would under the default READ COMMITTED isolation level in SQL Server. This non-blocking behavior also significantly reduces the likelihood of deadlocks for complex transactions. - Once snapshot isolation is enabled, updated row versions for each transaction must be maintained. Prior to SQL Server 2019, these versions were stored in **tempdb**. SQL Server 2019 introduces a new feature, Accelerated Database Recovery (ADR) which requires its own set of row versions. So, as of SQL Server 2019, if ADR is not enabled, row versions are kept in **tempdb** as always. If ADR is enabled, then all row versions, both related to snapshot isolation and ADR, are kept in ADR's Persistent Version Store (PVS), which is located in the user database in a filegroup which the user specifies. A unique transaction sequence number identifies each transaction, and these unique numbers are recorded for each row version. The transaction works with the most recent row versions having a sequence number before the sequence number of the transaction. Newer row versions created after the transaction has begun are ignored by the transaction. - - The term "snapshot" reflects the fact that all queries in the transaction see the same version, or snapshot, of the database, based on the state of the database at the moment in time when the transaction begins. No locks are acquired on the underlying data rows or data pages in a snapshot transaction, which permits other transactions to execute without being blocked by a prior uncompleted transaction. Transactions that modify data do not block transactions that read data, and transactions that read data do not block transactions that write data, as they normally would under the default READ COMMITTED isolation level in SQL Server. This non-blocking behavior also significantly reduces the likelihood of deadlocks for complex transactions. - Snapshot isolation uses an optimistic concurrency model. If a snapshot transaction attempts to commit modifications to data that has changed since the transaction began, the transaction will roll back and an error will be raised. You can avoid this by using UPDLOCK hints for SELECT statements that access data to be modified. For more information, see [Hints (Transact-SQL)](/sql/t-sql/queries/hints-transact-sql-table). - - Snapshot isolation must be enabled by setting the ALLOW_SNAPSHOT_ISOLATION ON database option before it is used in transactions. This activates the mechanism for storing row versions in the temporary database (**tempdb**). You must enable snapshot isolation in each database that uses it with the Transact-SQL ALTER DATABASE statement. In this respect, snapshot isolation differs from the traditional isolation levels of READ COMMITTED, REPEATABLE READ, SERIALIZABLE, and READ UNCOMMITTED, which require no configuration. The following statements activate snapshot isolation and replace the default READ COMMITTED behavior with SNAPSHOT: - -```sql -ALTER DATABASE MyDatabase -SET ALLOW_SNAPSHOT_ISOLATION ON - -ALTER DATABASE MyDatabase -SET READ_COMMITTED_SNAPSHOT ON -``` - - Setting the READ_COMMITTED_SNAPSHOT ON option allows access to versioned rows under the default READ COMMITTED isolation level. If the READ_COMMITTED_SNAPSHOT option is set to OFF, you must explicitly set the Snapshot isolation level for each session in order to access versioned rows. - -## Managing Concurrency with Isolation Levels - - The isolation level under which a Transact-SQL statement executes determines its locking and row versioning behavior. An isolation level has connection-wide scope, and once set for a connection with the SET TRANSACTION ISOLATION LEVEL statement, it remains in effect until the connection is closed or another isolation level is set. When a connection is closed and returned to the pool, the isolation level from the last SET TRANSACTION ISOLATION LEVEL statement is retained. Subsequent connections reusing a pooled connection use the isolation level that was in effect at the time the connection is pooled. - - Individual queries issued within a connection can contain lock hints that modify the isolation for a single statement or transaction but do not affect the isolation level of the connection. Isolation levels or lock hints set in stored procedures or functions do not change the isolation level of the connection that calls them and are in effect only for the duration of the stored procedure or function call. - - Four isolation levels defined in the SQL-92 standard were supported in early versions of SQL Server: - -- READ UNCOMMITTED is the least restrictive isolation level because it ignores locks placed by other transactions. Transactions executing under READ UNCOMMITTED can read modified data values that have not yet been committed by other transactions; these are called "dirty" reads. - -- READ COMMITTED is the default isolation level for SQL Server. It prevents dirty reads by specifying that statements cannot read data values that have been modified but not yet committed by other transactions. Other transactions can still modify, insert, or delete data between executions of individual statements within the current transaction, resulting in non-repeatable reads, or "phantom" data. - -- REPEATABLE READ is a more restrictive isolation level than READ COMMITTED. It encompasses READ COMMITTED and additionally specifies that no other transactions can modify or delete data that has been read by the current transaction until the current transaction commits. Concurrency is lower than for READ COMMITTED because shared locks on read data are held for the duration of the transaction instead of being released at the end of each statement. - -- SERIALIZABLE is the most restrictive isolation level, because it locks entire ranges of keys and holds the locks until the transaction is complete. It encompasses REPEATABLE READ and adds the restriction that other transactions cannot insert new rows into ranges that have been read by the transaction until the transaction is complete. - - For more information, refer to the [Transaction Locking and Row Versioning Guide](/sql/relational-databases/sql-server-transaction-locking-and-row-versioning-guide). - -### Snapshot Isolation Level Extensions - - SQL Server introduced extensions to the SQL-92 isolation levels with the introduction of the SNAPSHOT isolation level and an additional implementation of READ COMMITTED. The READ_COMMITTED_SNAPSHOT isolation level can transparently replace READ COMMITTED for all transactions. - -- SNAPSHOT isolation specifies that data read within a transaction will never reflect changes made by other simultaneous transactions. The transaction uses the data row versions that exist when the transaction begins. No locks are placed on the data when it is read, so SNAPSHOT transactions do not block other transactions from writing data. Transactions that write data do not block snapshot transactions from reading data. You need to enable snapshot isolation by setting the ALLOW_SNAPSHOT_ISOLATION database option in order to use it. - -- The READ_COMMITTED_SNAPSHOT database option determines the behavior of the default READ COMMITTED isolation level when snapshot isolation is enabled in a database. If you do not explicitly specify READ_COMMITTED_SNAPSHOT ON, READ COMMITTED is applied to all implicit transactions. This produces the same behavior as setting READ_COMMITTED_SNAPSHOT OFF (the default). When READ_COMMITTED_SNAPSHOT OFF is in effect, the Database Engine uses shared locks to enforce the default isolation level. If you set the READ_COMMITTED_SNAPSHOT database option to ON, the database engine uses row versioning and snapshot isolation as the default, instead of using locks to protect the data. - -## How Snapshot Isolation and Row Versioning Work - - When the SNAPSHOT isolation level is enabled, each time a row is updated, the SQL Server Database Engine stores a copy of the original row in **tempdb**, and adds a transaction sequence number to the row. The following is the sequence of events that occurs: - -- A new transaction is initiated, and it is assigned a transaction sequence number. - -- The Database Engine reads a row within the transaction and retrieves the row version from **tempdb** whose sequence number is closest to, and lower than, the transaction sequence number. - -- The Database Engine checks to see if the transaction sequence number is not in the list of transaction sequence numbers of the uncommitted transactions active when the snapshot transaction started. - -- The transaction reads the version of the row from **tempdb** that was current as of the start of the transaction. It will not see new rows inserted after the transaction was started because those sequence number values will be higher than the value of the transaction sequence number. - -- The current transaction will see rows that were deleted after the transaction began, because there will be a row version in **tempdb** with a lower sequence number value. - - The net effect of snapshot isolation is that the transaction sees all of the data as it existed at the start of the transaction, without honoring or placing any locks on the underlying tables. This can result in performance improvements in situations where there is contention. - - A snapshot transaction always uses optimistic concurrency control, withholding any locks that would prevent other transactions from updating rows. If a snapshot transaction attempts to commit an update to a row that was changed after the transaction began, the transaction is rolled back, and an error is raised. - -## Working with Snapshot Isolation in ADO.NET - - Snapshot isolation is supported in ADO.NET by the class. If a database has been enabled for snapshot isolation but is not configured for READ_COMMITTED_SNAPSHOT ON, you must initiate a using the **IsolationLevel.Snapshot** enumeration value when calling the method. This code fragment assumes that connection is an open object. - -```vb -Dim sqlTran As SqlTransaction = _ - connection.BeginTransaction(IsolationLevel.Snapshot) -``` - -```csharp + + Snapshot isolation must be enabled by setting the ALLOW_SNAPSHOT_ISOLATION ON database option before it is used in transactions. This activates the mechanism for storing row versions in the temporary database (**tempdb**). You must enable snapshot isolation in each database that uses it with the Transact-SQL ALTER DATABASE statement. In this respect, snapshot isolation differs from the traditional isolation levels of READ COMMITTED, REPEATABLE READ, SERIALIZABLE, and READ UNCOMMITTED, which require no configuration. The following statements activate snapshot isolation and replace the default READ COMMITTED behavior with SNAPSHOT: + +```sql +ALTER DATABASE MyDatabase +SET ALLOW_SNAPSHOT_ISOLATION ON + +ALTER DATABASE MyDatabase +SET READ_COMMITTED_SNAPSHOT ON +``` + + Setting the READ_COMMITTED_SNAPSHOT ON option allows access to versioned rows under the default READ COMMITTED isolation level. If the READ_COMMITTED_SNAPSHOT option is set to OFF, you must explicitly set the Snapshot isolation level for each session in order to access versioned rows. + +## Managing Concurrency with Isolation Levels + + The isolation level under which a Transact-SQL statement executes determines its locking and row versioning behavior. An isolation level has connection-wide scope, and once set for a connection with the SET TRANSACTION ISOLATION LEVEL statement, it remains in effect until the connection is closed or another isolation level is set. When a connection is closed and returned to the pool, the isolation level from the last SET TRANSACTION ISOLATION LEVEL statement is retained. Subsequent connections reusing a pooled connection use the isolation level that was in effect at the time the connection is pooled. + + Individual queries issued within a connection can contain lock hints that modify the isolation for a single statement or transaction but do not affect the isolation level of the connection. Isolation levels or lock hints set in stored procedures or functions do not change the isolation level of the connection that calls them and are in effect only for the duration of the stored procedure or function call. + + Four isolation levels defined in the SQL-92 standard were supported in early versions of SQL Server: + +- READ UNCOMMITTED is the least restrictive isolation level because it ignores locks placed by other transactions. Transactions executing under READ UNCOMMITTED can read modified data values that have not yet been committed by other transactions; these are called "dirty" reads. + +- READ COMMITTED is the default isolation level for SQL Server. It prevents dirty reads by specifying that statements cannot read data values that have been modified but not yet committed by other transactions. Other transactions can still modify, insert, or delete data between executions of individual statements within the current transaction, resulting in non-repeatable reads, or "phantom" data. + +- REPEATABLE READ is a more restrictive isolation level than READ COMMITTED. It encompasses READ COMMITTED and additionally specifies that no other transactions can modify or delete data that has been read by the current transaction until the current transaction commits. Concurrency is lower than for READ COMMITTED because shared locks on read data are held for the duration of the transaction instead of being released at the end of each statement. + +- SERIALIZABLE is the most restrictive isolation level, because it locks entire ranges of keys and holds the locks until the transaction is complete. It encompasses REPEATABLE READ and adds the restriction that other transactions cannot insert new rows into ranges that have been read by the transaction until the transaction is complete. + + For more information, refer to the [Transaction Locking and Row Versioning Guide](/sql/relational-databases/sql-server-transaction-locking-and-row-versioning-guide). + +### Snapshot Isolation Level Extensions + + SQL Server introduced extensions to the SQL-92 isolation levels with the introduction of the SNAPSHOT isolation level and an additional implementation of READ COMMITTED. The READ_COMMITTED_SNAPSHOT isolation level can transparently replace READ COMMITTED for all transactions. + +- SNAPSHOT isolation specifies that data read within a transaction will never reflect changes made by other simultaneous transactions. The transaction uses the data row versions that exist when the transaction begins. No locks are placed on the data when it is read, so SNAPSHOT transactions do not block other transactions from writing data. Transactions that write data do not block snapshot transactions from reading data. You need to enable snapshot isolation by setting the ALLOW_SNAPSHOT_ISOLATION database option in order to use it. + +- The READ_COMMITTED_SNAPSHOT database option determines the behavior of the default READ COMMITTED isolation level when snapshot isolation is enabled in a database. If you do not explicitly specify READ_COMMITTED_SNAPSHOT ON, READ COMMITTED is applied to all implicit transactions. This produces the same behavior as setting READ_COMMITTED_SNAPSHOT OFF (the default). When READ_COMMITTED_SNAPSHOT OFF is in effect, the Database Engine uses shared locks to enforce the default isolation level. If you set the READ_COMMITTED_SNAPSHOT database option to ON, the database engine uses row versioning and snapshot isolation as the default, instead of using locks to protect the data. + +## How Snapshot Isolation and Row Versioning Work + + When the SNAPSHOT isolation level is enabled, each time a row is updated, the SQL Server Database Engine stores a copy of the original row in **tempdb**, and adds a transaction sequence number to the row. The following is the sequence of events that occurs: + +- A new transaction is initiated, and it is assigned a transaction sequence number. + +- The Database Engine reads a row within the transaction and retrieves the row version from `tempdb` whose sequence number is closest to, and lower than, the transaction sequence number. + +- The Database Engine checks to see if the transaction sequence number is not in the list of transaction sequence numbers of the uncommitted transactions active when the snapshot transaction started. + +- The transaction reads the version of the row from `tempdb` that was current as of the start of the transaction. It will not see new rows inserted after the transaction was started because those sequence number values will be higher than the value of the transaction sequence number. + +- The current transaction will see rows that were deleted after the transaction began, because there will be a row version in `tempdb` with a lower sequence number value. + + The net effect of snapshot isolation is that the transaction sees all of the data as it existed at the start of the transaction, without honoring or placing any locks on the underlying tables. This can result in performance improvements in situations where there is contention. + + A snapshot transaction always uses optimistic concurrency control, withholding any locks that would prevent other transactions from updating rows. If a snapshot transaction attempts to commit an update to a row that was changed after the transaction began, the transaction is rolled back, and an error is raised. + +## Working with Snapshot Isolation in ADO.NET + + Snapshot isolation is supported in ADO.NET by the class. If a database has been enabled for snapshot isolation but is not configured for READ_COMMITTED_SNAPSHOT ON, you must initiate a using the **IsolationLevel.Snapshot** enumeration value when calling the method. This code fragment assumes that connection is an open object. + +```vb +Dim sqlTran As SqlTransaction = _ + connection.BeginTransaction(IsolationLevel.Snapshot) +``` + +```csharp SqlTransaction sqlTran = - connection.BeginTransaction(IsolationLevel.Snapshot); -``` - -### Example - - The following example demonstrates how the different isolation levels behave by attempting to access locked data, and it is not intended to be used in production code. - - The code connects to the **AdventureWorks** sample database in SQL Server and creates a table named **TestSnapshot** and inserts one row of data. The code uses the ALTER DATABASE Transact-SQL statement to turn on snapshot isolation for the database, but it does not set the READ_COMMITTED_SNAPSHOT option, leaving the default READ COMMITTED isolation-level behavior in effect. The code then performs the following actions: - -- It begins, but does not complete, sqlTransaction1, which uses the SERIALIZABLE isolation level to start an update transaction. This has the effect of locking the table. - -- It opens a second connection and initiates a second transaction using the SNAPSHOT isolation level to read the data in the **TestSnapshot** table. Because snapshot isolation is enabled, this transaction can read the data that existed before sqlTransaction1 started. - -- It opens a third connection and initiates a transaction using the READ COMMITTED isolation level to attempt to read the data in the table. In this case, the code cannot read the data because it cannot read past the locks placed on the table in the first transaction and times out. The same result would occur if the REPEATABLE READ and SERIALIZABLE isolation levels were used because these isolation levels also cannot read past the locks placed in the first transaction. - -- It opens a fourth connection and initiates a transaction using the READ UNCOMMITTED isolation level, which performs a dirty read of the uncommitted value in sqlTransaction1. This value may never actually exist in the database if the first transaction is not committed. - -- It rolls back the first transaction and cleans up by deleting the **TestSnapshot** table and turning off snapshot isolation for the **AdventureWorks** database. - + connection.BeginTransaction(IsolationLevel.Snapshot); +``` + +### Example + + The following example demonstrates how the different isolation levels behave by attempting to access locked data, and it is not intended to be used in production code. + + The code connects to the `AdventureWorks` sample database in SQL Server and creates a table named `TestSnapshot` and inserts one row of data. The code uses the ALTER DATABASE Transact-SQL statement to turn on snapshot isolation for the database, but it does not set the READ_COMMITTED_SNAPSHOT option, leaving the default READ COMMITTED isolation-level behavior in effect. The code then performs the following actions: + +- It begins, but does not complete, sqlTransaction1, which uses the SERIALIZABLE isolation level to start an update transaction. This has the effect of locking the table. + +- It opens a second connection and initiates a second transaction using the SNAPSHOT isolation level to read the data in the `TestSnapshot` table. Because snapshot isolation is enabled, this transaction can read the data that existed before sqlTransaction1 started. + +- It opens a third connection and initiates a transaction using the READ COMMITTED isolation level to attempt to read the data in the table. In this case, the code cannot read the data because it cannot read past the locks placed on the table in the first transaction and times out. The same result would occur if the REPEATABLE READ and SERIALIZABLE isolation levels were used because these isolation levels also cannot read past the locks placed in the first transaction. + +- It opens a fourth connection and initiates a transaction using the READ UNCOMMITTED isolation level, which performs a dirty read of the uncommitted value in sqlTransaction1. This value may never actually exist in the database if the first transaction is not committed. + +- It rolls back the first transaction and cleans up by deleting the `TestSnapshot` table and turning off snapshot isolation for the `AdventureWorks` database. + > [!NOTE] -> The following examples use the same connection string with connection pooling turned off. If a connection is pooled, resetting its isolation level does not reset the isolation level at the server. As a result, subsequent connections that use the same pooled inner connection start with their isolation levels set to that of the pooled connection. An alternative to turning off connection pooling is to set the isolation level explicitly for each connection. - +> The following examples use the same connection string with connection pooling turned off. If a connection is pooled, resetting its isolation level does not reset the isolation level at the server. As a result, subsequent connections that use the same pooled inner connection start with their isolation levels set to that of the pooled connection. An alternative to turning off connection pooling is to set the isolation level explicitly for each connection. + [!code-csharp[DataWorks SnapshotIsolation.Demo#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.Demo/CS/source.cs#1)] - [!code-vb[DataWorks SnapshotIsolation.Demo#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.Demo/VB/source.vb#1)] - -### Example - - The following example demonstrates the behavior of snapshot isolation when data is being modified. The code performs the following actions: - -- Connects to the **AdventureWorks** sample database and enables SNAPSHOT isolation. - -- Creates a table named **TestSnapshotUpdate** and inserts three rows of sample data. - -- Begins, but does not complete, sqlTransaction1 using SNAPSHOT isolation. Three rows of data are selected in the transaction. - -- Creates a second **SqlConnection** to **AdventureWorks** and creates a second transaction using the READ COMMITTED isolation level that updates a value in one of the rows selected in sqlTransaction1. - -- Commits sqlTransaction2. - -- Returns to sqlTransaction1 and attempts to update the same row that sqlTransaction1 already committed. Error 3960 is raised, and sqlTransaction1 is rolled back automatically. The **SqlException.Number** and **SqlException.Message** are displayed in the Console window. - -- Executes clean-up code to turn off snapshot isolation in **AdventureWorks** and delete the **TestSnapshotUpdate** table. - + [!code-vb[DataWorks SnapshotIsolation.Demo#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.Demo/VB/source.vb#1)] + +### Example + + The following example demonstrates the behavior of snapshot isolation when data is being modified. The code performs the following actions: + +- Connects to the `AdventureWorks` sample database and enables SNAPSHOT isolation. + +- Creates a table named `TestSnapshotUpdate` and inserts three rows of sample data. + +- Begins, but does not complete, sqlTransaction1 using SNAPSHOT isolation. Three rows of data are selected in the transaction. + +- Creates a second `SqlConnection` to `AdventureWorks` and creates a second transaction using the READ COMMITTED isolation level that updates a value in one of the rows selected in sqlTransaction1. + +- Commits sqlTransaction2. + +- Returns to sqlTransaction1 and attempts to update the same row that sqlTransaction1 already committed. Error 3960 is raised, and sqlTransaction1 is rolled back automatically. The **SqlException.Number** and **SqlException.Message** are displayed in the Console window. + +- Executes clean-up code to turn off snapshot isolation in `AdventureWorks` and delete the `TestSnapshotUpdate` table. + [!code-csharp[DataWorks SnapshotIsolation.DemoUpdate#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/CS/source.cs#1)] - [!code-vb[DataWorks SnapshotIsolation.DemoUpdate#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/VB/source.vb#1)] - -### Using Lock Hints with Snapshot Isolation + [!code-vb[DataWorks SnapshotIsolation.DemoUpdate#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SnapshotIsolation.DemoUpdate/VB/source.vb#1)] + +### Using Lock Hints with Snapshot Isolation - In the previous example, the first transaction selects data, and a second transaction updates the data before the first transaction is able to complete, causing an update conflict when the first transaction tries to update the same row. You can reduce the chance of update conflicts in long-running snapshot transactions by supplying lock hints at the beginning of the transaction. The following SELECT statement uses the UPDLOCK hint to lock the selected rows: - -```sql + In the previous example, the first transaction selects data, and a second transaction updates the data before the first transaction is able to complete, causing an update conflict when the first transaction tries to update the same row. You can reduce the chance of update conflicts in long-running snapshot transactions by supplying lock hints at the beginning of the transaction. The following SELECT statement uses the UPDLOCK hint to lock the selected rows: + +```sql SELECT * FROM TestSnapshotUpdate WITH (UPDLOCK) - WHERE PriKey BETWEEN 1 AND 3 -``` - + WHERE PriKey BETWEEN 1 AND 3 +``` + Using the UPDLOCK lock hint blocks any rows attempting to update the rows before the first transaction completes. This guarantees that the selected rows have no conflicts when they are updated later in the transaction. For more information, see [Hints (Transact-SQL)](/sql/t-sql/queries/hints-transact-sql-table). - If your application has many conflicts, snapshot isolation may not be the best choice. Hints should only be used when really needed. Your application should not be designed so that it constantly relies on lock hints for its operation. - + If your application has many conflicts, snapshot isolation may not be the best choice. Hints should only be used when really needed. Your application should not be designed so that it constantly relies on lock hints for its operation. + ## See also - [SQL Server and ADO.NET](index.md) diff --git a/docs/framework/data/adonet/sql/specifying-xml-values-as-parameters.md b/docs/framework/data/adonet/sql/specifying-xml-values-as-parameters.md index d1900322db78c..47dbfc289e2f4 100644 --- a/docs/framework/data/adonet/sql/specifying-xml-values-as-parameters.md +++ b/docs/framework/data/adonet/sql/specifying-xml-values-as-parameters.md @@ -12,12 +12,12 @@ If a query requires a parameter whose value is an XML string, you can supply tha ## Example - The following console application creates a new table in the **AdventureWorks** database. The new table includes a column named **SalesID** and an XML column named **SalesInfo**. + The following console application creates a new table in the `AdventureWorks` database. The new table includes a column named `SalesID` and an XML column named **SalesInfo**. > [!NOTE] -> The **AdventureWorks** sample database is not installed by default when you install SQL Server. You can install it by running SQL Server Setup. +> The `AdventureWorks` sample database is not installed by default when you install SQL Server. You can install it by running SQL Server Setup. - The example prepares a object to insert a row in the new table. A saved file provides the XML data needed for the **SalesInfo** column. + The example prepares a object to insert a row in the new table. A saved file provides the XML data needed for the `SalesInfo` column. To create the file needed for the example to run, create a new text file in the same folder as your project. Name the file MyTestStoreData.xml. Open the file in Notepad and copy and paste the following text: diff --git a/docs/framework/data/adonet/sql/sql-server-express-user-instances.md b/docs/framework/data/adonet/sql/sql-server-express-user-instances.md index 55e45d75c2026..fc507d6707020 100644 --- a/docs/framework/data/adonet/sql/sql-server-express-user-instances.md +++ b/docs/framework/data/adonet/sql/sql-server-express-user-instances.md @@ -19,7 +19,7 @@ SQL Server Express Edition supports the user instance feature, which is only ava ## Enable User Instances - To generate user instances, a parent instance of SQL Server Express must be running. User instances are enabled by default when SQL Server Express is installed, and they can be explicitly enabled or disabled by a system administrator executing the **sp_configure** system stored procedure on the parent instance. + To generate user instances, a parent instance of SQL Server Express must be running. User instances are enabled by default when SQL Server Express is installed, and they can be explicitly enabled or disabled by a system administrator executing the `sp_configure` system stored procedure on the parent instance. ```sql -- Enable user instances. @@ -117,14 +117,14 @@ private static void OpenSqlConnection() ## Lifetime of a User Instance Connection - Unlike versions of SQL Server that run as a service, SQL Server Express instances do not need to be manually started and stopped. Each time a user logs in and connects to a user instance, the user instance is started if it is not already running. User instance databases have the `AutoClose` option set so that the database is automatically shut down after a period of inactivity. The sqlservr.exe process that is started is kept running for a limited time-out period after the last connection to the instance is closed, so it does not need to be restarted if another connection is opened before the time-out has expired. The user instance automatically shuts down if no new connection opens before that time-out period has expired. A system administrator on the parent instance can set the duration of the time-out period for a user instance by using **sp_configure** to change the **user instance timeout** option. The default is 60 minutes. + Unlike versions of SQL Server that run as a service, SQL Server Express instances do not need to be manually started and stopped. Each time a user logs in and connects to a user instance, the user instance is started if it is not already running. User instance databases have the `AutoClose` option set so that the database is automatically shut down after a period of inactivity. The sqlservr.exe process that is started is kept running for a limited time-out period after the last connection to the instance is closed, so it does not need to be restarted if another connection is opened before the time-out has expired. The user instance automatically shuts down if no new connection opens before that time-out period has expired. A system administrator on the parent instance can set the duration of the time-out period for a user instance by using `sp_configure` to change the **user instance timeout** option. The default is 60 minutes. > [!NOTE] > If `Min Pool Size` is used in the connection string with a value greater than zero, the connection pooler will always maintain a few opened connections, and the user instance will not automatically shut down. ## How User Instances Work - The first time a user instance is generated for each user, the **master** and **msdb** system databases are copied from the Template Data folder to a path under the user's local application data repository directory for exclusive use by the user instance. This path is typically `C:\Documents and Settings\\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS`. When a user instance starts up, the **tempdb**, log, and trace files are also written to this directory. A name is generated for the instance, which is guaranteed to be unique for each user. + The first time a user instance is generated for each user, the `master` and `msdb` system databases are copied from the Template Data folder to a path under the user's local application data repository directory for exclusive use by the user instance. This path is typically `C:\Documents and Settings\\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS`. When a user instance starts up, the **tempdb**, log, and trace files are also written to this directory. A name is generated for the instance, which is guaranteed to be unique for each user. By default all members of the Windows Builtin\Users group are granted permissions to connect on the local instance as well as read and execute permissions on the SQL Server binaries. Once the credentials of the calling user hosting the user instance have been verified, that user becomes the `sysadmin` on that instance. Only shared memory is enabled for user instances, which means that only operations on the local machine are possible. diff --git a/docs/framework/data/adonet/sql/transaction-and-bulk-copy-operations.md b/docs/framework/data/adonet/sql/transaction-and-bulk-copy-operations.md index f310a3a4924b0..0d71d7d3f8314 100644 --- a/docs/framework/data/adonet/sql/transaction-and-bulk-copy-operations.md +++ b/docs/framework/data/adonet/sql/transaction-and-bulk-copy-operations.md @@ -2,62 +2,62 @@ description: "Learn more about: Transaction and Bulk Copy Operations" title: "Transaction and Bulk Copy Operations" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: f6f0cbc9-f7bf-4d6e-875f-ad1ba0b4aa62 --- # Transaction and Bulk Copy Operations -Bulk copy operations can be performed as isolated operations or as part of a multiple step transaction. This latter option enables you to perform more than one bulk copy operation within the same transaction, as well as perform other database operations (such as inserts, updates, and deletes) while still being able to commit or roll back the entire transaction. - - By default, a bulk copy operation is performed as an isolated operation. The bulk copy operation occurs in a non-transacted way, with no opportunity for rolling it back. If you need to roll back all or part of the bulk copy when an error occurs, you can use a -managed transaction, perform the bulk copy operation within an existing transaction, or be enlisted in a **System.Transactions**. - -## Performing a Non-transacted Bulk Copy Operation - - The following Console application shows what happens when a non-transacted bulk copy operation encounters an error partway through the operation. - - In the example, the source table and destination table each include an `Identity` column named **ProductID**. The code first prepares the destination table by deleting all rows and then inserting a single row whose **ProductID** is known to exist in the source table. By default, a new value for the `Identity` column is generated in the destination table for each row added. In this example, an option is set when the connection is opened that forces the bulk load process to use the `Identity` values from the source table instead. - - The bulk copy operation is executed with the property set to 10. When the operation encounters the invalid row, an exception is thrown. In this first example, the bulk copy operation is non-transacted. All batches copied up to the point of the error are committed; the batch containing the duplicate key is rolled back, and the bulk copy operation is halted before processing any other batches. - +Bulk copy operations can be performed as isolated operations or as part of a multiple step transaction. This latter option enables you to perform more than one bulk copy operation within the same transaction, as well as perform other database operations (such as inserts, updates, and deletes) while still being able to commit or roll back the entire transaction. + + By default, a bulk copy operation is performed as an isolated operation. The bulk copy operation occurs in a non-transacted way, with no opportunity for rolling it back. If you need to roll back all or part of the bulk copy when an error occurs, you can use a -managed transaction, perform the bulk copy operation within an existing transaction, or be enlisted in a **System.Transactions**. + +## Performing a Non-transacted Bulk Copy Operation + + The following Console application shows what happens when a non-transacted bulk copy operation encounters an error partway through the operation. + + In the example, the source table and destination table each include an `Identity` column named **ProductID**. The code first prepares the destination table by deleting all rows and then inserting a single row whose `ProductID` is known to exist in the source table. By default, a new value for the `Identity` column is generated in the destination table for each row added. In this example, an option is set when the connection is opened that forces the bulk load process to use the `Identity` values from the source table instead. + + The bulk copy operation is executed with the property set to 10. When the operation encounters the invalid row, an exception is thrown. In this first example, the bulk copy operation is non-transacted. All batches copied up to the point of the error are committed; the batch containing the duplicate key is rolled back, and the bulk copy operation is halted before processing any other batches. + > [!NOTE] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](bulk-copy-example-setup.md). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL`INSERT … SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](bulk-copy-example-setup.md). This code is provided to demonstrate the syntax for using `SqlBulkCopy` only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL`INSERT … SELECT` statement to copy the data. + [!code-csharp[DataWorks SqlBulkCopy.DefaultTransaction#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/CS/source.cs#1)] - [!code-vb[DataWorks SqlBulkCopy.DefaultTransaction#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/VB/source.vb#1)] - -## Performing a Dedicated Bulk Copy Operation in a Transaction - - By default, a bulk copy operation is its own transaction. When you want to perform a dedicated bulk copy operation, create a new instance of with a connection string, or use an existing object without an active transaction. In each scenario, the bulk copy operation creates, and then commits or rolls back the transaction. - - You can explicitly specify the option in the class constructor to explicitly cause a bulk copy operation to execute in its own transaction, causing each batch of the bulk copy operation to execute within a separate transaction. - + [!code-vb[DataWorks SqlBulkCopy.DefaultTransaction#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.DefaultTransaction/VB/source.vb#1)] + +## Performing a Dedicated Bulk Copy Operation in a Transaction + + By default, a bulk copy operation is its own transaction. When you want to perform a dedicated bulk copy operation, create a new instance of with a connection string, or use an existing object without an active transaction. In each scenario, the bulk copy operation creates, and then commits or rolls back the transaction. + + You can explicitly specify the option in the class constructor to explicitly cause a bulk copy operation to execute in its own transaction, causing each batch of the bulk copy operation to execute within a separate transaction. + > [!NOTE] -> Since different batches are executed in different transactions, if an error occurs during the bulk copy operation, all the rows in the current batch will be rolled back, but rows from previous batches will remain in the database. - - The following console application is similar to the previous example, with one exception: In this example, the bulk copy operation manages its own transactions. All batches copied up to the point of the error are committed; the batch containing the duplicate key is rolled back, and the bulk copy operation is halted before processing any other batches. - +> Since different batches are executed in different transactions, if an error occurs during the bulk copy operation, all the rows in the current batch will be rolled back, but rows from previous batches will remain in the database. + + The following console application is similar to the previous example, with one exception: In this example, the bulk copy operation manages its own transactions. All batches copied up to the point of the error are committed; the batch containing the duplicate key is rolled back, and the bulk copy operation is halted before processing any other batches. + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](bulk-copy-example-setup.md). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL`INSERT … SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](bulk-copy-example-setup.md). This code is provided to demonstrate the syntax for using `SqlBulkCopy` only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL`INSERT … SELECT` statement to copy the data. + [!code-csharp[DataWorks SqlBulkCopy.InternalTransaction#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/CS/source.cs#1)] - [!code-vb[DataWorks SqlBulkCopy.InternalTransaction#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/VB/source.vb#1)] - -## Using Existing Transactions - - You can specify an existing object as a parameter in a constructor. In this situation, the bulk copy operation is performed in an existing transaction, and no change is made to the transaction state (that is, it is neither committed nor aborted). This allows an application to include the bulk copy operation in a transaction with other database operations. However, if you do not specify a object and pass a null reference, and the connection has an active transaction, an exception is thrown. - - If you need to roll back the entire bulk copy operation because an error occurs, or if the bulk copy should execute as part of a larger process that can be rolled back, you can provide a object to the constructor. - - The following console application is similar to the first (non-transacted) example, with one exception: in this example, the bulk copy operation is included in a larger, external transaction. When the primary key violation error occurs, the entire transaction is rolled back and no rows are added to the destination table. - + [!code-vb[DataWorks SqlBulkCopy.InternalTransaction#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.InternalTransaction/VB/source.vb#1)] + +## Using Existing Transactions + + You can specify an existing object as a parameter in a constructor. In this situation, the bulk copy operation is performed in an existing transaction, and no change is made to the transaction state (that is, it is neither committed nor aborted). This allows an application to include the bulk copy operation in a transaction with other database operations. However, if you do not specify a object and pass a null reference, and the connection has an active transaction, an exception is thrown. + + If you need to roll back the entire bulk copy operation because an error occurs, or if the bulk copy should execute as part of a larger process that can be rolled back, you can provide a object to the constructor. + + The following console application is similar to the first (non-transacted) example, with one exception: in this example, the bulk copy operation is included in a larger, external transaction. When the primary key violation error occurs, the entire transaction is rolled back and no rows are added to the destination table. + > [!IMPORTANT] -> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](bulk-copy-example-setup.md). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL`INSERT … SELECT` statement to copy the data. - +> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](bulk-copy-example-setup.md). This code is provided to demonstrate the syntax for using `SqlBulkCopy` only. If the source and destination tables are located in the same SQL Server instance, it is easier and faster to use a Transact-SQL`INSERT … SELECT` statement to copy the data. + [!code-csharp[DataWorks SqlBulkCopy.SqlTransaction#1](../../../../../samples/snippets/csharp/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/CS/source.cs#1)] - [!code-vb[DataWorks SqlBulkCopy.SqlTransaction#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/VB/source.vb#1)] - + [!code-vb[DataWorks SqlBulkCopy.SqlTransaction#1](../../../../../samples/snippets/visualbasic/VS_Snippets_ADO.NET/DataWorks SqlBulkCopy.SqlTransaction/VB/source.vb#1)] + ## See also - [Bulk Copy Operations in SQL Server](bulk-copy-operations-in-sql-server.md) diff --git a/docs/framework/data/adonet/sql/xml-data-in-sql-server.md b/docs/framework/data/adonet/sql/xml-data-in-sql-server.md index 9bc16e6a750f9..9228dcd8cb3b1 100644 --- a/docs/framework/data/adonet/sql/xml-data-in-sql-server.md +++ b/docs/framework/data/adonet/sql/xml-data-in-sql-server.md @@ -6,16 +6,16 @@ ms.assetid: 9849d319-f518-4e3d-a7cd-f8fdcaaa1d4d --- # XML Data in SQL Server -SQL Server exposes the functionality of SQLXML inside the .NET Framework. Developers can write applications that access XML data from an instance of SQL Server, bring the data into the .NET Framework environment, process the data, and send the updates back to SQL Server. XML data can be used in several ways in SQL Server, including data storage, and as parameter values for retrieving data. The **SqlXml** class in the .NET Framework provides the client-side support for working with data stored in an XML column within SQL Server. For more information, see [SQLXML Managed Classes](/sql/relational-databases/sqlxml-annotated-xsd-schemas-xpath-queries/net-framework-classes/sqlxml-4-0-net-framework-support-managed-classes). - -## In This Section +SQL Server exposes the functionality of SQLXML inside the .NET Framework. Developers can write applications that access XML data from an instance of SQL Server, bring the data into the .NET Framework environment, process the data, and send the updates back to SQL Server. XML data can be used in several ways in SQL Server, including data storage, and as parameter values for retrieving data. The `SqlXml` class in the .NET Framework provides the client-side support for working with data stored in an XML column within SQL Server. For more information, see [SQLXML Managed Classes](/sql/relational-databases/sqlxml-annotated-xsd-schemas-xpath-queries/net-framework-classes/sqlxml-4-0-net-framework-support-managed-classes). + +## In This Section + + [SQL XML Column Values](sql-xml-column-values.md) + Demonstrates how to retrieve and work with XML data retrieved from SQL Server. + + [Specifying XML Values as Parameters](specifying-xml-values-as-parameters.md) + Demonstrates how to pass XML data as a parameter to a command. - [SQL XML Column Values](sql-xml-column-values.md) - Demonstrates how to retrieve and work with XML data retrieved from SQL Server. - - [Specifying XML Values as Parameters](specifying-xml-values-as-parameters.md) - Demonstrates how to pass XML data as a parameter to a command. - ## See also - [SQL Server and ADO.NET](index.md) diff --git a/docs/framework/data/adonet/system-requirements-for-the-dotnet-data-provider-for-oracle.md b/docs/framework/data/adonet/system-requirements-for-the-dotnet-data-provider-for-oracle.md index 076b7513036df..eefbff1a64703 100644 --- a/docs/framework/data/adonet/system-requirements-for-the-dotnet-data-provider-for-oracle.md +++ b/docs/framework/data/adonet/system-requirements-for-the-dotnet-data-provider-for-oracle.md @@ -6,36 +6,36 @@ ms.assetid: 054f76b9-1737-43f0-8160-84a00a387217 --- # System Requirements for the .NET Framework Data Provider for Oracle -The .NET Framework Data Provider for Oracle requires Microsoft Data Access Components (MDAC) version 2.6 or later. MDAC 2.8 SP1 is recommended. - - You must also have Oracle 8i Release 3 (8.1.7) Client or later installed. - - Oracle Client software prior to version Oracle 9i cannot access UTF16 databases because UTF16 is a new feature in Oracle 9i. To use this feature, you must upgrade your client software to Oracle 9i or later. - -## Working with the Data Provider for Oracle and Unicode Data - -The following is a list of Unicode-related issues that you should consider when working with the .NET Framework Data Provider for Oracle and Oracle client libraries. For more information, see your Oracle documentation. - -### Setting the Unicode Value in a Connection String Attribute - -When working with Oracle, you can use the connection string attribute - +The .NET Framework Data Provider for Oracle requires Microsoft Data Access Components (MDAC) version 2.6 or later. MDAC 2.8 SP1 is recommended. + + You must also have Oracle 8i Release 3 (8.1.7) Client or later installed. + + Oracle Client software prior to version Oracle 9i cannot access UTF16 databases because UTF16 is a new feature in Oracle 9i. To use this feature, you must upgrade your client software to Oracle 9i or later. + +## Working with the Data Provider for Oracle and Unicode Data + +The following is a list of Unicode-related issues that you should consider when working with the .NET Framework Data Provider for Oracle and Oracle client libraries. For more information, see your Oracle documentation. + +### Setting the Unicode Value in a Connection String Attribute + +When working with Oracle, you can use the connection string attribute + `Unicode=True` - -to initialize the Oracle client libraries in UTF-16 mode. This causes the Oracle client libraries to accept UTF-16 (which is very similar to UCS-2) instead of multi-byte strings. This allows the Data Provider for Oracle to always work with any Oracle code page without additional translation work. This configuration only works if you are using Oracle 9i clients to communicate with an Oracle 9i database with the alternate character set of AL16UTF16. When an Oracle 9i client communicates with an Oracle 9i server, additional resources are required to convert the Unicode **CommandText** values to the appropriate multi-byte character set that the Oracle9i server uses. This can be avoided when you know that you have the safe configuration by adding `Unicode=True` to your connection string. - -### Mixing Versions of Oracle Client and Oracle Server -Oracle 8i clients cannot access **NCHAR**, **NVARCHAR2**, or **NCLOB** data in Oracle 9i databases when the server's national character set is specified as AL16UTF16 (the default setting for Oracle 9i). Because support for the UTF-16 character set was not introduced until Oracle 9i, Oracle 8i clients cannot read it. - -### Working with UTF-8 Data +to initialize the Oracle client libraries in UTF-16 mode. This causes the Oracle client libraries to accept UTF-16 (which is very similar to UCS-2) instead of multi-byte strings. This allows the Data Provider for Oracle to always work with any Oracle code page without additional translation work. This configuration only works if you are using Oracle 9i clients to communicate with an Oracle 9i database with the alternate character set of AL16UTF16. When an Oracle 9i client communicates with an Oracle 9i server, additional resources are required to convert the Unicode `CommandText` values to the appropriate multi-byte character set that the Oracle9i server uses. This can be avoided when you know that you have the safe configuration by adding `Unicode=True` to your connection string. + +### Mixing Versions of Oracle Client and Oracle Server + +Oracle 8i clients cannot access **NCHAR**, **NVARCHAR2**, or `NCLOB` data in Oracle 9i databases when the server's national character set is specified as AL16UTF16 (the default setting for Oracle 9i). Because support for the UTF-16 character set was not introduced until Oracle 9i, Oracle 8i clients cannot read it. + +### Working with UTF-8 Data + +To set the alternate character set, set the Registry Key HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\HOMEID\NLS_LANG to UTF8. See the Oracle Installation notes on your platform for more information. The default setting is the primary character set of the language from which you are installing the Oracle Client software. Not setting the language to match the national language character set of the database to which you are connecting will cause parameter and column bindings to send or receive data in your primary database character set, not the national character set. + +### OracleLob Can Only Update Full Characters. -To set the alternate character set, set the Registry Key HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\HOMEID\NLS_LANG to UTF8. See the Oracle Installation notes on your platform for more information. The default setting is the primary character set of the language from which you are installing the Oracle Client software. Not setting the language to match the national language character set of the database to which you are connecting will cause parameter and column bindings to send or receive data in your primary database character set, not the national character set. - -### OracleLob Can Only Update Full Characters. +For usability reasons, the object inherits from the .NET Framework Stream class, and provides `ReadByte` and `WriteByte` methods. It also implements methods, such as `CopyTo` and **Erase**, that work on sections of Oracle `LOB` objects. In contrast, Oracle client software provides a number of APIs to work with character **LOB**s (**CLOB** and **NCLOB**). However, these APIs work on full characters only. Because of this difference, the Data Provider for Oracle implements support for `Read` and `ReadByte` to work with UTF-16 data in a byte-wise manner. However, the other methods of the `OracleLob` object only allow full-character operations. -For usability reasons, the object inherits from the .NET Framework Stream class, and provides **ReadByte** and **WriteByte** methods. It also implements methods, such as **CopyTo** and **Erase**, that work on sections of Oracle **LOB** objects. In contrast, Oracle client software provides a number of APIs to work with character **LOB**s (**CLOB** and **NCLOB**). However, these APIs work on full characters only. Because of this difference, the Data Provider for Oracle implements support for **Read** and **ReadByte** to work with UTF-16 data in a byte-wise manner. However, the other methods of the **OracleLob** object only allow full-character operations. - ## See also - [Oracle and ADO.NET](oracle-and-adonet.md) diff --git a/docs/framework/data/adonet/updating-data-in-a-data-source.md b/docs/framework/data/adonet/updating-data-in-a-data-source.md index bc28d374fc1d9..7a710bfb78125 100644 --- a/docs/framework/data/adonet/updating-data-in-a-data-source.md +++ b/docs/framework/data/adonet/updating-data-in-a-data-source.md @@ -2,92 +2,92 @@ description: "Learn more about: Updating Data in a Data Source" title: "Updating Data in a Data Source" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 55c545e5-dcd5-4323-a5b9-3825c2157462 --- # Updating Data in a Data Source -SQL statements that modify data (such as INSERT, UPDATE, or DELETE) do not return rows. Similarly, many stored procedures perform an action but do not return rows. To execute commands that do not return rows, create a **Command** object with the appropriate SQL command and a **Connection**, including any required **Parameters**. Execute the command with the **ExecuteNonQuery** method of the **Command** object. - - The **ExecuteNonQuery** method returns an integer that represents the number of rows affected by the statement or stored procedure that was executed. If multiple statements are executed, the value returned is the sum of the records affected by all of the statements executed. - -## Example - - The following code example executes an INSERT statement to insert a record into a database using **ExecuteNonQuery**. - -```vb -' Assumes connection is a valid SqlConnection. -connection.Open() - -Dim queryString As String = "INSERT INTO Customers " & _ - "(CustomerID, CompanyName) Values('NWIND', 'Northwind Traders')" - -Dim command As SqlCommand = New SqlCommand(queryString, connection) -Dim recordsAffected As Int32 = command.ExecuteNonQuery() -``` - -```csharp -// Assumes connection is a valid SqlConnection. -connection.Open(); - -string queryString = "INSERT INTO Customers " + - "(CustomerID, CompanyName) Values('NWIND', 'Northwind Traders')"; - -SqlCommand command = new SqlCommand(queryString, connection); -Int32 recordsAffected = command.ExecuteNonQuery(); -``` - - The following code example executes the stored procedure created by the sample code in [Performing Catalog Operations](performing-catalog-operations.md). No rows are returned by the stored procedure, so the **ExecuteNonQuery** method is used, but the stored procedure does receive an input parameter and returns an output parameter and a return value. - - For the object, the **ReturnValue** parameter must be added to the **Parameters** collection first. - -```vb -' Assumes connection is a valid SqlConnection. -Dim command As SqlCommand = _ - New SqlCommand("InsertCategory" , connection) -command.CommandType = CommandType.StoredProcedure - -Dim parameter As SqlParameter = _ - command.Parameters.Add("@RowCount", SqlDbType.Int) -parameter.Direction = ParameterDirection.ReturnValue - -parameter = command.Parameters.Add( _ - "@CategoryName", SqlDbType.NChar, 15) - -parameter = command.Parameters.Add("@Identity", SqlDbType.Int) -parameter.Direction = ParameterDirection.Output - -command.Parameters("@CategoryName").Value = "New Category" -command.ExecuteNonQuery() - -Dim categoryID As Int32 = CInt(command.Parameters("@Identity").Value) +SQL statements that modify data (such as INSERT, UPDATE, or DELETE) do not return rows. Similarly, many stored procedures perform an action but do not return rows. To execute commands that do not return rows, create a `Command` object with the appropriate SQL command and a **Connection**, including any required **Parameters**. Execute the command with the `ExecuteNonQuery` method of the `Command` object. + + The `ExecuteNonQuery` method returns an integer that represents the number of rows affected by the statement or stored procedure that was executed. If multiple statements are executed, the value returned is the sum of the records affected by all of the statements executed. + +## Example + + The following code example executes an INSERT statement to insert a record into a database using **ExecuteNonQuery**. + +```vb +' Assumes connection is a valid SqlConnection. +connection.Open() + +Dim queryString As String = "INSERT INTO Customers " & _ + "(CustomerID, CompanyName) Values('NWIND', 'Northwind Traders')" + +Dim command As SqlCommand = New SqlCommand(queryString, connection) +Dim recordsAffected As Int32 = command.ExecuteNonQuery() +``` + +```csharp +// Assumes connection is a valid SqlConnection. +connection.Open(); + +string queryString = "INSERT INTO Customers " + + "(CustomerID, CompanyName) Values('NWIND', 'Northwind Traders')"; + +SqlCommand command = new SqlCommand(queryString, connection); +Int32 recordsAffected = command.ExecuteNonQuery(); +``` + + The following code example executes the stored procedure created by the sample code in [Performing Catalog Operations](performing-catalog-operations.md). No rows are returned by the stored procedure, so the `ExecuteNonQuery` method is used, but the stored procedure does receive an input parameter and returns an output parameter and a return value. + + For the object, the `ReturnValue` parameter must be added to the `Parameters` collection first. + +```vb +' Assumes connection is a valid SqlConnection. +Dim command As SqlCommand = _ + New SqlCommand("InsertCategory" , connection) +command.CommandType = CommandType.StoredProcedure + +Dim parameter As SqlParameter = _ + command.Parameters.Add("@RowCount", SqlDbType.Int) +parameter.Direction = ParameterDirection.ReturnValue + +parameter = command.Parameters.Add( _ + "@CategoryName", SqlDbType.NChar, 15) + +parameter = command.Parameters.Add("@Identity", SqlDbType.Int) +parameter.Direction = ParameterDirection.Output + +command.Parameters("@CategoryName").Value = "New Category" +command.ExecuteNonQuery() + +Dim categoryID As Int32 = CInt(command.Parameters("@Identity").Value) Dim rowCount As Int32 = CInt(command.Parameters("@RowCount").Value) -``` - -```csharp -// Assumes connection is a valid SqlConnection. -SqlCommand command = new SqlCommand("InsertCategory" , connection); -command.CommandType = CommandType.StoredProcedure; - -SqlParameter parameter = command.Parameters.Add( - "@RowCount", SqlDbType.Int); -parameter.Direction = ParameterDirection.ReturnValue; - -parameter = command.Parameters.Add( - "@CategoryName", SqlDbType.NChar, 15); - -parameter = command.Parameters.Add("@Identity", SqlDbType.Int); -parameter.Direction = ParameterDirection.Output; - -command.Parameters["@CategoryName"].Value = "New Category"; -command.ExecuteNonQuery(); - -Int32 categoryID = (Int32) command.Parameters["@Identity"].Value; -Int32 rowCount = (Int32) command.Parameters["@RowCount"].Value; -``` - +``` + +```csharp +// Assumes connection is a valid SqlConnection. +SqlCommand command = new SqlCommand("InsertCategory" , connection); +command.CommandType = CommandType.StoredProcedure; + +SqlParameter parameter = command.Parameters.Add( + "@RowCount", SqlDbType.Int); +parameter.Direction = ParameterDirection.ReturnValue; + +parameter = command.Parameters.Add( + "@CategoryName", SqlDbType.NChar, 15); + +parameter = command.Parameters.Add("@Identity", SqlDbType.Int); +parameter.Direction = ParameterDirection.Output; + +command.Parameters["@CategoryName"].Value = "New Category"; +command.ExecuteNonQuery(); + +Int32 categoryID = (Int32) command.Parameters["@Identity"].Value; +Int32 rowCount = (Int32) command.Parameters["@RowCount"].Value; +``` + ## See also - [Using Commands to Modify Data](using-commands-to-modify-data.md) diff --git a/docs/framework/data/adonet/using-commands-to-modify-data.md b/docs/framework/data/adonet/using-commands-to-modify-data.md index 0ea0a9e6ea1c9..d2446c4ffaede 100644 --- a/docs/framework/data/adonet/using-commands-to-modify-data.md +++ b/docs/framework/data/adonet/using-commands-to-modify-data.md @@ -6,20 +6,20 @@ ms.assetid: f4160389-b9ff-4b74-b655-437c76dcd586 --- # Using Commands to Modify Data -Using a .NET Framework data provider, you can execute stored procedures or data definition language statements (for example, CREATE TABLE and ALTER COLUMN) to perform schema manipulation on a database or catalog. These commands do not return rows as a query would, so the **Command** object provides an **ExecuteNonQuery** to process them. - - In addition to using **ExecuteNonQuery** to modify schema, you can also use this method to process SQL statements that modify data but that do not return rows, such as INSERT, UPDATE, and DELETE. - - Although rows are not returned by the **ExecuteNonQuery** method, input and output parameters and return values can be passed and returned via the **Parameters** collection of the **Command** object. - -## In This Section - - [Updating Data in a Data Source](updating-data-in-a-data-source.md) - Describes how to execute commands or stored procedures that modify data in a database. - - [Performing Catalog Operations](performing-catalog-operations.md) - Describes how to execute commands that modify database schema. - +Using a .NET Framework data provider, you can execute stored procedures or data definition language statements (for example, CREATE TABLE and ALTER COLUMN) to perform schema manipulation on a database or catalog. These commands do not return rows as a query would, so the `Command` object provides an `ExecuteNonQuery` to process them. + + In addition to using `ExecuteNonQuery` to modify schema, you can also use this method to process SQL statements that modify data but that do not return rows, such as INSERT, UPDATE, and DELETE. + + Although rows are not returned by the `ExecuteNonQuery` method, input and output parameters and return values can be passed and returned via the `Parameters` collection of the `Command` object. + +## In This Section + + [Updating Data in a Data Source](updating-data-in-a-data-source.md) + Describes how to execute commands or stored procedures that modify data in a database. + + [Performing Catalog Operations](performing-catalog-operations.md) + Describes how to execute commands that modify database schema. + ## See also - [Retrieving and Modifying Data in ADO.NET](retrieving-and-modifying-data.md) diff --git a/docs/framework/data/transactions/diagnostic-traces.md b/docs/framework/data/transactions/diagnostic-traces.md index baf4746a33de8..ff43f39588317 100644 --- a/docs/framework/data/transactions/diagnostic-traces.md +++ b/docs/framework/data/transactions/diagnostic-traces.md @@ -6,134 +6,134 @@ ms.assetid: 28e77a63-d20d-4b6a-9caf-ddad86550427 --- # Diagnostic Traces -Traces are the publishing of specific messages that are generated during application execution. When using tracing, you must have a mechanism for collecting and recording the messages that are sent. Trace messages are received by listeners. The purpose of a listener is to collect, store, and route tracing messages. Listeners direct the tracing output to an appropriate target, such as a log, window, or text file. - - One such listener, the , is automatically created and initialized when tracing is enabled. If you want trace output to be directed to any additional sources, you must create and initialize additional trace listeners. The listeners you create should reflect your individual needs. For example, you might want a text record of all trace output. In this case, you would create a listener that wrote all output to a new text file when enabled. On the other hand, you might only want to view output during application execution. In that case, you might create a listener that directed all output to a console window. The can direct trace output to an event log, and the can write trace output to a stream. - -## Enabling Tracing - - To enable traces during transaction processing, you should edit your application’s configuration file. The following is an example. - -```xml - - - - - +Traces are the publishing of specific messages that are generated during application execution. When using tracing, you must have a mechanism for collecting and recording the messages that are sent. Trace messages are received by listeners. The purpose of a listener is to collect, store, and route tracing messages. Listeners direct the tracing output to an appropriate target, such as a log, window, or text file. + + One such listener, the , is automatically created and initialized when tracing is enabled. If you want trace output to be directed to any additional sources, you must create and initialize additional trace listeners. The listeners you create should reflect your individual needs. For example, you might want a text record of all trace output. In this case, you would create a listener that wrote all output to a new text file when enabled. On the other hand, you might only want to view output during application execution. In that case, you might create a listener that directed all output to a console window. The can direct trace output to an event log, and the can write trace output to a stream. + +## Enabling Tracing + + To enable traces during transaction processing, you should edit your application’s configuration file. The following is an example. + +```xml + + + + + - - - - - -``` - - traces are written to the source named "System.Transactions". You can use `add` to specify the name and type of the trace listener you want to use. In our example configuration, we named the Listener "tx" and added the standard .NET Framework trace listener () as the type we want to use. Use `initializeData` to set the name of the log file for that listener. In addition, you can substitute a fully qualified path for a simple file name. - - Each trace message type is assigned a level to indicate its degree of importance. If the app-domain’s trace level is equal or lower than the level of an event type, then that message is generated. The tracing level is controlled by the `switchValue` setting in the configuration file. The levels that are associated with diagnostic trace messages are defined in the following table. - -|Trace Level|Description| -|-----------------|-----------------| -|Critical|Serious failures, such as the following, have occurred:

- An error that can cause an immediate loss in user functionality.
- An event that requires an administrator to take action to avoid loss of functionality.
- Code hangs.
- This tracing level can also provide sufficient context for interpreting other critical traces. This can help to identify the sequence of operations leading to a serious failure.| -|Error|An error (for example, invalid configuration or network behavior) has occurred that can result in a loss of user functionality.| -|Warning|A condition exists that can subsequently result in an error or critical failure (for example, allocation failing or approaching a limit). Normal processing of errors from user code (for example, transaction aborted, timeouts, authentication failed) can also generate a warning.| -|Information|Messages helpful for monitoring and diagnosing system status, measuring performance, or profiling are generated. These can include transaction and enlistment lifetime events, such as a transaction being created or committed, the crossing of a significant boundary, or the allocation of significant resources. A developer can then utilize such information for capacity planning and performance management.| - -## Trace Codes - - The following table lists the trace codes that are generated by the infrastructure. Included in the table are the trace code identifier, the enumeration level for the trace, and the extra data contained in the **TraceRecord** for the trace. In addition, the corresponding trace level of the trace is also stored in the **TraceRecord**. - -|TraceCode|EventType|Extra data in TraceRecord| -|---------------|---------------|-------------------------------| -|TransactionCreated|Info|TransactionTraceId| -|TransactionPromoted|Info|Local TransactionTraceId, Distributed TransactionTraceId| -|EnlistmentCreated|Info|TransactionTraceId, EnlistmentTraceId, EnlistmentType (durable/volatile), EnlistmentOptions| -|EnlistmentCallbackNegative|Warning|TransactionTraceId, EnlistmentTraceId,

Callback (forcerollback/aborted/indoubt)| -|TransactionRollbackCalled|Warning|TransactionTraceId| -|TransactionAborted|Warning|TransactionTraceId| -|TransactionInDoubt|Warning|TransactionTraceId| -|TransactionScopeCreated|Info|TransactionScopeResult, which can be the following:

- New transaction.
- Transaction passed.
- Dependent transaction passed.
- Using current transaction.
- No transaction.

new current TransactionTraceId| -|TransactionScopeDisposed|Info|TransactionTraceId of the scope’s "expected" current transaction.| -|TransactionScopeIncomplete|Warning|TransactionTraceId of the scope’s "expected" current transaction.| -|TransactionScopeNestedIncorrectly|Warning|TransactionTraceId of the scope’s "expected" current transaction.| -|TransactionScopeCurrentTransactionChanged|Warning|Old current TransactionTraceId, other TransactionTraceId| -|TransactionScopeTimeout|Warning|TransactionTraceId of the scope’s "expected" current transaction.| -|DependentCloneCreated|Info|TransactionTraceId, type of dependent transaction created (RollbackIfNotComplete/BlockCommitUntilComplete)| -|DependentCloneComplete|Info|TransactionTraceId| -|RecoveryComplete|Info|Resource Manager GUID (from base)| -|Reenlist|Info|Resource Manager GUID (from base)| -|TransactionSerialized|Info|TransactionTraceId.| -|TransactionException|Error|Exception message| -|InvalidOperationException|Error|Exception message| -|InternalError|Critical|Exception message| -|TransferEvent||When a transaction is deserialized, or promoted from a transaction to a distributed one, the current ActivityID from the ExecutionContext and the distributed transaction ID are written.

When the DTC calls back into managed code, the distributed transaction ID is set as the ActivityID in the ExecutionContext for the duration of the callback.| -|ConfiguredDefaultTimeoutAdjusted|Warning|No extra data| -|TransactionTimeout|Warning|The TransactionTraceId of the transaction being timed out.| - - The XML schema for each of the preceding extra data items has the following format. - -### TransactionTraceIdentifier - - `` - - `` - - `string representation of transaction id` - - `` - - `< CloneIdentifier >` - - `the clone id number` - - `` - - `` - -### EnlistmentTraceIdentifier - - `` - - `` - - `string form of guid` - - `` - - `` - - `` - - `string representation of transaction id` - - `` - - `` - - `the clone id number` - - `` - - `` - - `` - - `the enlistment id number` - - `` - - `` - -### Resource Manager Identifier - - `` - - `string form of guid` - - `` - -## Security Issues For Tracing + initializeData= "tx.log" /> +
+ +
+
+
+``` + + traces are written to the source named "System.Transactions". You can use `add` to specify the name and type of the trace listener you want to use. In our example configuration, we named the Listener "tx" and added the standard .NET Framework trace listener () as the type we want to use. Use `initializeData` to set the name of the log file for that listener. In addition, you can substitute a fully qualified path for a simple file name. + + Each trace message type is assigned a level to indicate its degree of importance. If the app-domain’s trace level is equal or lower than the level of an event type, then that message is generated. The tracing level is controlled by the `switchValue` setting in the configuration file. The levels that are associated with diagnostic trace messages are defined in the following table. + +|Trace Level|Description| +|-----------------|-----------------| +|Critical|Serious failures, such as the following, have occurred:

- An error that can cause an immediate loss in user functionality.
- An event that requires an administrator to take action to avoid loss of functionality.
- Code hangs.
- This tracing level can also provide sufficient context for interpreting other critical traces. This can help to identify the sequence of operations leading to a serious failure.| +|Error|An error (for example, invalid configuration or network behavior) has occurred that can result in a loss of user functionality.| +|Warning|A condition exists that can subsequently result in an error or critical failure (for example, allocation failing or approaching a limit). Normal processing of errors from user code (for example, transaction aborted, timeouts, authentication failed) can also generate a warning.| +|Information|Messages helpful for monitoring and diagnosing system status, measuring performance, or profiling are generated. These can include transaction and enlistment lifetime events, such as a transaction being created or committed, the crossing of a significant boundary, or the allocation of significant resources. A developer can then utilize such information for capacity planning and performance management.| + +## Trace Codes + + The following table lists the trace codes that are generated by the infrastructure. Included in the table are the trace code identifier, the enumeration level for the trace, and the extra data contained in the `TraceRecord` for the trace. In addition, the corresponding trace level of the trace is also stored in the **TraceRecord**. + +|TraceCode|EventType|Extra data in TraceRecord| +|---------------|---------------|-------------------------------| +|TransactionCreated|Info|TransactionTraceId| +|TransactionPromoted|Info|Local TransactionTraceId, Distributed TransactionTraceId| +|EnlistmentCreated|Info|TransactionTraceId, EnlistmentTraceId, EnlistmentType (durable/volatile), EnlistmentOptions| +|EnlistmentCallbackNegative|Warning|TransactionTraceId, EnlistmentTraceId,

Callback (forcerollback/aborted/indoubt)| +|TransactionRollbackCalled|Warning|TransactionTraceId| +|TransactionAborted|Warning|TransactionTraceId| +|TransactionInDoubt|Warning|TransactionTraceId| +|TransactionScopeCreated|Info|TransactionScopeResult, which can be the following:

- New transaction.
- Transaction passed.
- Dependent transaction passed.
- Using current transaction.
- No transaction.

new current TransactionTraceId| +|TransactionScopeDisposed|Info|TransactionTraceId of the scope’s "expected" current transaction.| +|TransactionScopeIncomplete|Warning|TransactionTraceId of the scope’s "expected" current transaction.| +|TransactionScopeNestedIncorrectly|Warning|TransactionTraceId of the scope’s "expected" current transaction.| +|TransactionScopeCurrentTransactionChanged|Warning|Old current TransactionTraceId, other TransactionTraceId| +|TransactionScopeTimeout|Warning|TransactionTraceId of the scope’s "expected" current transaction.| +|DependentCloneCreated|Info|TransactionTraceId, type of dependent transaction created (RollbackIfNotComplete/BlockCommitUntilComplete)| +|DependentCloneComplete|Info|TransactionTraceId| +|RecoveryComplete|Info|Resource Manager GUID (from base)| +|Reenlist|Info|Resource Manager GUID (from base)| +|TransactionSerialized|Info|TransactionTraceId.| +|TransactionException|Error|Exception message| +|InvalidOperationException|Error|Exception message| +|InternalError|Critical|Exception message| +|TransferEvent||When a transaction is deserialized, or promoted from a transaction to a distributed one, the current ActivityID from the ExecutionContext and the distributed transaction ID are written.

When the DTC calls back into managed code, the distributed transaction ID is set as the ActivityID in the ExecutionContext for the duration of the callback.| +|ConfiguredDefaultTimeoutAdjusted|Warning|No extra data| +|TransactionTimeout|Warning|The TransactionTraceId of the transaction being timed out.| + + The XML schema for each of the preceding extra data items has the following format. + +### TransactionTraceIdentifier + + `` + + `` + + `string representation of transaction id` + + `` + + `< CloneIdentifier >` + + `the clone id number` + + `` + + `` + +### EnlistmentTraceIdentifier + + `` + + `` + + `string form of guid` + + `` + + `` + + `` + + `string representation of transaction id` + + `` + + `` + + `the clone id number` + + `` + + `` + + `` + + `the enlistment id number` + + `` + + `` + +### Resource Manager Identifier + + `` + + `string form of guid` + + `` + +## Security Issues For Tracing When you as an administrator turn on tracing, sensitive information might be written to a trace log that is publicly viewable by default. To mitigate any possible security threat, you should consider storing the trace log in a secure location controlled by share and file system access permissions. diff --git a/docs/framework/data/transactions/enlisting-resources-as-participants-in-a-transaction.md b/docs/framework/data/transactions/enlisting-resources-as-participants-in-a-transaction.md index 5ec1d07bd9a44..992893facb325 100644 --- a/docs/framework/data/transactions/enlisting-resources-as-participants-in-a-transaction.md +++ b/docs/framework/data/transactions/enlisting-resources-as-participants-in-a-transaction.md @@ -16,7 +16,7 @@ This topic covers how a resource (or multiple resources) can be enlisted in a tr ## Enlisting Resources in a Transaction -In order for a resource to participate in a transaction, it must enlist in the transaction. The class defines a set of methods whose names begin with **Enlist** that provide this functionality. The different **Enlist** methods correspond to the different types of enlistment that a resource manager may have. Specifically, you use the methods for volatile resources, and the method for durable resources. The durability (or conversely the volatility) of a resource manager refers to whether the resource manager supports failure recovery. If a resource manager supports failure recovery, it persists data to durable storage during Phase1 (prepare) such that if the resource manager goes down, it can re-enlist in the transaction upon recovery and perform the proper actions based on the notifications received from the TM. In general, volatile resource managers manage volatile resources such as an in-memory data structure (for example, an in-memory transacted-hashtable), and durable resource managers manage resources that have a more persistent backing store (for example, a database whose backing store is disk). +In order for a resource to participate in a transaction, it must enlist in the transaction. The class defines a set of methods whose names begin with `Enlist` that provide this functionality. The different `Enlist` methods correspond to the different types of enlistment that a resource manager may have. Specifically, you use the methods for volatile resources, and the method for durable resources. The durability (or conversely the volatility) of a resource manager refers to whether the resource manager supports failure recovery. If a resource manager supports failure recovery, it persists data to durable storage during Phase1 (prepare) such that if the resource manager goes down, it can re-enlist in the transaction upon recovery and perform the proper actions based on the notifications received from the TM. In general, volatile resource managers manage volatile resources such as an in-memory data structure (for example, an in-memory transacted-hashtable), and durable resource managers manage resources that have a more persistent backing store (for example, a database whose backing store is disk). For simplicity, after deciding whether to use the or method based on your resource's durability support, you should enlist your resource to participate in Two Phase Commit (2PC) by implementing the interface for your resource manager. For more information on 2PC, see [Committing a Transaction in Single-Phase and Multi-Phase](committing-a-transaction-in-single-phase-and-multi-phase.md). diff --git a/docs/framework/data/transactions/implementing-a-resource-manager.md b/docs/framework/data/transactions/implementing-a-resource-manager.md index 983fd8fc08b21..5dafb2ba91e2a 100644 --- a/docs/framework/data/transactions/implementing-a-resource-manager.md +++ b/docs/framework/data/transactions/implementing-a-resource-manager.md @@ -6,48 +6,48 @@ ms.assetid: d5c153f6-4419-49e3-a5f1-a50ae4c81bf3 --- # Implementing a Resource Manager -Each resource used in a transaction is managed by a resource manager, whose actions are coordinated by a transaction manager. Resource managers work in cooperation with the transaction manager to provide the application with a guarantee of atomicity and isolation. Microsoft SQL Server, durable message queues, in-memory hash tables are all examples of resource managers. - - A resource manager manages either durable or volatile data. The durability (or conversely the volatility) of a resource manager refers to whether the resource manager supports failure recovery. If a resource manager supports failure recovery, it persists data to durable storage during Phase1 (prepare) such that if the resource manager goes down, it can re-enlist in the transaction upon recovery and perform the proper actions based on the notifications received from the transaction manager. In general, volatile resource managers manage volatile resources such as an in-memory data structure (for example, an in-memory transacted-hashtable), and durable resource managers manage resources that have a more persistent backing store (for example, a database whose backing store is disk). - - In order for a resource to participate in a transaction, it must enlist in the transaction. The class defines a set of methods whose names begin with **Enlist** that provide this functionality. The different **Enlist** methods correspond to the different types of enlistment that a resource manager may have. Specifically, you use the methods for volatile resources, and the method for durable resources. For simplicity, after deciding whether to use the or method based on your resource's durability support, you should enlist your resource to participate in Two Phase Commit (2PC) by implementing the interface for your resource manager. For more information on 2PC, see [Committing a Transaction in Single-Phase and Multi-Phase](committing-a-transaction-in-single-phase-and-multi-phase.md). - - By enlisting, the resource manager ensures that it gets callbacks from the transaction manager when the transaction commits or aborts. There is one instance of per enlistment. Typically, there is one enlistment per transaction, but a resource manager can choose to enlist multiple times in the same transaction. - - After enlistment, the resource manager responds to the transaction's requests. A durable resource manager stores enough information to allow it to either undo or redo the transaction's work on resources it manages. There are many ways to do this; keeping versions of data or keeping a log of the changes are two common techniques. - - When the application commits the transaction, the transaction manager initiates the two-phase commit protocol. The transaction manager first asks each enlisted resource manager if it is prepared to commit the transaction. The resource manager must prepare to commit—it readies itself to either commit or abort the transaction. - - During the prepare phase, the durable resource manager records the old and new data in stable storage so that the resource manager can recover it even if the system fails. If the resource manager can prepare, it informs the transaction manager its vote on whether to commit or abort the transaction. If any resource manager reports a failure to prepare, the transaction manager sends a rollback command to each resource manager and indicates the failure of the commit to the application. - - Once prepared, a resource manager must wait until it gets a commit or abort callback from the transaction manager in phase 2. Typically, the entire prepare and commit protocol completes in a fraction of a second. If there are system or communication failures, the commit or abort notification may not arrive for minutes or hours. During this period, the resource manager is in doubt about the outcome of the transaction. It does not know whether the transaction committed or aborted. While the resource manager is in doubt about a transaction, it keeps the data modified by keeping the transaction locked, thereby isolating these changes from any other transactions. - - When a resource manager fails, all of its enlisted transactions are aborted except for those that are prepared or committed prior to the failure. When a durable resource manager restarts, it reconstructs the committed state of the resources it manages by retrieving the prepare information written in the prepare phase, and commits or aborts these transactions accordingly. - - In summary, the two-phase commit protocol and the resource managers combine to make transactions atomic and durable. - - The class also provides the method to enlist a Promotable Single Phase Enlistment (PSPE). This allows a durable resource manager (RM) to host and "own" a transaction that can later be escalated to be managed by the MSDTC if necessary. For more information on this, see [Optimization using Single Phase Commit and Promotable Single Phase Notification](optimization-spc-and-promotable-spn.md). - -## In This Section - - The steps generally followed by a resource manager are outlined in the following topics. - - [Enlisting Resources as Participants in a Transaction](enlisting-resources-as-participants-in-a-transaction.md) - - Describes how a durable or volatile resource can enlist in a transaction. - - [Committing a Transaction in Single-Phase and Multi-Phase](committing-a-transaction-in-single-phase-and-multi-phase.md) - - Describes how a resource manager responds to commit notification and prepare the commit. - - [Performing Recovery](performing-recovery.md) - - Describes how a durable resource manager recovers from failure. - - [Security Trust Levels in Accessing Resources](security-trust-levels-in-accessing-resources.md) - - Describes how the three levels of trust for System.Transactions restrict access on the types of resources that exposes. - - [Optimization using Single Phase Commit and Promotable Single Phase Notification](optimization-spc-and-promotable-spn.md) - +Each resource used in a transaction is managed by a resource manager, whose actions are coordinated by a transaction manager. Resource managers work in cooperation with the transaction manager to provide the application with a guarantee of atomicity and isolation. Microsoft SQL Server, durable message queues, in-memory hash tables are all examples of resource managers. + + A resource manager manages either durable or volatile data. The durability (or conversely the volatility) of a resource manager refers to whether the resource manager supports failure recovery. If a resource manager supports failure recovery, it persists data to durable storage during Phase1 (prepare) such that if the resource manager goes down, it can re-enlist in the transaction upon recovery and perform the proper actions based on the notifications received from the transaction manager. In general, volatile resource managers manage volatile resources such as an in-memory data structure (for example, an in-memory transacted-hashtable), and durable resource managers manage resources that have a more persistent backing store (for example, a database whose backing store is disk). + + In order for a resource to participate in a transaction, it must enlist in the transaction. The class defines a set of methods whose names begin with `Enlist` that provide this functionality. The different `Enlist` methods correspond to the different types of enlistment that a resource manager may have. Specifically, you use the methods for volatile resources, and the method for durable resources. For simplicity, after deciding whether to use the or method based on your resource's durability support, you should enlist your resource to participate in Two Phase Commit (2PC) by implementing the interface for your resource manager. For more information on 2PC, see [Committing a Transaction in Single-Phase and Multi-Phase](committing-a-transaction-in-single-phase-and-multi-phase.md). + + By enlisting, the resource manager ensures that it gets callbacks from the transaction manager when the transaction commits or aborts. There is one instance of per enlistment. Typically, there is one enlistment per transaction, but a resource manager can choose to enlist multiple times in the same transaction. + + After enlistment, the resource manager responds to the transaction's requests. A durable resource manager stores enough information to allow it to either undo or redo the transaction's work on resources it manages. There are many ways to do this; keeping versions of data or keeping a log of the changes are two common techniques. + + When the application commits the transaction, the transaction manager initiates the two-phase commit protocol. The transaction manager first asks each enlisted resource manager if it is prepared to commit the transaction. The resource manager must prepare to commit—it readies itself to either commit or abort the transaction. + + During the prepare phase, the durable resource manager records the old and new data in stable storage so that the resource manager can recover it even if the system fails. If the resource manager can prepare, it informs the transaction manager its vote on whether to commit or abort the transaction. If any resource manager reports a failure to prepare, the transaction manager sends a rollback command to each resource manager and indicates the failure of the commit to the application. + + Once prepared, a resource manager must wait until it gets a commit or abort callback from the transaction manager in phase 2. Typically, the entire prepare and commit protocol completes in a fraction of a second. If there are system or communication failures, the commit or abort notification may not arrive for minutes or hours. During this period, the resource manager is in doubt about the outcome of the transaction. It does not know whether the transaction committed or aborted. While the resource manager is in doubt about a transaction, it keeps the data modified by keeping the transaction locked, thereby isolating these changes from any other transactions. + + When a resource manager fails, all of its enlisted transactions are aborted except for those that are prepared or committed prior to the failure. When a durable resource manager restarts, it reconstructs the committed state of the resources it manages by retrieving the prepare information written in the prepare phase, and commits or aborts these transactions accordingly. + + In summary, the two-phase commit protocol and the resource managers combine to make transactions atomic and durable. + + The class also provides the method to enlist a Promotable Single Phase Enlistment (PSPE). This allows a durable resource manager (RM) to host and "own" a transaction that can later be escalated to be managed by the MSDTC if necessary. For more information on this, see [Optimization using Single Phase Commit and Promotable Single Phase Notification](optimization-spc-and-promotable-spn.md). + +## In This Section + + The steps generally followed by a resource manager are outlined in the following topics. + + [Enlisting Resources as Participants in a Transaction](enlisting-resources-as-participants-in-a-transaction.md) + + Describes how a durable or volatile resource can enlist in a transaction. + + [Committing a Transaction in Single-Phase and Multi-Phase](committing-a-transaction-in-single-phase-and-multi-phase.md) + + Describes how a resource manager responds to commit notification and prepare the commit. + + [Performing Recovery](performing-recovery.md) + + Describes how a durable resource manager recovers from failure. + + [Security Trust Levels in Accessing Resources](security-trust-levels-in-accessing-resources.md) + + Describes how the three levels of trust for System.Transactions restrict access on the types of resources that exposes. + + [Optimization using Single Phase Commit and Promotable Single Phase Notification](optimization-spc-and-promotable-spn.md) + Describes optimization practices available to implementations of resource managers. diff --git a/docs/framework/data/transactions/optimization-spc-and-promotable-spn.md b/docs/framework/data/transactions/optimization-spc-and-promotable-spn.md index 692bb2087a61f..48807e935a1e5 100644 --- a/docs/framework/data/transactions/optimization-spc-and-promotable-spn.md +++ b/docs/framework/data/transactions/optimization-spc-and-promotable-spn.md @@ -28,7 +28,7 @@ If the transaction never requires escalation, when th If the transaction needs to be escalated (e.g., to support multiple RMs), informs the resource manager by calling the method on the interface, from which the interface derives. The resource manager then converts the transaction internally from a local transaction (which does not require logging) to a transaction object that is capable of participating in a DTC transaction, and associates it with the work already done. When the transaction is asked to commit, the transaction manager still sends the notification to the resource manager, which commits the distributed transaction that it created during escalation. > [!NOTE] -> The **TransactionCommitted** traces (that are generated when a Commit is invoked on the escalated transaction) contain the activity ID of the DTC transaction. +> The `TransactionCommitted` traces (that are generated when a Commit is invoked on the escalated transaction) contain the activity ID of the DTC transaction. For more information on management escalation, see [Transaction Management Escalation](transaction-management-escalation.md). diff --git a/docs/framework/data/transactions/security-trust-levels-in-accessing-resources.md b/docs/framework/data/transactions/security-trust-levels-in-accessing-resources.md index c355182f97958..16206d5583ca2 100644 --- a/docs/framework/data/transactions/security-trust-levels-in-accessing-resources.md +++ b/docs/framework/data/transactions/security-trust-levels-in-accessing-resources.md @@ -6,59 +6,59 @@ ms.assetid: fb5be924-317d-4d69-b33a-3d18ecfb9d6e --- # Security Trust Levels in Accessing Resources -This topic discusses how access is restricted on the types of resources that exposes. - - There are three main levels of trust for . The trust levels are defined based on the types of resources that exposes, and the level of trust that should be required to access those resources. The resources that provides access to are system memory, shared process wide resources, and system wide resources. The levels are: - -- **AllowPartiallyTrustedCallers** (APTCA) for applications using transactions within a single application domain. - -- **DistributedTransactionPermission** (DTP) for applications using distributed transactions. - -- Full trust for durable resources, configuration management applications, and legacy interop applications. - +This topic discusses how access is restricted on the types of resources that exposes. + + There are three main levels of trust for . The trust levels are defined based on the types of resources that exposes, and the level of trust that should be required to access those resources. The resources that provides access to are system memory, shared process wide resources, and system wide resources. The levels are: + +- **AllowPartiallyTrustedCallers** (APTCA) for applications using transactions within a single application domain. + +- **DistributedTransactionPermission** (DTP) for applications using distributed transactions. + +- Full trust for durable resources, configuration management applications, and legacy interop applications. + > [!NOTE] -> You should not call any of the enlistment interfaces with impersonated contexts. - -## Trust Levels - -### APTCA (Partial Trust) - - The assembly can be called by partially trusted code because it has been marked with the **AllowPartiallyTrustedCallers** attribute (APTCA). This attribute essentially removes the implicit for the **FullTrust** permission set that is otherwise automatically placed on each publicly accessible method in each type. However, some types and members still require stronger permissions. - - The APTCA attribute enables applications to use transactions in partial trust within a single application domain. This enables non-escalated transactions and volatile enlistments that can be used for error handling. One example of this is a transacted hash table and an application that uses it. Data can be added to and removed from the hash table under a single transaction. If the transaction is later rolled back, all of the changes made to the hash table under that transaction can be undone. - -### DistributedTransactionPermission (DTP) - - When a transaction is escalated to be managed by MSDTC, demands the (DTP) to create the distributed transaction. This means that the code that causes the transaction to be escalated (such as through serialization or additional durable enlistments) would need to be granted DTP. The code that originally created the transaction does not necessarily need to possess this permission. - -### FullTrust Link Demands - - This permission level is intended to restrict applications that are writing to durable resources. Upon failure, the application needs to be able to recover with the transaction manager to determine the final outcome of the transaction, so that it can update permanent data. This type of application is known as a durable source manager. A classic example of this type of application is SQL. - - To enable recovery, this type of application has the ability to permanently consume system resources. This is because the recoverable transaction manager must remember transactions that have committed until it can confirm that all durable resource managers that are participating in the transaction have received the outcome. Therefore, this type of application requires full trust and should not be run unless that level of trust has been granted. - - For more information on durable enlistments and recovery, see the [Enlisting Resources as Participants in a Transaction](enlisting-resources-as-participants-in-a-transaction.md) and [Performing Recovery](performing-recovery.md) topics. - - Applications that perform legacy interop work with COM+ are also required to have full trust. - - The following is a list of types and members that are not callable by partially trusted code because they are decorated with the **FullTrust** declarative security attribute: - - `PermissionSetAttribute(SecurityAction.LinkDemand, Name := "FullTrust")` - -- - -- - -- - -- - -- - -- - -- - -- - +> You should not call any of the enlistment interfaces with impersonated contexts. + +## Trust Levels + +### APTCA (Partial Trust) + + The assembly can be called by partially trusted code because it has been marked with the `AllowPartiallyTrustedCallers` attribute (APTCA). This attribute essentially removes the implicit for the **FullTrust** permission set that is otherwise automatically placed on each publicly accessible method in each type. However, some types and members still require stronger permissions. + + The APTCA attribute enables applications to use transactions in partial trust within a single application domain. This enables non-escalated transactions and volatile enlistments that can be used for error handling. One example of this is a transacted hash table and an application that uses it. Data can be added to and removed from the hash table under a single transaction. If the transaction is later rolled back, all of the changes made to the hash table under that transaction can be undone. + +### DistributedTransactionPermission (DTP) + + When a transaction is escalated to be managed by MSDTC, demands the (DTP) to create the distributed transaction. This means that the code that causes the transaction to be escalated (such as through serialization or additional durable enlistments) would need to be granted DTP. The code that originally created the transaction does not necessarily need to possess this permission. + +### FullTrust Link Demands + + This permission level is intended to restrict applications that are writing to durable resources. Upon failure, the application needs to be able to recover with the transaction manager to determine the final outcome of the transaction, so that it can update permanent data. This type of application is known as a durable source manager. A classic example of this type of application is SQL. + + To enable recovery, this type of application has the ability to permanently consume system resources. This is because the recoverable transaction manager must remember transactions that have committed until it can confirm that all durable resource managers that are participating in the transaction have received the outcome. Therefore, this type of application requires full trust and should not be run unless that level of trust has been granted. + + For more information on durable enlistments and recovery, see the [Enlisting Resources as Participants in a Transaction](enlisting-resources-as-participants-in-a-transaction.md) and [Performing Recovery](performing-recovery.md) topics. + + Applications that perform legacy interop work with COM+ are also required to have full trust. + + The following is a list of types and members that are not callable by partially trusted code because they are decorated with the **FullTrust** declarative security attribute: + + `PermissionSetAttribute(SecurityAction.LinkDemand, Name := "FullTrust")` + +- + +- + +- + +- + +- + +- + +- + +- + Only the immediate caller is required to possess the **FullTrust** permission set to use the above types or methods. diff --git a/docs/framework/debug-trace-profile/making-an-image-easier-to-debug.md b/docs/framework/debug-trace-profile/making-an-image-easier-to-debug.md index 4be13e62fb89f..3bcc8fa13a6ad 100644 --- a/docs/framework/debug-trace-profile/making-an-image-easier-to-debug.md +++ b/docs/framework/debug-trace-profile/making-an-image-easier-to-debug.md @@ -39,14 +39,14 @@ You can set the value of each option to 0 or 1, and any absent option defaults t Starting with .NET Framework 2.0, the JIT compiler always generates tracking information regardless of the value for `GenerateTrackingInfo`; however, the `AllowOptimize` value still has an effect. When using the [Ngen.exe (Native Image Generator)](../tools/ngen-exe-native-image-generator.md) to precompile the native image without optimization, the .ini file must be present in the target folder with `AllowOptimize=0` when Ngen.exe executes. If you've precompiled an assembly without optimization, you must remove the precompiled code using NGen.exe **/uninstall** option before rerunning Ngen.exe to precompile the code as optimized. If the .ini file isn't present in the folder, by default Ngen.exe precompiles the code as optimized. -The controls the settings for an assembly. **DebuggableAttribute** includes two fields that control whether the JIT compiler should optimize and/or generate tracking information. In .NET Framework 2.0 and later versions, the JIT compiler always generates tracking information. +The controls the settings for an assembly. `DebuggableAttribute` includes two fields that control whether the JIT compiler should optimize and/or generate tracking information. In .NET Framework 2.0 and later versions, the JIT compiler always generates tracking information. For a retail build, compilers don't set any **DebuggableAttribute**. By default, the JIT compiler generates the highest performance, hardest to debug machine code. Enabling JIT tracking lowers performance a little, and disabling optimization lowers performance a lot. -The **DebuggableAttribute** applies to a whole assembly at a time, not to individual modules within the assembly. Development tools must therefore attach custom attributes to the assembly metadata token, if an assembly has already been created, or to the class called **System.Runtime.CompilerServices.AssemblyAttributesGoHere**. The ALink tool then promotes these **DebuggableAttribute** attributes from each module to the assembly they become a part of. If there's a conflict, the ALink operation fails. +The `DebuggableAttribute` applies to a whole assembly at a time, not to individual modules within the assembly. Development tools must therefore attach custom attributes to the assembly metadata token, if an assembly has already been created, or to the class called **System.Runtime.CompilerServices.AssemblyAttributesGoHere**. The ALink tool then promotes these `DebuggableAttribute` attributes from each module to the assembly they become a part of. If there's a conflict, the ALink operation fails. > [!NOTE] -> In version 1.0 of the .NET Framework, the Microsoft Visual C++ compiler adds the **DebuggableAttribute** when the **/clr** and **/Zi** compiler options are specified. In version 1.1 of the .NET Framework, you must either add the **DebuggableAttribute** manually in your code or use the **/ASSEMBLYDEBUG** linker option. +> In version 1.0 of the .NET Framework, the Microsoft Visual C++ compiler adds the `DebuggableAttribute` when the **/clr** and **/Zi** compiler options are specified. In version 1.1 of the .NET Framework, you must either add the `DebuggableAttribute` manually in your code or use the **/ASSEMBLYDEBUG** linker option. ## See also diff --git a/docs/framework/deployment/configuring-assembly-binding-redirection.md b/docs/framework/deployment/configuring-assembly-binding-redirection.md index 22e2fb7ade075..ed99c7e26574f 100644 --- a/docs/framework/deployment/configuring-assembly-binding-redirection.md +++ b/docs/framework/deployment/configuring-assembly-binding-redirection.md @@ -11,12 +11,12 @@ ms.assetid: d266cbd8-bf91-41d1-baf0-afbc481a741f [!INCLUDE [net-framework-specific](../includes/net-framework-specific.md)] -By default, applications use the set of .NET Framework assemblies that shipped with the runtime version used to compile the application. You can use the **appliesTo** attribute on the [\](../configure-apps/file-schema/runtime/assemblybinding-element-for-runtime.md) element in an application configuration file to redirect assembly binding references to a specific version of the .NET Framework assemblies. This optional attribute uses a .NET Framework version number to indicate which version it applies to. If no **appliesTo** attribute is specified, the **\** element applies to all versions of the .NET Framework. +By default, applications use the set of .NET Framework assemblies that shipped with the runtime version used to compile the application. You can use the `appliesTo` attribute on the [\](../configure-apps/file-schema/runtime/assemblybinding-element-for-runtime.md) element in an application configuration file to redirect assembly binding references to a specific version of the .NET Framework assemblies. This optional attribute uses a .NET Framework version number to indicate which version it applies to. If no `appliesTo` attribute is specified, the `` element applies to all versions of the .NET Framework. - The **appliesTo** attribute was introduced in the .NET Framework version 1.1; it is ignored by .NET Framework version 1.0. This means that all **\** elements are applied when using .NET Framework version 1.0, even if an **appliesTo** attribute is specified. + The `appliesTo` attribute was introduced in the .NET Framework version 1.1; it is ignored by .NET Framework version 1.0. This means that all `` elements are applied when using .NET Framework version 1.0, even if an `appliesTo` attribute is specified. > [!NOTE] -> Use the **appliesTo** attribute to limit assembly binding redirection to a specific version of the runtime. +> Use the `appliesTo` attribute to limit assembly binding redirection to a specific version of the runtime. For example, to redirect assembly binding for a .NET Framework version 1.0 assembly, you would include the following XML code in your application configuration file. @@ -30,7 +30,7 @@ By default, applications use the set of .NET Framework assemblies that shipped w ``` - The **\** elements are order-sensitive. You should enter assembly binding redirection information for any .NET Framework version 1.0 assemblies first, followed by assembly binding redirection information for any .NET Framework version 1.1 assemblies. Finally, enter assembly binding redirection information for any .NET Framework assembly redirection that does not use the **appliesTo** attribute and therefore applies to all versions of the .NET Framework. In case of a conflict in redirection, the first matching redirection statement in the configuration file is used. + The `` elements are order-sensitive. You should enter assembly binding redirection information for any .NET Framework version 1.0 assemblies first, followed by assembly binding redirection information for any .NET Framework version 1.1 assemblies. Finally, enter assembly binding redirection information for any .NET Framework assembly redirection that does not use the `appliesTo` attribute and therefore applies to all versions of the .NET Framework. In case of a conflict in redirection, the first matching redirection statement in the configuration file is used. For example, to redirect one reference to a .NET Framework version 1.0 assembly and another reference to a .NET Framework version 1.1 assembly, you would use the pattern shown in the following pseudocode. diff --git a/docs/framework/deployment/how-the-runtime-locates-assemblies.md b/docs/framework/deployment/how-the-runtime-locates-assemblies.md index 75bffc72ec05c..72067298bc429 100644 --- a/docs/framework/deployment/how-the-runtime-locates-assemblies.md +++ b/docs/framework/deployment/how-the-runtime-locates-assemblies.md @@ -69,7 +69,7 @@ Assembly binding behavior can be configured at different levels based on three X - Machine configuration file. -These files follow the same syntax and provide information such as binding redirects, the location of code, and binding modes for particular assemblies. Each configuration file can contain an [\ element](../configure-apps/file-schema/runtime/assemblybinding-element-for-runtime.md) that redirects the binding process. The child elements of the [\ element](../configure-apps/file-schema/runtime/assemblybinding-element-for-runtime.md) include the [\ element](../configure-apps/file-schema/runtime/dependentassembly-element.md). The children of [\ element](../configure-apps/file-schema/runtime/dependentassembly-element.md) include the [\ element](/visualstudio/deployment/assemblyidentity-element-clickonce-deployment), the [\ element](../configure-apps/file-schema/runtime/bindingredirect-element.md), and the [\ element](../configure-apps/file-schema/runtime/codebase-element.md). +These files follow the same syntax and provide information such as binding redirects, the location of code, and binding modes for particular assemblies. Each configuration file can contain an [`` element](../configure-apps/file-schema/runtime/assemblybinding-element-for-runtime.md) that redirects the binding process. The child elements of the [`` element](../configure-apps/file-schema/runtime/assemblybinding-element-for-runtime.md) include the [`` element](../configure-apps/file-schema/runtime/dependentassembly-element.md). The children of [`` element](../configure-apps/file-schema/runtime/dependentassembly-element.md) include the [`` element](/visualstudio/deployment/assemblyidentity-element-clickonce-deployment), the [`` element](../configure-apps/file-schema/runtime/bindingredirect-element.md), and the [`` element](../configure-apps/file-schema/runtime/codebase-element.md). > [!NOTE] > Configuration information can be found in the three configuration files; not all elements are valid in all configuration files. For example, binding mode and private path information can only be in the application configuration file. For a complete list of the information that is contained in each file, see [Configuring Apps by Using Configuration Files](../configure-apps/index.md). @@ -78,7 +78,7 @@ These files follow the same syntax and provide information such as binding redir First, the common language runtime checks the application configuration file for information that overrides the version information stored in the calling assembly's manifest. The application configuration file can be deployed with an application, but is not required for application execution. Usually the retrieval of this file is almost instantaneous, but in situations where the application base is on a remote computer, such as in a Web-based scenario, the configuration file must be downloaded. -For client executables, the application configuration file resides in the same directory as the application's executable and has the same base name as the executable with a .config extension. For example, the configuration file for C:\Program Files\Myapp\Myapp.exe is C:\Program Files\Myapp\Myapp.exe.config. In a browser-based scenario, the HTML file must use the **\** element to explicitly point to the configuration file. +For client executables, the application configuration file resides in the same directory as the application's executable and has the same base name as the executable with a .config extension. For example, the configuration file for C:\Program Files\Myapp\Myapp.exe is C:\Program Files\Myapp\Myapp.exe.config. In a browser-based scenario, the HTML file must use the `` element to explicitly point to the configuration file. The following code provides a simple example of an application configuration file. This example adds a to the collection to enable recording debug information to a file. @@ -149,7 +149,7 @@ If the requested assembly has also been requested in previous calls, the common If a previous request for the assembly failed, subsequent requests for the assembly are failed immediately without attempting to load the assembly. Starting with .NET Framework version 2.0, assembly binding failures are cached, and the cached information is used to determine whether to attempt to load the assembly. > [!NOTE] -> To revert to the behavior of the .NET Framework versions 1.0 and 1.1, which did not cache binding failures, include the [\ Element](../configure-apps/file-schema/runtime/disablecachingbindingfailures-element.md) in your configuration file. +> To revert to the behavior of the .NET Framework versions 1.0 and 1.1, which did not cache binding failures, include the [`` Element](../configure-apps/file-schema/runtime/disablecachingbindingfailures-element.md) in your configuration file. diff --git a/docs/framework/deployment/in-process-side-by-side-execution.md b/docs/framework/deployment/in-process-side-by-side-execution.md index 3705c85d9f96c..0ea9492514d6b 100644 --- a/docs/framework/deployment/in-process-side-by-side-execution.md +++ b/docs/framework/deployment/in-process-side-by-side-execution.md @@ -58,7 +58,7 @@ Starting with the .NET Framework 4, you can use in-process side-by-side hosting .NET Framework versions installed: An earlier version of the .NET Framework and the .NET Framework 4. - What to do: In the [application configuration file](../configure-apps/index.md) in the application directory, use the [\ element](../configure-apps/file-schema/startup/startup-element.md) and the [\ element](../configure-apps/file-schema/startup/supportedruntime-element.md) set as follows: + What to do: In the [application configuration file](../configure-apps/index.md) in the application directory, use the [`` element](../configure-apps/file-schema/startup/startup-element.md) and the [`` element](../configure-apps/file-schema/startup/supportedruntime-element.md) set as follows: ```xml @@ -174,5 +174,5 @@ int _tmain(int argc, _TCHAR* argv[]) ## See also -- [\ Element](../configure-apps/file-schema/startup/startup-element.md) -- [\ Element](../configure-apps/file-schema/startup/supportedruntime-element.md) +- [`` Element](../configure-apps/file-schema/startup/startup-element.md) +- [`` Element](../configure-apps/file-schema/startup/supportedruntime-element.md) diff --git a/docs/framework/deployment/side-by-side-execution.md b/docs/framework/deployment/side-by-side-execution.md index 1005563e63493..f693df44250aa 100644 --- a/docs/framework/deployment/side-by-side-execution.md +++ b/docs/framework/deployment/side-by-side-execution.md @@ -58,7 +58,7 @@ The portable executable (PE) file header of each managed application and compone ### Runtime Version Information in the Application Configuration File -In addition to the information in the PE file header, an application can be deployed with an application configuration file that provides runtime version information. The application configuration file is an XML-based file that is created by the application developer and that ships with an application. The [\ Element](../configure-apps/file-schema/startup/requiredruntime-element.md) of the [\ section](../configure-apps/file-schema/startup/startup-element.md), if it is present in this file, specifies which versions of the runtime and which versions of a component the application supports. You can also use this file in testing to test an application's compatibility with different versions of the runtime. +In addition to the information in the PE file header, an application can be deployed with an application configuration file that provides runtime version information. The application configuration file is an XML-based file that is created by the application developer and that ships with an application. The [`` Element](../configure-apps/file-schema/startup/requiredruntime-element.md) of the [`` section](../configure-apps/file-schema/startup/startup-element.md), if it is present in this file, specifies which versions of the runtime and which versions of a component the application supports. You can also use this file in testing to test an application's compatibility with different versions of the runtime. Unmanaged code, including COM and COM+ applications, can have application configuration files that the runtime uses for interacting with managed code. The application configuration file affects any managed code that you activate through COM. The file can specify which runtime versions it supports, as well as assembly redirects. By default, COM interop applications calling to managed code use the latest version of the runtime installed on the computer. @@ -78,7 +78,7 @@ The runtime uses the application configuration file and the portable executable If an application configuration file is present, the runtime determines the appropriate runtime version to load based on the results of the following process: -1. The runtime examines the [\ Element](../configure-apps/file-schema/startup/supportedruntime-element.md) element in the application configuration file. If one or more of the supported runtime versions specified in the **\** element are present, the runtime loads the runtime version specified by the first **\** element. If this version is not available, the runtime examines the next **\** element and attempts to load the runtime version specified. If this runtime version is not available, subsequent **\** elements are examined. If none of the supported runtime versions are available, the runtime fails to load a runtime version and displays a message to the user (see step 3). +1. The runtime examines the [`` Element](../configure-apps/file-schema/startup/supportedruntime-element.md) element in the application configuration file. If one or more of the supported runtime versions specified in the `` element are present, the runtime loads the runtime version specified by the first `` element. If this version is not available, the runtime examines the next `` element and attempts to load the runtime version specified. If this runtime version is not available, subsequent `` elements are examined. If none of the supported runtime versions are available, the runtime fails to load a runtime version and displays a message to the user (see step 3). 2. The runtime reads the PE file header of the application's executable file. If the runtime version specified by the PE file header is available, the runtime loads that version. If the runtime version specified is not available, the runtime searches for a runtime version determined by Microsoft to be compatible with the runtime version in the PE header. If that version is not found, the process continues to step 3. @@ -94,7 +94,7 @@ If an application configuration file is present, the runtime determines the appr Because they are a potential source of side-by-side problems, partially qualified assembly references can be used only to bind to assemblies within an application directory. Avoid partially qualified assembly references in your code. -To mitigate partially qualified assembly references in code, you can use the [\](../configure-apps/file-schema/runtime/qualifyassembly-element.md) element in an application configuration file to fully qualify partially qualified assembly references that occur in code. Use the **\** element to specify only fields that were not set in the partial reference. The assembly identity listed in the **fullName** attribute must contain all the information needed to fully qualify the assembly name: assembly name, public key, culture, and version. +To mitigate partially qualified assembly references in code, you can use the [\](../configure-apps/file-schema/runtime/qualifyassembly-element.md) element in an application configuration file to fully qualify partially qualified assembly references that occur in code. Use the `` element to specify only fields that were not set in the partial reference. The assembly identity listed in the `fullName` attribute must contain all the information needed to fully qualify the assembly name: assembly name, public key, culture, and version. The following example shows the application configuration file entry to fully qualify an assembly called `myAssembly`. @@ -111,7 +111,7 @@ publicKeyToken=..., Whenever an assembly load statement references `myAssembly`, these configuration file settings cause the runtime to automatically translate the partially qualified `myAssembly` reference to a fully qualified reference. For example, Assembly.Load("myAssembly") becomes Assembly.Load("myAssembly, version=1.0.0.0, publicKeyToken=..., culture=neutral"). > [!NOTE] -> You can use the **LoadWithPartialName** method to bypass the common language runtime restriction that prohibits partially referenced assemblies from being loaded from the global assembly cache. This method should be used only in remoting scenarios as it can easily cause problems in side-by-side execution. +> You can use the `LoadWithPartialName` method to bypass the common language runtime restriction that prohibits partially referenced assemblies from being loaded from the global assembly cache. This method should be used only in remoting scenarios as it can easily cause problems in side-by-side execution. ## Related Topics diff --git a/docs/framework/interop/callback-functions.md b/docs/framework/interop/callback-functions.md index 805db8d5a1c73..1fc06b7633c9a 100644 --- a/docs/framework/interop/callback-functions.md +++ b/docs/framework/interop/callback-functions.md @@ -2,25 +2,25 @@ title: "Callback Functions" description: Read about callback functions, which are code with a managed application that helps an unmanaged DLL function complete a task. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "callback function" - "platform invoke, calling unmanaged functions" ms.assetid: c0aa8533-3b3b-42e8-9f60-84919793098c --- # Callback Functions -A callback function is code within a managed application that helps an unmanaged DLL function complete a task. Calls to a callback function pass indirectly from a managed application, through a DLL function, and back to the managed implementation. Some of the many DLL functions called with platform invoke require a callback function in managed code to run properly. - - To call most DLL functions from managed code, you create a managed definition of the function and then call it. The process is straightforward. - +A callback function is code within a managed application that helps an unmanaged DLL function complete a task. Calls to a callback function pass indirectly from a managed application, through a DLL function, and back to the managed implementation. Some of the many DLL functions called with platform invoke require a callback function in managed code to run properly. + + To call most DLL functions from managed code, you create a managed definition of the function and then call it. The process is straightforward. + Using a DLL function that requires a callback function has some additional steps. First, you must determine whether the function requires a callback by looking at the documentation for the function. Next, you have to create the callback function in your managed application. Finally, you call the DLL function, passing a pointer to the callback function as an argument. - The following illustration summarizes the callback function and implementation steps: - - ![Diagram showing the platform invoke callback process.](./media/callback-functions/platform-invoke-callback-process.gif) - - Callback functions are ideal for use in situations in which a task is performed repeatedly. Another common usage is with enumeration functions, such as **EnumFontFamilies**, **EnumPrinters**, and **EnumWindows** in the Windows API. The **EnumWindows** function enumerates through all existing windows on your computer, calling the callback function to perform a task on each window. For instructions and an example, see [How to: Implement Callback Functions](how-to-implement-callback-functions.md). - + The following illustration summarizes the callback function and implementation steps: + + ![Diagram showing the platform invoke callback process.](./media/callback-functions/platform-invoke-callback-process.gif) + + Callback functions are ideal for use in situations in which a task is performed repeatedly. Another common usage is with enumeration functions, such as **EnumFontFamilies**, **EnumPrinters**, and `EnumWindows` in the Windows API. The `EnumWindows` function enumerates through all existing windows on your computer, calling the callback function to perform a task on each window. For instructions and an example, see [How to: Implement Callback Functions](how-to-implement-callback-functions.md). + ## See also - [How to: Implement Callback Functions](how-to-implement-callback-functions.md) diff --git a/docs/framework/interop/com-interop-sample-net-client-and-com-server.md b/docs/framework/interop/com-interop-sample-net-client-and-com-server.md index bfc6335e881cd..7e97de218dc64 100644 --- a/docs/framework/interop/com-interop-sample-net-client-and-com-server.md +++ b/docs/framework/interop/com-interop-sample-net-client-and-com-server.md @@ -2,299 +2,299 @@ title: "COM Interop Sample: .NET Client and COM Server" description: Read a code sample that shows how a .NET client accesses a COM server to create a COM coclass instance and call class members to perform mortgage calculations. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "interoperation with unmanaged code, samples" - "COM interop, samples" ms.assetid: a3f752bb-8945-4e1b-8163-71def6e9f137 --- # COM Interop Sample: .NET Client and COM Server -This sample demonstrates how a [.NET client](#cpconcominteropsamplenetclientcomserveranchor1), built to access a [COM server](#cpconcominteropsamplenetclientcomserveranchor2), creates an instance of a COM coclass and calls class members to perform mortgage calculations. - - In this example, the client creates and calls an instance of the **Loan** coclass, passes four arguments (one of those four being equal to zero) to the instance, and displays the computations. Code fragments from this sample appear throughout this section. - +This sample demonstrates how a [.NET client](#cpconcominteropsamplenetclientcomserveranchor1), built to access a [COM server](#cpconcominteropsamplenetclientcomserveranchor2), creates an instance of a COM coclass and calls class members to perform mortgage calculations. + + In this example, the client creates and calls an instance of the `Loan` coclass, passes four arguments (one of those four being equal to zero) to the instance, and displays the computations. Code fragments from this sample appear throughout this section. + -## .NET Client - -```vb -Imports System -Imports Microsoft.VisualBasic -Imports LoanLib - -Public Class LoanApp - - Public Shared Sub Main() - Dim Args As String() - Args = System.Environment.GetCommandLineArgs() - - Dim ln As New Loan() - - If Args.Length < 5 Then - Console.WriteLine("Usage: ConLoan Balance Rate Term Payment") - Console.WriteLine(" Either Balance, Rate, Term, or Payment " _ - & "must be 0") - Exit Sub - End If - - ln.OpeningBalance = Convert.ToDouble(Args(1)) - ln.Rate = Convert.ToDouble(Args(2)) / 100.0 - ln.Term = Convert.ToInt16(Args(3)) - ln.Payment = Convert.ToDouble(Args(4)) - - If ln.OpeningBalance = 0.0 Then - ln.ComputeOpeningBalance() - End If - If ln.Rate = 0.0 Then - ln.ComputeRate() - End If - If ln.Term = 0 Then - ln.ComputeTerm() - End If - If ln.Payment = 0.0 Then - ln.ComputePayment() +## .NET Client + +```vb +Imports System +Imports Microsoft.VisualBasic +Imports LoanLib + +Public Class LoanApp + + Public Shared Sub Main() + Dim Args As String() + Args = System.Environment.GetCommandLineArgs() + + Dim ln As New Loan() + + If Args.Length < 5 Then + Console.WriteLine("Usage: ConLoan Balance Rate Term Payment") + Console.WriteLine(" Either Balance, Rate, Term, or Payment " _ + & "must be 0") + Exit Sub End If - Console.WriteLine("Balance = {0,10:0.00}", ln.OpeningBalance) - Console.WriteLine("Rate = {0,10:0.0%}", ln.Rate) - Console.WriteLine("Term = {0,10:0.00}", ln.Term) - Console.WriteLine("Payment = {0,10:0.00}" & ControlChars.Cr, _ - ln.Payment) - - Dim MorePmts As Boolean - Dim Balance As Double = 0.0 - Dim Principal As Double = 0.0 - Dim Interest As Double = 0.0 - - Console.WriteLine("{0,4}{1,10}{2,12}{3,10}{4,12}", _ - "Nbr", "Payment", "Principal", "Interest", "Balance") - Console.WriteLine("{0,4}{1,10}{2,12}{3,10}{4,12}", _ - "---", "-------", "---------", "--------", "-------") - - MorePmts = ln.GetFirstPmtDistribution(ln.Payment, Balance, _ - Principal, Interest) - - Dim PmtNbr As Short - - While MorePmts - - Console.WriteLine("{0,4}{1,10:0.00}{2,12:0.00}{3,10:0.00}" _ - & "{4,12:0.00}", PmtNbr, ln.Payment, Principal, Interest, - Balance) - MorePmts = ln.GetNextPmtDistribution(ln.Payment, Balance, _ - Principal, Interest) - PmtNbr += CShort(1) - End While - End Sub -End Class -``` - -```csharp -using System; -using LoanLib; - -public class LoanApp { - public static void Main(String[] Args) { - - Loan ln = new Loan(); - + + ln.OpeningBalance = Convert.ToDouble(Args(1)) + ln.Rate = Convert.ToDouble(Args(2)) / 100.0 + ln.Term = Convert.ToInt16(Args(3)) + ln.Payment = Convert.ToDouble(Args(4)) + + If ln.OpeningBalance = 0.0 Then + ln.ComputeOpeningBalance() + End If + If ln.Rate = 0.0 Then + ln.ComputeRate() + End If + If ln.Term = 0 Then + ln.ComputeTerm() + End If + If ln.Payment = 0.0 Then + ln.ComputePayment() + End If + Console.WriteLine("Balance = {0,10:0.00}", ln.OpeningBalance) + Console.WriteLine("Rate = {0,10:0.0%}", ln.Rate) + Console.WriteLine("Term = {0,10:0.00}", ln.Term) + Console.WriteLine("Payment = {0,10:0.00}" & ControlChars.Cr, _ + ln.Payment) + + Dim MorePmts As Boolean + Dim Balance As Double = 0.0 + Dim Principal As Double = 0.0 + Dim Interest As Double = 0.0 + + Console.WriteLine("{0,4}{1,10}{2,12}{3,10}{4,12}", _ + "Nbr", "Payment", "Principal", "Interest", "Balance") + Console.WriteLine("{0,4}{1,10}{2,12}{3,10}{4,12}", _ + "---", "-------", "---------", "--------", "-------") + + MorePmts = ln.GetFirstPmtDistribution(ln.Payment, Balance, _ + Principal, Interest) + + Dim PmtNbr As Short + + While MorePmts + + Console.WriteLine("{0,4}{1,10:0.00}{2,12:0.00}{3,10:0.00}" _ + & "{4,12:0.00}", PmtNbr, ln.Payment, Principal, Interest, + Balance) + MorePmts = ln.GetNextPmtDistribution(ln.Payment, Balance, _ + Principal, Interest) + PmtNbr += CShort(1) + End While + End Sub +End Class +``` + +```csharp +using System; +using LoanLib; + +public class LoanApp { + public static void Main(String[] Args) { + + Loan ln = new Loan(); + if (Args.Length < 4) - { - Console.WriteLine("Usage: ConLoan Balance Rate Term Payment"); + { + Console.WriteLine("Usage: ConLoan Balance Rate Term Payment"); Console.WriteLine(" Either Balance, Rate, Term, or Payment - must be 0"); - return; - } - - ln.OpeningBalance = Convert.ToDouble(Args[0]); - ln.Rate = Convert.ToDouble(Args[1])/100.0; - ln.Term = Convert.ToInt16(Args[2]); - ln.Payment = Convert.ToDouble(Args[3]); - - if (ln.OpeningBalance == 0.00) ln.ComputeOpeningBalance(); - if (ln.Rate == 0.00) ln.ComputeRate(); - if (ln.Term == 0) ln.ComputeTerm(); - if (ln.Payment == 0.00) ln.ComputePayment(); - - Console.WriteLine("Balance = {0,10:0.00}", ln.OpeningBalance); - Console.WriteLine("Rate = {0,10:0.0%}", ln.Rate); - Console.WriteLine("Term = {0,10:0.00}", ln.Term); - Console.WriteLine("Payment = {0,10:0.00}\n", ln.Payment); - - bool MorePmts; - double Balance = 0.0; - double Principal = 0.0; - double Interest = 0.0; - - Console.WriteLine("{0,4}{1,10}{2,12}{3,10}{4,12}", "Nbr", "Payment", - "Principal", "Interest", "Balance"); - Console.WriteLine("{0,4}{1,10}{2,12}{3,10}{4,12}", "---", "-------", - "---------", "--------", "-------"); - + must be 0"); + return; + } + + ln.OpeningBalance = Convert.ToDouble(Args[0]); + ln.Rate = Convert.ToDouble(Args[1])/100.0; + ln.Term = Convert.ToInt16(Args[2]); + ln.Payment = Convert.ToDouble(Args[3]); + + if (ln.OpeningBalance == 0.00) ln.ComputeOpeningBalance(); + if (ln.Rate == 0.00) ln.ComputeRate(); + if (ln.Term == 0) ln.ComputeTerm(); + if (ln.Payment == 0.00) ln.ComputePayment(); + + Console.WriteLine("Balance = {0,10:0.00}", ln.OpeningBalance); + Console.WriteLine("Rate = {0,10:0.0%}", ln.Rate); + Console.WriteLine("Term = {0,10:0.00}", ln.Term); + Console.WriteLine("Payment = {0,10:0.00}\n", ln.Payment); + + bool MorePmts; + double Balance = 0.0; + double Principal = 0.0; + double Interest = 0.0; + + Console.WriteLine("{0,4}{1,10}{2,12}{3,10}{4,12}", "Nbr", "Payment", + "Principal", "Interest", "Balance"); + Console.WriteLine("{0,4}{1,10}{2,12}{3,10}{4,12}", "---", "-------", + "---------", "--------", "-------"); + MorePmts = ln.GetFirstPmtDistribution(ln.Payment, out Balance, - out Principal, out Interest); - - for (short PmtNbr = 1; MorePmts; PmtNbr++) { - Console.WriteLine("{0,4}{1,10:0.00}{2,12:0.00}{3,10:0.00} - {4,12:0.00}", PmtNbr, ln.Payment, Principal, Interest, - Balance); + out Principal, out Interest); + + for (short PmtNbr = 1; MorePmts; PmtNbr++) { + Console.WriteLine("{0,4}{1,10:0.00}{2,12:0.00}{3,10:0.00} + {4,12:0.00}", PmtNbr, ln.Payment, Principal, Interest, + Balance); MorePmts = ln.GetNextPmtDistribution(ln.Payment, ref Balance, out Principal, out Interest); - } - } -} -``` - + } + } +} +``` + -## COM Server - -```cpp -// Loan.cpp : Implementation of CLoan -#include "stdafx.h" -#include "math.h" -#include "LoanLib.h" -#include "Loan.h" - +## COM Server + +```cpp +// Loan.cpp : Implementation of CLoan +#include "stdafx.h" +#include "math.h" +#include "LoanLib.h" +#include "Loan.h" + static double Round(double value, short digits); - -STDMETHODIMP CLoan::get_OpeningBalance(double *pVal) -{ - *pVal = OpeningBalance; - return S_OK; -} - -STDMETHODIMP CLoan::put_OpeningBalance(double newVal) -{ - OpeningBalance = newVal; - return S_OK; -} - -STDMETHODIMP CLoan::get_Rate(double *pVal) -{ - *pVal = Rate; - return S_OK; -} - -STDMETHODIMP CLoan::put_Rate(double newVal) -{ - Rate = newVal; - return S_OK; -} - -STDMETHODIMP CLoan::get_Payment(double *pVal) -{ - *pVal = Payment; - return S_OK; -} - -STDMETHODIMP CLoan::put_Payment(double newVal) -{ - Payment = newVal; - return S_OK; -} - -STDMETHODIMP CLoan::get_Term(short *pVal) -{ - *pVal = Term; - return S_OK; -} - -STDMETHODIMP CLoan::put_Term(short newVal) -{ - Term = newVal; - return S_OK; -} - -STDMETHODIMP CLoan::ComputePayment(double *pVal) -{ + +STDMETHODIMP CLoan::get_OpeningBalance(double *pVal) +{ + *pVal = OpeningBalance; + return S_OK; +} + +STDMETHODIMP CLoan::put_OpeningBalance(double newVal) +{ + OpeningBalance = newVal; + return S_OK; +} + +STDMETHODIMP CLoan::get_Rate(double *pVal) +{ + *pVal = Rate; + return S_OK; +} + +STDMETHODIMP CLoan::put_Rate(double newVal) +{ + Rate = newVal; + return S_OK; +} + +STDMETHODIMP CLoan::get_Payment(double *pVal) +{ + *pVal = Payment; + return S_OK; +} + +STDMETHODIMP CLoan::put_Payment(double newVal) +{ + Payment = newVal; + return S_OK; +} + +STDMETHODIMP CLoan::get_Term(short *pVal) +{ + *pVal = Term; + return S_OK; +} + +STDMETHODIMP CLoan::put_Term(short newVal) +{ + Term = newVal; + return S_OK; +} + +STDMETHODIMP CLoan::ComputePayment(double *pVal) +{ Payment = Round(OpeningBalance * (Rate / - (1 - pow((1 + Rate), -Term))),2); - *pVal = Payment; - return S_OK; -} - -STDMETHODIMP CLoan::ComputeOpeningBalance(double *pVal) -{ + (1 - pow((1 + Rate), -Term))),2); + *pVal = Payment; + return S_OK; +} + +STDMETHODIMP CLoan::ComputeOpeningBalance(double *pVal) +{ OpeningBalance = Round(Payment / (Rate / - (1 - pow((1 + Rate), -Term))),2); - *pVal = OpeningBalance ; - return S_OK; -} - -STDMETHODIMP CLoan::ComputeRate(double *pVal) -{ - double DesiredPayment = Payment; - - for (Rate = 0.001; Rate < 28.0; Rate += 0.001) - { + (1 - pow((1 + Rate), -Term))),2); + *pVal = OpeningBalance ; + return S_OK; +} + +STDMETHODIMP CLoan::ComputeRate(double *pVal) +{ + double DesiredPayment = Payment; + + for (Rate = 0.001; Rate < 28.0; Rate += 0.001) + { Payment = Round(OpeningBalance * (Rate / - (1 - pow((1 + Rate), -Term))),2); - - if (Payment >= DesiredPayment) - break; - } - + (1 - pow((1 + Rate), -Term))),2); + + if (Payment >= DesiredPayment) + break; + } + *pVal = Rate; - return S_OK; -} - -STDMETHODIMP CLoan::ComputeTerm(short *pVal) -{ - double DesiredPayment = Payment; - for (Term = 1; Term < 480 ; Term ++) - { + return S_OK; +} + +STDMETHODIMP CLoan::ComputeTerm(short *pVal) +{ + double DesiredPayment = Payment; + for (Term = 1; Term < 480 ; Term ++) + { Payment = Round(OpeningBalance * (Rate / - (1 - pow((1 + Rate), -Term))),2); - if (Payment <= DesiredPayment) - break; - } + (1 - pow((1 + Rate), -Term))),2); + if (Payment <= DesiredPayment) + break; + } *pVal = Term; - return S_OK; -} - -STDMETHODIMP CLoan::GetFirstPmtDistribution(double PmtAmt, double *Balance, double *PrinPortion, double *IntPortion, VARIANT_BOOL *pVal) -{ - *Balance = OpeningBalance; + return S_OK; +} + +STDMETHODIMP CLoan::GetFirstPmtDistribution(double PmtAmt, double *Balance, double *PrinPortion, double *IntPortion, VARIANT_BOOL *pVal) +{ + *Balance = OpeningBalance; GetNextPmtDistribution(PmtAmt, Balance, PrinPortion, IntPortion, - pVal); - return S_OK; -} - -STDMETHODIMP CLoan::GetNextPmtDistribution(double PmtAmt, double *Balance, double *PrinPortion, double *IntPortion, VARIANT_BOOL *pVal) -{ - *IntPortion = Round(*Balance * Rate, 2); - *PrinPortion = Round(PmtAmt - *IntPortion, 2); - *Balance = Round(*Balance - *PrinPortion, 2); - - if (*Balance <= 0.0) - *pVal = FALSE; - else - *pVal = TRUE; - return S_OK; -} - -STDMETHODIMP CLoan::get_RiskRating(BSTR *pVal) -{ - *pVal = (BSTR)RiskRating; - return S_OK; -} - -STDMETHODIMP CLoan::put_RiskRating(BSTR newVal) -{ - RiskRating = newVal; - return S_OK; -} + pVal); + return S_OK; +} + +STDMETHODIMP CLoan::GetNextPmtDistribution(double PmtAmt, double *Balance, double *PrinPortion, double *IntPortion, VARIANT_BOOL *pVal) +{ + *IntPortion = Round(*Balance * Rate, 2); + *PrinPortion = Round(PmtAmt - *IntPortion, 2); + *Balance = Round(*Balance - *PrinPortion, 2); + + if (*Balance <= 0.0) + *pVal = FALSE; + else + *pVal = TRUE; + return S_OK; +} + +STDMETHODIMP CLoan::get_RiskRating(BSTR *pVal) +{ + *pVal = (BSTR)RiskRating; + return S_OK; +} + +STDMETHODIMP CLoan::put_RiskRating(BSTR newVal) +{ + RiskRating = newVal; + return S_OK; +} static double Round(double value, short digits) -{ - double factor = pow(10, digits); - return floor(value * factor + 0.5)/factor; -} -``` - +{ + double factor = pow(10, digits); + return floor(value * factor + 0.5)/factor; +} +``` + ## See also - [Exposing COM Components to the .NET Framework](exposing-com-components.md) diff --git a/docs/framework/interop/consuming-unmanaged-dll-functions.md b/docs/framework/interop/consuming-unmanaged-dll-functions.md index d3b3177a2bac6..5f634b257f08c 100644 --- a/docs/framework/interop/consuming-unmanaged-dll-functions.md +++ b/docs/framework/interop/consuming-unmanaged-dll-functions.md @@ -2,7 +2,7 @@ title: "Consuming Unmanaged DLL Functions" description: Consume unmanaged DLL functions by using the platform invoke service, which lets managed code call unmanaged functions implemented in DLL libraries. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "unmanaged functions, calling" - "COM interop, DLL functions" - "unmanaged functions" @@ -17,53 +17,53 @@ ms.assetid: eca7606e-ebfb-4f47-b8d9-289903fdc045 --- # Consuming Unmanaged DLL Functions -Platform invoke is a service that enables managed code to call unmanaged functions implemented in dynamic link libraries (DLLs), such as those in the Windows API. It locates and invokes an exported function and marshals its arguments (integers, strings, arrays, structures, and so on) across the interoperation boundary as needed. - - This section introduces tasks associated with consuming unmanaged DLL functions and provides more information about platform invoke. In addition to the following tasks, there are general considerations and a link providing additional information and examples. - -#### To consume exported DLL functions - -1. [Identify functions in DLLs](identifying-functions-in-dlls.md). - - Minimally, you must specify the name of the function and name of the DLL that contains it. - -2. [Create a class to hold DLL functions](creating-a-class-to-hold-dll-functions.md). - - You can use an existing class, create an individual class for each unmanaged function, or create one class that contains a set of related unmanaged functions. - -3. [Create prototypes in managed code](creating-prototypes-in-managed-code.md). - - [Visual Basic] Use the **Declare** statement with the **Function** and **Lib** keywords. In some rare cases, you can use the **DllImportAttribute** with the **Shared Function** keywords. These cases are explained later in this section. - - [C#] Use the **DllImportAttribute** to identify the DLL and function. Mark the method with the **static** and **extern** modifiers. - - [C++] Use the **DllImportAttribute** to identify the DLL and function. Mark the wrapper method or function with **extern "C"**. - -4. [Call a DLL function](calling-a-dll-function.md). - - Call the method on your managed class as you would any other managed method. [Passing structures](passing-structures.md) and [implementing callback functions](callback-functions.md) are special cases. - - For examples that demonstrate how to construct .NET-based declarations to be used with platform invoke, see [Marshalling Data with Platform Invoke](marshalling-data-with-platform-invoke.md). - -## A closer look at platform invoke - - Platform invoke relies on metadata to locate exported functions and marshal their arguments at run time. The following illustration shows this process. - - ![Diagram that shows a platform invoke call.](./media/consuming-unmanaged-dll-functions/platform-invoke-call.gif) - - When platform invoke calls an unmanaged function, it performs the following sequence of actions: - -1. Locates the DLL containing the function. - -2. Loads the DLL into memory. - -3. Locates the address of the function in memory and pushes its arguments onto the stack, marshalling data as required. - +Platform invoke is a service that enables managed code to call unmanaged functions implemented in dynamic link libraries (DLLs), such as those in the Windows API. It locates and invokes an exported function and marshals its arguments (integers, strings, arrays, structures, and so on) across the interoperation boundary as needed. + + This section introduces tasks associated with consuming unmanaged DLL functions and provides more information about platform invoke. In addition to the following tasks, there are general considerations and a link providing additional information and examples. + +#### To consume exported DLL functions + +1. [Identify functions in DLLs](identifying-functions-in-dlls.md). + + Minimally, you must specify the name of the function and name of the DLL that contains it. + +2. [Create a class to hold DLL functions](creating-a-class-to-hold-dll-functions.md). + + You can use an existing class, create an individual class for each unmanaged function, or create one class that contains a set of related unmanaged functions. + +3. [Create prototypes in managed code](creating-prototypes-in-managed-code.md). + + [Visual Basic] Use the `Declare` statement with the `Function` and `Lib` keywords. In some rare cases, you can use the `DllImportAttribute` with the **Shared Function** keywords. These cases are explained later in this section. + + [C#] Use the `DllImportAttribute` to identify the DLL and function. Mark the method with the `static` and `extern` modifiers. + + [C++] Use the `DllImportAttribute` to identify the DLL and function. Mark the wrapper method or function with **extern "C"**. + +4. [Call a DLL function](calling-a-dll-function.md). + + Call the method on your managed class as you would any other managed method. [Passing structures](passing-structures.md) and [implementing callback functions](callback-functions.md) are special cases. + + For examples that demonstrate how to construct .NET-based declarations to be used with platform invoke, see [Marshalling Data with Platform Invoke](marshalling-data-with-platform-invoke.md). + +## A closer look at platform invoke + + Platform invoke relies on metadata to locate exported functions and marshal their arguments at run time. The following illustration shows this process. + + ![Diagram that shows a platform invoke call.](./media/consuming-unmanaged-dll-functions/platform-invoke-call.gif) + + When platform invoke calls an unmanaged function, it performs the following sequence of actions: + +1. Locates the DLL containing the function. + +2. Loads the DLL into memory. + +3. Locates the address of the function in memory and pushes its arguments onto the stack, marshalling data as required. + > [!NOTE] - > Locating and loading the DLL, and locating the address of the function in memory occur only on the first call to the function. - -4. Transfers control to the unmanaged function. - + > Locating and loading the DLL, and locating the address of the function in memory occur only on the first call to the function. + +4. Transfers control to the unmanaged function. + Platform invoke throws exceptions generated by the unmanaged function to the managed caller. ## See also diff --git a/docs/framework/interop/copying-and-pinning.md b/docs/framework/interop/copying-and-pinning.md index 3b9098f231d5a..bef48f7e81b93 100644 --- a/docs/framework/interop/copying-and-pinning.md +++ b/docs/framework/interop/copying-and-pinning.md @@ -40,7 +40,7 @@ Formatted [non-blittable](blittable-and-non-blittable-types.md) classes have fix - If the attribute is set, the state is always copied back to the instance on return, marshalling as necessary. -- If both **InAttribute** and **OutAttribute** are set, both copies are required. If either attribute is omitted, the marshaller can optimize by eliminating either copy. +- If both `InAttribute` and `OutAttribute` are set, both copies are required. If either attribute is omitted, the marshaller can optimize by eliminating either copy. ## Reference Types @@ -54,15 +54,15 @@ Reference types have the following conditional behavior: - On return from the call. - To avoid unnecessarily copying and conversion, these types are marshalled as In parameters. You must explicitly apply the **InAttribute** and **OutAttribute** attributes to an argument for the caller to see changes made by the callee. + To avoid unnecessarily copying and conversion, these types are marshalled as In parameters. You must explicitly apply the `InAttribute` and `OutAttribute` attributes to an argument for the caller to see changes made by the callee. -- If a reference type is passed by value and it has only members of blittable types, it can be pinned during marshalling and any changes made to the members of the type by the callee are seen by the caller. Apply **InAttribute** and **OutAttribute** explicitly if you want this behavior. Without these directional attributes, the interop marshaller does not export directional information to the type library (it exports as In, which is the default) and this can cause problems with COM cross-apartment marshalling. +- If a reference type is passed by value and it has only members of blittable types, it can be pinned during marshalling and any changes made to the members of the type by the callee are seen by the caller. Apply `InAttribute` and `OutAttribute` explicitly if you want this behavior. Without these directional attributes, the interop marshaller does not export directional information to the type library (it exports as In, which is the default) and this can cause problems with COM cross-apartment marshalling. - If a reference type is passed by reference, it will be marshalled as In/Out by default. ## System.String and System.Text.StringBuilder -When data is marshalled to unmanaged code by value or by reference, the marshaller typically copies the data to a secondary buffer (possibly converting character sets during the copy) and passes a reference to the buffer to the callee. Unless the reference is a **BSTR** allocated with **SysAllocString**, the reference is always allocated with **CoTaskMemAlloc**. +When data is marshalled to unmanaged code by value or by reference, the marshaller typically copies the data to a secondary buffer (possibly converting character sets during the copy) and passes a reference to the buffer to the callee. Unless the reference is a `BSTR` allocated with **SysAllocString**, the reference is always allocated with **CoTaskMemAlloc**. As an optimization when either or is marshalled by value (such as a Unicode character string), the marshaller passes the callee a direct pointer to managed strings in the internal Unicode buffer instead of copying it to a new buffer. @@ -71,7 +71,7 @@ As an optimization when either or is passed by reference, the marshaller copies the contents of the string to a secondary buffer before making the call. It then copies the contents of the buffer into a new string on return from the call. This technique ensures that the immutable managed string remains unaltered. -When a is passed by value, the marshaller passes a reference to a temporary copy of the internal buffer of the **StringBuilder** to the caller. The caller and callee must agree on the size of the buffer. The caller is responsible for creating a **StringBuilder** of adequate length. The callee must take the necessary precautions to ensure that the buffer is not overrun. **StringBuilder** is an exception to the rule that reference types passed by value are passed as `In` parameters by default. `StringBuilder` is always passed as `In`/`Out`. +When a is passed by value, the marshaller passes a reference to a temporary copy of the internal buffer of the `StringBuilder` to the caller. The caller and callee must agree on the size of the buffer. The caller is responsible for creating a `StringBuilder` of adequate length. The callee must take the necessary precautions to ensure that the buffer is not overrun. `StringBuilder` is an exception to the rule that reference types passed by value are passed as `In` parameters by default. `StringBuilder` is always passed as `In`/`Out`. ## See also diff --git a/docs/framework/interop/default-marshalling-behavior.md b/docs/framework/interop/default-marshalling-behavior.md index 372f3c3c62fca..f8c54083a51a9 100644 --- a/docs/framework/interop/default-marshalling-behavior.md +++ b/docs/framework/interop/default-marshalling-behavior.md @@ -2,10 +2,10 @@ title: "Default Marshalling Behavior" description: Learn default marshalling behavior in .NET. Review memory management with interop marshalling, and see default marshalling for classes, delegates, and value types. ms.date: "06/26/2018" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "interop marshalling, default" - "interoperation with unmanaged code, marshalling" - "marshaling behavior" @@ -13,229 +13,229 @@ ms.assetid: c0a9bcdf-3df8-4db3-b1b6-abbdb2af809a --- # Default Marshalling Behavior -Interop marshalling operates on rules that dictate how data associated with method parameters behaves as it passes between managed and unmanaged memory. These built-in rules control such marshalling activities as data type transformations, whether a callee can change data passed to it and return those changes to the caller, and under which circumstances the marshaller provides performance optimizations. - - This section identifies the default behavioral characteristics of the interop marshalling service. It presents detailed information on marshalling arrays, Boolean types, char types, delegates, classes, objects, strings, and structures. - +Interop marshalling operates on rules that dictate how data associated with method parameters behaves as it passes between managed and unmanaged memory. These built-in rules control such marshalling activities as data type transformations, whether a callee can change data passed to it and return those changes to the caller, and under which circumstances the marshaller provides performance optimizations. + + This section identifies the default behavioral characteristics of the interop marshalling service. It presents detailed information on marshalling arrays, Boolean types, char types, delegates, classes, objects, strings, and structures. + > [!NOTE] -> Marshalling of generic types is not supported. For more information see, [Interoperating Using Generic Types](/previous-versions/dotnet/netframework-4.0/ms229590(v=vs.100)). - -## Memory management with the interop marshaller - - The interop marshaller always attempts to free memory allocated by unmanaged code. This behavior complies with COM memory management rules, but differs from the rules that govern native C++. - - Confusion can arise if you anticipate native C++ behavior (no memory freeing) when using platform invoke, which automatically frees memory for pointers. For example, calling the following unmanaged method from a C++ DLL does not automatically free any memory. - -### Unmanaged signature - -```cpp -BSTR MethodOne (BSTR b) { - return b; -} -``` - - However, if you define the method as a platform invoke prototype, replace each **BSTR** type with a type, and call `MethodOne`, the common language runtime attempts to free `b` twice. You can change the marshalling behavior by using types rather than **String** types. - - The runtime always uses the **CoTaskMemFree** method on Windows and **free** method on other platforms to free memory. If the memory you are working with was not allocated with the **CoTaskMemAlloc** method on Windows or **malloc** method on other platforms, you must use an **IntPtr** and free the memory manually using the appropriate method. Similarly, you can avoid automatic memory freeing in situations where memory should never be freed, such as when using the **GetCommandLine** function from Kernel32.dll, which returns a pointer to kernel memory. For details on manually freeing memory, see the [Buffers Sample](/previous-versions/dotnet/netframework-4.0/x3txb6xc(v=vs.100)). - -## Default marshalling for classes - - Classes can be marshalled only by COM interop and are always marshalled as interfaces. In some cases the interface used to marshal the class is known as the class interface. For information about overriding the class interface with an interface of your choice, see [Introducing the class interface](../../standard/native-interop/com-callable-wrapper.md#introducing-the-class-interface). - -### Passing Classes to COM - - When a managed class is passed to COM, the interop marshaller automatically wraps the class with a COM proxy and passes the class interface produced by the proxy to the COM method call. The proxy then delegates all calls on the class interface back to the managed object. The proxy also exposes other interfaces that are not explicitly implemented by the class. The proxy automatically implements interfaces such as **IUnknown** and **IDispatch** on behalf of the class. - -### Passing Classes to .NET Code - - Coclasses are not typically used as method arguments in COM. Instead, a default interface is usually passed in place of the coclass. - - When an interface is passed into managed code, the interop marshaller is responsible for wrapping the interface with the proper wrapper and passing the wrapper to the managed method. Determining which wrapper to use can be difficult. Every instance of a COM object has a single, unique wrapper, no matter how many interfaces the object implements. For example, a single COM object that implements five distinct interfaces has only one wrapper. The same wrapper exposes all five interfaces. If two instances of the COM object are created, then two instances of the wrapper are created. - - For the wrapper to maintain the same type throughout its lifetime, the interop marshaller must identify the correct wrapper the first time an interface exposed by the object is passed through the marshaller. The marshaller identifies the object by looking at one of the interfaces the object implements. - - For example, the marshaller determines that the class wrapper should be used to wrap the interface that was passed into managed code. When the interface is first passed through the marshaller, the marshaller checks whether the interface is coming from a known object. This check occurs in two situations: - -- An interface is being implemented by another managed object that was passed to COM elsewhere. The marshaller can readily identify interfaces exposed by managed objects and is able to match the interface with the managed object that provides the implementation. The managed object is then passed to the method and no wrapper is needed. - -- An object that has already been wrapped is implementing the interface. To determine whether this is the case, the marshaller queries the object for its **IUnknown** interface and compares the returned interface to the interfaces of other objects that are already wrapped. If the interface is the same as that of another wrapper, the objects have the same identity and the existing wrapper is passed to the method. - - If an interface is not from a known object, the marshaller does the following: - -1. The marshaller queries the object for the **IProvideClassInfo2** interface. If provided, the marshaller uses the CLSID returned from **IProvideClassInfo2.GetGUID** to identify the coclass providing the interface. With the CLSID, the marshaller can locate the wrapper from the registry if the assembly has previously been registered. - -2. The marshaller queries the interface for the **IProvideClassInfo** interface. If provided, the marshaller uses the **ITypeInfo** returned from **IProvideClassInfo.GetClassinfo** to determine the CLSID of the class exposing the interface. The marshaller can use the CLSID to locate the metadata for the wrapper. - -3. If the marshaller still cannot identify the class, it wraps the interface with a generic wrapper class called **System.__ComObject**. - -## Default marshalling for delegates - - A managed delegate is marshalled as a COM interface or as a function pointer, based on the calling mechanism: - -- For platform invoke, a delegate is marshalled as an unmanaged function pointer by default. - -- For COM interop, a delegate is marshalled as a COM interface of type **_Delegate** by default. The **_Delegate** interface is defined in the Mscorlib.tlb type library and contains the method, which enables you to call the method that the delegate references. - - The following table shows the marshalling options for the managed delegate data type. The attribute provides several enumeration values to marshal delegates. - -|Enumeration type|Description of unmanaged format| -|----------------------|-------------------------------------| -|**UnmanagedType.FunctionPtr**|An unmanaged function pointer.| -|**UnmanagedType.Interface**|An interface of type **_Delegate**, as defined in Mscorlib.tlb.| - - Consider the following example code in which the methods of `DelegateTestInterface` are exported to a COM type library. Notice that only delegates marked with the **ref** (or **ByRef**) keyword are passed as In/Out parameters. - -```csharp -using System; -using System.Runtime.InteropServices; - -public interface DelegateTest { -void m1(Delegate d); +> Marshalling of generic types is not supported. For more information see, [Interoperating Using Generic Types](/previous-versions/dotnet/netframework-4.0/ms229590(v=vs.100)). + +## Memory management with the interop marshaller + + The interop marshaller always attempts to free memory allocated by unmanaged code. This behavior complies with COM memory management rules, but differs from the rules that govern native C++. + + Confusion can arise if you anticipate native C++ behavior (no memory freeing) when using platform invoke, which automatically frees memory for pointers. For example, calling the following unmanaged method from a C++ DLL does not automatically free any memory. + +### Unmanaged signature + +```cpp +BSTR MethodOne (BSTR b) { + return b; +} +``` + + However, if you define the method as a platform invoke prototype, replace each `BSTR` type with a type, and call `MethodOne`, the common language runtime attempts to free `b` twice. You can change the marshalling behavior by using types rather than `String` types. + + The runtime always uses the `CoTaskMemFree` method on Windows and `free` method on other platforms to free memory. If the memory you are working with was not allocated with the `CoTaskMemAlloc` method on Windows or `malloc` method on other platforms, you must use an `IntPtr` and free the memory manually using the appropriate method. Similarly, you can avoid automatic memory freeing in situations where memory should never be freed, such as when using the `GetCommandLine` function from Kernel32.dll, which returns a pointer to kernel memory. For details on manually freeing memory, see the [Buffers Sample](/previous-versions/dotnet/netframework-4.0/x3txb6xc(v=vs.100)). + +## Default marshalling for classes + + Classes can be marshalled only by COM interop and are always marshalled as interfaces. In some cases the interface used to marshal the class is known as the class interface. For information about overriding the class interface with an interface of your choice, see [Introducing the class interface](../../standard/native-interop/com-callable-wrapper.md#introducing-the-class-interface). + +### Passing Classes to COM + + When a managed class is passed to COM, the interop marshaller automatically wraps the class with a COM proxy and passes the class interface produced by the proxy to the COM method call. The proxy then delegates all calls on the class interface back to the managed object. The proxy also exposes other interfaces that are not explicitly implemented by the class. The proxy automatically implements interfaces such as `IUnknown` and `IDispatch` on behalf of the class. + +### Passing Classes to .NET Code + + Coclasses are not typically used as method arguments in COM. Instead, a default interface is usually passed in place of the coclass. + + When an interface is passed into managed code, the interop marshaller is responsible for wrapping the interface with the proper wrapper and passing the wrapper to the managed method. Determining which wrapper to use can be difficult. Every instance of a COM object has a single, unique wrapper, no matter how many interfaces the object implements. For example, a single COM object that implements five distinct interfaces has only one wrapper. The same wrapper exposes all five interfaces. If two instances of the COM object are created, then two instances of the wrapper are created. + + For the wrapper to maintain the same type throughout its lifetime, the interop marshaller must identify the correct wrapper the first time an interface exposed by the object is passed through the marshaller. The marshaller identifies the object by looking at one of the interfaces the object implements. + + For example, the marshaller determines that the class wrapper should be used to wrap the interface that was passed into managed code. When the interface is first passed through the marshaller, the marshaller checks whether the interface is coming from a known object. This check occurs in two situations: + +- An interface is being implemented by another managed object that was passed to COM elsewhere. The marshaller can readily identify interfaces exposed by managed objects and is able to match the interface with the managed object that provides the implementation. The managed object is then passed to the method and no wrapper is needed. + +- An object that has already been wrapped is implementing the interface. To determine whether this is the case, the marshaller queries the object for its `IUnknown` interface and compares the returned interface to the interfaces of other objects that are already wrapped. If the interface is the same as that of another wrapper, the objects have the same identity and the existing wrapper is passed to the method. + + If an interface is not from a known object, the marshaller does the following: + +1. The marshaller queries the object for the **IProvideClassInfo2** interface. If provided, the marshaller uses the CLSID returned from **IProvideClassInfo2.GetGUID** to identify the coclass providing the interface. With the CLSID, the marshaller can locate the wrapper from the registry if the assembly has previously been registered. + +2. The marshaller queries the interface for the `IProvideClassInfo` interface. If provided, the marshaller uses the `ITypeInfo` returned from **IProvideClassInfo.GetClassinfo** to determine the CLSID of the class exposing the interface. The marshaller can use the CLSID to locate the metadata for the wrapper. + +3. If the marshaller still cannot identify the class, it wraps the interface with a generic wrapper class called **System.__ComObject**. + +## Default marshalling for delegates + + A managed delegate is marshalled as a COM interface or as a function pointer, based on the calling mechanism: + +- For platform invoke, a delegate is marshalled as an unmanaged function pointer by default. + +- For COM interop, a delegate is marshalled as a COM interface of type `_Delegate` by default. The `_Delegate` interface is defined in the Mscorlib.tlb type library and contains the method, which enables you to call the method that the delegate references. + + The following table shows the marshalling options for the managed delegate data type. The attribute provides several enumeration values to marshal delegates. + +|Enumeration type|Description of unmanaged format| +|----------------------|-------------------------------------| +|**UnmanagedType.FunctionPtr**|An unmanaged function pointer.| +|**UnmanagedType.Interface**|An interface of type **_Delegate**, as defined in Mscorlib.tlb.| + + Consider the following example code in which the methods of `DelegateTestInterface` are exported to a COM type library. Notice that only delegates marked with the `ref` (or **ByRef**) keyword are passed as In/Out parameters. + +```csharp +using System; +using System.Runtime.InteropServices; + +public interface DelegateTest { +void m1(Delegate d); void m2([MarshalAs(UnmanagedType.Interface)] Delegate d); void m3([MarshalAs(UnmanagedType.Interface)] ref Delegate d); void m4([MarshalAs(UnmanagedType.FunctionPtr)] Delegate d); void m5([MarshalAs(UnmanagedType.FunctionPtr)] ref Delegate d); -} -``` - -### Type library representation - -```cpp -importlib("mscorlib.tlb"); -interface DelegateTest : IDispatch { -[id(…)] HRESULT m1([in] _Delegate* d); -[id(…)] HRESULT m2([in] _Delegate* d); -[id(…)] HRESULT m3([in, out] _Delegate** d); -[id()] HRESULT m4([in] int d); -[id()] HRESULT m5([in, out] int *d); - }; -``` - - A function pointer can be dereferenced, just as any other unmanaged function pointer can be dereferenced. +} +``` + +### Type library representation + +```cpp +importlib("mscorlib.tlb"); +interface DelegateTest : IDispatch { +[id(…)] HRESULT m1([in] _Delegate* d); +[id(…)] HRESULT m2([in] _Delegate* d); +[id(…)] HRESULT m3([in, out] _Delegate** d); +[id()] HRESULT m4([in] int d); +[id()] HRESULT m5([in, out] int *d); + }; +``` + + A function pointer can be dereferenced, just as any other unmanaged function pointer can be dereferenced. In this example, when the two delegates are marshalled as , the result is an `int` and a pointer to an `int`. Because delegate types are being marshalled, `int` here represents a pointer to a void (`void*`), which is the address of the delegate in memory. In other words, this result is specific to 32-bit Windows systems, since `int` here represents the size of the function pointer. > [!NOTE] -> A reference to the function pointer to a managed delegate held by unmanaged code does not prevent the common language runtime from performing garbage collection on the managed object. - - For example, the following code is incorrect because the reference to the `cb` object, passed to the `SetChangeHandler` method, does not keep `cb` alive beyond the life of the `Test` method. Once the `cb` object is garbage collected, the function pointer passed to `SetChangeHandler` is no longer valid. - -```csharp -public class ExternalAPI { - [DllImport("External.dll")] - public static extern void SetChangeHandler( - [MarshalAs(UnmanagedType.FunctionPtr)]ChangeDelegate d); -} -public delegate bool ChangeDelegate([MarshalAs(UnmanagedType.LPWStr) string S); -public class CallBackClass { - public bool OnChange(string S){ return true;} -} -internal class DelegateTest { - public static void Test() { - CallBackClass cb = new CallBackClass(); +> A reference to the function pointer to a managed delegate held by unmanaged code does not prevent the common language runtime from performing garbage collection on the managed object. + + For example, the following code is incorrect because the reference to the `cb` object, passed to the `SetChangeHandler` method, does not keep `cb` alive beyond the life of the `Test` method. Once the `cb` object is garbage collected, the function pointer passed to `SetChangeHandler` is no longer valid. + +```csharp +public class ExternalAPI { + [DllImport("External.dll")] + public static extern void SetChangeHandler( + [MarshalAs(UnmanagedType.FunctionPtr)]ChangeDelegate d); +} +public delegate bool ChangeDelegate([MarshalAs(UnmanagedType.LPWStr) string S); +public class CallBackClass { + public bool OnChange(string S){ return true;} +} +internal class DelegateTest { + public static void Test() { + CallBackClass cb = new CallBackClass(); // Caution: The following reference on the cb object does not keep the // object from being garbage collected after the Main method - // executes. + // executes. ExternalAPI.SetChangeHandler(new ChangeDelegate(cb.OnChange)); - } -} -``` - - To compensate for unexpected garbage collection, the caller must ensure that the `cb` object is kept alive as long as the unmanaged function pointer is in use. Optionally, you can have the unmanaged code notify the managed code when the function pointer is no longer needed, as the following example shows. - -```csharp -internal class DelegateTest { - CallBackClass cb; - // Called before ever using the callback function. - public static void SetChangeHandler() { - cb = new CallBackClass(); - ExternalAPI.SetChangeHandler(new ChangeDelegate(cb.OnChange)); - } - // Called after using the callback function for the last time. - public static void RemoveChangeHandler() { + } +} +``` + + To compensate for unexpected garbage collection, the caller must ensure that the `cb` object is kept alive as long as the unmanaged function pointer is in use. Optionally, you can have the unmanaged code notify the managed code when the function pointer is no longer needed, as the following example shows. + +```csharp +internal class DelegateTest { + CallBackClass cb; + // Called before ever using the callback function. + public static void SetChangeHandler() { + cb = new CallBackClass(); + ExternalAPI.SetChangeHandler(new ChangeDelegate(cb.OnChange)); + } + // Called after using the callback function for the last time. + public static void RemoveChangeHandler() { // The cb object can be collected now. The unmanaged code is - // finished with the callback function. - cb = null; - } -} -``` - -## Default marshalling for value types - - Most value types, such as integers and floating-point numbers, are [blittable](blittable-and-non-blittable-types.md) and do not require marshalling. Other [non-blittable](blittable-and-non-blittable-types.md) types have dissimilar representations in managed and unmanaged memory and do require marshalling. Still other types require explicit formatting across the interoperation boundary. - - This section provides information on the following formatted value types: - -- [Value Types Used in Platform Invoke](#value-types-used-in-platform-invoke) - -- [Value Types Used in COM Interop](#value-types-used-in-com-interop) - - In addition to describing formatted types, this topic identifies [System Value Types](#system-value-types) that have unusual marshalling behavior. - - A formatted type is a complex type that contains information that explicitly controls the layout of its members in memory. The member layout information is provided using the attribute. The layout can be one of the following enumeration values: - -- **LayoutKind.Auto** - - Indicates that the common language runtime is free to reorder the members of the type for efficiency. However, when a value type is passed to unmanaged code, the layout of the members is predictable. An attempt to marshal such a structure automatically causes an exception. - -- **LayoutKind.Sequential** - - Indicates that the members of the type are to be laid out in unmanaged memory in the same order in which they appear in the managed type definition. - -- **LayoutKind.Explicit** - - Indicates that the members are laid out according to the supplied with each field. - -### Value Types Used in Platform Invoke - - In the following example the `Point` and `Rect` types provide member layout information using the **StructLayoutAttribute**. - -```vb -Imports System.Runtime.InteropServices - Public Structure Point - Public x As Integer - Public y As Integer -End Structure - Public Structure Rect - Public left As Integer - Public top As Integer - Public right As Integer - Public bottom As Integer -End Structure -``` - -```csharp -using System.Runtime.InteropServices; -[StructLayout(LayoutKind.Sequential)] -public struct Point { - public int x; - public int y; + // finished with the callback function. + cb = null; + } +} +``` + +## Default marshalling for value types + + Most value types, such as integers and floating-point numbers, are [blittable](blittable-and-non-blittable-types.md) and do not require marshalling. Other [non-blittable](blittable-and-non-blittable-types.md) types have dissimilar representations in managed and unmanaged memory and do require marshalling. Still other types require explicit formatting across the interoperation boundary. + + This section provides information on the following formatted value types: + +- [Value Types Used in Platform Invoke](#value-types-used-in-platform-invoke) + +- [Value Types Used in COM Interop](#value-types-used-in-com-interop) + + In addition to describing formatted types, this topic identifies [System Value Types](#system-value-types) that have unusual marshalling behavior. + + A formatted type is a complex type that contains information that explicitly controls the layout of its members in memory. The member layout information is provided using the attribute. The layout can be one of the following enumeration values: + +- **LayoutKind.Auto** + + Indicates that the common language runtime is free to reorder the members of the type for efficiency. However, when a value type is passed to unmanaged code, the layout of the members is predictable. An attempt to marshal such a structure automatically causes an exception. + +- **LayoutKind.Sequential** + + Indicates that the members of the type are to be laid out in unmanaged memory in the same order in which they appear in the managed type definition. + +- **LayoutKind.Explicit** + + Indicates that the members are laid out according to the supplied with each field. + +### Value Types Used in Platform Invoke + + In the following example the `Point` and `Rect` types provide member layout information using the **StructLayoutAttribute**. + +```vb +Imports System.Runtime.InteropServices + Public Structure Point + Public x As Integer + Public y As Integer +End Structure + Public Structure Rect + Public left As Integer + Public top As Integer + Public right As Integer + Public bottom As Integer +End Structure +``` + +```csharp +using System.Runtime.InteropServices; +[StructLayout(LayoutKind.Sequential)] +public struct Point { + public int x; + public int y; +} + +[StructLayout(LayoutKind.Explicit)] +public struct Rect { + [FieldOffset(0)] public int left; + [FieldOffset(4)] public int top; + [FieldOffset(8)] public int right; + [FieldOffset(12)] public int bottom; } - -[StructLayout(LayoutKind.Explicit)] -public struct Rect { - [FieldOffset(0)] public int left; - [FieldOffset(4)] public int top; - [FieldOffset(8)] public int right; - [FieldOffset(12)] public int bottom; -} -``` - - When marshalled to unmanaged code, these formatted types are marshalled as C-style structures. This provides an easy way of calling an unmanaged API that has structure arguments. For example, the `POINT` and `RECT` structures can be passed to the Microsoft Windows API **PtInRect** function as follows: - -```cpp -BOOL PtInRect(const RECT *lprc, POINT pt); -``` - - You can pass structures using the following platform invoke definition: - +``` + + When marshalled to unmanaged code, these formatted types are marshalled as C-style structures. This provides an easy way of calling an unmanaged API that has structure arguments. For example, the `POINT` and `RECT` structures can be passed to the Microsoft Windows API `PtInRect` function as follows: + +```cpp +BOOL PtInRect(const RECT *lprc, POINT pt); +``` + + You can pass structures using the following platform invoke definition: + ```vb Friend Class NativeMethods Friend Declare Auto Function PtInRect Lib "User32.dll" ( ByRef r As Rect, p As Point) As Boolean End Class ``` - + ```csharp internal static class NativeMethods { @@ -243,61 +243,61 @@ internal static class NativeMethods internal static extern bool PtInRect(ref Rect r, Point p); } ``` - - The `Rect` value type must be passed by reference because the unmanaged API is expecting a pointer to a `RECT` to be passed to the function. The `Point` value type is passed by value because the unmanaged API expects the `POINT` to be passed on the stack. This subtle difference is very important. References are passed to unmanaged code as pointers. Values are passed to unmanaged code on the stack. - + + The `Rect` value type must be passed by reference because the unmanaged API is expecting a pointer to a `RECT` to be passed to the function. The `Point` value type is passed by value because the unmanaged API expects the `POINT` to be passed on the stack. This subtle difference is very important. References are passed to unmanaged code as pointers. Values are passed to unmanaged code on the stack. + > [!NOTE] -> When a formatted type is marshalled as a structure, only the fields within the type are accessible. If the type has methods, properties, or events, they are inaccessible from unmanaged code. - - Classes can also be marshalled to unmanaged code as C-style structures, provided they have fixed member layout. The member layout information for a class is also provided with the attribute. The main difference between value types with fixed layout and classes with fixed layout is the way in which they are marshalled to unmanaged code. Value types are passed by value (on the stack) and consequently any changes made to the members of the type by the callee are not seen by the caller. Reference types are passed by reference (a reference to the type is passed on the stack); consequently, all changes made to blittable-type members of a type by the callee are seen by the caller. - +> When a formatted type is marshalled as a structure, only the fields within the type are accessible. If the type has methods, properties, or events, they are inaccessible from unmanaged code. + + Classes can also be marshalled to unmanaged code as C-style structures, provided they have fixed member layout. The member layout information for a class is also provided with the attribute. The main difference between value types with fixed layout and classes with fixed layout is the way in which they are marshalled to unmanaged code. Value types are passed by value (on the stack) and consequently any changes made to the members of the type by the callee are not seen by the caller. Reference types are passed by reference (a reference to the type is passed on the stack); consequently, all changes made to blittable-type members of a type by the callee are seen by the caller. + > [!NOTE] -> If a reference type has members of non-blittable types, conversion is required twice: the first time when an argument is passed to the unmanaged side and the second time on return from the call. Due to this added overhead, In/Out parameters must be explicitly applied to an argument if the caller wants to see changes made by the callee. - - In the following example, the `SystemTime` class has sequential member layout and can be passed to the Windows API **GetSystemTime** function. - -```vb - Public Class SystemTime - Public wYear As System.UInt16 - Public wMonth As System.UInt16 - Public wDayOfWeek As System.UInt16 - Public wDay As System.UInt16 - Public wHour As System.UInt16 - Public wMinute As System.UInt16 - Public wSecond As System.UInt16 - Public wMilliseconds As System.UInt16 -End Class -``` - -```csharp -[StructLayout(LayoutKind.Sequential)] - public class SystemTime { +> If a reference type has members of non-blittable types, conversion is required twice: the first time when an argument is passed to the unmanaged side and the second time on return from the call. Due to this added overhead, In/Out parameters must be explicitly applied to an argument if the caller wants to see changes made by the callee. + + In the following example, the `SystemTime` class has sequential member layout and can be passed to the Windows API `GetSystemTime` function. + +```vb + Public Class SystemTime + Public wYear As System.UInt16 + Public wMonth As System.UInt16 + Public wDayOfWeek As System.UInt16 + Public wDay As System.UInt16 + Public wHour As System.UInt16 + Public wMinute As System.UInt16 + Public wSecond As System.UInt16 + Public wMilliseconds As System.UInt16 +End Class +``` + +```csharp +[StructLayout(LayoutKind.Sequential)] + public class SystemTime { public ushort wYear; - public ushort wMonth; + public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMilliseconds; -} -``` - - The **GetSystemTime** function is defined as follows: - -```cpp -void GetSystemTime(SYSTEMTIME* SystemTime); -``` - - The equivalent platform invoke definition for **GetSystemTime** is as follows: - +} +``` + + The `GetSystemTime` function is defined as follows: + +```cpp +void GetSystemTime(SYSTEMTIME* SystemTime); +``` + + The equivalent platform invoke definition for `GetSystemTime` is as follows: + ```vb Friend Class NativeMethods Friend Declare Auto Sub GetSystemTime Lib "Kernel32.dll" ( ByVal sysTime As SystemTime) End Class ``` - + ```csharp internal static class NativeMethods { @@ -305,143 +305,143 @@ internal static class NativeMethods internal static extern void GetSystemTime(SystemTime st); } ``` - - Notice that the `SystemTime` argument is not typed as a reference argument because `SystemTime` is a class, not a value type. Unlike value types, classes are always passed by reference. - - The following code example shows a different `Point` class that has a method called `SetXY`. Because the type has sequential layout, it can be passed to unmanaged code and marshalled as a structure. However, the `SetXY` member is not callable from unmanaged code, even though the object is passed by reference. - -```vb - Public Class Point - Private x, y As Integer - Public Sub SetXY(x As Integer, y As Integer) - Me.x = x - Me.y = y - End Sub -End Class -``` - -```csharp -[StructLayout(LayoutKind.Sequential)] -public class Point { - int x, y; + + Notice that the `SystemTime` argument is not typed as a reference argument because `SystemTime` is a class, not a value type. Unlike value types, classes are always passed by reference. + + The following code example shows a different `Point` class that has a method called `SetXY`. Because the type has sequential layout, it can be passed to unmanaged code and marshalled as a structure. However, the `SetXY` member is not callable from unmanaged code, even though the object is passed by reference. + +```vb + Public Class Point + Private x, y As Integer + Public Sub SetXY(x As Integer, y As Integer) + Me.x = x + Me.y = y + End Sub +End Class +``` + +```csharp +[StructLayout(LayoutKind.Sequential)] +public class Point { + int x, y; public void SetXY(int x, int y){ - this.x = x; - this.y = y; - } -} -``` - -### Value Types Used in COM Interop - - Formatted types can also be passed to COM interop method calls. In fact, when exported to a type library, value types are automatically converted to structures. As the following example shows, the `Point` value type becomes a type definition (typedef) with the name `Point`. All references to the `Point` value type elsewhere in the type library are replaced with the `Point` typedef. - - **Type library representation** - -```cpp -typedef struct tagPoint { - int x; - int y; -} Point; -interface _Graphics { - … - HRESULT SetPoint ([in] Point p) - HRESULT SetPointRef ([in,out] Point *p) - HRESULT GetPoint ([out,retval] Point *p) -} -``` - - The same rules used to marshal values and references to platform invoke calls are used when marshalling through COM interfaces. For example, when an instance of the `Point` value type is passed from the .NET Framework to COM, the `Point` is passed by value. If the `Point` value type is passed by reference, a pointer to a `Point` is passed on the stack. The interop marshaller does not support higher levels of indirection (**Point** \*\*) in either direction. - + this.x = x; + this.y = y; + } +} +``` + +### Value Types Used in COM Interop + + Formatted types can also be passed to COM interop method calls. In fact, when exported to a type library, value types are automatically converted to structures. As the following example shows, the `Point` value type becomes a type definition (typedef) with the name `Point`. All references to the `Point` value type elsewhere in the type library are replaced with the `Point` typedef. + + **Type library representation** + +```cpp +typedef struct tagPoint { + int x; + int y; +} Point; +interface _Graphics { + … + HRESULT SetPoint ([in] Point p) + HRESULT SetPointRef ([in,out] Point *p) + HRESULT GetPoint ([out,retval] Point *p) +} +``` + + The same rules used to marshal values and references to platform invoke calls are used when marshalling through COM interfaces. For example, when an instance of the `Point` value type is passed from the .NET Framework to COM, the `Point` is passed by value. If the `Point` value type is passed by reference, a pointer to a `Point` is passed on the stack. The interop marshaller does not support higher levels of indirection (**Point** \*\*) in either direction. + > [!NOTE] -> Structures having the enumeration value set to **Explicit** cannot be used in COM interop because the exported type library cannot express an explicit layout. - -### System Value Types - - The namespace has several value types that represent the boxed form of the runtime primitive types. For example, the value type structure represents the boxed form of **ELEMENT_TYPE_I4**. Instead of marshalling these types as structures, as other formatted types are, you marshal them in the same way as the primitive types they box. **System.Int32** is therefore marshalled as **ELEMENT_TYPE_I4** instead of as a structure containing a single member of type **long**. The following table contains a list of the value types in the **System** namespace that are boxed representations of primitive types. - -|System value type|Element type| -|-----------------------|------------------| -||**ELEMENT_TYPE_BOOLEAN**| -||**ELEMENT_TYPE_I1**| -||**ELEMENT_TYPE_UI1**| -||**ELEMENT_TYPE_CHAR**| -||**ELEMENT_TYPE_I2**| -||**ELEMENT_TYPE_U2**| -||**ELEMENT_TYPE_I4**| -||**ELEMENT_TYPE_U4**| -||**ELEMENT_TYPE_I8**| -||**ELEMENT_TYPE_U8**| -||**ELEMENT_TYPE_R4**| -||**ELEMENT_TYPE_R8**| -||**ELEMENT_TYPE_STRING**| -||**ELEMENT_TYPE_I**| -||**ELEMENT_TYPE_U**| - - Some other value types in the **System** namespace are handled differently. Because the unmanaged code already has well-established formats for these types, the marshaller has special rules for marshalling them. The following table lists the special value types in the **System** namespace, as well as the unmanaged type they are marshalled to. - -|System value type|IDL type| -|-----------------------|--------------| -||**DATE**| -||**DECIMAL**| -||**GUID**| -||**OLE_COLOR**| - - The following code shows the definition of the unmanaged types **DATE**, **GUID**, **DECIMAL**, and **OLE_COLOR** in the Stdole2 type library. - -#### Type library representation - -```cpp -typedef double DATE; -typedef DWORD OLE_COLOR; - -typedef struct tagDEC { - USHORT wReserved; - BYTE scale; - BYTE sign; - ULONG Hi32; - ULONGLONG Lo64; -} DECIMAL; - -typedef struct tagGUID { - DWORD Data1; - WORD Data2; - WORD Data3; - BYTE Data4[ 8 ]; -} GUID; -``` - - The following code shows the corresponding definitions in the managed `IValueTypes` interface. - -```vb -Public Interface IValueTypes - Sub M1(d As System.DateTime) - Sub M2(d As System.Guid) - Sub M3(d As System.Decimal) - Sub M4(d As System.Drawing.Color) -End Interface -``` - -```csharp -public interface IValueTypes { - void M1(System.DateTime d); - void M2(System.Guid d); - void M3(System.Decimal d); - void M4(System.Drawing.Color d); -} -``` - -#### Type library representation - -```cpp -[…] -interface IValueTypes : IDispatch { - HRESULT M1([in] DATE d); - HRESULT M2([in] GUID d); - HRESULT M3([in] DECIMAL d); - HRESULT M4([in] OLE_COLOR d); -}; -``` - +> Structures having the enumeration value set to `Explicit` cannot be used in COM interop because the exported type library cannot express an explicit layout. + +### System Value Types + + The namespace has several value types that represent the boxed form of the runtime primitive types. For example, the value type structure represents the boxed form of **ELEMENT_TYPE_I4**. Instead of marshalling these types as structures, as other formatted types are, you marshal them in the same way as the primitive types they box. **System.Int32** is therefore marshalled as **ELEMENT_TYPE_I4** instead of as a structure containing a single member of type **long**. The following table contains a list of the value types in the `System` namespace that are boxed representations of primitive types. + +|System value type|Element type| +|-----------------------|------------------| +||**ELEMENT_TYPE_BOOLEAN**| +||**ELEMENT_TYPE_I1**| +||**ELEMENT_TYPE_UI1**| +||**ELEMENT_TYPE_CHAR**| +||**ELEMENT_TYPE_I2**| +||**ELEMENT_TYPE_U2**| +||**ELEMENT_TYPE_I4**| +||**ELEMENT_TYPE_U4**| +||**ELEMENT_TYPE_I8**| +||**ELEMENT_TYPE_U8**| +||**ELEMENT_TYPE_R4**| +||**ELEMENT_TYPE_R8**| +||**ELEMENT_TYPE_STRING**| +||**ELEMENT_TYPE_I**| +||**ELEMENT_TYPE_U**| + + Some other value types in the `System` namespace are handled differently. Because the unmanaged code already has well-established formats for these types, the marshaller has special rules for marshalling them. The following table lists the special value types in the `System` namespace, as well as the unmanaged type they are marshalled to. + +|System value type|IDL type| +|-----------------------|--------------| +||**DATE**| +||**DECIMAL**| +||**GUID**| +||**OLE_COLOR**| + + The following code shows the definition of the unmanaged types **DATE**, **GUID**, **DECIMAL**, and `OLE_COLOR` in the Stdole2 type library. + +#### Type library representation + +```cpp +typedef double DATE; +typedef DWORD OLE_COLOR; + +typedef struct tagDEC { + USHORT wReserved; + BYTE scale; + BYTE sign; + ULONG Hi32; + ULONGLONG Lo64; +} DECIMAL; + +typedef struct tagGUID { + DWORD Data1; + WORD Data2; + WORD Data3; + BYTE Data4[ 8 ]; +} GUID; +``` + + The following code shows the corresponding definitions in the managed `IValueTypes` interface. + +```vb +Public Interface IValueTypes + Sub M1(d As System.DateTime) + Sub M2(d As System.Guid) + Sub M3(d As System.Decimal) + Sub M4(d As System.Drawing.Color) +End Interface +``` + +```csharp +public interface IValueTypes { + void M1(System.DateTime d); + void M2(System.Guid d); + void M3(System.Decimal d); + void M4(System.Drawing.Color d); +} +``` + +#### Type library representation + +```cpp +[…] +interface IValueTypes : IDispatch { + HRESULT M1([in] DATE d); + HRESULT M2([in] GUID d); + HRESULT M3([in] DECIMAL d); + HRESULT M4([in] OLE_COLOR d); +}; +``` + ## See also - [Blittable and Non-Blittable Types](blittable-and-non-blittable-types.md) diff --git a/docs/framework/interop/default-marshalling-for-arrays.md b/docs/framework/interop/default-marshalling-for-arrays.md index 88c61a078c49b..fed2c00de0252 100644 --- a/docs/framework/interop/default-marshalling-for-arrays.md +++ b/docs/framework/interop/default-marshalling-for-arrays.md @@ -26,11 +26,11 @@ In an application consisting entirely of managed code, the common language runti As the following table shows, any instance of a managed array must be of a specific element type, rank, and lower bound. -|Managed array type|Element type|Rank|Lower bound|Signature notation| -|------------------------|------------------|----------|-----------------|------------------------| -|**ELEMENT_TYPE_ARRAY**|Specified by type.|Specified by rank.|Optionally specified by bounds.|*type* **[** *n*,*m* **]**| -|**ELEMENT_TYPE_CLASS**|Unknown|Unknown|Unknown|**System.Array**| -|**ELEMENT_TYPE_SZARRAY**|Specified by type.|1|0|*type* **[** *n* **]**| +| Managed array type | Element type | Rank | Lower bound | Signature notation | +|--------------------------|-------------------|---------|-------------|------------------------| +| **ELEMENT_TYPE_ARRAY** | Specified by type | Specified by rank | Optionally specified by bounds | *type* **[** *n*,*m* **]** | +| **ELEMENT_TYPE_CLASS** | Unknown | Unknown | Unknown | **System.Array** | +| **ELEMENT_TYPE_SZARRAY** | Specified by type | 1 | 0 | *type* **[** *n* **]** | ## Unmanaged Arrays @@ -40,14 +40,14 @@ In an application consisting entirely of managed code, the common language runti Both C-style arrays and safe arrays can be passed to .NET code from unmanaged code as either a safe array or a C-style array. The following table shows the unmanaged type value and the imported type. -|Unmanaged type|Imported type| -|--------------------|-------------------| +| Unmanaged type | Imported type | +|----------------|---------------| |**SafeArray(** *Type* **)**|**ELEMENT_TYPE_SZARRAY** **\<** *ConvertedType* **>**

Rank = 1, lower bound = 0. Size is known only if provided in the managed signature. Safe arrays that are not rank = 1 or lower bound = 0 cannot be marshalled as **SZARRAY**.| |*Type* **[]**|**ELEMENT_TYPE_SZARRAY** **\<** *ConvertedType* **>**

Rank = 1, lower bound = 0. Size is known only if provided in the managed signature.| ### Safe Arrays - When a safe array is imported from a type library to a .NET assembly, the array is converted to a one-dimensional array of a known type (such as **int**). The same type conversion rules that apply to parameters also apply to array elements. For example, a safe array of **BSTR** types becomes a managed array of strings and a safe array of variants becomes a managed array of objects. The **SAFEARRAY** element type is captured from the type library and saved in the **SAFEARRAY** value of the enumeration. + When a safe array is imported from a type library to a .NET assembly, the array is converted to a one-dimensional array of a known type (such as **int**). The same type conversion rules that apply to parameters also apply to array elements. For example, a safe array of `BSTR` types becomes a managed array of strings and a safe array of variants becomes a managed array of objects. The `SAFEARRAY` element type is captured from the type library and saved in the `SAFEARRAY` value of the enumeration. Because the rank and bounds of the safe array cannot be determined from the type library, the rank is assumed to equal 1 and the lower bound is assumed to equal 0. The rank and bounds must be defined in the managed signature produced by the [Type Library Importer (Tlbimp.exe)](../tools/tlbimp-exe-type-library-importer.md). If the rank passed to the method at run time differs, a is thrown. If the type of the array passed at run time differs, a is thrown. The following example shows safe arrays in managed and unmanaged code. @@ -78,17 +78,17 @@ void New3([MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VT_BSTR)] ref String[] ar); ``` - Multidimensional, or nonzero-bound safe arrays, can be marshalled into managed code if the method signature produced by Tlbimp.exe is modified to indicate an element type of **ELEMENT_TYPE_ARRAY** instead of **ELEMENT_TYPE_SZARRAY**. Alternatively, you can use the **/sysarray** switch with Tlbimp.exe to import all arrays as objects. In cases where the array being passed is known to be multidimensional, you can edit the common intermediate language (CIL) code produced by Tlbimp.exe and then recompile it. For details about how to modify CIL code, see [Customizing Runtime Callable Wrappers](/previous-versions/dotnet/netframework-4.0/e753eftz(v=vs.100)). + Multidimensional, or nonzero-bound safe arrays, can be marshalled into managed code if the method signature produced by Tlbimp.exe is modified to indicate an element type of `ELEMENT_TYPE_ARRAY` instead of **ELEMENT_TYPE_SZARRAY**. Alternatively, you can use the **/sysarray** switch with Tlbimp.exe to import all arrays as objects. In cases where the array being passed is known to be multidimensional, you can edit the common intermediate language (CIL) code produced by Tlbimp.exe and then recompile it. For details about how to modify CIL code, see [Customizing Runtime Callable Wrappers](/previous-versions/dotnet/netframework-4.0/e753eftz(v=vs.100)). ### C-Style Arrays When a C-style array is imported from a type library to a .NET assembly, the array is converted to **ELEMENT_TYPE_SZARRAY**. - The array element type is determined from the type library and preserved during the import. The same conversion rules that apply to parameters also apply to array elements. For example, an array of **LPStr** types becomes an array of **String** types. Tlbimp.exe captures the array element type and applies the attribute to the parameter. + The array element type is determined from the type library and preserved during the import. The same conversion rules that apply to parameters also apply to array elements. For example, an array of `LPStr` types becomes an array of `String` types. Tlbimp.exe captures the array element type and applies the attribute to the parameter. The array rank is assumed to equal 1. If the rank is greater than 1, the array is marshalled as a one-dimensional array in column-major order. The lower bound always equals 0. - Type libraries can contain arrays of fixed or variable length. Tlbimp.exe can import only fixed-length arrays from type libraries because type libraries lack the information needed to marshal variable-length arrays. With fixed-length arrays, the size is imported from the type library and captured in the **MarshalAsAttribute** that is applied to the parameter. + Type libraries can contain arrays of fixed or variable length. Tlbimp.exe can import only fixed-length arrays from type libraries because type libraries lack the information needed to marshal variable-length arrays. With fixed-length arrays, the size is imported from the type library and captured in the `MarshalAsAttribute` that is applied to the parameter. You must manually define type libraries containing variable-length arrays, as shown in the following example. @@ -119,7 +119,7 @@ void New2([MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.LPWStr, SizeConst=10)] String[] ar); ``` - Although you can apply the **size_is** or **length_is** attributes to an array in Interface Definition Language (IDL) source to convey the size to a client, the Microsoft Interface Definition Language (MIDL) compiler does not propagate that information to the type library. Without knowing the size, the interop marshalling service cannot marshal the array elements. Consequently, variable-length arrays are imported as reference arguments. For example: + Although you can apply the `size_is` or `length_is` attributes to an array in Interface Definition Language (IDL) source to convey the size to a client, the Microsoft Interface Definition Language (MIDL) compiler does not propagate that information to the type library. Without knowing the size, the interop marshalling service cannot marshal the array elements. Consequently, variable-length arrays are imported as reference arguments. For example: **Unmanaged signature** @@ -149,7 +149,7 @@ void New3(ref String ar); ```vb Sub [New](ElemCnt As Integer, _ - \ _ + _ ar() As Integer) ``` @@ -162,7 +162,7 @@ void New3(ref String ar); - Define the size of the array as a constant. For example: ```vb - Sub [New](\ _ + Sub [New]( _ ar() As Integer) ``` @@ -171,12 +171,12 @@ void New3(ref String ar); [MarshalAs(UnmanagedType.LPArray, SizeConst=128)] int[] ar ); ``` - When marshalling arrays from unmanaged code to managed code, the marshaller checks the **MarshalAsAttribute** associated with the parameter to determine the array size. If the array size is not specified, only one element is marshalled. + When marshalling arrays from unmanaged code to managed code, the marshaller checks the `MarshalAsAttribute` associated with the parameter to determine the array size. If the array size is not specified, only one element is marshalled. > [!NOTE] -> The **MarshalAsAttribute** has no effect on marshalling managed arrays to unmanaged code. In that direction, the array size is determined by examination. There is no way to marshal a subset of a managed array. +> The `MarshalAsAttribute` has no effect on marshalling managed arrays to unmanaged code. In that direction, the array size is determined by examination. There is no way to marshal a subset of a managed array. - The interop marshaller uses the **CoTaskMemAlloc** and **CoTaskMemFree** methods on Windows or **malloc** and **free** methods on other operating systems to allocate and retrieve memory. Memory allocation performed by unmanaged code must also use these methods. + The interop marshaller uses the `CoTaskMemAlloc` and `CoTaskMemFree` methods on Windows or `malloc` and `free` methods on other operating systems to allocate and retrieve memory. Memory allocation performed by unmanaged code must also use these methods. ## Passing Arrays to COM @@ -188,11 +188,11 @@ void New3(ref String ar); |**ELEMENT_TYPE_ARRAY** **\<** *type* **>** **\<** *rank* **>**[**\<** *bounds* **>**]|**UnmanagedType.SafeArray(** *type* **)**

**UnmanagedType.LPArray**

Type, rank, bounds are provided in the signature. Size is always known at run time.| |**ELEMENT_TYPE_CLASS** **\<****>**|**UT_Interface**

**UnmanagedType.SafeArray(** *type* **)**

Type, rank, bounds, and size are always known at run time.| - There is a limitation in OLE Automation relating to arrays of structures that contain LPSTR or LPWSTR. Therefore, **String** fields have to be marshalled as **UnmanagedType.BSTR**. Otherwise, an exception will be thrown. + There is a limitation in OLE Automation relating to arrays of structures that contain LPSTR or LPWSTR. Therefore, `String` fields have to be marshalled as **UnmanagedType.BSTR**. Otherwise, an exception will be thrown. ### ELEMENT_TYPE_SZARRAY - When a method containing an **ELEMENT_TYPE_SZARRAY** parameter (one-dimensional array) is exported from a .NET assembly to a type library, the array parameter is converted to a **SAFEARRAY** of a given type. The same conversion rules apply to the array element types. The contents of the managed array are automatically copied from managed memory into the **SAFEARRAY**. For example: + When a method containing an `ELEMENT_TYPE_SZARRAY` parameter (one-dimensional array) is exported from a .NET assembly to a type library, the array parameter is converted to a `SAFEARRAY` of a given type. The same conversion rules apply to the array element types. The contents of the managed array are automatically copied from managed memory into the **SAFEARRAY**. For example: #### Managed signature @@ -251,7 +251,7 @@ HRESULT New(LPStr ar[]); ### ELEMENT_TYPE_ARRAY - When a method containing an **ELEMENT_TYPE_ARRAY** parameter is exported from a .NET assembly to a type library, the array parameter is converted to a **SAFEARRAY** of a given type. The contents of the managed array are automatically copied from managed memory into the **SAFEARRAY**. For example: + When a method containing an `ELEMENT_TYPE_ARRAY` parameter is exported from a .NET assembly to a type library, the array parameter is converted to a `SAFEARRAY` of a given type. The contents of the managed array are automatically copied from managed memory into the **SAFEARRAY**. For example: #### Managed signature @@ -315,7 +315,7 @@ void New(long [][][] ar ); ### ELEMENT_TYPE_CLASS \ - When a method containing a parameter is exported from a .NET assembly to a type library, the array parameter is converted to an **_Array** interface. The contents of the managed array are accessible only through the methods and properties of the **_Array** interface. **System.Array** can also be marshalled as a **SAFEARRAY** by using the attribute. When marshalled as a safe array, the array elements are marshalled as variants. For example: + When a method containing a parameter is exported from a .NET assembly to a type library, the array parameter is converted to an `_Array` interface. The contents of the managed array are accessible only through the methods and properties of the `_Array` interface. **System.Array** can also be marshalled as a `SAFEARRAY` by using the attribute. When marshalled as a safe array, the array elements are marshalled as variants. For example: #### Managed signature diff --git a/docs/framework/interop/default-marshalling-for-objects.md b/docs/framework/interop/default-marshalling-for-objects.md index eea2b3596c068..e013d2e4a17c5 100644 --- a/docs/framework/interop/default-marshalling-for-objects.md +++ b/docs/framework/interop/default-marshalling-for-objects.md @@ -18,18 +18,18 @@ Parameters and fields typed as - An interface when the object is a structure field. -Only COM interop supports marshalling for object types. The default behavior is to marshal objects to COM variants. These rules apply only to the type **Object** and do not apply to strongly typed objects that derive from the **Object** class. +Only COM interop supports marshalling for object types. The default behavior is to marshal objects to COM variants. These rules apply only to the type `Object` and do not apply to strongly typed objects that derive from the `Object` class. ## Marshalling Options -The following table shows the marshalling options for the **Object** data type. The attribute provides several enumeration values to marshal objects. +The following table shows the marshalling options for the `Object` data type. The attribute provides several enumeration values to marshal objects. |Enumeration type|Description of unmanaged format| |----------------------|-------------------------------------| |**UnmanagedType.Struct**

(default for parameters)|A COM-style variant.| -|**UnmanagedType.Interface**|An **IDispatch** interface, if possible; otherwise, an **IUnknown** interface.| -|**UnmanagedType.IUnknown**

(default for fields)|An **IUnknown** interface.| -|**UnmanagedType.IDispatch**|An **IDispatch** interface.| +|**UnmanagedType.Interface**|An `IDispatch` interface, if possible; otherwise, an `IUnknown` interface.| +|**UnmanagedType.IUnknown**

(default for fields)|An `IUnknown` interface.| +|**UnmanagedType.IDispatch**|An `IDispatch` interface.| The following example shows the managed interface definition for `MarshalObject`. @@ -111,7 +111,7 @@ struct ObjectHolder { ## Marshalling Object to Interface -When an object is exposed to COM as an interface, that interface is the class interface for the managed type (the **_Object** interface). This interface is typed as an **IDispatch** () or an **IUnknown** (**UnmanagedType.IUnknown**) in the resulting type library. COM clients can dynamically invoke the members of the managed class or any members implemented by its derived classes through the **_Object** interface. The client can also call **QueryInterface** to obtain any other interface explicitly implemented by the managed type. +When an object is exposed to COM as an interface, that interface is the class interface for the managed type (the `_Object` interface). This interface is typed as an `IDispatch` () or an `IUnknown` (**UnmanagedType.IUnknown**) in the resulting type library. COM clients can dynamically invoke the members of the managed class or any members implemented by its derived classes through the `_Object` interface. The client can also call `QueryInterface` to obtain any other interface explicitly implemented by the managed type. ## Marshalling Object to Variant @@ -206,9 +206,9 @@ The wrapper classes are defined in the nam ### Marshalling the IConvertible Interface to Variant -Types other than those listed in the previous section can control how they are marshalled by implementing the interface. If the object implements the **IConvertible** interface, the COM variant type is determined at run time by the value of the enumeration returned from the method. +Types other than those listed in the previous section can control how they are marshalled by implementing the interface. If the object implements the `IConvertible` interface, the COM variant type is determined at run time by the value of the enumeration returned from the method. -The following table shows the possible values for the **TypeCode** enumeration and the corresponding COM variant type for each value. +The following table shows the possible values for the `TypeCode` enumeration and the corresponding COM variant type for each value. |TypeCode|COM variant type| |--------------|----------------------| @@ -237,7 +237,7 @@ The following table shows the possible values for the **TypeCode** enumeration a |Not supported.|**VT_CY**| |Not supported.|**VT_VARIANT**| -The value of the COM variant is determined by calling the **IConvertible.To** *Type* interface, where **To** *Type* is the conversion routine that corresponds to the type that was returned from **IConvertible.GetTypeCode**. For example, an object that returns **TypeCode.Double** from **IConvertible.GetTypeCode** is marshalled as a COM variant of type **VT_R8**. You can obtain the value of the variant (stored in the **dblVal** field of the COM variant) by casting to the **IConvertible** interface and calling the method. +The value of the COM variant is determined by calling the **IConvertible.To** *Type* interface, where `To` *Type* is the conversion routine that corresponds to the type that was returned from **IConvertible.GetTypeCode**. For example, an object that returns **TypeCode.Double** from **IConvertible.GetTypeCode** is marshalled as a COM variant of type **VT_R8**. You can obtain the value of the variant (stored in the `dblVal` field of the COM variant) by casting to the `IConvertible` interface and calling the method. ## Marshalling Variant to Object @@ -271,11 +271,11 @@ When marshalling a variant to an object, the type, and sometimes the value, of t |**VT_RECORD**|Corresponding boxed value type.| |**VT_VARIANT**|Not supported.| -Variant types passed from COM to managed code and then back to COM might not retain the same variant type for the duration of the call. Consider what happens when a variant of type **VT_DISPATCH** is passed from COM to the .NET Framework. During marshalling, the variant is converted to a . If the **Object** is then passed back to COM, it is marshalled back to a variant of type **VT_UNKNOWN**. There is no guarantee that the variant produced when an object is marshalled from managed code to COM will be the same type as the variant initially used to produce the object. +Variant types passed from COM to managed code and then back to COM might not retain the same variant type for the duration of the call. Consider what happens when a variant of type `VT_DISPATCH` is passed from COM to the .NET Framework. During marshalling, the variant is converted to a . If the `Object` is then passed back to COM, it is marshalled back to a variant of type **VT_UNKNOWN**. There is no guarantee that the variant produced when an object is marshalled from managed code to COM will be the same type as the variant initially used to produce the object. ## Marshalling ByRef Variants -Although variants themselves can be passed by value or by reference, the **VT_BYREF** flag can also be used with any variant type to indicate that the contents of the variant are being passed by reference instead of by value. The difference between marshalling variants by reference and marshalling a variant with the **VT_BYREF** flag set can be confusing. The following illustration clarifies the differences: +Although variants themselves can be passed by value or by reference, the `VT_BYREF` flag can also be used with any variant type to indicate that the contents of the variant are being passed by reference instead of by value. The difference between marshalling variants by reference and marshalling a variant with the `VT_BYREF` flag set can be confusing. The following illustration clarifies the differences: ![Diagram that shows variant passed on the stack.](./media/default-marshaling-for-objects/interop-variant-passed-value-reference.gif) Variants passed by value and by reference @@ -288,7 +288,7 @@ Variants passed by value and by reference **Default behavior for marshalling objects and variants by reference** -To propagate changes back to the caller, the parameters must be passed by reference. For example, you can use the **ref** keyword in C# (or **ByRef** in Visual Basic managed code) to pass parameters by reference. In COM, reference parameters are passed using a pointer such as a **variant \***. +To propagate changes back to the caller, the parameters must be passed by reference. For example, you can use the `ref` keyword in C# (or `ByRef` in Visual Basic managed code) to pass parameters by reference. In COM, reference parameters are passed using a pointer such as a **variant \***. - When passing an object to COM by reference, the marshaller creates a new variant and copies the contents of the object reference into the variant before the call is made. The variant is passed to the unmanaged function where the user is free to change the contents of the variant. On return from the call, any changes made to the variant on the unmanaged side are propagated back to the original object. If the type of the variant differs from the type of the variant passed to the call, then the changes are propagated back to an object of a different type. That is, the type of the object passed into the call can differ from the type of the object returned from the call. @@ -296,12 +296,12 @@ To propagate changes back to the caller, the parameters must be passed by refere **Default behavior for marshalling a variant with the VT_BYREF flag set** -- A variant being passed to managed code by value can have the **VT_BYREF** flag set to indicate that the variant contains a reference instead of a value. In this case, the variant is still marshalled to an object because the variant is being passed by value. The marshaller automatically dereferences the contents of the variant and copies it into a newly created object before making the call. The object is then passed into the managed function; however, on return from the call, the object is not propagated back into the original variant. Changes made to the managed object are lost. +- A variant being passed to managed code by value can have the `VT_BYREF` flag set to indicate that the variant contains a reference instead of a value. In this case, the variant is still marshalled to an object because the variant is being passed by value. The marshaller automatically dereferences the contents of the variant and copies it into a newly created object before making the call. The object is then passed into the managed function; however, on return from the call, the object is not propagated back into the original variant. Changes made to the managed object are lost. > [!CAUTION] - > There is no way to change the value of a variant passed by value, even if the variant has the **VT_BYREF** flag set. + > There is no way to change the value of a variant passed by value, even if the variant has the `VT_BYREF` flag set. -- A variant being passed to managed code by reference can also have the **VT_BYREF** flag set to indicate that the variant contains another reference. If it does, the variant is marshalled to a **ref** object because the variant is being passed by reference. The marshaller automatically dereferences the contents of the variant and copies it into a newly created object before making the call. On return from the call, the value of the object is propagated back to the reference within the original variant only if the object is the same type as the object passed in. That is, propagation does not change the type of a variant with the **VT_BYREF** flag set. If the type of the object is changed during the call, an occurs on return from the call. +- A variant being passed to managed code by reference can also have the `VT_BYREF` flag set to indicate that the variant contains another reference. If it does, the variant is marshalled to a `ref` object because the variant is being passed by reference. The marshaller automatically dereferences the contents of the variant and copies it into a newly created object before making the call. On return from the call, the value of the object is propagated back to the reference within the original variant only if the object is the same type as the object passed in. That is, propagation does not change the type of a variant with the `VT_BYREF` flag set. If the type of the object is changed during the call, an occurs on return from the call. The following table summarizes the propagation rules for variants and objects. diff --git a/docs/framework/interop/exposing-dotnet-components-to-com.md b/docs/framework/interop/exposing-dotnet-components-to-com.md index 93e0aa4b5276a..64cd4a5f4a8df 100644 --- a/docs/framework/interop/exposing-dotnet-components-to-com.md +++ b/docs/framework/interop/exposing-dotnet-components-to-com.md @@ -38,7 +38,7 @@ Writing a .NET type and consuming that type from unmanaged code are distinct act 3. [Call a .NET object](/previous-versions/dotnet/netframework-4.0/8hw8h46b(v=vs.100)). - COM developers can call methods on the .NET object the same way they call methods on any unmanaged type. For example, the COM **CoCreateInstance** API activates .NET objects. + COM developers can call methods on the .NET object the same way they call methods on any unmanaged type. For example, the COM `CoCreateInstance` API activates .NET objects. 4. [Deploy an application for COM access](/previous-versions/dotnet/netframework-4.0/c2850st8(v=vs.100)). diff --git a/docs/framework/interop/how-to-implement-callback-functions.md b/docs/framework/interop/how-to-implement-callback-functions.md index 7a9fcdc6aa92d..0ddd05607cca4 100644 --- a/docs/framework/interop/how-to-implement-callback-functions.md +++ b/docs/framework/interop/how-to-implement-callback-functions.md @@ -2,127 +2,127 @@ title: "How to: Implement Callback Functions" description: See how to implement callback functions. In this example, a managed application, using platform invoke, prints the handle value for each window on a computer. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "callback function, implementing" ms.assetid: e55b3712-b9ea-4453-bd9a-ad5cfa2f6bfa --- # How to: Implement callback functions -The following procedure and example demonstrate how a managed application, using platform invoke, can print the handle value for each window on the local computer. Specifically, the procedure and example use the **EnumWindows** function to step through the list of windows and a managed callback function (named CallBack) to print the value of the window handle. - -## To implement a callback function - -1. Look at the signature for the **EnumWindows** function before going further with the implementation. **EnumWindows** has the following signature: - +The following procedure and example demonstrate how a managed application, using platform invoke, can print the handle value for each window on the local computer. Specifically, the procedure and example use the `EnumWindows` function to step through the list of windows and a managed callback function (named CallBack) to print the value of the window handle. + +## To implement a callback function + +1. Look at the signature for the `EnumWindows` function before going further with the implementation. `EnumWindows` has the following signature: + ```cpp BOOL EnumWindows(WNDENUMPROC lpEnumFunc, LPARAM lParam) ``` - - One clue that this function requires a callback is the presence of the **lpEnumFunc** argument. It is common to see the **lp** (long pointer) prefix combined with the **Func** suffix in the name of arguments that take a pointer to a callback function. For documentation about Win32 functions, see the Microsoft Platform SDK. - -2. Create the managed callback function. The example declares a delegate type, called `CallBack`, which takes two arguments (**hwnd** and **lparam**). The first argument is a handle to the window; the second argument is application-defined. In this release, both arguments must be integers. - - Callback functions generally return nonzero values to indicate success and zero to indicate failure. This example explicitly sets the return value to **true** to continue the enumeration. - -3. Create a delegate and pass it as an argument to the **EnumWindows** function. Platform invoke converts the delegate to a familiar callback format automatically. - -4. Ensure that the garbage collector does not reclaim the delegate before the callback function completes its work. When you pass a delegate as a parameter, or pass a delegate contained as a field in a structure, it remains uncollected for the duration of the call. So, as is the case in the following enumeration example, the callback function completes its work before the call returns and requires no additional action by the managed caller. - + + One clue that this function requires a callback is the presence of the `lpEnumFunc` argument. It is common to see the `lp` (long pointer) prefix combined with the `Func` suffix in the name of arguments that take a pointer to a callback function. For documentation about Win32 functions, see the Microsoft Platform SDK. + +2. Create the managed callback function. The example declares a delegate type, called `CallBack`, which takes two arguments (**hwnd** and **lparam**). The first argument is a handle to the window; the second argument is application-defined. In this release, both arguments must be integers. + + Callback functions generally return nonzero values to indicate success and zero to indicate failure. This example explicitly sets the return value to `true` to continue the enumeration. + +3. Create a delegate and pass it as an argument to the `EnumWindows` function. Platform invoke converts the delegate to a familiar callback format automatically. + +4. Ensure that the garbage collector does not reclaim the delegate before the callback function completes its work. When you pass a delegate as a parameter, or pass a delegate contained as a field in a structure, it remains uncollected for the duration of the call. So, as is the case in the following enumeration example, the callback function completes its work before the call returns and requires no additional action by the managed caller. + If, however, the callback function can be invoked after the call returns, the managed caller must take steps to ensure that the delegate remains uncollected until the callback function finishes. For an example, see the [GCHandle sample](/previous-versions/dotnet/netframework-4.0/44ey4b32(v=vs.100)). - -## Example - -```vb -Imports System -Imports System.Runtime.InteropServices - -Public Delegate Function CallBack( _ -hwnd As Integer, lParam As Integer) As Boolean - -Public Class EnumReportApp - - Declare Function EnumWindows Lib "user32" ( _ - x As CallBack, y As Integer) As Integer - - Public Shared Sub Main() - EnumWindows(AddressOf EnumReportApp.Report, 0) - End Sub 'Main - - Public Shared Function Report(hwnd As Integer, lParam As Integer) _ - As Boolean - Console.Write("Window handle is ") - Console.WriteLine(hwnd) - Return True - End Function 'Report -End Class 'EnumReportApp -``` - -```csharp -using System; -using System.Runtime.InteropServices; - -public delegate bool CallBack(int hwnd, int lParam); - -public class EnumReportApp -{ - [DllImport("user32")] + +## Example + +```vb +Imports System +Imports System.Runtime.InteropServices + +Public Delegate Function CallBack( _ +hwnd As Integer, lParam As Integer) As Boolean + +Public Class EnumReportApp + + Declare Function EnumWindows Lib "user32" ( _ + x As CallBack, y As Integer) As Integer + + Public Shared Sub Main() + EnumWindows(AddressOf EnumReportApp.Report, 0) + End Sub 'Main + + Public Shared Function Report(hwnd As Integer, lParam As Integer) _ + As Boolean + Console.Write("Window handle is ") + Console.WriteLine(hwnd) + Return True + End Function 'Report +End Class 'EnumReportApp +``` + +```csharp +using System; +using System.Runtime.InteropServices; + +public delegate bool CallBack(int hwnd, int lParam); + +public class EnumReportApp +{ + [DllImport("user32")] public static extern int EnumWindows(CallBack x, int y); - + public static void Main() - { - CallBack myCallBack = new CallBack(EnumReportApp.Report); - EnumWindows(myCallBack, 0); - } - - public static bool Report(int hwnd, int lParam) { - Console.Write("Window handle is "); - Console.WriteLine(hwnd); - return true; - } -} -``` - -```cpp -using namespace System; -using namespace System::Runtime::InteropServices; - -// A delegate type. -delegate bool CallBack(int hwnd, int lParam); - -// Managed type with the method to call. -ref class EnumReport -{ -// Report the window handle. -public: - [DllImport("user32")] - static int EnumWindows(CallBack^ x, int y); - - static void Main() - { - EnumReport^ er = gcnew EnumReport; - CallBack^ myCallBack = gcnew CallBack(&EnumReport::Report); - EnumWindows(myCallBack, 0); - } - - static bool Report(int hwnd, int lParam) - { - Console::Write(L"Window handle is "); - Console::WriteLine(hwnd); - return true; - } -}; - -int main() -{ - EnumReport::Main(); -} -``` - + CallBack myCallBack = new CallBack(EnumReportApp.Report); + EnumWindows(myCallBack, 0); + } + + public static bool Report(int hwnd, int lParam) + { + Console.Write("Window handle is "); + Console.WriteLine(hwnd); + return true; + } +} +``` + +```cpp +using namespace System; +using namespace System::Runtime::InteropServices; + +// A delegate type. +delegate bool CallBack(int hwnd, int lParam); + +// Managed type with the method to call. +ref class EnumReport +{ +// Report the window handle. +public: + [DllImport("user32")] + static int EnumWindows(CallBack^ x, int y); + + static void Main() + { + EnumReport^ er = gcnew EnumReport; + CallBack^ myCallBack = gcnew CallBack(&EnumReport::Report); + EnumWindows(myCallBack, 0); + } + + static bool Report(int hwnd, int lParam) + { + Console::Write(L"Window handle is "); + Console::WriteLine(hwnd); + return true; + } +}; + +int main() +{ + EnumReport::Main(); +} +``` + ## See also - [Callback Functions](callback-functions.md) diff --git a/docs/framework/interop/how-to-reference-net-types-from-com.md b/docs/framework/interop/how-to-reference-net-types-from-com.md index 6cbfb3ac4aad6..b34079568ff21 100644 --- a/docs/framework/interop/how-to-reference-net-types-from-com.md +++ b/docs/framework/interop/how-to-reference-net-types-from-com.md @@ -2,9 +2,9 @@ title: "How to: Reference .NET Types from COM" description: Reference .NET types from COM. VB clients can view a .NET object in the object browser, but C++ clients must reference a TLB file with the \#import directive. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "importing type library" - "COM interop, referencing .NET types" - "interoperation with unmanaged code, referencing .NET types" @@ -16,27 +16,27 @@ ms.assetid: 54917f6f-cb18-4103-b622-856b55da93f3 --- # How to: Reference .NET Types from COM -From the point of view of client and server code, the differences between COM and the .NET Framework are largely invisible. Microsoft Visual Basic clients can view a .NET object in the object browser, which exposes the object methods and syntax, properties, and fields exactly as if it were any other COM object. - - The process for importing a type library is slightly more complicated for C++ clients, although you use the same tools to export metadata to a COM type library. To reference .NET object members from an unmanaged C++ client, reference the TLB file (produced with Tlbexp.exe) with the **#import** directive. When referencing a type library from C++, you must either specify the **raw_interfaces_only** option or import the definitions in the base class library, Mscorlib.tlb. - -### To import a library - -- Specify the **raw_interfaces_only** option in the **#import** directive. For example: - - ```cpp - #import "..\LoanLib\LoanLib.tlb" raw_interfaces_only - ``` - - -or- - -- Include an #import directive for Mscorlib.tlb. For example: - - ```cpp - #import "mscorlib.tlb" - #import "..\LoanLib\LoanLib.tlb" - ``` - +From the point of view of client and server code, the differences between COM and the .NET Framework are largely invisible. Microsoft Visual Basic clients can view a .NET object in the object browser, which exposes the object methods and syntax, properties, and fields exactly as if it were any other COM object. + + The process for importing a type library is slightly more complicated for C++ clients, although you use the same tools to export metadata to a COM type library. To reference .NET object members from an unmanaged C++ client, reference the TLB file (produced with Tlbexp.exe) with the **#import** directive. When referencing a type library from C++, you must either specify the `raw_interfaces_only` option or import the definitions in the base class library, Mscorlib.tlb. + +### To import a library + +- Specify the `raw_interfaces_only` option in the **#import** directive. For example: + + ```cpp + #import "..\LoanLib\LoanLib.tlb" raw_interfaces_only + ``` + + -or- + +- Include an #import directive for Mscorlib.tlb. For example: + + ```cpp + #import "mscorlib.tlb" + #import "..\LoanLib\LoanLib.tlb" + ``` + ## See also - [Exposing .NET Framework Components to COM](exposing-dotnet-components-to-com.md) diff --git a/docs/framework/interop/identifying-functions-in-dlls.md b/docs/framework/interop/identifying-functions-in-dlls.md index 1ea7a47fe7a9f..c58f0ad69a357 100644 --- a/docs/framework/interop/identifying-functions-in-dlls.md +++ b/docs/framework/interop/identifying-functions-in-dlls.md @@ -2,7 +2,7 @@ title: "Identifying Functions in DLLs" description: Identify functions in DLLs. A DLL function's identity consists of a function name or ordinal, and the DLL file name in which the implementation can be found. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "platform invoke, identifying functions" - "COM interop, DLL functions" - "unmanaged functions" @@ -15,30 +15,30 @@ ms.assetid: 3e3f6780-6d90-4413-bad7-ba641220364d --- # Identifying Functions in DLLs -The identity of a DLL function consists of the following elements: - -- Function name or ordinal - -- Name of the DLL file in which the implementation can be found - - For example, specifying the **MessageBox** function in the User32.dll identifies the function (**MessageBox**) and its location (User32.dll, User32, or user32). The Microsoft Windows application programming interface (Windows API) can contain two versions of each function that handles characters and strings: a 1-byte character ANSI version and a 2-byte character Unicode version. When unspecified, the character set, represented by the field, defaults to ANSI. Some functions can have more than two versions. - - **MessageBoxA** is the ANSI entry point for the **MessageBox** function; **MessageBoxW** is the Unicode version. You can list function names for a specific DLL, such as user32.dll, by running a variety of command-line tools. For example, you can use `dumpbin /exports user32.dll` or `link /dump /exports user32.dll` to obtain function names. - - You can rename an unmanaged function to whatever you like within your code as long as you map the new name to the original entry point in the DLL. For instructions on renaming an unmanaged DLL function in managed source code, see the [Specifying an Entry Point](specifying-an-entry-point.md). - - Platform invoke enables you to control a significant portion of the operating system by calling functions in the Windows API and other DLLs. In addition to the Windows API, there are numerous other APIs and DLLs available to you through platform invoke. - - The following table describes several commonly used DLLs in the Windows API. - -|DLL|Description of Contents| -|---------|-----------------------------| -|GDI32.dll|Graphics Device Interface (GDI) functions for device output, such as those for drawing and font management.| -|Kernel32.dll|Low-level operating system functions for memory management and resource handling.| -|User32.dll|Windows management functions for message handling, timers, menus, and communications.| - - For complete documentation on the Windows API, see the Platform SDK. For examples that demonstrate how to construct .NET-based declarations to be used with platform invoke, see [Marshalling Data with Platform Invoke](marshalling-data-with-platform-invoke.md). - +The identity of a DLL function consists of the following elements: + +- Function name or ordinal + +- Name of the DLL file in which the implementation can be found + + For example, specifying the `MessageBox` function in the User32.dll identifies the function (**MessageBox**) and its location (User32.dll, User32, or user32). The Microsoft Windows application programming interface (Windows API) can contain two versions of each function that handles characters and strings: a 1-byte character ANSI version and a 2-byte character Unicode version. When unspecified, the character set, represented by the field, defaults to ANSI. Some functions can have more than two versions. + + `MessageBoxA` is the ANSI entry point for the `MessageBox` function; `MessageBoxW` is the Unicode version. You can list function names for a specific DLL, such as user32.dll, by running a variety of command-line tools. For example, you can use `dumpbin /exports user32.dll` or `link /dump /exports user32.dll` to obtain function names. + + You can rename an unmanaged function to whatever you like within your code as long as you map the new name to the original entry point in the DLL. For instructions on renaming an unmanaged DLL function in managed source code, see the [Specifying an Entry Point](specifying-an-entry-point.md). + + Platform invoke enables you to control a significant portion of the operating system by calling functions in the Windows API and other DLLs. In addition to the Windows API, there are numerous other APIs and DLLs available to you through platform invoke. + + The following table describes several commonly used DLLs in the Windows API. + +|DLL|Description of Contents| +|---------|-----------------------------| +|GDI32.dll|Graphics Device Interface (GDI) functions for device output, such as those for drawing and font management.| +|Kernel32.dll|Low-level operating system functions for memory management and resource handling.| +|User32.dll|Windows management functions for message handling, timers, menus, and communications.| + + For complete documentation on the Windows API, see the Platform SDK. For examples that demonstrate how to construct .NET-based declarations to be used with platform invoke, see [Marshalling Data with Platform Invoke](marshalling-data-with-platform-invoke.md). + ## See also - [Consuming Unmanaged DLL Functions](consuming-unmanaged-dll-functions.md) diff --git a/docs/framework/interop/marshalling-classes-structures-and-unions.md b/docs/framework/interop/marshalling-classes-structures-and-unions.md index edcf08b258b96..008ad3872b4f3 100644 --- a/docs/framework/interop/marshalling-classes-structures-and-unions.md +++ b/docs/framework/interop/marshalling-classes-structures-and-unions.md @@ -46,7 +46,7 @@ This sample demonstrates how to pass a structure that points to a second structu The Structs sample uses the following unmanaged functions, shown with their original function declaration: -- **TestStructInStruct** exported from PinvokeLib.dll. +- `TestStructInStruct` exported from PinvokeLib.dll. ```cpp int TestStructInStruct(MYPERSON2* pPerson2); @@ -58,7 +58,7 @@ The Structs sample uses the following unmanaged functions, shown with their orig void TestStructInStruct3(MYPERSON3 person3); ``` -- **TestArrayInStruct** exported from PinvokeLib.dll. +- `TestArrayInStruct` exported from PinvokeLib.dll. ```cpp void TestArrayInStruct(MYARRAYSTRUCT* pStruct); @@ -96,7 +96,7 @@ The managed `MyPerson`, `MyPerson2`, `MyPerson3`, and `MyArrayStruct` structures - `MyPerson` contains only string members. The [CharSet](specifying-a-character-set.md) field sets the strings to ANSI format when passed to the unmanaged function. -- `MyPerson2` contains an **IntPtr** to the `MyPerson` structure. The **IntPtr** type replaces the original pointer to the unmanaged structure because .NET Framework applications do not use pointers unless the code is marked **unsafe**. +- `MyPerson2` contains an `IntPtr` to the `MyPerson` structure. The `IntPtr` type replaces the original pointer to the unmanaged structure because .NET Framework applications do not use pointers unless the code is marked **unsafe**. - `MyPerson3` contains `MyPerson` as an embedded structure. A structure embedded within another structure can be flattened by placing the elements of the embedded structure directly into the main structure, or it can be left as an embedded structure, as is done in this sample. @@ -112,7 +112,7 @@ The `NativeMethods` class contains managed prototypes for the `TestStructInStruc - `TestArrayInStruct` declares a reference to type `MyArrayStruct` as its parameter. -Structures as arguments to methods are passed by value unless the parameter contains the **ref** (**ByRef** in Visual Basic) keyword. For example, the `TestStructInStruct` method passes a reference (the value of an address) to an object of type `MyPerson2` to unmanaged code. To manipulate the structure that `MyPerson2` points to, the sample creates a buffer of a specified size and returns its address by combining the and methods. Next, the sample copies the content of the managed structure to the unmanaged buffer. Finally, the sample uses the method to marshal data from the unmanaged buffer to a managed object and the method to free the unmanaged block of memory. +Structures as arguments to methods are passed by value unless the parameter contains the `ref` (**ByRef** in Visual Basic) keyword. For example, the `TestStructInStruct` method passes a reference (the value of an address) to an object of type `MyPerson2` to unmanaged code. To manipulate the structure that `MyPerson2` points to, the sample creates a buffer of a specified size and returns its address by combining the and methods. Next, the sample copies the content of the managed structure to the unmanaged buffer. Finally, the sample uses the method to marshal data from the unmanaged buffer to a managed object and the method to free the unmanaged block of memory. ### Declaring Prototypes @@ -132,7 +132,7 @@ This sample demonstrates how to pass a structure that contains a second, embedde The FindFile sample uses the following unmanaged function, shown with its original function declaration: -- **FindFirstFile** exported from Kernel32.dll. +- `FindFirstFile` exported from Kernel32.dll. ```cpp HANDLE FindFirstFile(LPCTSTR lpFileName, LPWIN32_FIND_DATA lpFindFileData); @@ -156,7 +156,7 @@ typedef struct _WIN32_FIND_DATA } WIN32_FIND_DATA, *PWIN32_FIND_DATA; ``` -In this sample, the `FindData` class contains a corresponding data member for each element of the original structure and the embedded structure. In place of two original character buffers, the class substitutes strings. **MarshalAsAttribute** sets the enumeration to **ByValTStr**, which is used to identify the inline, fixed-length character arrays that appear within the unmanaged structures. +In this sample, the `FindData` class contains a corresponding data member for each element of the original structure and the embedded structure. In place of two original character buffers, the class substitutes strings. `MarshalAsAttribute` sets the enumeration to `ByValTStr`, which is used to identify the inline, fixed-length character arrays that appear within the unmanaged structures. The `NativeMethods` class contains a managed prototype of the `FindFirstFile` method, which passes the `FindData` class as a parameter. The parameter must be declared with the and attributes because classes, which are reference types, are passed as In parameters by default. @@ -178,13 +178,13 @@ This sample demonstrates how to pass structures containing only value types, and The Unions sample uses the following unmanaged function, shown with its original function declaration: -- **TestUnion** exported from PinvokeLib.dll. +- `TestUnion` exported from PinvokeLib.dll. ```cpp void TestUnion(MYUNION u, int type); ``` -[PinvokeLib.dll](marshalling-data-with-platform-invoke.md#pinvokelibdll) is a custom unmanaged library that contains an implementation for the previously listed function and two unions, **MYUNION** and **MYUNION2**. The unions contain the following elements: +[PinvokeLib.dll](marshalling-data-with-platform-invoke.md#pinvokelibdll) is a custom unmanaged library that contains an implementation for the previously listed function and two unions, `MYUNION` and `MYUNION2`. The unions contain the following elements: ```cpp union MYUNION @@ -303,7 +303,7 @@ This sample demonstrates how to pass a pointer to a class to an unmanaged functi The SysTime sample uses the following unmanaged function, shown with its original function declaration: -- **GetSystemTime** exported from Kernel32.dll. +- `GetSystemTime` exported from Kernel32.dll. ```cpp VOID GetSystemTime(LPSYSTEMTIME lpSystemTime); diff --git a/docs/framework/interop/marshalling-different-types-of-arrays.md b/docs/framework/interop/marshalling-different-types-of-arrays.md index fca49b99634b6..4e1b436121988 100644 --- a/docs/framework/interop/marshalling-different-types-of-arrays.md +++ b/docs/framework/interop/marshalling-different-types-of-arrays.md @@ -2,115 +2,115 @@ title: "Marshalling Different Types of Arrays" description: Marshal different array types, like integers by value or reference, 2-dimensional integers by value, strings by value, and structures with integers or strings. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "marshaling, Arrays sample" - "data marshalling, Arrays sample" ms.assetid: c5ac9920-5b6e-4dc9-bf2d-1f6f8ad3b0bf --- # Marshalling Different Types of Arrays -An array is a reference type in managed code that contains one or more elements of the same type. Although arrays are reference types, they are passed as In parameters to unmanaged functions. This behavior is inconsistent with the way managed arrays are passed to managed objects, which is as In/Out parameters. For additional details, see [Copying and Pinning](copying-and-pinning.md). - - The following table lists marshalling options for arrays and describes their usage. - -|Array|Description| -|-----------|-----------------| -|Of integers by value.|Passes an array of integers as an In parameter.| -|Of integers by reference.|Passes an array of integers as an In/Out parameter.| -|Of integers by value (two-dimensional).|Passes a matrix of integers as an In parameter.| -|Of strings by value.|Passes an array of strings as an In parameter.| -|Of structures with integers.|Passes an array of structures that contain integers as an In parameter.| -|Of structures with strings.|Passes an array of structures that contain only strings as an In/Out parameter. Members of the array can be changed.| - -## Example - - This sample demonstrates how to pass the following types of arrays: - -- Array of integers by value. - -- Array of integers by reference, which can be resized. - -- Multidimensional array (matrix) of integers by value. - -- Array of strings by value. - -- Array of structures with integers. - -- Array of structures with strings. - - Unless an array is explicitly marshalled by reference, the default behavior marshals the array as an In parameter. You can change this behavior by applying the and attributes explicitly. - - The Arrays sample uses the following unmanaged functions, shown with their original function declaration: - -- **TestArrayOfInts** exported from PinvokeLib.dll. - +An array is a reference type in managed code that contains one or more elements of the same type. Although arrays are reference types, they are passed as In parameters to unmanaged functions. This behavior is inconsistent with the way managed arrays are passed to managed objects, which is as In/Out parameters. For additional details, see [Copying and Pinning](copying-and-pinning.md). + + The following table lists marshalling options for arrays and describes their usage. + +|Array|Description| +|-----------|-----------------| +|Of integers by value.|Passes an array of integers as an In parameter.| +|Of integers by reference.|Passes an array of integers as an In/Out parameter.| +|Of integers by value (two-dimensional).|Passes a matrix of integers as an In parameter.| +|Of strings by value.|Passes an array of strings as an In parameter.| +|Of structures with integers.|Passes an array of structures that contain integers as an In parameter.| +|Of structures with strings.|Passes an array of structures that contain only strings as an In/Out parameter. Members of the array can be changed.| + +## Example + + This sample demonstrates how to pass the following types of arrays: + +- Array of integers by value. + +- Array of integers by reference, which can be resized. + +- Multidimensional array (matrix) of integers by value. + +- Array of strings by value. + +- Array of structures with integers. + +- Array of structures with strings. + + Unless an array is explicitly marshalled by reference, the default behavior marshals the array as an In parameter. You can change this behavior by applying the and attributes explicitly. + + The Arrays sample uses the following unmanaged functions, shown with their original function declaration: + +- `TestArrayOfInts` exported from PinvokeLib.dll. + ```cpp - int TestArrayOfInts(int* pArray, int pSize); - ``` - -- **TestRefArrayOfInts** exported from PinvokeLib.dll. - + int TestArrayOfInts(int* pArray, int pSize); + ``` + +- `TestRefArrayOfInts` exported from PinvokeLib.dll. + ```cpp - int TestRefArrayOfInts(int** ppArray, int* pSize); - ``` - -- **TestMatrixOfInts** exported from PinvokeLib.dll. - + int TestRefArrayOfInts(int** ppArray, int* pSize); + ``` + +- `TestMatrixOfInts` exported from PinvokeLib.dll. + ```cpp - int TestMatrixOfInts(int pMatrix[][COL_DIM], int row); - ``` - -- **TestArrayOfStrings** exported from PinvokeLib.dll. - + int TestMatrixOfInts(int pMatrix[][COL_DIM], int row); + ``` + +- `TestArrayOfStrings` exported from PinvokeLib.dll. + ```cpp - int TestArrayOfStrings(char** ppStrArray, int size); - ``` - -- **TestArrayOfStructs** exported from PinvokeLib.dll. - + int TestArrayOfStrings(char** ppStrArray, int size); + ``` + +- `TestArrayOfStructs` exported from PinvokeLib.dll. + ```cpp - int TestArrayOfStructs(MYPOINT* pPointArray, int size); - ``` - -- **TestArrayOfStructs2** exported from PinvokeLib.dll. - + int TestArrayOfStructs(MYPOINT* pPointArray, int size); + ``` + +- **TestArrayOfStructs2** exported from PinvokeLib.dll. + ```cpp - int TestArrayOfStructs2 (MYPERSON* pPersonArray, int size); - ``` - - [PinvokeLib.dll](marshalling-data-with-platform-invoke.md#pinvokelibdll) is a custom unmanaged library that contains implementations for the previously listed functions and two structure variables, **MYPOINT** and **MYPERSON**. The structures contain the following elements: - + int TestArrayOfStructs2 (MYPERSON* pPersonArray, int size); + ``` + + [PinvokeLib.dll](marshalling-data-with-platform-invoke.md#pinvokelibdll) is a custom unmanaged library that contains implementations for the previously listed functions and two structure variables, `MYPOINT` and `MYPERSON`. The structures contain the following elements: + ```cpp -typedef struct _MYPOINT -{ +typedef struct _MYPOINT +{ int x; int y; -} MYPOINT; - -typedef struct _MYPERSON -{ +} MYPOINT; + +typedef struct _MYPERSON +{ char* first; char* last; -} MYPERSON; -``` - - In this sample, the `MyPoint` and `MyPerson` structures contain embedded types. The attribute is set to ensure that the members are arranged in memory sequentially, in the order in which they appear. - - The `NativeMethods` class contains a set of methods called by the `App` class. For specific details about passing arrays, see the comments in the following sample. An array, which is a reference type, is passed as an In parameter by default. For the caller to receive the results, **InAttribute** and **OutAttribute** must be applied explicitly to the argument containing the array. - -### Declaring Prototypes +} MYPERSON; +``` + + In this sample, the `MyPoint` and `MyPerson` structures contain embedded types. The attribute is set to ensure that the members are arranged in memory sequentially, in the order in which they appear. + + The `NativeMethods` class contains a set of methods called by the `App` class. For specific details about passing arrays, see the comments in the following sample. An array, which is a reference type, is passed as an In parameter by default. For the caller to receive the results, `InAttribute` and `OutAttribute` must be applied explicitly to the argument containing the array. + +### Declaring Prototypes [!code-csharp[Conceptual.Interop.Marshaling#31](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/arrays.cs#31)] - [!code-vb[Conceptual.Interop.Marshaling#31](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.interop.marshaling/vb/arrays.vb#31)] - -### Calling Functions + [!code-vb[Conceptual.Interop.Marshaling#31](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.interop.marshaling/vb/arrays.vb#31)] + +### Calling Functions [!code-csharp[Conceptual.Interop.Marshaling#32](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/arrays.cs#32)] - [!code-vb[Conceptual.Interop.Marshaling#32](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.interop.marshaling/vb/arrays.vb#32)] - + [!code-vb[Conceptual.Interop.Marshaling#32](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.interop.marshaling/vb/arrays.vb#32)] + ## See also - [Platform invoke data types](marshalling-data-with-platform-invoke.md#platform-invoke-data-types) diff --git a/docs/framework/interop/msgbox-sample.md b/docs/framework/interop/msgbox-sample.md index 726b66dba13d0..253f5307f54ba 100644 --- a/docs/framework/interop/msgbox-sample.md +++ b/docs/framework/interop/msgbox-sample.md @@ -2,44 +2,44 @@ title: "MsgBox Sample" description: See a sample of passing string types by values as In parameters using MsgBox. It shows when to use the EntryPoint, CharSet, and ExactSpelling fields in .NET. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "marshaling, MsgBox sample" - "data marshalling, MsgBox sample" ms.assetid: 9e0edff6-cc0d-4d5c-a445-aecf283d9c3a --- # MsgBox Sample -This sample demonstrates how to pass string types by value as In parameters and when to use the , , and fields. - - The MsgBox sample uses the following unmanaged function, shown with its original function declaration: - -- **MessageBox** exported from User32.dll. - +This sample demonstrates how to pass string types by value as In parameters and when to use the , , and fields. + + The MsgBox sample uses the following unmanaged function, shown with its original function declaration: + +- `MessageBox` exported from User32.dll. + ```cpp int MessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, - UINT uType); - ``` - - In this sample, the `NativeMethods` class contains a managed prototype for each unmanaged function called by the `MsgBoxSample` class. The managed prototype methods `MsgBox`, `MsgBox2`, and `MsgBox3` have different declarations for the same unmanaged function. - - The declaration for `MsgBox2` produces incorrect output in the message box because the character type, specified as ANSI, is mismatched with the entry point `MessageBoxW`, which is the name of the Unicode function. The declaration for `MsgBox3` creates a mismatch between the **EntryPoint**, **CharSet**, and **ExactSpelling** fields. When called, `MsgBox3` throws an exception. For detailed information on string naming and name marshalling, see [Specifying a Character Set](specifying-a-character-set.md). - -## Declaring Prototypes + UINT uType); + ``` + + In this sample, the `NativeMethods` class contains a managed prototype for each unmanaged function called by the `MsgBoxSample` class. The managed prototype methods `MsgBox`, `MsgBox2`, and `MsgBox3` have different declarations for the same unmanaged function. + + The declaration for `MsgBox2` produces incorrect output in the message box because the character type, specified as ANSI, is mismatched with the entry point `MessageBoxW`, which is the name of the Unicode function. The declaration for `MsgBox3` creates a mismatch between the `EntryPoint`, `CharSet`, and `ExactSpelling` fields. When called, `MsgBox3` throws an exception. For detailed information on string naming and name marshalling, see [Specifying a Character Set](specifying-a-character-set.md). + +## Declaring Prototypes [!code-cpp[Conceptual.Interop.Marshaling#5](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.interop.marshaling/cpp/msgbox.cpp#5)] [!code-csharp[Conceptual.Interop.Marshaling#5](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/msgbox.cs#5)] - [!code-vb[Conceptual.Interop.Marshaling#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.interop.marshaling/vb/msgbox.vb#5)] - -## Calling Functions + [!code-vb[Conceptual.Interop.Marshaling#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.interop.marshaling/vb/msgbox.vb#5)] + +## Calling Functions [!code-cpp[Conceptual.Interop.Marshaling#6](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.interop.marshaling/cpp/msgbox.cpp#6)] [!code-csharp[Conceptual.Interop.Marshaling#6](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.interop.marshaling/cs/msgbox.cs#6)] - [!code-vb[Conceptual.Interop.Marshaling#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.interop.marshaling/vb/msgbox.vb#6)] - + [!code-vb[Conceptual.Interop.Marshaling#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.interop.marshaling/vb/msgbox.vb#6)] + ## See also - [Marshalling Strings](marshalling-strings.md) diff --git a/docs/framework/interop/passing-structures.md b/docs/framework/interop/passing-structures.md index bbbe269688606..8fdc6bf9a429b 100644 --- a/docs/framework/interop/passing-structures.md +++ b/docs/framework/interop/passing-structures.md @@ -2,175 +2,175 @@ title: "Passing Structures" description: Understand how to pass structures and classes to unmanaged functions. Learn about the StructLayoutAttribute attribute, which you use to define formatted types. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "platform invoke, calling unmanaged functions" ms.assetid: 9b92ac73-32b7-4e1b-862e-6d8d950cf169 --- # Passing Structures -Many unmanaged functions expect you to pass, as a parameter to the function, members of structures (user-defined types in Visual Basic) or members of classes that are defined in managed code. When passing structures or classes to unmanaged code using platform invoke, you must provide additional information to preserve the original layout and alignment. This topic introduces the attribute, which you use to define formatted types. For managed structures and classes, you can select from several predictable layout behaviors supplied by the **LayoutKind** enumeration. - - Central to the concepts presented in this topic is an important difference between structure and class types. Structures are value types and classes are reference types — classes always provide at least one level of memory indirection (a pointer to a value). This difference is important because unmanaged functions often demand indirection, as shown by the signatures in the first column of the following table. The managed structure and class declarations in the remaining columns show the degree to which you can adjust the level of indirection in your declaration. Declarations are provided for both Visual Basic and Visual C#. - -|Unmanaged signature|Managed declaration:
no indirection
`Structure MyType`
`struct MyType;`|Managed declaration:
one level of indirection
`Class MyType`
`class MyType;`| -|-------------------------|---------------------------------------------------------------------------------|--------------------------------------------------------------------------------------| -|`DoWork(MyType x);`

Demands zero levels of indirection.|`DoWork(ByVal x As MyType)`
`DoWork(MyType x)`

Adds zero levels of indirection.|Not possible because there is already one level of indirection.| -|`DoWork(MyType* x);`

Demands one level of indirection.|`DoWork(ByRef x As MyType)`
`DoWork(ref MyType x)`

Adds one level of indirection.|`DoWork(ByVal x As MyType)`
`DoWork(MyType x)`

Adds zero levels of indirection.| -|`DoWork(MyType** x);`

Demands two levels of indirection.|Not possible because **ByRef** **ByRef** or `ref` `ref` cannot be used.|`DoWork(ByRef x As MyType)`
`DoWork(ref MyType x)`

Adds one level of indirection.| - - The table describes the following guidelines for platform invoke declarations: - -- Use a structure passed by value when the unmanaged function demands no indirection. - -- Use either a structure passed by reference or a class passed by value when the unmanaged function demands one level of indirection. - -- Use a class passed by reference when the unmanaged function demands two levels of indirection. - -## Declaring and Passing Structures - - The following example shows how to define the `Point` and `Rect` structures in managed code, and pass the types as parameter to the **PtInRect** function in the User32.dll file. **PtInRect** has the following unmanaged signature: - +Many unmanaged functions expect you to pass, as a parameter to the function, members of structures (user-defined types in Visual Basic) or members of classes that are defined in managed code. When passing structures or classes to unmanaged code using platform invoke, you must provide additional information to preserve the original layout and alignment. This topic introduces the attribute, which you use to define formatted types. For managed structures and classes, you can select from several predictable layout behaviors supplied by the `LayoutKind` enumeration. + + Central to the concepts presented in this topic is an important difference between structure and class types. Structures are value types and classes are reference types — classes always provide at least one level of memory indirection (a pointer to a value). This difference is important because unmanaged functions often demand indirection, as shown by the signatures in the first column of the following table. The managed structure and class declarations in the remaining columns show the degree to which you can adjust the level of indirection in your declaration. Declarations are provided for both Visual Basic and Visual C#. + +|Unmanaged signature|Managed declaration:
no indirection
`Structure MyType`
`struct MyType;`|Managed declaration:
one level of indirection
`Class MyType`
`class MyType;`| +|-------------------------|---------------------------------------------------------------------------------|--------------------------------------------------------------------------------------| +|`DoWork(MyType x);`

Demands zero levels of indirection.|`DoWork(ByVal x As MyType)`
`DoWork(MyType x)`

Adds zero levels of indirection.|Not possible because there is already one level of indirection.| +|`DoWork(MyType* x);`

Demands one level of indirection.|`DoWork(ByRef x As MyType)`
`DoWork(ref MyType x)`

Adds one level of indirection.|`DoWork(ByVal x As MyType)`
`DoWork(MyType x)`

Adds zero levels of indirection.| +|`DoWork(MyType** x);`

Demands two levels of indirection.|Not possible because `ByRef ByRef` or `ref ref` cannot be used.|`DoWork(ByRef x As MyType)`
`DoWork(ref MyType x)`

Adds one level of indirection.| + + The table describes the following guidelines for platform invoke declarations: + +- Use a structure passed by value when the unmanaged function demands no indirection. + +- Use either a structure passed by reference or a class passed by value when the unmanaged function demands one level of indirection. + +- Use a class passed by reference when the unmanaged function demands two levels of indirection. + +## Declaring and Passing Structures + + The following example shows how to define the `Point` and `Rect` structures in managed code, and pass the types as parameter to the `PtInRect` function in the User32.dll file. `PtInRect` has the following unmanaged signature: + ```cpp -BOOL PtInRect(const RECT *lprc, POINT pt); -``` - - Notice that you must pass the Rect structure by reference, since the function expects a pointer to a RECT type. - -```vb -Imports System.Runtime.InteropServices - - Public Structure Point - Public x As Integer - Public y As Integer -End Structure - -Public Structure Rect - Public left As Integer - Public top As Integer - Public right As Integer - Public bottom As Integer -End Structure - +BOOL PtInRect(const RECT *lprc, POINT pt); +``` + + Notice that you must pass the Rect structure by reference, since the function expects a pointer to a RECT type. + +```vb +Imports System.Runtime.InteropServices + + Public Structure Point + Public x As Integer + Public y As Integer +End Structure + +Public Structure Rect + Public left As Integer + Public top As Integer + Public right As Integer + Public bottom As Integer +End Structure + Friend Class NativeMethods Friend Declare Auto Function PtInRect Lib "user32.dll" ( - ByRef r As Rect, p As Point) As Boolean -End Class -``` - -```csharp -using System.Runtime.InteropServices; - -[StructLayout(LayoutKind.Sequential)] -public struct Point { - public int x; - public int y; + ByRef r As Rect, p As Point) As Boolean +End Class +``` + +```csharp +using System.Runtime.InteropServices; + +[StructLayout(LayoutKind.Sequential)] +public struct Point { + public int x; + public int y; } - -[StructLayout(LayoutKind.Explicit)] -public struct Rect { - [FieldOffset(0)] public int left; - [FieldOffset(4)] public int top; - [FieldOffset(8)] public int right; - [FieldOffset(12)] public int bottom; + +[StructLayout(LayoutKind.Explicit)] +public struct Rect { + [FieldOffset(0)] public int left; + [FieldOffset(4)] public int top; + [FieldOffset(8)] public int right; + [FieldOffset(12)] public int bottom; } - + internal static class NativeMethods -{ - [DllImport("User32.dll")] - internal static extern bool PtInRect(ref Rect r, Point p); -} -``` - -## Declaring and Passing Classes - - You can pass members of a class to an unmanaged DLL function, as long as the class has a fixed member layout. The following example demonstrates how to pass members of the `MySystemTime` class, which are defined in sequential order, to the **GetSystemTime** in the User32.dll file. **GetSystemTime** has the following unmanaged signature: - +{ + [DllImport("User32.dll")] + internal static extern bool PtInRect(ref Rect r, Point p); +} +``` + +## Declaring and Passing Classes + + You can pass members of a class to an unmanaged DLL function, as long as the class has a fixed member layout. The following example demonstrates how to pass members of the `MySystemTime` class, which are defined in sequential order, to the `GetSystemTime` in the User32.dll file. `GetSystemTime` has the following unmanaged signature: + ```cpp -void GetSystemTime(SYSTEMTIME* SystemTime); -``` - - Unlike value types, classes always have at least one level of indirection. - -```vb -Imports System.Runtime.InteropServices - - Public Class MySystemTime - Public wYear As Short - Public wMonth As Short +void GetSystemTime(SYSTEMTIME* SystemTime); +``` + + Unlike value types, classes always have at least one level of indirection. + +```vb +Imports System.Runtime.InteropServices + + Public Class MySystemTime + Public wYear As Short + Public wMonth As Short Public wDayOfWeek As Short - Public wDay As Short - Public wHour As Short - Public wMinute As Short - Public wSecond As Short - Public wMiliseconds As Short -End Class - -Friend Class NativeMethods + Public wDay As Short + Public wHour As Short + Public wMinute As Short + Public wSecond As Short + Public wMiliseconds As Short +End Class + +Friend Class NativeMethods Friend Declare Auto Sub GetSystemTime Lib "Kernel32.dll" ( - sysTime As MySystemTime) + sysTime As MySystemTime) Friend Declare Auto Function MessageBox Lib "User32.dll" ( - hWnd As IntPtr, lpText As String, lpCaption As String, uType As UInteger) As Integer -End Class - + hWnd As IntPtr, lpText As String, lpCaption As String, uType As UInteger) As Integer +End Class + Public Class TestPlatformInvoke - Public Shared Sub Main() - Dim sysTime As New MySystemTime() - NativeMethods.GetSystemTime(sysTime) - - Dim dt As String - dt = "System time is:" & ControlChars.CrLf & _ - "Year: " & sysTime.wYear & _ - ControlChars.CrLf & "Month: " & sysTime.wMonth & _ - ControlChars.CrLf & "DayOfWeek: " & sysTime.wDayOfWeek & _ - ControlChars.CrLf & "Day: " & sysTime.wDay + Public Shared Sub Main() + Dim sysTime As New MySystemTime() + NativeMethods.GetSystemTime(sysTime) + + Dim dt As String + dt = "System time is:" & ControlChars.CrLf & _ + "Year: " & sysTime.wYear & _ + ControlChars.CrLf & "Month: " & sysTime.wMonth & _ + ControlChars.CrLf & "DayOfWeek: " & sysTime.wDayOfWeek & _ + ControlChars.CrLf & "Day: " & sysTime.wDay NativeMethods.MessageBox(IntPtr.Zero, dt, "Platform Invoke Sample", 0) - End Sub -End Class -``` - -```csharp -[StructLayout(LayoutKind.Sequential)] -public class MySystemTime { + End Sub +End Class +``` + +```csharp +[StructLayout(LayoutKind.Sequential)] +public class MySystemTime { public ushort wYear; - public ushort wMonth; + public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMilliseconds; -} +} internal static class NativeMethods -{ - [DllImport("Kernel32.dll")] - internal static extern void GetSystemTime(MySystemTime st); - - [DllImport("user32.dll", CharSet = CharSet.Auto)] +{ + [DllImport("Kernel32.dll")] + internal static extern void GetSystemTime(MySystemTime st); + + [DllImport("user32.dll", CharSet = CharSet.Auto)] internal static extern int MessageBox( - IntPtr hWnd, string lpText, string lpCaption, uint uType); -} - -public class TestPlatformInvoke -{ - public static void Main() - { - MySystemTime sysTime = new MySystemTime(); - NativeMethods.GetSystemTime(sysTime); - - string dt; - dt = "System time is: \n" + - "Year: " + sysTime.wYear + "\n" + - "Month: " + sysTime.wMonth + "\n" + - "DayOfWeek: " + sysTime.wDayOfWeek + "\n" + - "Day: " + sysTime.wDay; - NativeMethods.MessageBox(IntPtr.Zero, dt, "Platform Invoke Sample", 0); - } -} -``` - + IntPtr hWnd, string lpText, string lpCaption, uint uType); +} + +public class TestPlatformInvoke +{ + public static void Main() + { + MySystemTime sysTime = new MySystemTime(); + NativeMethods.GetSystemTime(sysTime); + + string dt; + dt = "System time is: \n" + + "Year: " + sysTime.wYear + "\n" + + "Month: " + sysTime.wMonth + "\n" + + "DayOfWeek: " + sysTime.wDayOfWeek + "\n" + + "Day: " + sysTime.wDay; + NativeMethods.MessageBox(IntPtr.Zero, dt, "Platform Invoke Sample", 0); + } +} +``` + ## See also - [Calling a DLL Function](calling-a-dll-function.md) diff --git a/docs/framework/interop/platform-invoke-examples.md b/docs/framework/interop/platform-invoke-examples.md index 73824c869c05b..76da7ff5d19eb 100644 --- a/docs/framework/interop/platform-invoke-examples.md +++ b/docs/framework/interop/platform-invoke-examples.md @@ -2,11 +2,11 @@ title: "Platform Invoke Examples" description: See a platform invoke example that demonstrates how to define and call the MessageBox function in User32.dll. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "examples [.NET Framework], platform invoke" - "unmanaged functions" - "COM interop, platform invoke" @@ -17,14 +17,14 @@ ms.assetid: 15926806-f0b7-487e-93a6-4e9367ec689f --- # Platform Invoke Examples -The following examples demonstrate how to define and call the **MessageBox** function in User32.dll, passing a simple string as an argument. In the examples, the field is set to **Auto** to let the target platform determine the character width and string marshalling. - +The following examples demonstrate how to define and call the `MessageBox` function in User32.dll, passing a simple string as an argument. In the examples, the field is set to `Auto` to let the target platform determine the character width and string marshalling. + [!code-cpp[Conceptual.Interop.PInvoke#1](../../../samples/snippets/cpp/VS_Snippets_CLR/Conceptual.Interop.PInvoke/cpp/Example.cpp#1)] [!code-csharp[Conceptual.Interop.PInvoke#1](../../../samples/snippets/csharp/VS_Snippets_CLR/Conceptual.Interop.PInvoke/cs/Example1.cs#1)] - [!code-vb[Conceptual.Interop.PInvoke#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.Interop.PInvoke/vb/Example1.vb#1)] - - For additional examples, see [Marshalling Data with Platform Invoke](marshalling-data-with-platform-invoke.md). - + [!code-vb[Conceptual.Interop.PInvoke#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.Interop.PInvoke/vb/Example1.vb#1)] + + For additional examples, see [Marshalling Data with Platform Invoke](marshalling-data-with-platform-invoke.md). + ## See also - diff --git a/docs/framework/interop/registering-assemblies-with-com.md b/docs/framework/interop/registering-assemblies-with-com.md index 76fb5eb1d7832..5730e90de5b64 100644 --- a/docs/framework/interop/registering-assemblies-with-com.md +++ b/docs/framework/interop/registering-assemblies-with-com.md @@ -2,7 +2,7 @@ title: "Registering Assemblies with COM" description: Register or unregister assemblies with COM using the Assembly Registration Tool (Regasm.exe), which adds information about the class to the system registry. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "COM interop, registering assemblies" - "unregistering assemblies" - "interoperation with unmanaged code, registering assemblies" @@ -11,33 +11,33 @@ ms.assetid: 87925795-a3ae-4833-b138-125413478551 --- # Registering Assemblies with COM -You can run a command-line tool called the [Assembly Registration Tool (Regasm.exe)](../tools/regasm-exe-assembly-registration-tool.md) to register or unregister an assembly for use with COM. Regasm.exe adds information about the class to the system registry so COM clients can use the .NET Framework class transparently. The class provides the equivalent functionality. - - A managed component must be registered in the Windows registry before it can be activated from a COM client. The following table shows the keys that Regasm.exe typically adds to the Windows registry. (000000 indicates the actual GUID value.) - -|GUID|Description|Registry key| -|----------|-----------------|------------------| -|CLSID|Class identifier|HKEY_CLASSES_ROOT\CLSID\\{000…000}| -|IID|Interface identifier|HKEY_CLASSES_ROOT\Interface\\{000…000}| -|LIBID|Library identifier|HKEY_CLASSES_ROOT\TypeLib\\{000…000}| -|ProgID|Programmatic identifier|HKEY_CLASSES_ROOT\000…000| - - Under the HKCR\CLSID\\{0000…0000} key, the default value is set to the ProgID of the class, and two new named values, Class and Assembly, are added. The runtime reads the Assembly value from the registry and passes it on to the runtime assembly resolver. The assembly resolver attempts to locate the assembly, based on assembly information such as the name and version number. For the assembly resolver to locate an assembly, the assembly has to be in one of the following locations: - -- The global assembly cache (must be a strong-named assembly). - -- In the application directory. Assemblies loaded from the application path are only accessible from that application. - -- Along an file path specified with the **/codebase** option to Regasm.exe. - - Regasm.exe also creates the InProcServer32 key under the HKCR\CLSID\\{0000…0000} key. The default value for the key is set to the name of the DLL that initializes the common language runtime (Mscoree.dll). - -## Examining Registry Entries - - COM interop provides a standard class factory implementation to create an instance of any .NET Framework class. Clients can call **DllGetClassObject** on the managed DLL to get a class factory and create objects, just as they would with any other COM component. - - For the `InprocServer32` subkey, a reference to Mscoree.dll appears in place of a traditional COM type library to indicate that the common language runtime creates the managed object. - +You can run a command-line tool called the [Assembly Registration Tool (Regasm.exe)](../tools/regasm-exe-assembly-registration-tool.md) to register or unregister an assembly for use with COM. Regasm.exe adds information about the class to the system registry so COM clients can use the .NET Framework class transparently. The class provides the equivalent functionality. + + A managed component must be registered in the Windows registry before it can be activated from a COM client. The following table shows the keys that Regasm.exe typically adds to the Windows registry. (000000 indicates the actual GUID value.) + +|GUID|Description|Registry key| +|----------|-----------------|------------------| +|CLSID|Class identifier|HKEY_CLASSES_ROOT\CLSID\\{000…000}| +|IID|Interface identifier|HKEY_CLASSES_ROOT\Interface\\{000…000}| +|LIBID|Library identifier|HKEY_CLASSES_ROOT\TypeLib\\{000…000}| +|ProgID|Programmatic identifier|HKEY_CLASSES_ROOT\000…000| + + Under the HKCR\CLSID\\{0000…0000} key, the default value is set to the ProgID of the class, and two new named values, Class and Assembly, are added. The runtime reads the Assembly value from the registry and passes it on to the runtime assembly resolver. The assembly resolver attempts to locate the assembly, based on assembly information such as the name and version number. For the assembly resolver to locate an assembly, the assembly has to be in one of the following locations: + +- The global assembly cache (must be a strong-named assembly). + +- In the application directory. Assemblies loaded from the application path are only accessible from that application. + +- Along an file path specified with the **/codebase** option to Regasm.exe. + + Regasm.exe also creates the InProcServer32 key under the HKCR\CLSID\\{0000…0000} key. The default value for the key is set to the name of the DLL that initializes the common language runtime (Mscoree.dll). + +## Examining Registry Entries + + COM interop provides a standard class factory implementation to create an instance of any .NET Framework class. Clients can call `DllGetClassObject` on the managed DLL to get a class factory and create objects, just as they would with any other COM component. + + For the `InprocServer32` subkey, a reference to Mscoree.dll appears in place of a traditional COM type library to indicate that the common language runtime creates the managed object. + ## See also - [Exposing .NET Framework Components to COM](exposing-dotnet-components-to-com.md) diff --git a/docs/framework/interop/specifying-a-character-set.md b/docs/framework/interop/specifying-a-character-set.md index 8eec8408cf7ba..63364c11ae41a 100644 --- a/docs/framework/interop/specifying-a-character-set.md +++ b/docs/framework/interop/specifying-a-character-set.md @@ -2,11 +2,11 @@ title: "Specifying a Character Set" description: Learn how to specify a character set that uses narrow (ANSI) or wide (Unicode) encoding. You can alternatively specify automatic runtime selection. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "platform invoke, attribute fields" - "attribute fields in platform invoke, CharSet" - "CharSet field" @@ -14,55 +14,55 @@ ms.assetid: a8347eb1-295f-46b9-8a78-63331f9ecc50 --- # Specify a character set -The field controls string marshalling and determines how platform invoke finds function names in a DLL. This topic describes both behaviors. - - Some APIs export two versions of functions that take string arguments: narrow (ANSI) and wide (Unicode). The Windows API, for instance, includes the following entry-point names for the **MessageBox** function: - -- **MessageBoxA** - - Provides 1-byte character ANSI formatting, distinguished by an "A" appended to the entry-point name. Calls to **MessageBoxA** always marshal strings in ANSI format. - -- **MessageBoxW** - - Provides 2-byte character Unicode formatting, distinguished by a "W" appended to the entry-point name. Calls to **MessageBoxW** always marshal strings in Unicode format. - -## String Marshalling and Name Matching - - The `CharSet` field accepts the following values: - - (default value) - -- String marshalling - - Platform invoke marshals strings from their managed format (Unicode) to ANSI format. - -- Name matching - - When the field is `true`, as it is by default in Visual Basic, platform invoke searches only for the name you specify. For example, if you specify **MessageBox**, platform invoke searches for **MessageBox** and fails when it cannot locate the exact spelling. - - When the `ExactSpelling` field is `false`, as it is by default in C++ and C#, platform invoke searches for the unmangled alias first (**MessageBox**), then the mangled name (**MessageBoxA**) if the unmangled alias is not found. Notice that ANSI name-matching behavior differs from Unicode name-matching behavior. - - - -- String marshalling - - Platform invoke copies strings from their managed format (Unicode) to Unicode format. - -- Name matching - - When the `ExactSpelling` field is `true`, as it is by default in Visual Basic, platform invoke searches only for the name you specify. For example, if you specify **MessageBox**, platform invoke searches for **MessageBox** and fails if it cannot locate the exact spelling. - - When the `ExactSpelling` field is `false`, as it is by default in C++ and C#, platform invoke searches for the mangled name first (**MessageBoxW**), then the unmangled alias (**MessageBox**) if the mangled name is not found. Notice that Unicode name-matching behavior differs from ANSI name-matching behavior. - - - -- Platform invoke chooses between ANSI and Unicode formats at run time, based on the target platform. - +The field controls string marshalling and determines how platform invoke finds function names in a DLL. This topic describes both behaviors. + + Some APIs export two versions of functions that take string arguments: narrow (ANSI) and wide (Unicode). The Windows API, for instance, includes the following entry-point names for the `MessageBox` function: + +- `MessageBoxA` + + Provides 1-byte character ANSI formatting, distinguished by an "A" appended to the entry-point name. Calls to `MessageBoxA` always marshal strings in ANSI format. + +- `MessageBoxW` + + Provides 2-byte character Unicode formatting, distinguished by a "W" appended to the entry-point name. Calls to `MessageBoxW` always marshal strings in Unicode format. + +## String Marshalling and Name Matching + + The `CharSet` field accepts the following values: + + (default value) + +- String marshalling + + Platform invoke marshals strings from their managed format (Unicode) to ANSI format. + +- Name matching + + When the field is `true`, as it is by default in Visual Basic, platform invoke searches only for the name you specify. For example, if you specify **MessageBox**, platform invoke searches for `MessageBox` and fails when it cannot locate the exact spelling. + + When the `ExactSpelling` field is `false`, as it is by default in C++ and C#, platform invoke searches for the unmangled alias first (**MessageBox**), then the mangled name (**MessageBoxA**) if the unmangled alias is not found. Notice that ANSI name-matching behavior differs from Unicode name-matching behavior. + + + +- String marshalling + + Platform invoke copies strings from their managed format (Unicode) to Unicode format. + +- Name matching + + When the `ExactSpelling` field is `true`, as it is by default in Visual Basic, platform invoke searches only for the name you specify. For example, if you specify **MessageBox**, platform invoke searches for `MessageBox` and fails if it cannot locate the exact spelling. + + When the `ExactSpelling` field is `false`, as it is by default in C++ and C#, platform invoke searches for the mangled name first (**MessageBoxW**), then the unmangled alias (**MessageBox**) if the mangled name is not found. Notice that Unicode name-matching behavior differs from ANSI name-matching behavior. + + + +- Platform invoke chooses between ANSI and Unicode formats at run time, based on the target platform. + ## Specify a character set in Visual Basic You can specify character-set behavior in Visual Basic by adding the `Ansi`, `Unicode`, or `Auto` keyword to the declaration statement. If you omit the character-set keyword, the field defaults to the ANSI character set. -The following example declares the **MessageBox** function three times, each time with different character-set behavior. The first statement omits the character-set keyword, so the character set defaults to ANSI. The second and third statements explicitly specify a character set with a keyword. +The following example declares the `MessageBox` function three times, each time with different character-set behavior. The first statement omits the character-set keyword, so the character set defaults to ANSI. The second and third statements explicitly specify a character set with a keyword. ```vb Friend Class NativeMethods @@ -85,26 +85,26 @@ Friend Class NativeMethods ByVal uType As UInteger) As Integer End Class ``` - + ## Specify a character set in C# and C++ -The field identifies the underlying character set as ANSI or Unicode. The character set controls how string arguments to a method should be marshalled. Use one of the following forms to indicate the character set: - +The field identifies the underlying character set as ANSI or Unicode. The character set controls how string arguments to a method should be marshalled. Use one of the following forms to indicate the character set: + ```csharp [DllImport("DllName", CharSet = CharSet.Ansi)] [DllImport("DllName", CharSet = CharSet.Unicode)] [DllImport("DllName", CharSet = CharSet.Auto)] ``` - + ```cpp [DllImport("DllName", CharSet = CharSet::Ansi)] [DllImport("DllName", CharSet = CharSet::Unicode)] [DllImport("DllName", CharSet = CharSet::Auto)] ``` - - The following example shows three managed definitions of the **MessageBox** function attributed to specify a character set. In the first definition, by its omission, the `CharSet` field defaults to the ANSI character set. - -```csharp + + The following example shows three managed definitions of the `MessageBox` function attributed to specify a character set. In the first definition, by its omission, the `CharSet` field defaults to the ANSI character set. + +```csharp using System; using System.Runtime.InteropServices; @@ -122,8 +122,8 @@ internal static class NativeMethods internal static extern int MessageBox( IntPtr hWnd, string lpText, string lpCaption, uint uType); } -``` - +``` + ```cpp typedef void* HWND; @@ -142,7 +142,7 @@ extern "C" int MessageBoxW( extern "C" int MessageBox( HWND hWnd, String* lpText, String* lpCaption, unsigned int uType); ``` - + ## See also - diff --git a/docs/framework/interop/specifying-an-entry-point.md b/docs/framework/interop/specifying-an-entry-point.md index 482ae476fe865..0fe98c55079b5 100644 --- a/docs/framework/interop/specifying-an-entry-point.md +++ b/docs/framework/interop/specifying-an-entry-point.md @@ -2,7 +2,7 @@ title: "Specifying an Entry Point" description: Learn to specify an entry point, which identifies a function's location in a DLL. You can rename the function by mapping the entry point to another name. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "EntryPoint field" - "platform invoke, attribute fields" - "attribute fields in platform invoke, EntryPoint" @@ -10,24 +10,24 @@ ms.assetid: d1247f08-0965-416a-b978-e0b50652dfe3 --- # Specifying an Entry Point -An entry point identifies the location of a function in a DLL. Within a managed project, the original name or ordinal entry point of a target function identifies that function across the interoperation boundary. Further, you can map the entry point to a different name, effectively renaming the function. - - The following is a list of possible reasons to rename a DLL function: - -- To avoid using case-sensitive API function names - -- To comply with existing naming standards - -- To accommodate functions that take different data types (by declaring multiple versions of the same DLL function) - -- To simplify using APIs that contain ANSI and Unicode versions - - This topic demonstrates how to rename a DLL function in managed code. - -## Renaming a Function in Visual Basic - -Visual Basic uses the **Function** keyword in the **Declare** statement to set the field. The following example shows a basic declaration. - +An entry point identifies the location of a function in a DLL. Within a managed project, the original name or ordinal entry point of a target function identifies that function across the interoperation boundary. Further, you can map the entry point to a different name, effectively renaming the function. + + The following is a list of possible reasons to rename a DLL function: + +- To avoid using case-sensitive API function names + +- To comply with existing naming standards + +- To accommodate functions that take different data types (by declaring multiple versions of the same DLL function) + +- To simplify using APIs that contain ANSI and Unicode versions + + This topic demonstrates how to rename a DLL function in managed code. + +## Renaming a Function in Visual Basic + +Visual Basic uses the `Function` keyword in the `Declare` statement to set the field. The following example shows a basic declaration. + ```vb Friend Class NativeMethods Friend Declare Auto Function MessageBox Lib "user32.dll" ( @@ -37,9 +37,9 @@ Friend Class NativeMethods ByVal uType As UInteger) As Integer End Class ``` - -You can replace the **MessageBox** entry point with **MsgBox** by including the **Alias** keyword in your definition, as shown in the following example. In both examples the **Auto** keyword eliminates the need to specify the character-set version of the entry point. For more information about selecting a character set, see [Specifying a Character Set](specifying-a-character-set.md). - + +You can replace the `MessageBox` entry point with `MsgBox` by including the `Alias` keyword in your definition, as shown in the following example. In both examples the `Auto` keyword eliminates the need to specify the character-set version of the entry point. For more information about selecting a character set, see [Specifying a Character Set](specifying-a-character-set.md). + ```vb Friend Class NativeMethods Friend Declare Auto Function MsgBox _ @@ -50,20 +50,20 @@ Friend Class NativeMethods ByVal uType As UInteger) As Integer End Class ``` - -## Renaming a Function in C# and C++ - You can use the field to specify a DLL function by name or ordinal. If the name of the function in your method definition is the same as the entry point in the DLL, you do not have to explicitly identify the function with the **EntryPoint** field. Otherwise, use one of the following attribute forms to indicate a name or ordinal: - +## Renaming a Function in C# and C++ + + You can use the field to specify a DLL function by name or ordinal. If the name of the function in your method definition is the same as the entry point in the DLL, you do not have to explicitly identify the function with the `EntryPoint` field. Otherwise, use one of the following attribute forms to indicate a name or ordinal: + ```csharp [DllImport("DllName", EntryPoint = "Functionname")] [DllImport("DllName", EntryPoint = "#123")] ``` - - Notice that you must prefix an ordinal with the pound sign (#). - - The following example demonstrates how to replace **MessageBoxA** with **MsgBox** in your code by using the **EntryPoint** field. - + + Notice that you must prefix an ordinal with the pound sign (#). + + The following example demonstrates how to replace `MessageBoxA` with `MsgBox` in your code by using the `EntryPoint` field. + ```csharp using System; using System.Runtime.InteropServices; @@ -75,7 +75,7 @@ internal static class NativeMethods IntPtr hWnd, string lpText, string lpCaption, uint uType); } ``` - + ```cpp using namespace System; using namespace System::Runtime::InteropServices; @@ -85,7 +85,7 @@ typedef void* HWND; extern "C" int MsgBox( HWND hWnd, String* lpText, String* lpCaption, unsigned int uType); ``` - + ## See also - diff --git a/docs/framework/migration-guide/how-to-configure-an-app-to-support-net-framework-4-or-4-5.md b/docs/framework/migration-guide/how-to-configure-an-app-to-support-net-framework-4-or-4-5.md index 037242031bc5d..7c982f076c9aa 100644 --- a/docs/framework/migration-guide/how-to-configure-an-app-to-support-net-framework-4-or-4-5.md +++ b/docs/framework/migration-guide/how-to-configure-an-app-to-support-net-framework-4-or-4-5.md @@ -2,7 +2,7 @@ title: "How to: Configure an app to support .NET Framework 4 or later versions" description: Use the included example to learn how to configure your desktop app to support .NET Framework 4 or later. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "configuring apps to support .NET Framework" - ".NET Framework, configuring apps" ms.assetid: 63c6b9a8-0088-4077-9aa3-521ab7290f79 @@ -16,7 +16,7 @@ All apps that host the common language runtime (CLR) need to start, or *activate - Configuration file. - If the application configuration file includes [\](../configure-apps/file-schema/startup/supportedruntime-element.md) entries that specify one or more .NET Framework versions, and one of those versions is present on the user's computer, the app runs on that version. The configuration file reads [\](../configure-apps/file-schema/startup/supportedruntime-element.md) entries in the order they are listed, and uses the first .NET Framework version listed that is present on the user's computer. (Use the [\ element](../configure-apps/file-schema/startup/requiredruntime-element.md) for version 1.0.) + If the application configuration file includes [\](../configure-apps/file-schema/startup/supportedruntime-element.md) entries that specify one or more .NET Framework versions, and one of those versions is present on the user's computer, the app runs on that version. The configuration file reads [\](../configure-apps/file-schema/startup/supportedruntime-element.md) entries in the order they are listed, and uses the first .NET Framework version listed that is present on the user's computer. (Use the [`` element](../configure-apps/file-schema/startup/requiredruntime-element.md) for version 1.0.) - Compiled version. @@ -24,7 +24,7 @@ All apps that host the common language runtime (CLR) need to start, or *activate - Latest version installed. - If the version of the .NET Framework that the app was built on is not present and a configuration file does not specify a version in a [\ element](../configure-apps/file-schema/startup/supportedruntime-element.md), the app tries to run on the latest version of the .NET Framework that is present on the user's computer. + If the version of the .NET Framework that the app was built on is not present and a configuration file does not specify a version in a [`` element](../configure-apps/file-schema/startup/supportedruntime-element.md), the app tries to run on the latest version of the .NET Framework that is present on the user's computer. However, .NET Framework 1.0, 1.1, 2.0, 3.0, and 3.5 apps do not automatically run on the .NET Framework 4 or later, and in some cases, the user may receive an error and may be prompted to install .NET Framework 3.5. The activation behavior may also depend on the user’s operating system, because different versions of Windows system include different versions of the .NET Framework. If your app supports both the .NET Framework 3.5 and 4 or later, we recommend that you indicate this with multiple entries in the configuration file to avoid .NET Framework initialization errors. For more information, see [Versions and Dependencies](../install/versions-and-dependencies.md). @@ -53,7 +53,7 @@ All apps that host the common language runtime (CLR) need to start, or *activate
``` - *\* specifies the CLR version that aligns with the .NET Framework version that your app supports. Use the following strings: + The `version` attribute specifies the CLR version that aligns with the .NET Framework version that your app supports. Use the following strings: - .NET Framework 1.0: "v1.0.3705" - .NET Framework 1.1: "v1.1.4322" diff --git a/docs/framework/migration-guide/mitigation-new-64-bit-jit-compiler.md b/docs/framework/migration-guide/mitigation-new-64-bit-jit-compiler.md index 4ea92dce4babd..ee5db33ee30d5 100644 --- a/docs/framework/migration-guide/mitigation-new-64-bit-jit-compiler.md +++ b/docs/framework/migration-guide/mitigation-new-64-bit-jit-compiler.md @@ -2,7 +2,7 @@ title: "Mitigation: New 64-bit JIT Compiler" description: Learn about the new 64-bit JIT compiler included in .NET Framework 4.6 and unexpected behavior or exceptions that might occur during compilation. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "JIT compiler, 64-bit" - "JIT compilation, 64-bit" - "RyuJIT compiler" @@ -10,65 +10,65 @@ ms.assetid: 0332dabc-72c5-4bdc-8975-20d717802b17 --- # Mitigation: New 64-bit JIT Compiler -Starting with .NET Framework 4.6, the runtime includes a new 64-bit JIT compiler for just-in-time compilation. This change does not affect compilation with the 32-bit JIT compiler. - -## Unexpected behavior or exceptions +Starting with .NET Framework 4.6, the runtime includes a new 64-bit JIT compiler for just-in-time compilation. This change does not affect compilation with the 32-bit JIT compiler. + +## Unexpected behavior or exceptions + + In some cases, compilation with the new 64-bit JIT compiler results in a runtime exception or in behavior that is not observed when executing code compiled by the older 64-bit JIT compiler. The known differences include the following: - In some cases, compilation with the new 64-bit JIT compiler results in a runtime exception or in behavior that is not observed when executing code compiled by the older 64-bit JIT compiler. The known differences include the following: - > [!IMPORTANT] -> All of these known issues have been addressed in the new 64-bit compiler released with the .NET Framework 4.6.2. Most have also been addressed in service releases of the .NET Framework 4.6 and 4.6.1 that are included with Windows Update. You can eliminate these issues by ensuring that your version of Windows is up to date, or by upgrading to the .NET Framework 4.6.2. - -- Under certain conditions, an unboxing operation may throw a in Release builds with optimization turned on. - -- In some cases, execution of production code in a large method body may throw a . - -- Under certain conditions, structures passed to a method are treated as reference types rather than value types in Release builds. One of the manifestations of this issue is that the individual items in a collection appear in an unexpected order. - -- Under certain conditions, the comparison of values with their high bit set is incorrect if optimization is enabled. - -- Under certain conditions, particularly when initializing array values, memory initialization by the IL instruction may initialize memory with an incorrect value. This can result either in an unhandled exception or incorrect output. - -- Under certain rare conditions, a conditional bit test can return the incorrect value or throw an exception if compiler optimizations are enabled. - -- Under certain conditions, if an `if` statement is used to test for a condition before entering a `try` block and in the exit from the `try` block, and the same condition is evaluated in the `catch` or `finally` block, the new 64-bit JIT compiler removes the `if` condition from the `catch` or `finally` block when it optimizes code. As a result, code inside the `if` statement in the `catch` or `finally` block is executed unconditionally. - +> All of these known issues have been addressed in the new 64-bit compiler released with the .NET Framework 4.6.2. Most have also been addressed in service releases of the .NET Framework 4.6 and 4.6.1 that are included with Windows Update. You can eliminate these issues by ensuring that your version of Windows is up to date, or by upgrading to the .NET Framework 4.6.2. + +- Under certain conditions, an unboxing operation may throw a in Release builds with optimization turned on. + +- In some cases, execution of production code in a large method body may throw a . + +- Under certain conditions, structures passed to a method are treated as reference types rather than value types in Release builds. One of the manifestations of this issue is that the individual items in a collection appear in an unexpected order. + +- Under certain conditions, the comparison of values with their high bit set is incorrect if optimization is enabled. + +- Under certain conditions, particularly when initializing array values, memory initialization by the IL instruction may initialize memory with an incorrect value. This can result either in an unhandled exception or incorrect output. + +- Under certain rare conditions, a conditional bit test can return the incorrect value or throw an exception if compiler optimizations are enabled. + +- Under certain conditions, if an `if` statement is used to test for a condition before entering a `try` block and in the exit from the `try` block, and the same condition is evaluated in the `catch` or `finally` block, the new 64-bit JIT compiler removes the `if` condition from the `catch` or `finally` block when it optimizes code. As a result, code inside the `if` statement in the `catch` or `finally` block is executed unconditionally. + -## Mitigation of known issues +## Mitigation of known issues + + If you encounter the issues listed above, you can address them by doing any of the following: + +- Upgrade to the .NET Framework 4.6.2. The new 64-bit compiler included with the .NET Framework 4.6.2 addresses each of these known issues. + +- Ensure that your version of Windows is up to date by running Windows Update. Service updates to the .NET Framework 4.6 and 4.6.1 address each of these issues except the in an unboxing operation. + +- Compile with the older 64-bit JIT compiler. See the [Mitigation of other issues](#Other) section for more information on how to do this. - If you encounter the issues listed above, you can address them by doing any of the following: - -- Upgrade to the .NET Framework 4.6.2. The new 64-bit compiler included with the .NET Framework 4.6.2 addresses each of these known issues. - -- Ensure that your version of Windows is up to date by running Windows Update. Service updates to the .NET Framework 4.6 and 4.6.1 address each of these issues except the in an unboxing operation. - -- Compile with the older 64-bit JIT compiler. See the [Mitigation of other issues](#Other) section for more information on how to do this. - -## Mitigation of other issues - - If you encounter any other difference in behavior between code compiled with the older 64-bit compiler and the new 64-bit JIT compiler, or between the debug and release versions of your app that are both compiled with the new 64-bit JIT compiler, you can do the following to compile your app with the older 64-bit JIT compiler: - -- On a per-application basis, you can add the [\](../configure-apps/file-schema/runtime/uselegacyjit-element.md) element to your application's configuration file. The following disables compilation with the new 64-bit JIT compiler and instead uses the legacy 64-bit JIT compiler. - - ```xml - - - - - - - ``` - -- On a per-user basis, you can add a `REG_DWORD` value named `useLegacyJit` to the `HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NETFramework` key of the registry. A value of 1 enables the legacy 64-bit JIT compiler; a value of 0 disables it and enables the new 64-bit JIT compiler. - -- On a per-machine basis, you can add a `REG_DWORD` value named `useLegacyJit` to the `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework` key of the registry. A value of 1 enables the legacy 64-bit JIT compiler; a value of 0 disables it and enables the new 64-bit JIT compiler. - - You can also let us know about the problem by reporting a bug on [Microsoft Connect](https://connect.microsoft.com/VisualStudio). - +## Mitigation of other issues + + If you encounter any other difference in behavior between code compiled with the older 64-bit compiler and the new 64-bit JIT compiler, or between the debug and release versions of your app that are both compiled with the new 64-bit JIT compiler, you can do the following to compile your app with the older 64-bit JIT compiler: + +- On a per-application basis, you can add the [\](../configure-apps/file-schema/runtime/uselegacyjit-element.md) element to your application's configuration file. The following disables compilation with the new 64-bit JIT compiler and instead uses the legacy 64-bit JIT compiler. + + ```xml + + + + + + + ``` + +- On a per-user basis, you can add a `REG_DWORD` value named `useLegacyJit` to the `HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NETFramework` key of the registry. A value of 1 enables the legacy 64-bit JIT compiler; a value of 0 disables it and enables the new 64-bit JIT compiler. + +- On a per-machine basis, you can add a `REG_DWORD` value named `useLegacyJit` to the `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework` key of the registry. A value of 1 enables the legacy 64-bit JIT compiler; a value of 0 disables it and enables the new 64-bit JIT compiler. + + You can also let us know about the problem by reporting a bug on [Microsoft Connect](https://connect.microsoft.com/VisualStudio). + ## See also - [Application compatibility](application-compatibility.md) -- [\ Element](../configure-apps/file-schema/runtime/uselegacyjit-element.md) +- [`` Element](../configure-apps/file-schema/runtime/uselegacyjit-element.md) diff --git a/docs/framework/migration-guide/net-framework-4-migration-issues.md b/docs/framework/migration-guide/net-framework-4-migration-issues.md index 604e4a1358079..71010e7099a4a 100644 --- a/docs/framework/migration-guide/net-framework-4-migration-issues.md +++ b/docs/framework/migration-guide/net-framework-4-migration-issues.md @@ -42,7 +42,7 @@ Assembly: System.Web (in System.Web.dll) | **Passport types** | The Passport support built into ASP.NET 2.0 is obsolete and is unsupported due to changes in Passport (now Live ID SDK). As a result, the types related to Passport in are now marked with the `ObsoleteAttribute` attribute. | Change any code that uses Passport types in the namespace (for example, ) to use the Windows Live ID SDK. | | **PathInfo information in the FilePath property** | ASP.NET 4 no longer includes the `PathInfo` value in the return values from properties such as , , and . Instead, the `PathInfo` information is available in . For example, imagine the following URL fragment:

`/testapp/Action.mvc/SomeAction`

In earlier versions of ASP.NET, properties have the following values:

\* : `/testapp/Action.mvc/SomeAction`
\* : (empty)

In ASP.NET 4, properties instead have the following values:

\* : `/testapp/Action.mvc`
\* : `SomeAction` | Examine your code for places where you rely on properties of the class to return path information; change the code to reflect the changes in how path information is returned. | | **Request validation** | To improve request validation, the ASP.NET request validation is invoked earlier in the request life cycle. As a result, request validation runs for requests that are not for .aspx files, such as for Web service calls and for custom handlers. Request validation will also be active when custom HTTP modules are running in the request processing pipeline.

As a result of this change, requests for resources other than .aspx files might throw request validation errors. Custom code that runs in the request pipeline (for example, custom HTTP modules) might also throw request validation errors. | If necessary, you can revert to the old behavior of having only .aspx pages triggering request validation by using the following setting in the Web configuration file:

``

Warning: If you revert to the old behavior, make sure that all code in existing handlers, modules, and other custom code performs checks for potentially unsafe HTTP inputs that could be XSS attack vectors. | -| **Routing** | If you create a file system Web site in Visual Studio 2010 and the Web site is in a folder that contains a dot (.) in the folder name, URL routing will not work reliably. An HTTP 404 error is returned from some virtual paths. This occurs because Visual Studio 2010 launches the Visual Studio Development Server using an incorrect path for the root virtual directory. | * In the **Properties** page for the file-based Web site, change the **Virtual Path** attribute to "/".

-or-

\* Create a Web application project instead of a Web site project. Web application projects do not have this issue, and URL routing works even if the project folder has a dot in its name.

-or-

\* Create an HTTP-based Web site that is hosted in IIS. IIS-hosted Web sites can have dots in the virtual path as well as in the project file folder. | +| **Routing** | If you create a file system Web site in Visual Studio 2010 and the Web site is in a folder that contains a dot (.) in the folder name, URL routing will not work reliably. An HTTP 404 error is returned from some virtual paths. This occurs because Visual Studio 2010 launches the Visual Studio Development Server using an incorrect path for the root virtual directory. | * In the **Properties** page for the file-based Web site, change the `Virtual Path` attribute to "/".

-or-

\* Create a Web application project instead of a Web site project. Web application projects do not have this issue, and URL routing works even if the project folder has a dot in its name.

-or-

\* Create an HTTP-based Web site that is hosted in IIS. IIS-hosted Web sites can have dots in the virtual path as well as in the project file folder. | | **SharePoint sites** | If you try to run an ASP.NET 4 Web site that is deployed as a child of a SharePoint Web site that contains a custom partial-trust level named `WSS_Minimal`, you will see the following error:

`Could not find permission set named 'ASP.Net'.` | Currently, no versions of SharePoint are compatible with ASP.NET. As a result, you should not attempt to run an ASP.NET 4 Web site as a child of a SharePoint Web site. | | **XHTML 1.1 standards** | To enable XHTML 1.1 compliance for new Web sites, the ASP.NET controls in .NET Framework 4 will generate XHTML 1.1 compliant HTML. This rendering is enabled using the following option in the Web.config file inside the `` element:

``

This option is set by default to 4.0. Web projects that are upgraded from Visual Studio 2008 have the 3.5 setting enabled for compatibility. | None. | diff --git a/docs/framework/migration-guide/version-compatibility.md b/docs/framework/migration-guide/version-compatibility.md index 2044340345d78..e16b5efdd715f 100644 --- a/docs/framework/migration-guide/version-compatibility.md +++ b/docs/framework/migration-guide/version-compatibility.md @@ -53,7 +53,7 @@ If your app or component doesn't work as expected on .NET Framework 4.5 or a lat - If you're recompiling existing source code to run on the .NET Framework 4.5 or its point releases, or if you're developing a new version of an app or component that targets the .NET Framework 4.5 or its point releases from an existing source code base, check [What's Obsolete in the Class Library](../whats-new/whats-obsolete.md) for obsolete types and members, and apply the workaround described. (Previously compiled code will continue to run against types and members that have been marked as obsolete.) -- If you determine that a change in the .NET Framework 4.5 has broken your app, check the [Runtime Settings Schema](../configure-apps/file-schema/runtime/index.md), and particularly the [\ Element](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md), to determine whether you can use a runtime setting in your app's configuration file to restore the previous behavior. +- If you determine that a change in the .NET Framework 4.5 has broken your app, check the [Runtime Settings Schema](../configure-apps/file-schema/runtime/index.md), and particularly the [`` Element](../configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md), to determine whether you can use a runtime setting in your app's configuration file to restore the previous behavior. - If you come across an issue that isn't documented, open a problem on the [Developer Community site for .NET](https://aka.ms/feedback/report?space=61) or open an issue in the [Microsoft/dotnet GitHub repo](https://github.com/microsoft/dotnet/issues). diff --git a/docs/framework/network-programming/best-practices-for-system-net-classes.md b/docs/framework/network-programming/best-practices-for-system-net-classes.md index ab4a9155165d5..2bb25b5d21bbb 100644 --- a/docs/framework/network-programming/best-practices-for-system-net-classes.md +++ b/docs/framework/network-programming/best-practices-for-system-net-classes.md @@ -2,7 +2,7 @@ title: "Best Practices for System.Net Classes" description: Follow these recommendations to use the classes contained in System.Net to their best advantage in .NET Framework programming. ms.date: 07/21/2022 -helpviewer_keywords: +helpviewer_keywords: - "sending data, best practices" - "requesting data from internet, best practices" - "WebRequest class, best practices" @@ -14,20 +14,20 @@ ms.assetid: 716decc6-5952-47b7-9c5a-ba6fc5698684 --- # Best practices for System.Net classes -The following recommendations will help you use the classes contained in to their best advantage: - +The following recommendations will help you use the classes contained in to their best advantage: + - For Transport Layer Security (TLS) best practices, see [Transport Layer Security (TLS) best practices with .NET Framework](tls.md). - Use to send HTTP requests instead of , which was obsoleted in .NET 6. In .NET Framework, create a new `HttpClient` instance each time you need to send a request. (The guidance for .NET 5+/.NET Core is more nuanced. For more information, see [Guidelines for using HttpClient](../../fundamentals/networking/http/httpclient-guidelines.md).) - + - When writing ASP.NET applications that run on a server using the `System.Net` classes, it's often better, from a performance standpoint, to use the asynchronous method instead of . - -- The number of connections opened to an internet resource can have a significant impact on network performance and throughput. **System.Net** uses two connections per application per host by default. Setting the property in the for your application can increase this number for a particular host. Setting the property can increase this default for all hosts. - -- When writing socket-level protocols, try to use or whenever possible instead of writing directly to a . These two client classes encapsulate the creation of TCP and UDP sockets without requiring you to handle the details of the connection. - -- When accessing sites that require credentials, use the class to create a cache of credentials rather than supplying them with every request. The **CredentialCache** class searches the cache to find the appropriate credential to present with a request, relieving you of the responsibility of creating and presenting credentials based on the URL. - + +- The number of connections opened to an internet resource can have a significant impact on network performance and throughput. **System.Net** uses two connections per application per host by default. Setting the property in the for your application can increase this number for a particular host. Setting the property can increase this default for all hosts. + +- When writing socket-level protocols, try to use or whenever possible instead of writing directly to a . These two client classes encapsulate the creation of TCP and UDP sockets without requiring you to handle the details of the connection. + +- When accessing sites that require credentials, use the class to create a cache of credentials rather than supplying them with every request. The `CredentialCache` class searches the cache to find the appropriate credential to present with a request, relieving you of the responsibility of creating and presenting credentials based on the URL. + ## See also - [Network programming in .NET](../../fundamentals/networking/overview.md) diff --git a/docs/framework/network-programming/cache-policy.md b/docs/framework/network-programming/cache-policy.md index 420a9faccdc8c..7527796cf4ee4 100644 --- a/docs/framework/network-programming/cache-policy.md +++ b/docs/framework/network-programming/cache-policy.md @@ -2,7 +2,7 @@ title: "Cache Policy" description: Learn about cache policy, the rules that determine whether a request can be satisfied using a cached copy of the requested resource. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "time-based cache policies" - "location-based cache policies" - "cache [.NET Framework], policies" @@ -14,26 +14,26 @@ ms.assetid: 1a7e04ec-7872-41c2-96c6-52566dcb412b --- # Cache Policy -A cache policy defines rules that are used to determine whether a request can be satisfied using a cached copy of the requested resource. Applications specify client cache requirements for freshness, but the effective cache policy is determined by the client cache requirements, the server's content expiration requirements, and the server's revalidation requirements. The interaction of client cache policy and server requirements always results in the most conservative cache policy, to help ensure that the freshest content is returned to the client application. - - Cache policies are either location-based or time-based. A location-based cache policy defines the freshness of cached entries based on where the requested resource can be taken from. A time-based cache policy defines the freshness of cached entries using the time the resource was retrieved, headers returned with the resource, and the current time. Most applications can use the default time-based cache policy, which implements the caching policy specified in RFC 2616, available at [Internet Engineering Task Force (IETF)](https://www.ietf.org/) website. - - The classes described in the following table are used to specify cache policies. - -|Class name|Description| -|----------------|-----------------| -||Represents location-based and time-based cache policies for resources requested using objects.| -||Represents location-based cache policies or the time-based cache policy for resources requested using objects.| -||Specifies values used to create time-based objects.| -||Specifies values used to create location-based and time-based objects.| -||Specifies values used to create location-based or the time-based objects.| - - You can define a cache policy for all requests made by your application or for individual requests. When you specify both an application-level cache policy and a request-level cache policy, the request-level policy is used. You can specify an application-level cache policy programmatically or by using the application or machine configuration files. For more information, see [\ Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md). - - To create a cache policy, you must create a policy object by creating an instance of the or class. To specify the policy on a request, set the request's property to the policy object. When setting an application-level policy programmatically, set the property to the policy object. - - For code examples that demonstrate creating and using cache policies, see [Configuring Caching in Network Applications](configuring-caching-in-network-applications.md). - +A cache policy defines rules that are used to determine whether a request can be satisfied using a cached copy of the requested resource. Applications specify client cache requirements for freshness, but the effective cache policy is determined by the client cache requirements, the server's content expiration requirements, and the server's revalidation requirements. The interaction of client cache policy and server requirements always results in the most conservative cache policy, to help ensure that the freshest content is returned to the client application. + + Cache policies are either location-based or time-based. A location-based cache policy defines the freshness of cached entries based on where the requested resource can be taken from. A time-based cache policy defines the freshness of cached entries using the time the resource was retrieved, headers returned with the resource, and the current time. Most applications can use the default time-based cache policy, which implements the caching policy specified in RFC 2616, available at [Internet Engineering Task Force (IETF)](https://www.ietf.org/) website. + + The classes described in the following table are used to specify cache policies. + +|Class name|Description| +|----------------|-----------------| +||Represents location-based and time-based cache policies for resources requested using objects.| +||Represents location-based cache policies or the time-based cache policy for resources requested using objects.| +||Specifies values used to create time-based objects.| +||Specifies values used to create location-based and time-based objects.| +||Specifies values used to create location-based or the time-based objects.| + + You can define a cache policy for all requests made by your application or for individual requests. When you specify both an application-level cache policy and a request-level cache policy, the request-level policy is used. You can specify an application-level cache policy programmatically or by using the application or machine configuration files. For more information, see [`` Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md). + + To create a cache policy, you must create a policy object by creating an instance of the or class. To specify the policy on a request, set the request's property to the policy object. When setting an application-level policy programmatically, set the property to the policy object. + + For code examples that demonstrate creating and using cache policies, see [Configuring Caching in Network Applications](configuring-caching-in-network-applications.md). + ## See also - [Cache Management for Network Applications](cache-management-for-network-applications.md) diff --git a/docs/framework/network-programming/configuring-caching-in-network-applications.md b/docs/framework/network-programming/configuring-caching-in-network-applications.md index 2590c8abde409..2fb72d425c475 100644 --- a/docs/framework/network-programming/configuring-caching-in-network-applications.md +++ b/docs/framework/network-programming/configuring-caching-in-network-applications.md @@ -2,24 +2,24 @@ description: "Learn more about: Configuring Caching in Network Applications" title: "Configuring Caching in Network Applications" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "cache [.NET Framework], configuring" ms.assetid: 3f694a1c-de5d-47cf-a6eb-cfc369fb8a9f --- # Configuring Caching in Network Applications -To configure caching, you must specify a cache policy at the application or level. The following topics provide code examples that demonstrate configuring applications and requests to use caching. - -- [How to: Set a Location-Based Cache Policy for an Application](how-to-set-a-location-based-cache-policy-for-an-application.md) - -- [How to: Set the Default Time-Based Cache Policy for an Application](how-to-set-the-default-time-based-cache-policy-for-an-application.md) - -- [How to: Customize a Time-Based Cache Policy](how-to-customize-a-time-based-cache-policy.md) - -- [How to: Set Cache Policy for a Request](how-to-set-cache-policy-for-a-request.md) - - You can also configure cache policy using application or machine configuration files. For more information, see | [\ Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md). - +To configure caching, you must specify a cache policy at the application or level. The following topics provide code examples that demonstrate configuring applications and requests to use caching. + +- [How to: Set a Location-Based Cache Policy for an Application](how-to-set-a-location-based-cache-policy-for-an-application.md) + +- [How to: Set the Default Time-Based Cache Policy for an Application](how-to-set-the-default-time-based-cache-policy-for-an-application.md) + +- [How to: Customize a Time-Based Cache Policy](how-to-customize-a-time-based-cache-policy.md) + +- [How to: Set Cache Policy for a Request](how-to-set-cache-policy-for-a-request.md) + + You can also configure cache policy using application or machine configuration files. For more information, see | [`` Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md). + ## See also - [Cache Management for Network Applications](cache-management-for-network-applications.md) diff --git a/docs/framework/network-programming/configuring-internet-applications.md b/docs/framework/network-programming/configuring-internet-applications.md index e39da3335b2b1..628a544ac7a67 100644 --- a/docs/framework/network-programming/configuring-internet-applications.md +++ b/docs/framework/network-programming/configuring-internet-applications.md @@ -2,7 +2,7 @@ title: "Configuring Internet Applications" description: Learn how to use the element to configure internet applications in the .NET Framework. This article contains example code. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "downloading Internet resources, default proxy" - "sending data, default proxy" - "receiving data, default proxy" @@ -25,76 +25,76 @@ ms.topic: how-to --- # Configuring Internet Applications -The [\ Element (Network Settings)](../configure-apps/file-schema/network/system-net-element-network-settings.md) configuration element contains network configuration information for applications. Using the [\ Element (Network Settings)](../configure-apps/file-schema/network/system-net-element-network-settings.md) element, you can set proxy servers, set connection management parameters, and include custom authentication and request modules in your application. - - The [\ Element (Network Settings)](../configure-apps/file-schema/network/defaultproxy-element-network-settings.md) element defines the proxy server returned by the `GlobalProxySelection` class. Any that does not have its own property set to a specific value uses the default proxy. In addition to setting the proxy address, you can create a list of server addresses that will not use the proxy, and you can indicate that the proxy should not be used for local addresses. - - It is important to note that system's Internet settings are combined with the configuration settings, with the latter taking precedence. - - The following example sets the default proxy server address to `http://proxyserver`, indicates that the proxy should not be used for local addresses, and specifies that all requests to servers located in the contoso.com domain should bypass the proxy. - -```xml - - - - - - - - - - -``` - - Use the [\ Element (Network Settings)](../configure-apps/file-schema/network/connectionmanagement-element-network-settings.md) element to configure the number of persistent connections that can be made to a specific server or to all other servers. The following example configures the application to use two persistent connections to the server `www.contoso.com`, four persistent connections to the server with the IP address 192.168.1.2, and one persistent connection to all other servers. - -```xml - - - - - - - - - -``` - - Custom authentication modules are configured with the [\ Element (Network Settings)](../configure-apps/file-schema/network/authenticationmodules-element-network-settings.md) element. Custom authentication modules must implement the interface. - - The following example configures a custom authentication module. - -```xml - - - - - - - -``` - - You can use the [\ Element (Network Settings)](../configure-apps/file-schema/network/webrequestmodules-element-network-settings.md) element to configure your application to use custom protocol-specific modules to request information from Internet resources. The specified modules must implement the interface. You can override the default HTTP, HTTPS, and file request modules by specifying your custom module in the configuration file, as in the following example. - -```xml - - - - - - - -``` - +The [`` Element (Network Settings)](../configure-apps/file-schema/network/system-net-element-network-settings.md) configuration element contains network configuration information for applications. Using the [`` Element (Network Settings)](../configure-apps/file-schema/network/system-net-element-network-settings.md) element, you can set proxy servers, set connection management parameters, and include custom authentication and request modules in your application. + + The [`` element](../configure-apps/file-schema/network/defaultproxy-element-network-settings.md) defines the proxy server returned by the `GlobalProxySelection` class. Any that does not have its own property set to a specific value uses the default proxy. In addition to setting the proxy address, you can create a list of server addresses that will not use the proxy, and you can indicate that the proxy should not be used for local addresses. + + It is important to note that system's Internet settings are combined with the configuration settings, with the latter taking precedence. + + The following example sets the default proxy server address to `http://proxyserver`, indicates that the proxy should not be used for local addresses, and specifies that all requests to servers located in the contoso.com domain should bypass the proxy. + +```xml + + + + + + + + + + +``` + + Use the [`` Element (Network Settings)](../configure-apps/file-schema/network/connectionmanagement-element-network-settings.md) element to configure the number of persistent connections that can be made to a specific server or to all other servers. The following example configures the application to use two persistent connections to the server `www.contoso.com`, four persistent connections to the server with the IP address 192.168.1.2, and one persistent connection to all other servers. + +```xml + + + + + + + + + +``` + + Custom authentication modules are configured with the [`` Element (Network Settings)](../configure-apps/file-schema/network/authenticationmodules-element-network-settings.md) element. Custom authentication modules must implement the interface. + + The following example configures a custom authentication module. + +```xml + + + + + + + +``` + + You can use the [`` Element (Network Settings)](../configure-apps/file-schema/network/webrequestmodules-element-network-settings.md) element to configure your application to use custom protocol-specific modules to request information from Internet resources. The specified modules must implement the interface. You can override the default HTTP, HTTPS, and file request modules by specifying your custom module in the configuration file, as in the following example. + +```xml + + + + + + + +``` + ## See also - [Network programming in .NET](../../fundamentals/networking/overview.md) - [Network Settings Schema](../configure-apps/file-schema/network/index.md) -- [\ Element (Network Settings)](../configure-apps/file-schema/network/system-net-element-network-settings.md) +- [`` Element (Network Settings)](../configure-apps/file-schema/network/system-net-element-network-settings.md) diff --git a/docs/framework/network-programming/how-to-configure-network-tracing.md b/docs/framework/network-programming/how-to-configure-network-tracing.md index 22f4a129a07e1..8dab96906cc12 100644 --- a/docs/framework/network-programming/how-to-configure-network-tracing.md +++ b/docs/framework/network-programming/how-to-configure-network-tracing.md @@ -96,9 +96,9 @@ The attributes listed in the following table configure trace output: |Attribute name|Attribute value| |--------------------|---------------------| -|`value`|Required attribute. Sets the verbosity of the output. Legitimate values are `Critical`, `Error`, `Verbose`, `Warning`, and `Information`.

This attribute must be set on the **add** element of the **switches** element. An exception is thrown if this attribute is set on the **source** element.

Example: ``| -|`maxdatasize`|Optional attribute. Sets the maximum number of bytes of network data included in each line trace. The default value is 1024.

This attribute must be set on the **source** element. An exception is thrown if this attribute is set on an element under the **switches** element.

Example: ``| -|`tracemode`|Optional attribute. Set to `includehex` to show protocol traces in hexadecimal and text format. Set to `protocolonly` to show only text. The default value is `includehex`.

This attribute must be set on the **source** element. An exception is thrown if this attribute is set on an element under the **switches** element.

Example: ``| +|`value`|Required attribute. Sets the verbosity of the output. Legitimate values are `Critical`, `Error`, `Verbose`, `Warning`, and `Information`.

This attribute must be set on the `add` element of the `switches` element. An exception is thrown if this attribute is set on the `source` element.

Example: ``| +|`maxdatasize`|Optional attribute. Sets the maximum number of bytes of network data included in each line trace. The default value is 1024.

This attribute must be set on the `source` element. An exception is thrown if this attribute is set on an element under the `switches` element.

Example: ``| +|`tracemode`|Optional attribute. Set to `includehex` to show protocol traces in hexadecimal and text format. Set to `protocolonly` to show only text. The default value is `includehex`.

This attribute must be set on the `source` element. An exception is thrown if this attribute is set on an element under the `switches` element.

Example: ``| ## See also diff --git a/docs/framework/network-programming/how-to-customize-a-time-based-cache-policy.md b/docs/framework/network-programming/how-to-customize-a-time-based-cache-policy.md index a610281927873..becbc6327255b 100644 --- a/docs/framework/network-programming/how-to-customize-a-time-based-cache-policy.md +++ b/docs/framework/network-programming/how-to-customize-a-time-based-cache-policy.md @@ -100,21 +100,21 @@ End Function ``` For the following invocation: - + ```csharp -CreateFreshAndAgePolicy(new TimeSpan(5,0,0), new TimeSpan(10,0,0)); -``` +CreateFreshAndAgePolicy(new TimeSpan(5,0,0), new TimeSpan(10,0,0)); +``` The output is: - + ```output -Level:Default MaxAge:36000 MinFresh:18000 -``` - +Level:Default MaxAge:36000 MinFresh:18000 +``` + ## See also - [Cache Management for Network Applications](cache-management-for-network-applications.md) - [Cache Policy](cache-policy.md) - [Location-Based Cache Policies](location-based-cache-policies.md) - [Time-Based Cache Policies](time-based-cache-policies.md) -- [\ Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) +- [`` Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) diff --git a/docs/framework/network-programming/how-to-set-a-location-based-cache-policy-for-an-application.md b/docs/framework/network-programming/how-to-set-a-location-based-cache-policy-for-an-application.md index d4439056d6821..94f321a9b52db 100644 --- a/docs/framework/network-programming/how-to-set-a-location-based-cache-policy-for-an-application.md +++ b/docs/framework/network-programming/how-to-set-a-location-based-cache-policy-for-an-application.md @@ -2,10 +2,10 @@ description: "Learn more about: How to: Set a Location-Based Cache Policy for an Application" title: "How to: Set a Location-Based Cache Policy for an Application" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "explicitly defining cache behavior" - "location-based cache policies" - "local cache" @@ -15,144 +15,144 @@ ms.assetid: 683bb88e-3411-4f46-9686-3411b6ba511c --- # How to: Set a Location-Based Cache Policy for an Application -Location-based cache policies allow an application to explicitly define caching behavior based on the location of the requested resource. This topic demonstrates setting the cache policy programmatically. For information on setting the policy for an application using the configuration files, see [\ Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md). - -### To set a location-based cache policy for an application - -1. Create a or object. - -2. Set the policy object as the default for the application domain. - -### To set a policy that takes requested resources from a cache - -- Create a policy that takes requested resources from a cache if available, and otherwise, sends requests to the server, by setting the cache level to . A request can be fulfilled by any cache between the client and server, including remote caches. - - ```csharp - public static void UseCacheIfAvailable() - { - HttpRequestCachePolicy policy = new HttpRequestCachePolicy - (HttpRequestCacheLevel.CacheIfAvailable); - HttpWebRequest.DefaultCachePolicy = policy; - } - ``` - - ```vb - Public Shared Sub UseCacheIfAvailable() - Dim policy As New HttpRequestCachePolicy _ - (HttpRequestCacheLevel.CacheIfAvailable) - HttpWebRequest.DefaultCachePolicy = policy - End Sub - ``` - -### To set a policy that prevents any cache from supplying resources - -- Create a policy that prevents any cache from supplying requested resources by setting the cache level to . This policy level removes the resource from the local cache if it is present and indicates to remote caches that they should also remove the resource. - - ```csharp - public static void DoNotUseCache() - { +Location-based cache policies allow an application to explicitly define caching behavior based on the location of the requested resource. This topic demonstrates setting the cache policy programmatically. For information on setting the policy for an application using the configuration files, see [`` Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md). + +### To set a location-based cache policy for an application + +1. Create a or object. + +2. Set the policy object as the default for the application domain. + +### To set a policy that takes requested resources from a cache + +- Create a policy that takes requested resources from a cache if available, and otherwise, sends requests to the server, by setting the cache level to . A request can be fulfilled by any cache between the client and server, including remote caches. + + ```csharp + public static void UseCacheIfAvailable() + { + HttpRequestCachePolicy policy = new HttpRequestCachePolicy + (HttpRequestCacheLevel.CacheIfAvailable); + HttpWebRequest.DefaultCachePolicy = policy; + } + ``` + + ```vb + Public Shared Sub UseCacheIfAvailable() + Dim policy As New HttpRequestCachePolicy _ + (HttpRequestCacheLevel.CacheIfAvailable) + HttpWebRequest.DefaultCachePolicy = policy + End Sub + ``` + +### To set a policy that prevents any cache from supplying resources + +- Create a policy that prevents any cache from supplying requested resources by setting the cache level to . This policy level removes the resource from the local cache if it is present and indicates to remote caches that they should also remove the resource. + + ```csharp + public static void DoNotUseCache() + { HttpRequestCachePolicy policy = new HttpRequestCachePolicy - (HttpRequestCacheLevel.NoCacheNoStore); - HttpWebRequest.DefaultCachePolicy = policy; - } - ``` - - ```vb - Public Shared Sub DoNotUseCache() - Dim policy As New HttpRequestCachePolicy _ - (HttpRequestCacheLevel.NoCacheNoStore) - HttpWebRequest.DefaultCachePolicy = policy - End Sub - ``` - -### To set a policy that returns requested resources only if they are in the local cache - -- Create a policy that returns requested resources only if they are in the local cache by setting the cache level to . If the requested resource is not in the cache, a exception is thrown. - - ```csharp - public static void OnlyUseCache() - { + (HttpRequestCacheLevel.NoCacheNoStore); + HttpWebRequest.DefaultCachePolicy = policy; + } + ``` + + ```vb + Public Shared Sub DoNotUseCache() + Dim policy As New HttpRequestCachePolicy _ + (HttpRequestCacheLevel.NoCacheNoStore) + HttpWebRequest.DefaultCachePolicy = policy + End Sub + ``` + +### To set a policy that returns requested resources only if they are in the local cache + +- Create a policy that returns requested resources only if they are in the local cache by setting the cache level to . If the requested resource is not in the cache, a exception is thrown. + + ```csharp + public static void OnlyUseCache() + { HttpRequestCachePolicy policy = new HttpRequestCachePolicy - (HttpRequestCacheLevel.CacheOnly); - HttpWebRequest.DefaultCachePolicy = policy; - } - ``` - - ```vb - Public Shared Sub OnlyUseCache() - Dim policy As New HttpRequestCachePolicy _ - (HttpRequestCacheLevel.CacheOnly) - HttpWebRequest.DefaultCachePolicy = policy - End Sub - ``` - -### To set a policy that prevents the local cache from supplying resources - -- Create a policy that prevents the local cache from supplying requested resources by setting the cache level to . If the requested resource is in an intermediate cache and is successfully revalidated, the intermediate cache can supply the requested resource. - - ```csharp - public static void DoNotUseLocalCache() - { + (HttpRequestCacheLevel.CacheOnly); + HttpWebRequest.DefaultCachePolicy = policy; + } + ``` + + ```vb + Public Shared Sub OnlyUseCache() + Dim policy As New HttpRequestCachePolicy _ + (HttpRequestCacheLevel.CacheOnly) + HttpWebRequest.DefaultCachePolicy = policy + End Sub + ``` + +### To set a policy that prevents the local cache from supplying resources + +- Create a policy that prevents the local cache from supplying requested resources by setting the cache level to . If the requested resource is in an intermediate cache and is successfully revalidated, the intermediate cache can supply the requested resource. + + ```csharp + public static void DoNotUseLocalCache() + { HttpRequestCachePolicy policy = new HttpRequestCachePolicy - (HttpRequestCacheLevel.Refresh); - HttpWebRequest.DefaultCachePolicy = policy; - } - ``` - - ```vb - Public Shared Sub DoNotUseLocalCache() - Dim policy As New HttpRequestCachePolicy _ - (HttpRequestCacheLevel.Refresh) - HttpWebRequest.DefaultCachePolicy = policy - End Sub - ``` - -### To set a policy that prevents any cache from supplying requested resources - -- Create a policy that prevents any cache from supplying requested resources by setting the cache level to . The resource returned by the server can be stored in the cache. - - ```csharp - public static void SendToServer() - { + (HttpRequestCacheLevel.Refresh); + HttpWebRequest.DefaultCachePolicy = policy; + } + ``` + + ```vb + Public Shared Sub DoNotUseLocalCache() + Dim policy As New HttpRequestCachePolicy _ + (HttpRequestCacheLevel.Refresh) + HttpWebRequest.DefaultCachePolicy = policy + End Sub + ``` + +### To set a policy that prevents any cache from supplying requested resources + +- Create a policy that prevents any cache from supplying requested resources by setting the cache level to . The resource returned by the server can be stored in the cache. + + ```csharp + public static void SendToServer() + { HttpRequestCachePolicy policy = new HttpRequestCachePolicy - (HttpRequestCacheLevel.Reload); - HttpWebRequest.DefaultCachePolicy = policy; - } - ``` - - ```vb - Public Shared Sub SendToServer() - Dim policy As New HttpRequestCachePolicy _ - (HttpRequestCacheLevel.Reload) - HttpWebRequest.DefaultCachePolicy = policy - End Sub - ``` - -### To set a policy that allows any cache to supply requested resources if the resource on the server is not newer than the cached copy - -- Create a policy that allows any cache to supply requested resources if the resource on the server is not newer than the cached copy by setting the cache level to . - - ```csharp - public static void CheckServer() - { - HttpRequestCachePolicy policy = new HttpRequestCachePolicy - (HttpRequestCacheLevel.Revalidate); - HttpWebRequest.DefaultCachePolicy = policy; - } - ``` - - ```vb - Public Shared Sub CheckServer() - Dim policy As New HttpRequestCachePolicy _ - (HttpRequestCacheLevel.Revalidate) - HttpWebRequest.DefaultCachePolicy = policy - End Sub - ``` - + (HttpRequestCacheLevel.Reload); + HttpWebRequest.DefaultCachePolicy = policy; + } + ``` + + ```vb + Public Shared Sub SendToServer() + Dim policy As New HttpRequestCachePolicy _ + (HttpRequestCacheLevel.Reload) + HttpWebRequest.DefaultCachePolicy = policy + End Sub + ``` + +### To set a policy that allows any cache to supply requested resources if the resource on the server is not newer than the cached copy + +- Create a policy that allows any cache to supply requested resources if the resource on the server is not newer than the cached copy by setting the cache level to . + + ```csharp + public static void CheckServer() + { + HttpRequestCachePolicy policy = new HttpRequestCachePolicy + (HttpRequestCacheLevel.Revalidate); + HttpWebRequest.DefaultCachePolicy = policy; + } + ``` + + ```vb + Public Shared Sub CheckServer() + Dim policy As New HttpRequestCachePolicy _ + (HttpRequestCacheLevel.Revalidate) + HttpWebRequest.DefaultCachePolicy = policy + End Sub + ``` + ## See also - [Cache Management for Network Applications](cache-management-for-network-applications.md) - [Cache Policy](cache-policy.md) - [Location-Based Cache Policies](location-based-cache-policies.md) - [Time-Based Cache Policies](time-based-cache-policies.md) -- [\ Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) +- [`` Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) diff --git a/docs/framework/network-programming/how-to-set-cache-policy-for-a-request.md b/docs/framework/network-programming/how-to-set-cache-policy-for-a-request.md index 69b71c101e677..7fef7bd482ad9 100644 --- a/docs/framework/network-programming/how-to-set-cache-policy-for-a-request.md +++ b/docs/framework/network-programming/how-to-set-cache-policy-for-a-request.md @@ -2,110 +2,110 @@ title: "How to: Set Cache Policy for a Request" description: Learn how to set a cache policy for a request in the .NET Framework. This cache policy allows a resource to be used from the cache for up to a day. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "request cache policies" ms.assetid: 39c15e40-586b-4ac9-9cce-146f74b7e545 --- # How to: Set Cache Policy for a Request -The following example demonstrates setting a cache policy for a request. The example input is a URI such as `http://www.contoso.com/`. - -## Example +The following example demonstrates setting a cache policy for a request. The example input is a URI such as `http://www.contoso.com/`. - The following code example creates a cache policy that allows the requested resource to be used from the cache if it has not been in the cache for longer than one day. The example displays a message that indicates whether the resource was used from the cache—for example, `"The response was retrieved from the cache : False."`—and then displays the resource. A request can be fulfilled by any cache between the client and server. - -```csharp -using System; -using System.Net; -using System.Net.Cache; -using System.IO; - -namespace Examples.System.Net.Cache -{ - public class CacheExample +## Example + + The following code example creates a cache policy that allows the requested resource to be used from the cache if it has not been in the cache for longer than one day. The example displays a message that indicates whether the resource was used from the cache—for example, `"The response was retrieved from the cache : False."`—and then displays the resource. A request can be fulfilled by any cache between the client and server. + +```csharp +using System; +using System.Net; +using System.Net.Cache; +using System.IO; + +namespace Examples.System.Net.Cache +{ + public class CacheExample { - public static void UseCacheForOneDay(Uri resource) - { - // Create a policy that allows items in the cache - // to be used if they have been cached one day or less. + public static void UseCacheForOneDay(Uri resource) + { + // Create a policy that allows items in the cache + // to be used if they have been cached one day or less. HttpRequestCachePolicy requestPolicy = - new HttpRequestCachePolicy (HttpCacheAgeControl.MaxAge, - TimeSpan.FromDays(1)); - - WebRequest request = WebRequest.Create (resource); - // Set the policy for this request only. - request.CachePolicy = requestPolicy; - HttpWebResponse response = (HttpWebResponse)request.GetResponse(); - // Determine whether the response was retrieved from the cache. - Console.WriteLine ("The response was retrieved from the cache : {0}.", - response.IsFromCache); - Stream s = response.GetResponseStream (); - StreamReader reader = new StreamReader (s); - // Display the requested resource. - Console.WriteLine(reader.ReadToEnd()); - reader.Close (); - s.Close(); - response.Close(); - } - public static void Main(string[] args) - { - if (args == null || args.Length != 1) - { - Console.WriteLine ("You must specify the URI to retrieve."); - return; - } - UseCacheForOneDay (new Uri(args[0])); - } - } -} -``` - -```vb -Imports System -Imports System.Net -Imports System.Net.Cache -Imports System.IO -Namespace Examples.System.Net.Cache - Public Class CacheExample - Public Shared Sub UseCacheForOneDay(ByVal resource As Uri) - ' Create a policy that allows items in the cache - ' to be used if they have been cached one day or less. - Dim requestPolicy As New HttpRequestCachePolicy _ - (HttpCacheAgeControl.MaxAge, TimeSpan.FromDays(1)) - Dim request As WebRequest = WebRequest.Create(resource) - ' Set the policy for this request only. - request.CachePolicy = requestPolicy - Dim response As HttpWebResponse = _ - CType(request.GetResponse(), HttpWebResponse) - ' Determine whether the response was retrieved from the cache. - Console.WriteLine("The response was retrieved from the cache : {0}.", _ - response.IsFromCache) - Dim s As Stream = response.GetResponseStream() - Dim reader As New StreamReader(s) - ' Display the requested resource. - Console.WriteLine(reader.ReadToEnd()) - reader.Close() - s.Close() - response.Close() - End Sub - Public Shared Sub Main(ByVal args() As String) - If args Is Nothing OrElse args.Length <> 1 Then - Console.WriteLine("You must specify the URI to retrieve.") - Return - End If - UseCacheForOneDay(New Uri(args(0))) - End Sub - End Class -End Namespace -``` - + new HttpRequestCachePolicy (HttpCacheAgeControl.MaxAge, + TimeSpan.FromDays(1)); + + WebRequest request = WebRequest.Create (resource); + // Set the policy for this request only. + request.CachePolicy = requestPolicy; + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + // Determine whether the response was retrieved from the cache. + Console.WriteLine ("The response was retrieved from the cache : {0}.", + response.IsFromCache); + Stream s = response.GetResponseStream (); + StreamReader reader = new StreamReader (s); + // Display the requested resource. + Console.WriteLine(reader.ReadToEnd()); + reader.Close (); + s.Close(); + response.Close(); + } + public static void Main(string[] args) + { + if (args == null || args.Length != 1) + { + Console.WriteLine ("You must specify the URI to retrieve."); + return; + } + UseCacheForOneDay (new Uri(args[0])); + } + } +} +``` + +```vb +Imports System +Imports System.Net +Imports System.Net.Cache +Imports System.IO +Namespace Examples.System.Net.Cache + Public Class CacheExample + Public Shared Sub UseCacheForOneDay(ByVal resource As Uri) + ' Create a policy that allows items in the cache + ' to be used if they have been cached one day or less. + Dim requestPolicy As New HttpRequestCachePolicy _ + (HttpCacheAgeControl.MaxAge, TimeSpan.FromDays(1)) + Dim request As WebRequest = WebRequest.Create(resource) + ' Set the policy for this request only. + request.CachePolicy = requestPolicy + Dim response As HttpWebResponse = _ + CType(request.GetResponse(), HttpWebResponse) + ' Determine whether the response was retrieved from the cache. + Console.WriteLine("The response was retrieved from the cache : {0}.", _ + response.IsFromCache) + Dim s As Stream = response.GetResponseStream() + Dim reader As New StreamReader(s) + ' Display the requested resource. + Console.WriteLine(reader.ReadToEnd()) + reader.Close() + s.Close() + response.Close() + End Sub + Public Shared Sub Main(ByVal args() As String) + If args Is Nothing OrElse args.Length <> 1 Then + Console.WriteLine("You must specify the URI to retrieve.") + Return + End If + UseCacheForOneDay(New Uri(args(0))) + End Sub + End Class +End Namespace +``` + ## See also - [Cache Management for Network Applications](cache-management-for-network-applications.md) - [Cache Policy](cache-policy.md) - [Location-Based Cache Policies](location-based-cache-policies.md) - [Time-Based Cache Policies](time-based-cache-policies.md) -- [\ Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) +- [`` Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) diff --git a/docs/framework/network-programming/how-to-set-the-default-time-based-cache-policy-for-an-application.md b/docs/framework/network-programming/how-to-set-the-default-time-based-cache-policy-for-an-application.md index 909bba4381003..02a525faea36b 100644 --- a/docs/framework/network-programming/how-to-set-the-default-time-based-cache-policy-for-an-application.md +++ b/docs/framework/network-programming/how-to-set-the-default-time-based-cache-policy-for-an-application.md @@ -2,10 +2,10 @@ description: "Learn more about: How to: Set the Default Time-Based Cache Policy for an Application" title: "How to: Set the Default Time-Based Cache Policy for an Application" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "time-based cache policies" - "cache [.NET Framework], time-based policies" - "default time-based cache policy" @@ -13,56 +13,56 @@ ms.assetid: 6bfce066-a2e7-4add-a05e-85c12ec9f07f --- # How to: Set the Default Time-Based Cache Policy for an Application -The default time-based cache policy allows an application to have its cache behavior defined by the headers sent with the cached resource and the cache behavior defined in sections 13 and 14 of RFC 2616, available at [Internet Engineering Task Force (IETF)](https://www.ietf.org/) website. This is the appropriate cache behavior for most applications. - -### To set the default automatic policy for an application - -1. Create a default time-based policy object. - -2. Set the policy object as the default for the application domain. - -## Example +The default time-based cache policy allows an application to have its cache behavior defined by the headers sent with the cached resource and the cache behavior defined in sections 13 and 14 of RFC 2616, available at [Internet Engineering Task Force (IETF)](https://www.ietf.org/) website. This is the appropriate cache behavior for most applications. + +### To set the default automatic policy for an application + +1. Create a default time-based policy object. + +2. Set the policy object as the default for the application domain. + +## Example + + The two examples in this section produce identical policies. + + The following example creates a default time-based policy and sets it as the default for the application domain. + +```csharp +public static void SetDefaultTimeBasedPolicy () +{ + HttpRequestCachePolicy policy = new HttpRequestCachePolicy (); + HttpWebRequest.DefaultCachePolicy = policy ; +} +``` + +```vb +Public Shared Sub SetDefaultTimeBasedPolicy () + Dim policy = New HttpRequestCachePolicy () + HttpWebRequest.DefaultCachePolicy = policy +End Sub +``` + + You can also create the default time-based cache policy using the class as shown in the following example: + +```csharp +public static void SetDefaultTimeBasedPolicy2() +{ + RequestCachePolicy policy = new RequestCachePolicy (); + HttpWebRequest.DefaultCachePolicy = policy ; +} +``` + +```vb +Public Shared Sub SetDefaultTimeBasedPolicy2() + Dim policy As New RequestCachePolicy() + HttpWebRequest.DefaultCachePolicy = policy +End Sub +``` - The two examples in this section produce identical policies. - - The following example creates a default time-based policy and sets it as the default for the application domain. - -```csharp -public static void SetDefaultTimeBasedPolicy () -{ - HttpRequestCachePolicy policy = new HttpRequestCachePolicy (); - HttpWebRequest.DefaultCachePolicy = policy ; -} -``` - -```vb -Public Shared Sub SetDefaultTimeBasedPolicy () - Dim policy = New HttpRequestCachePolicy () - HttpWebRequest.DefaultCachePolicy = policy -End Sub -``` - - You can also create the default time-based cache policy using the class as shown in the following example: - -```csharp -public static void SetDefaultTimeBasedPolicy2() -{ - RequestCachePolicy policy = new RequestCachePolicy (); - HttpWebRequest.DefaultCachePolicy = policy ; -} -``` - -```vb -Public Shared Sub SetDefaultTimeBasedPolicy2() - Dim policy As New RequestCachePolicy() - HttpWebRequest.DefaultCachePolicy = policy -End Sub -``` - ## See also - [Cache Management for Network Applications](cache-management-for-network-applications.md) - [Cache Policy](cache-policy.md) - [Location-Based Cache Policies](location-based-cache-policies.md) - [Time-Based Cache Policies](time-based-cache-policies.md) -- [\ Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) +- [`` Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) diff --git a/docs/framework/network-programming/internet-authentication.md b/docs/framework/network-programming/internet-authentication.md index 32521e282381e..83eb0398699b6 100644 --- a/docs/framework/network-programming/internet-authentication.md +++ b/docs/framework/network-programming/internet-authentication.md @@ -2,7 +2,7 @@ title: "Internet Authentication" description: Learn about the variety of client authentication mechanisms that System.Net classes support for your applications in the .NET Framework. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "authentication [.NET Framework], classes" - "IAuthenticationModule interface" - "ICredentialLookup interface" @@ -19,22 +19,22 @@ ms.assetid: d342e87c-f672-4660-a513-41a2f2b80c4a --- # Internet Authentication -The classes support a variety of client authentication mechanisms, including the standard Internet authentication methods basic, digest, negotiate, NTLM, and Kerberos authentication, as well as custom methods that you can create. - - Authentication credentials are stored in the and classes, which implement the interface. When one of these classes is queried for credentials, it returns an instance of the **NetworkCredential** class. The authentication process is managed by the class, and the actual authentication process is performed by an authentication module class that implements the interface. You must register a custom authentication module with the **AuthenticationManager** before it can be used; modules for the basic, digest, negotiate, NTLM, and Kerberos authentication methods are registered by default. - - **NetworkCredential** stores a set of credentials associated with a single Internet resource identified by a URI and returns them in response to any call to the method. The **NetworkCredential** class is typically used by applications that access a limited number of Internet resources or by applications that use the same set of credentials in all cases. - - The **CredentialCache** class stores a collection of credentials for various Web resources. When the method is called, **CredentialCache** returns the proper set of credentials, as determined by the URI of the Web resource and the requested authentication scheme. Applications that use a variety of Internet resources with different authentication schemes benefit from using the **CredentialCache** class, since it stores all the credentials and provides them as requested. - - When an Internet resource requests authentication, the method sends the to the **AuthenticationManager** along with the request for credentials. The request is then authenticated according to the following process: - -1. The **AuthenticationManager** calls the method on each of the registered authentication modules in the order they were registered. The **AuthenticationManager** uses the first module that does not return **null** to carry out the authentication process. The details of the process vary depending on the type of authentication module involved. - -2. When the authentication process is complete, the authentication module returns an to the **WebRequest** that contains the information needed to access the Internet resource. - - Some authentication schemes can authenticate a user without first making a request for a resource. An application can save time by preauthenticating the user with the resource, thus eliminating at least one round trip to the server. Or, it can perform authentication during program startup in order to be more responsive to the user later. Authentication schemes that can use preauthentication set the property to **true**. - +The classes support a variety of client authentication mechanisms, including the standard Internet authentication methods basic, digest, negotiate, NTLM, and Kerberos authentication, as well as custom methods that you can create. + + Authentication credentials are stored in the and classes, which implement the interface. When one of these classes is queried for credentials, it returns an instance of the `NetworkCredential` class. The authentication process is managed by the class, and the actual authentication process is performed by an authentication module class that implements the interface. You must register a custom authentication module with the `AuthenticationManager` before it can be used; modules for the basic, digest, negotiate, NTLM, and Kerberos authentication methods are registered by default. + + `NetworkCredential` stores a set of credentials associated with a single Internet resource identified by a URI and returns them in response to any call to the method. The `NetworkCredential` class is typically used by applications that access a limited number of Internet resources or by applications that use the same set of credentials in all cases. + + The `CredentialCache` class stores a collection of credentials for various Web resources. When the method is called, `CredentialCache` returns the proper set of credentials, as determined by the URI of the Web resource and the requested authentication scheme. Applications that use a variety of Internet resources with different authentication schemes benefit from using the `CredentialCache` class, since it stores all the credentials and provides them as requested. + + When an Internet resource requests authentication, the method sends the to the `AuthenticationManager` along with the request for credentials. The request is then authenticated according to the following process: + +1. The `AuthenticationManager` calls the method on each of the registered authentication modules in the order they were registered. The `AuthenticationManager` uses the first module that does not return `null` to carry out the authentication process. The details of the process vary depending on the type of authentication module involved. + +2. When the authentication process is complete, the authentication module returns an to the `WebRequest` that contains the information needed to access the Internet resource. + + Some authentication schemes can authenticate a user without first making a request for a resource. An application can save time by preauthenticating the user with the resource, thus eliminating at least one round trip to the server. Or, it can perform authentication during program startup in order to be more responsive to the user later. Authentication schemes that can use preauthentication set the property to **true**. + ## See also - [Basic and Digest Authentication](basic-and-digest-authentication.md) diff --git a/docs/framework/network-programming/interpreting-network-tracing.md b/docs/framework/network-programming/interpreting-network-tracing.md index fab28b2873f6d..64dcf5fc20fb0 100644 --- a/docs/framework/network-programming/interpreting-network-tracing.md +++ b/docs/framework/network-programming/interpreting-network-tracing.md @@ -2,7 +2,7 @@ title: "Interpreting Network Tracing" description: Find out how to use tracing to capture calls your application makes to various System.Net class members in the .NET Framework. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "TraceMode attribute" - "hexadecimal data, network tracing output" - "network tracing, analyzing" @@ -13,33 +13,33 @@ ms.assetid: ad22b4b8-00af-4778-9cca-cb609ce1f8ff --- # Interpreting Network Tracing -When network tracing is enabled, you can use tracing to capture calls your application makes to various class members. The output from these calls may be similar to the following examples. - +When network tracing is enabled, you can use tracing to capture calls your application makes to various class members. The output from these calls may be similar to the following examples. + ```output -[588] (4357) Entering Socket#33574638::Send() +[588] (4357) Entering Socket#33574638::Send() [588] (4387) Exiting Socket#33574638::Send()-> 61#61 -``` - - In the preceding example, [588] is the current thread's unique identifier. (4357) and (4387) are timestamps denoting the number of milliseconds that have elapsed since the application started. The data following the timestamp shows the application entering and exiting the method **Socket.Send**. The object executing the **Send** method has 33574638 as its unique identifier. The method exit trace includes the return value (61 in the preceding example). - - Network traces can capture network traffic that is sent from or received by your application using application-level protocols such as Hypertext Transfer Protocol (HTTP). This data can be captured as text and, optionally, hexadecimal data. Hexadecimal data is available when you specify **includehex** as the value of the **tracemode** attribute. (For detailed information about this attribute, see [How to: Configure Network Tracing](how-to-configure-network-tracing.md).) The following example trace was generated using **includehex**. - - `[1692] (1142) 00000000 : 47 45 54 20 2F 77 70 61-64 2E 64 61 74 20 48 54 : GET /wpad.dat HT` - - `[1692] (1142) 00000010 : 54 50 2F 31 2E 31 0D 0A-48 6F 73 74 3A 20 69 74 : TP/1.1..Host: it` - - `[1692] (1142) 00000020 : 67 70 72 6F 78 79 0D 0A-43 6F 6E 6E 65 63 74 69 : gproxy..Connecti` - - `[1692] (1142) 00000030 : 6F 6E 3A 20 43 6C 6F 73-65 0D 0A 0D 0A : on: Close....` - - To omit hexadecimal data, specify **protocolonly** as the value for the **tracemode** attribute. The following example shows the trace when **protocolonly** is specified. - - `[2444] (594) Data from ConnectStream#33574638::WriteHeaders< or class constructor. The type of location-based policy is passed to the constructor using a or enumeration value. For code examples that create location-based cache policies, see [How to: Set a Location-Based Cache Policy for an Application](how-to-set-a-location-based-cache-policy-for-an-application.md). The following sections explain each type of location-based cache policy for Hypertext Transfer Protocol (http and https) resources. - -## Cache If Available Policy +A location-based cache policy defines the freshness of valid cached entries based on where the requested resource can be taken from. A cached resource is valid if using it does not does not violate server-specified revalidation requirements. A location-based cache policy is created programmatically by using a or class constructor. The type of location-based policy is passed to the constructor using a or enumeration value. For code examples that create location-based cache policies, see [How to: Set a Location-Based Cache Policy for an Application](how-to-set-a-location-based-cache-policy-for-an-application.md). The following sections explain each type of location-based cache policy for Hypertext Transfer Protocol (http and https) resources. - If a valid requested resource is in the local cache, the cached resource is used; otherwise, the request for the resource is sent to the server. If the requested resource is available in any cache between the client and the server, the request can be satisfied by an intermediate cache. - -## Cache Only Policy +## Cache If Available Policy - If a valid requested resource is in the local cache, the cached resource is used. When this cache policy level is specified, a exception is thrown if the item is not in the local cache. - -## Cache Or Next Cache Only Policy + If a valid requested resource is in the local cache, the cached resource is used; otherwise, the request for the resource is sent to the server. If the requested resource is available in any cache between the client and the server, the request can be satisfied by an intermediate cache. - If a valid requested resource is in the local cache or an intermediate cache on the local area network, the cached resource is used. Otherwise, a exception is thrown. In the HTTP caching protocol, this is achieved using the only-if-cached cache control directive. - -## No Cache No Store Policy +## Cache Only Policy - A requested resource is never used from any cache and is never placed in any cache. If a requested resource is present in the local cache, it is removed. This policy level indicates to intermediate caches that they should also remove the resource. In the HTTP caching protocol, this is achieved using the no-store cache control directive. - -## Refresh Policy + If a valid requested resource is in the local cache, the cached resource is used. When this cache policy level is specified, a exception is thrown if the item is not in the local cache. - A requested resource can be used if it is obtained from the server or found in a cache other than the local cache. Before the request can be satisfied by an intermediate cache, that cache must revalidate its cached entry with the server. In the HTTP caching protocol, this is achieved using the max-age = 0 cache control directive and the no-cache Pragma header. - -## Reload Policy +## Cache Or Next Cache Only Policy - Requested resources must be obtained from the server. The response might be saved in the local cache. In the HTTP caching protocol, this is achieved using the no-cache cache control directive and the no-cache Pragma header. - -## Revalidate Policy + If a valid requested resource is in the local cache or an intermediate cache on the local area network, the cached resource is used. Otherwise, a exception is thrown. In the HTTP caching protocol, this is achieved using the only-if-cached cache control directive. + +## No Cache No Store Policy + + A requested resource is never used from any cache and is never placed in any cache. If a requested resource is present in the local cache, it is removed. This policy level indicates to intermediate caches that they should also remove the resource. In the HTTP caching protocol, this is achieved using the no-store cache control directive. + +## Refresh Policy + + A requested resource can be used if it is obtained from the server or found in a cache other than the local cache. Before the request can be satisfied by an intermediate cache, that cache must revalidate its cached entry with the server. In the HTTP caching protocol, this is achieved using the max-age = 0 cache control directive and the no-cache Pragma header. + +## Reload Policy + + Requested resources must be obtained from the server. The response might be saved in the local cache. In the HTTP caching protocol, this is achieved using the no-cache cache control directive and the no-cache Pragma header. + +## Revalidate Policy + + Compares the copy of the resource in the cache with the copy on the server. If the copy on the server is newer, it is used to satisfy the request and replaces the copy in the cache. If the copy in the cache is the same as the server copy, the cached copy is used. In the HTTP caching protocol, this is achieved using a conditional request. - Compares the copy of the resource in the cache with the copy on the server. If the copy on the server is newer, it is used to satisfy the request and replaces the copy in the cache. If the copy in the cache is the same as the server copy, the cached copy is used. In the HTTP caching protocol, this is achieved using a conditional request. - ## See also - [Cache Management for Network Applications](cache-management-for-network-applications.md) - [Cache Policy](cache-policy.md) - [Time-Based Cache Policies](time-based-cache-policies.md) - [Configuring Caching in Network Applications](configuring-caching-in-network-applications.md) -- [\ Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) +- [`` Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) diff --git a/docs/framework/network-programming/time-based-cache-policies.md b/docs/framework/network-programming/time-based-cache-policies.md index 43d14ff81ba01..0426412e89d8a 100644 --- a/docs/framework/network-programming/time-based-cache-policies.md +++ b/docs/framework/network-programming/time-based-cache-policies.md @@ -2,7 +2,7 @@ description: "Learn more about: Time-Based Cache Policies" title: "Time-Based Cache Policies" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "time-based cache policies" - "cache synchronization date policy" - "cache [.NET Framework], time-based policies" @@ -21,51 +21,51 @@ ms.assetid: 74f0bcaf-5c95-40c1-9967-f3bbf1d2360a --- # Time-Based Cache Policies -A time-based cache policy defines the freshness of cached entries using the time the resource was retrieved, the headers returned with the resource, and the current time. When setting a time-based cache policy, you can either use the time-based policy or create a customized time-based policy. When using the default time-based policy for resources obtained using Hypertext Transfer Protocol (HTTP), the exact cache behavior is determined by the headers included in the cached response and by the behaviors specified in sections 13 and 14 of RFC 2616, available at [Internet Engineering Task Force (IETF)](https://www.ietf.org/) website. For a code example that demonstrates setting the default time-based policy for HTTP resources, see [How to: Set the Default Time-Based Cache Policy for an Application](how-to-set-the-default-time-based-cache-policy-for-an-application.md). For code examples that demonstrate creating and using cache policies, see [Configuring Caching in Network Applications](configuring-caching-in-network-applications.md). - -## Criteria to Determine Freshness of Cached Entries - - To customize a time-based cache policy, you can specify that one or more of the following criteria be used to determine the freshness of cached entries: - -- Maximum age - -- Maximum staleness - -- Minimum freshness - -- Cache synchronization date - +A time-based cache policy defines the freshness of cached entries using the time the resource was retrieved, the headers returned with the resource, and the current time. When setting a time-based cache policy, you can either use the time-based policy or create a customized time-based policy. When using the default time-based policy for resources obtained using Hypertext Transfer Protocol (HTTP), the exact cache behavior is determined by the headers included in the cached response and by the behaviors specified in sections 13 and 14 of RFC 2616, available at [Internet Engineering Task Force (IETF)](https://www.ietf.org/) website. For a code example that demonstrates setting the default time-based policy for HTTP resources, see [How to: Set the Default Time-Based Cache Policy for an Application](how-to-set-the-default-time-based-cache-policy-for-an-application.md). For code examples that demonstrate creating and using cache policies, see [Configuring Caching in Network Applications](configuring-caching-in-network-applications.md). + +## Criteria to Determine Freshness of Cached Entries + + To customize a time-based cache policy, you can specify that one or more of the following criteria be used to determine the freshness of cached entries: + +- Maximum age + +- Maximum staleness + +- Minimum freshness + +- Cache synchronization date + > [!NOTE] -> Using the default time-based cache policy should not be confused with setting a default cache policy for your application. The default time-based policy is a specific policy that can be used at the request or application level. The default cache policy for your application is a policy (location-based or time-based) that takes effect when no policy is set on a request. For details on setting a default cache policy for your application, see . - -### Maximum Age - - The maximum age policy criterion specifies the amount of time a cached copy of a resource can be used. If the cached copy of the resource is older than the amount of time specified, the resource must be revalidated by checking it against the content on the server. If the maximum age would allow the resource to be used after it expires, this criteria is not honored unless a maximum staleness value is also specified. - -### Maximum Staleness - - The maximum staleness policy criterion specifies the length of time after content expiration that the cached copy of the resource can be used. This is the only cache policy criterion that permits resources to be used after they have expired. - -### Minimum Freshness - - The minimum freshness policy criterion specifies the length of time before content expiration that the cached copy of the resource can be used. This policy has the effect of causing a cache entry to expire before its expiration date; therefore, the minimum freshness and maximum staleness settings are mutually exclusive. - -## Cache Synchronization Date - - The cache synchronization date policy criterion determines when a cached copy of a resource must be revalidated by checking it against the content on the server. If the content has changed since the item was cached, it is retrieved from the server, stored in the cache, and returned to the application. If the content has not changed, its timestamp is updated and the application gets the cached content. - - The cache synchronization date allows you to specify an absolute date when cached contents must be revalidated. If a fresh cache entry was last revalidated prior to the cache synchronization date, revalidation with the server still occurs. If the cache entry was revalidated after the cache synchronization date and there are no additional freshness or server revalidation requirements that invalidate the cached entry, the entry from the cache is used. If the cache synchronization date is set to a future date, the entry is revalidated every time it is requested, until the cache synchronization date passes. - - The following topics provide information about the effects of combining time-based cache policy criteria: - -- [Cache Policy Interaction—Maximum Age and Maximum Staleness](cache-policy-interaction-maximum-age-and-maximum-staleness.md) - -- [Cache Policy Interaction—Maximum Age and Minimum Freshness](cache-policy-interaction-maximum-age-and-minimum-freshness.md) - +> Using the default time-based cache policy should not be confused with setting a default cache policy for your application. The default time-based policy is a specific policy that can be used at the request or application level. The default cache policy for your application is a policy (location-based or time-based) that takes effect when no policy is set on a request. For details on setting a default cache policy for your application, see . + +### Maximum Age + + The maximum age policy criterion specifies the amount of time a cached copy of a resource can be used. If the cached copy of the resource is older than the amount of time specified, the resource must be revalidated by checking it against the content on the server. If the maximum age would allow the resource to be used after it expires, this criteria is not honored unless a maximum staleness value is also specified. + +### Maximum Staleness + + The maximum staleness policy criterion specifies the length of time after content expiration that the cached copy of the resource can be used. This is the only cache policy criterion that permits resources to be used after they have expired. + +### Minimum Freshness + + The minimum freshness policy criterion specifies the length of time before content expiration that the cached copy of the resource can be used. This policy has the effect of causing a cache entry to expire before its expiration date; therefore, the minimum freshness and maximum staleness settings are mutually exclusive. + +## Cache Synchronization Date + + The cache synchronization date policy criterion determines when a cached copy of a resource must be revalidated by checking it against the content on the server. If the content has changed since the item was cached, it is retrieved from the server, stored in the cache, and returned to the application. If the content has not changed, its timestamp is updated and the application gets the cached content. + + The cache synchronization date allows you to specify an absolute date when cached contents must be revalidated. If a fresh cache entry was last revalidated prior to the cache synchronization date, revalidation with the server still occurs. If the cache entry was revalidated after the cache synchronization date and there are no additional freshness or server revalidation requirements that invalidate the cached entry, the entry from the cache is used. If the cache synchronization date is set to a future date, the entry is revalidated every time it is requested, until the cache synchronization date passes. + + The following topics provide information about the effects of combining time-based cache policy criteria: + +- [Cache Policy Interaction—Maximum Age and Maximum Staleness](cache-policy-interaction-maximum-age-and-maximum-staleness.md) + +- [Cache Policy Interaction—Maximum Age and Minimum Freshness](cache-policy-interaction-maximum-age-and-minimum-freshness.md) + ## See also - [Cache Management for Network Applications](cache-management-for-network-applications.md) - [Cache Policy](cache-policy.md) - [Location-Based Cache Policies](location-based-cache-policies.md) - [Configuring Caching in Network Applications](configuring-caching-in-network-applications.md) -- [\ Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) +- [`` Element (Network Settings)](../configure-apps/file-schema/network/requestcaching-element-network-settings.md) diff --git a/docs/framework/network-programming/web-and-socket-permissions.md b/docs/framework/network-programming/web-and-socket-permissions.md index acbe23bdeb433..c2931e705e3f8 100644 --- a/docs/framework/network-programming/web-and-socket-permissions.md +++ b/docs/framework/network-programming/web-and-socket-permissions.md @@ -2,7 +2,7 @@ title: "Web and Socket Permissions" description: Learn how the WebPermission and SocketPermission classes provide internet security for using the System.Net namespace in the .NET Framework. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "Networking" - "positions [.NET Framework], accepting" - "sockets, permissions" @@ -19,16 +19,16 @@ ms.assetid: d51ad8cb-03ae-4a51-bfcd-cfcf6b98afa9 --- # Web and Socket Permissions -Internet security for applications using the namespace is provided by the and classes. The **WebPermission** class controls an application's right to request data from a URI or to serve a URI to the Internet. The **SocketPermission** class controls an application's right to use a to accept data on a local port or to contact remote devices using a transport protocol at another address, based on the host, port number, and transport protocol of the socket. - - Which permission class you use depends on your application type. Applications that use and its descendants should use the **WebPermission** class to manage permissions. Applications that use socket-level access should use the **SocketPermission** class to manage permissions. - - **WebPermission** and **SocketPermission** define two permissions: accept and connect. Accept grants the application the right to answer an incoming connection from another party. Connect grants the application the right to initiate a connection to another party. - - For **SocketPermission** instances, accept means that an application can accept incoming connections on a local transport address; connect means that an application can connect to some remote (or local) transport address. - - For **WebPermission** instances, accept means that an application can export the URI controlled by the **WebPermission** to the world; connect means that an application can access that URI (whether it is remote or local). - +Internet security for applications using the namespace is provided by the and classes. The `WebPermission` class controls an application's right to request data from a URI or to serve a URI to the Internet. The `SocketPermission` class controls an application's right to use a to accept data on a local port or to contact remote devices using a transport protocol at another address, based on the host, port number, and transport protocol of the socket. + + Which permission class you use depends on your application type. Applications that use and its descendants should use the `WebPermission` class to manage permissions. Applications that use socket-level access should use the `SocketPermission` class to manage permissions. + + `WebPermission` and `SocketPermission` define two permissions: accept and connect. Accept grants the application the right to answer an incoming connection from another party. Connect grants the application the right to initiate a connection to another party. + + For `SocketPermission` instances, accept means that an application can accept incoming connections on a local transport address; connect means that an application can connect to some remote (or local) transport address. + + For `WebPermission` instances, accept means that an application can export the URI controlled by the `WebPermission` to the world; connect means that an application can access that URI (whether it is remote or local). + ## See also - [Security](../../standard/security/index.md) diff --git a/docs/framework/reflection-and-codedom/using-the-codedom.md b/docs/framework/reflection-and-codedom/using-the-codedom.md index cdbc556995f2c..23b73a127a273 100644 --- a/docs/framework/reflection-and-codedom/using-the-codedom.md +++ b/docs/framework/reflection-and-codedom/using-the-codedom.md @@ -45,7 +45,7 @@ The following walkthrough provides an example of how to build a CodeDOM object g #### Create a compile unit -The CodeDOM defines an object called a , which can reference a CodeDOM object graph that models the source code to compile. A **CodeCompileUnit** has properties for storing references to attributes, namespaces, and assemblies. +The CodeDOM defines an object called a , which can reference a CodeDOM object graph that models the source code to compile. A `CodeCompileUnit` has properties for storing references to attributes, namespaces, and assemblies. The CodeDom providers that derive from the class contain methods that process the object graph referenced by a **CodeCompileUnit**. @@ -61,7 +61,7 @@ A can contain a section of source c #### Define a namespace -To define a namespace, create a and assign a name for it using the appropriate constructor or by setting its **Name** property. +To define a namespace, create a and assign a name for it using the appropriate constructor or by setting its `Name` property. [!code-cpp[CodeDomExample#13](../../../samples/snippets/cpp/VS_Snippets_CLR/CodeDomExample/CPP/source2.cpp#13)] [!code-csharp[CodeDomExample#13](../../../samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source2.cs#13)] @@ -71,7 +71,7 @@ To define a namespace, create a and assign a To add a namespace import directive to the namespace, add a that indicates the namespace to import to the **CodeNamespace.Imports** collection. -The following code adds an import for the **System** namespace to the **Imports** collection of a **CodeNamespace** named `samples`: +The following code adds an import for the `System` namespace to the `Imports` collection of a `CodeNamespace` named `samples`: [!code-cpp[CodeDomExample#14](../../../samples/snippets/cpp/VS_Snippets_CLR/CodeDomExample/CPP/source2.cpp#14)] [!code-csharp[CodeDomExample#14](../../../samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source2.cs#14)] @@ -81,7 +81,7 @@ The following code adds an import for the **System** namespace to the **Imports* All code elements that form a CodeDOM graph must be linked to the that is the root element of the tree by a series of references between elements directly referenced from the properties of the root object of the graph. Set an object to a property of a container object to establish a reference from the container object. -The following statement adds the `samples` **CodeNamespace** to the **Namespaces** collection property of the root **CodeCompileUnit**. +The following statement adds the `samples` `CodeNamespace` to the `Namespaces` collection property of the root **CodeCompileUnit**. [!code-cpp[CodeDomExample#15](../../../samples/snippets/cpp/VS_Snippets_CLR/CodeDomExample/CPP/source2.cpp#15)] [!code-csharp[CodeDomExample#15](../../../samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source2.cs#15)] @@ -89,15 +89,15 @@ The following statement adds the `samples` **CodeNamespace** to the **Namespaces #### Define a type -To declare a class, structure, interface, or enumeration using the CodeDOM, create a new , and assign it a name. The following example demonstrates this using a constructor overload to set the **Name** property: +To declare a class, structure, interface, or enumeration using the CodeDOM, create a new , and assign it a name. The following example demonstrates this using a constructor overload to set the `Name` property: [!code-cpp[CodeDomExample#16](../../../samples/snippets/cpp/VS_Snippets_CLR/CodeDomExample/CPP/source2.cpp#16)] [!code-csharp[CodeDomExample#16](../../../samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source2.cs#16)] [!code-vb[CodeDomExample#16](../../../samples/snippets/visualbasic/VS_Snippets_CLR/CodeDomExample/VB/source2.vb#16)] -To add a type to a namespace, add a that represents the type to add to the namespace to the **Types** collection of a **CodeNamespace**. +To add a type to a namespace, add a that represents the type to add to the namespace to the `Types` collection of a **CodeNamespace**. -The following example demonstrates how to add a class named `class1` to a **CodeNamespace** named `samples`: +The following example demonstrates how to add a class named `class1` to a `CodeNamespace` named `samples`: [!code-cpp[CodeDomExample#17](../../../samples/snippets/cpp/VS_Snippets_CLR/CodeDomExample/CPP/source2.cpp#17)] [!code-csharp[CodeDomExample#17](../../../samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source2.cs#17)] @@ -105,7 +105,7 @@ The following example demonstrates how to add a class named `class1` to a **Code #### Add class members to a class -The namespace provides a variety of elements that can be used to represent class members. Each class member can be added to the **Members** collection of a . +The namespace provides a variety of elements that can be used to represent class members. Each class member can be added to the `Members` collection of a . #### Define a code entry point method for an executable @@ -117,7 +117,7 @@ The following example demonstrates how to define an entry point method that cont [!code-csharp[CodeDomExample#18](../../../samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source2.cs#18)] [!code-vb[CodeDomExample#18](../../../samples/snippets/visualbasic/VS_Snippets_CLR/CodeDomExample/VB/source2.vb#18)] -The following statement adds the entry point method named `Start` to the **Members** collection of `class1`: +The following statement adds the entry point method named `Start` to the `Members` collection of `class1`: [!code-cpp[CodeDomExample#19](../../../samples/snippets/cpp/VS_Snippets_CLR/CodeDomExample/CPP/source2.cpp#19)] [!code-csharp[CodeDomExample#19](../../../samples/snippets/csharp/VS_Snippets_CLR/CodeDomExample/CS/source2.cs#19)] diff --git a/docs/framework/tools/al-exe-assembly-linker.md b/docs/framework/tools/al-exe-assembly-linker.md index 7737af7307d77..7264e542831ac 100644 --- a/docs/framework/tools/al-exe-assembly-linker.md +++ b/docs/framework/tools/al-exe-assembly-linker.md @@ -48,7 +48,7 @@ You can specify the following `options`; you must specify **/out**. |**/copy[right]:** `text`|Specifies a string for the Copyright field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/copyright** appears in File Explorer as the Win32 Copyright resource.

If text is an empty string, the Win32 Copyright resource appears as a single space.

If you specify **/win32res**, **/copyright** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| |**/c[ulture]:** `text`|Specifies the culture string to associate with the assembly. Valid values for cultures are those defined by the Internet Requests for Comments (RFC) document 1766 titled "Tags for the Identification of Languages."

Place the string in double quotation marks (" ") if `text` contains a space. There is no default culture string. This string is available for viewing with reflection.

For information about valid `text` strings, see the .

You can also specify this option as a custom attribute () in the source code for any CIL module.| |`/delay[sign][+ or -]`|Specifies whether the assembly will be fully or partially signed. Use **/delaysign-** if you want a fully signed assembly. Use **/delaysign+** if you only want to include the public key in the assembly.

When you request a fully signed assembly, *Al.exe* hashes the file that contains the manifest (assembly metadata) and signs that hash with the private key. The resulting digital signature is stored in the file that contains the manifest. When an assembly is delay signed, *Al.exe* does not compute and store the signature, but just reserves space in the file so the signature can be added later.

The default is **/delaysign-**.

The **/delaysign** option has no effect unless used with **/keyfile** or **/keyname**.

For example, using **/delaysign+** enables a tester to put the assembly in the global cache. After testing, you can fully sign the assembly by including the private key in the assembly.

Note: Before using the [*Gacutil.exe* (Global Assembly Cache Tool)](gacutil-exe-gac-tool.md) to put a delay-signed assembly into the global cache, use the [*Sn.exe* (Strong Name Tool)](sn-exe-strong-name-tool.md) to register the assembly for verification skipping. For example, `Sn.exe -Vr delaySignedAssembly`. Use this only for development.

You can also specify this option as a custom attribute () in the source code for any CIL module.| -|**/descr[iption]:** `text`|Specifies a string for the field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/description** appears in File Explorer as the Win32 **Comments** resource.

If text is an empty string, the Win32 **Comments** resource appears as a single space.

If you specify **/win32res**, **/description** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| +|**/descr[iption]:** `text`|Specifies a string for the field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/description** appears in File Explorer as the Win32 `Comments` resource.

If text is an empty string, the Win32 `Comments` resource appears as a single space.

If you specify **/win32res**, **/description** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| |**/e[vidence]:** `file`|Embeds `file` in the assembly with the resource name of Security.Evidence.

You cannot use Security.Evidence for regular resources.| |**/fileversion:** `version`|Specifies a string for the **File Version** field in the assembly. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/fileversion** will be used as the Win32 **File Version** resource. If you do not specify **/fileversion**, the Win32 **File Version** resource will be populated by the Win32 **Assembly Version** resource.

If **/win32res** is specified, **/fileversion** does not affect the Win32 resource.

You can also specify this option as a custom attribute (AssemblyFileVersionAttribute) in the source code for any CIL module.| |**/flags:** `flags`|Specifies a value for the `Flags` field in the assembly. Possible values for `flags`:

0x0000
The assembly is side-by-side compatible.

0x0010
The assembly cannot execute with other versions if they are executing in the same application domain.

0x0020
The assembly cannot execute with other versions if they are executing in the same process.

0x0030
The assembly cannot execute with other versions if they are executing on the same computer.

You can also specify this option as a custom attribute () in the source code for any CIL module.| @@ -60,12 +60,12 @@ You can specify the following `options`; you must specify **/out**. |**/nologo**|Suppresses the banner, or logo, displayed at the command line when you invoke *Al.exe*.| |**/out:** `filename`|Specifies the name of the file produced by *Al.exe*. This is a required option.| |**/platform:** `text`|Limits which platform this code can run on; must be one of x86, Itanium, x64, anycpu (the default), or anycpu32bitpreferred.| -|**/prod[uct]:** `text`|Specifies a string for the **Product** field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/product** appears in File Explorer as the Win32 **Product Name** resource.

If text is an empty string, the Win32 **Product Name** resource appears as a single space.

If you specify **/win32res**, **/product** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| +|**/prod[uct]:** `text`|Specifies a string for the `Product` field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/product** appears in File Explorer as the Win32 **Product Name** resource.

If text is an empty string, the Win32 **Product Name** resource appears as a single space.

If you specify **/win32res**, **/product** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| |**/productv[ersion]:** `text`|Specifies a string for the **Product Version** field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/productversion** will be used as the Win32 **Product Version** resource. If you do not specify **/productversion**, the Win32 **Product Version** resource will be populated by the Win32 **File Version** resource.

If you specify **/win32res**, **/productversion** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| |**/t[arget]:** `lib[rary]` | `exe` | `win[exe]`|Specifies the file format of the output file: `lib[rary]` (code library), `exe` (console application), or `win[exe]` (Windows-based application). The default is `lib[rary]`.| |**/template:** `filename`|Specifies the assembly, `filename`, from which to inherit all assembly metadata, except the culture field.

An assembly that you create with **/template** will be a satellite assembly.| -|**/title:** `text`|Specifies a string for the **Title** field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/title** appears in File Explorer as the Win32 **Description** resource, which is used by the shell as the friendly name of an application. It is also displayed on the **Open With** submenu of the shortcut menu for a file type for which there are multiple supporting applications.

If text is an empty string, the Win32 **Description** resource appears as a single space.

If you specify **/win32res**, **/title** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| -|**/trade[mark]:** `text`|Specifies a string for the **Trademark** field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/trademark** appears in File Explorer as the Win32 **Trademark** resource.

If text is an empty string, the Win32 **Trademark** resource appears as a single space.

If you specify **/win32res**, **/trademark** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| +|**/title:** `text`|Specifies a string for the `Title` field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/title** appears in File Explorer as the Win32 `Description` resource, which is used by the shell as the friendly name of an application. It is also displayed on the **Open With** submenu of the shortcut menu for a file type for which there are multiple supporting applications.

If text is an empty string, the Win32 `Description` resource appears as a single space.

If you specify **/win32res**, **/title** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| +|**/trade[mark]:** `text`|Specifies a string for the `Trademark` field in the assembly. Place the string in double quotation marks (" ") if `text` contains a space. This string is a custom attribute on the assembly and is available for viewing with reflection.

If you do not specify **/win32res**, **/trademark** appears in File Explorer as the Win32 `Trademark` resource.

If text is an empty string, the Win32 `Trademark` resource appears as a single space.

If you specify **/win32res**, **/trademark** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| |**/v[ersion]:** `version`|Specifies version information for this assembly. The format of the version string is `major`.`minor`.`build`.`revision`. The default value is 0.

If you do specify **/version**, you must specify `major`. If you specify `major` and `minor`, you can specify an asterisk (\*)for `build`. This causes `build` to be equal to the number of days since January 1, 2000, local time, and `revision` to be equal to the number of seconds since midnight of the current day, local time, divided by 2.

If you specify `major`, `minor`, and `build`, you can specify an asterisk for `revision`. This causes `revision` to be equal to the number of seconds since midnight of the current day, local time, divided by 2.

To summarize, the valid version strings are as follows:

X

X.X

X.X.\*

X.X.X

X.X.X.\*

X.X.X.X

where X is any unsigned short constant except 65535 (0-65534).

If you do not specify **/win32res**, **/version** will be used as the Win32 **Assembly Version** resource.

If you do not specify **/win32res**, **/productversion**, and **/fileversion**, **/version** will be used for the **Assembly Version**, File Version, and **Product Version** Win32 resources.

If you specify **/win32res**, **/version** will not affect the Win32 resource information.

You can also specify this option as a custom attribute () in the source code for any CIL module.| |**/win32icon:** `filename`|Inserts an .ico file in the assembly. The .ico file gives the output file the desired appearance in File Explorer.| |**/win32res:** `filename`|Inserts a Win32 resource (.res file) in the output file. A Win32 resource file can be created by using the Resource Compiler. The Resource Compiler is invoked when you compile a Visual C++ program; a .res file is created from the .rc file.| diff --git a/docs/framework/tools/caspol-exe-code-access-security-policy-tool.md b/docs/framework/tools/caspol-exe-code-access-security-policy-tool.md index b5c9b0b194d89..a22ddad0ac433 100644 --- a/docs/framework/tools/caspol-exe-code-access-security-policy-tool.md +++ b/docs/framework/tools/caspol-exe-code-access-security-policy-tool.md @@ -22,7 +22,7 @@ ms.assetid: d2bf6123-7b0c-4e60-87ad-a39a1c3eb2e0 The Code Access Security (CAS) Policy tool (Caspol.exe) enables users and administrators to modify security policy for the machine policy level, the user policy level, and the enterprise policy level. > [!IMPORTANT] -> Starting with .NET Framework 4, Caspol.exe does not affect CAS policy unless the [\ element](../configure-apps/file-schema/runtime/netfx40-legacysecuritypolicy-element.md) is set to `true`. Any settings shown or modified by CasPol.exe will only affect applications that opt in to using CAS policy. +> Starting with .NET Framework 4, Caspol.exe does not affect CAS policy unless the [`` element](../configure-apps/file-schema/runtime/netfx40-legacysecuritypolicy-element.md) is set to `true`. Any settings shown or modified by CasPol.exe will only affect applications that opt in to using CAS policy. [!INCLUDE [cas-deprecated](../../../includes/cas-deprecated.md)] diff --git a/docs/framework/tools/ilasm-exe-il-assembler.md b/docs/framework/tools/ilasm-exe-il-assembler.md index daf01ba76ce24..4e409d7b0ac19 100644 --- a/docs/framework/tools/ilasm-exe-il-assembler.md +++ b/docs/framework/tools/ilasm-exe-il-assembler.md @@ -2,7 +2,7 @@ title: "Ilasm.exe (IL Assembler)" description: Get started with Ilasm.exe, the IL Assembler. This tool generates a portable executable (PE) file from intermediate language (IL) assembly. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "MSIL generators" - "metadata, MSIL Assembler" - "MSIL Assembler" @@ -41,7 +41,7 @@ ilasm [options] filename [[options]filename...] |**/arm**|Specifies the Advanced RISC Machine (ARM) as the target processor.

If no image bitness is specified, the default is **/32bitpreferred**.| |**/base:** `integer`|Sets ImageBase to the value specified by `integer` in the NT Optional header. If the .imagebase IL directive is specified in the file, this option overrides it.| |**/clock**|Measures and reports the following compilation times in milliseconds for the specified .il source file:

**Total Run**: The total time spent performing all the specific operations that follow.

**Startup**: Loading and opening the file.

**Emitting MD**: Emitting metadata.

**Ref to Def Resolution**: Resolving references to definitions in the file.

**CEE File Generation**: Generating the file image in memory.

**PE File Writing**: Writing the image to a PE file.| -|**/debug**[:**IMPL**|**OPT**]|Includes debug information (local variable and argument names, and line numbers). Creates a PDB file.

**/debug** with no additional value disables JIT optimization and uses sequence points from the PDB file.

**IMPL** disables JIT optimization and uses implicit sequence points.

**OPT** enables JIT optimization and uses implicit sequence points.| +|**/debug**[:**IMPL**|**OPT**]|Includes debug information (local variable and argument names, and line numbers). Creates a PDB file.

**/debug** with no additional value disables JIT optimization and uses sequence points from the PDB file.

`IMPL` disables JIT optimization and uses implicit sequence points.

`OPT` enables JIT optimization and uses implicit sequence points.| |**/dll**|Produces a *.dll* file as output.| |**/enc:** `file`|Creates Edit-and-Continue deltas from the specified source file.

This argument is for academic use only and is not supported for commercial use.| |**/exe**|Produces an executable file as output. This is the default.| diff --git a/docs/framework/tools/ildasm-exe-il-disassembler.md b/docs/framework/tools/ildasm-exe-il-disassembler.md index b387166a567e9..8277484e06251 100644 --- a/docs/framework/tools/ildasm-exe-il-disassembler.md +++ b/docs/framework/tools/ildasm-exe-il-disassembler.md @@ -2,7 +2,7 @@ title: "Ildasm.exe (IL Disassembler)" description: Use Ildasm.exe (IL Disassembler), which takes a portable executable (PE) file containing intermediate language (IL) code, and makes a text file for Ilasm.exe. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "PE files, MSIL Disassembler" - "portable executable files, MSIL Disassembler" - "Ildasm.exe" @@ -52,7 +52,7 @@ The following additional options are available for *.exe*, *.dll*, and *.winmd* |**/raweh**|Shows exception handling clauses in raw form.| |**/source**|Shows original source lines as comments.| |**/tokens**|Shows metadata tokens of classes and members.| -|**/visibility:** `vis`[+`vis`...]|Disassembles only types or members with the specified visibility. The following are valid values for `vis`:

**PUB** — Public

**PRI** — Private

**FAM** — Family

**ASM** — Assembly

**FAA** — Family and Assembly

**FOA** — Family or Assembly

**PSC** — Private Scope

For definitions of these visibility modifiers, see and .| +|**/visibility:** `vis`[+`vis`...]|Disassembles only types or members with the specified visibility. The following are valid values for `vis`:

`PUB` — Public

`PRI` — Private

`FAM` — Family

`ASM` — Assembly

`FAA` — Family and Assembly

`FOA` — Family or Assembly

`PSC` — Private Scope

For definitions of these visibility modifiers, see and .| The following options are valid for *.exe*, *.dll*, and *.winmd* files for file or console output only. @@ -62,7 +62,7 @@ The following options are valid for *.exe*, *.dll*, and *.winmd* files for file |**/classlist**|Includes a list of classes defined in the module.| |**/forward**|Uses forward class declaration.| |**/headers**|Includes file header information in the output.| -|**/item:** `class`[**::** `member`[`(sig`]]|Disassembles the following depending upon the argument supplied:

- Disassembles the specified `class`.
- Disassembles the specified `member` of the `class`.
- Disassembles the `member` of the `class` with the specified signature `sig`. The format of `sig` is:
[`instance`] `returnType`(`parameterType1`, `parameterType2`, …, `parameterTypeN`)
**Note** In the .NET Framework versions 1.0 and 1.1, `sig` must be followed by a closing parenthesis: `(sig)`. Starting with the Net Framework 2.0 the closing parenthesis must be omitted: `(sig`.| +|**/item:** `class`[**::** `member`[`(sig`]]|Disassembles the following depending upon the argument supplied:

- Disassembles the specified `class`.
- Disassembles the specified `member` of the `class`.
- Disassembles the `member` of the `class` with the specified signature `sig`. The format of `sig` is:
[`instance`] `returnType`(`parameterType1`, `parameterType2`, …, `parameterTypeN`).| |**/noil**|Suppresses IL assembly code output.| |**/stats**|Includes statistics on the image.| |**/typelist**|Produces the full list of types, to preserve type ordering in a round trip.| @@ -73,7 +73,7 @@ The following options are valid for *.exe*, *.dll*, *.obj*, *.lib*, and *.winmd* | Option | Description | | ------ | ----------- | -|**/metadata**[=`specifier`]|Shows metadata, where `specifier` is:

**MDHEADER** — Show the metadata header information and sizes.

**HEX** — Show information in hex as well as in words.

**CSV** — Show the record counts and heap sizes.

**UNREX** — Show unresolved externals.

**SCHEMA** — Show the metadata header and schema information.

**RAW** — Show the raw metadata tables.

**HEAPS** — Show the raw heaps.

**VALIDATE** — Validate the consistency of the metadata.

You can specify **/metadata** multiple times, with different values for `specifier`.| +|**/metadata**[=`specifier`]|Shows metadata, where `specifier` is:

`MDHEADER` — Show the metadata header information and sizes.

`HEX` — Show information in hex as well as in words.

`CSV` — Show the record counts and heap sizes.

`UNREX` — Show unresolved externals.

`SCHEMA` — Show the metadata header and schema information.

`RAW` — Show the raw metadata tables.

`HEAPS` — Show the raw heaps.

`VALIDATE` — Validate the consistency of the metadata.

You can specify **/metadata** multiple times, with different values for `specifier`.| The following options are valid for *.lib* files for file or console output only. @@ -91,9 +91,9 @@ The following options are valid for *.lib* files for file or console output only The text file produced by *Ildasm.exe* can be used as input to the IL Assembler (*Ilasm.exe*). This is useful, for example, when compiling code in a programming language that does not support all the runtime metadata attributes. After compiling the code and running its output through *Ildasm.exe*, the resulting IL text file can be hand-edited to add the missing attributes. You can then run this text file through the IL Assembler to produce a final executable file. > [!NOTE] -> Currently, you cannot use this technique with PE files that contain embedded native code (for example, PE files produced by Visual C++). +> Currently, you cannot use this technique with PE files that contain embedded native code (for example, PE files produced by Visual C++). -You can use the default GUI in the IL Disassembler to view the metadata and disassembled code of any existing PE file in a hierarchical tree view. To use the GUI, type **ildasm** at the command line without supplying the *PEfilename* argument or any options. From the **File** menu, you can navigate to the PE file that you want to load into *Ildasm.exe*. To save the metadata and disassembled code displayed for the selected PE, select the **Dump** command from the **File** menu. To save the hierarchical tree view only, select the **Dump Treeview** command from the **File** menu. For a detailed guide to loading a file into *Ildasm.exe* and interpreting the output, see the *Ildasm.exe* Tutorial, located in the Samples folder that ships with the Windows SDK. +You can use the default GUI in the IL Disassembler to view the metadata and disassembled code of any existing PE file in a hierarchical tree view. To use the GUI, type `ildasm` at the command line without supplying the *PEfilename* argument or any options. From the `File` menu, you can navigate to the PE file that you want to load into *Ildasm.exe*. To save the metadata and disassembled code displayed for the selected PE, select the `Dump` command from the `File` menu. To save the hierarchical tree view only, select the **Dump Treeview** command from the `File` menu. For a detailed guide to loading a file into *Ildasm.exe* and interpreting the output, see the *Ildasm.exe* Tutorial, located in the Samples folder that ships with the Windows SDK. If you provide *Ildasm.exe* with a *PEfilename* argument that contains embedded resources, the tool produces multiple output files: a text file that contains IL code and, for each embedded managed resource, a .resources file produced using the resource's name from metadata. If an unmanaged resource is embedded in *PEfilename*, a .res file is produced using the filename specified for IL output by the **/output** option. @@ -160,7 +160,7 @@ The following command disassembles the method `MyMethod` within the class `MyCla ildasm /item:MyClass::MyMethod MyFile.exe /text ``` -In the previous example, there could be several methods named `MyMethod` with different signatures. The following command disassembles the instance method `MyMethod` with the return type of **void** and the parameter types **int32** and **string**. +In the previous example, there could be several methods named `MyMethod` with different signatures. The following command disassembles the instance method `MyMethod` with the return type of `void` and the parameter types `int32` and `string`. ```console ildasm /item:"MyClass::MyMethod(instance void(int32,string)" MyFile.exe /text diff --git a/docs/framework/tools/index.md b/docs/framework/tools/index.md index f4cc2f8bdb8ab..0680d038496bf 100644 --- a/docs/framework/tools/index.md +++ b/docs/framework/tools/index.md @@ -31,7 +31,7 @@ Generates a file that has an assembly manifest from modules or resource files. Converts type definitions in a COM type library for an ActiveX control into a Windows Forms control. [Caspol.exe (Code Access Security Policy Tool)](caspol-exe-code-access-security-policy-tool.md)\ -Enables you to view and configure security policy for the machine policy level, the user policy level, and the enterprise policy level. In .NET Framework 4 and later, this tool does not affect code access security (CAS) policy unless the [\ element](../configure-apps/file-schema/runtime/netfx40-legacysecuritypolicy-element.md)\ is set to `true`. +Enables you to view and configure security policy for the machine policy level, the user policy level, and the enterprise policy level. In .NET Framework 4 and later, this tool does not affect code access security (CAS) policy unless the [`` element](../configure-apps/file-schema/runtime/netfx40-legacysecuritypolicy-element.md)\ is set to `true`. [Cert2spc.exe (Software Publisher Certificate Test Tool)](cert2spc-exe-software-publisher-certificate-test-tool.md)\ Creates a Software Publisher's Certificate (SPC) from one or more X.509 certificates. This tool is for testing purposes only. diff --git a/docs/framework/tools/mage-exe-manifest-generation-and-editing-tool.md b/docs/framework/tools/mage-exe-manifest-generation-and-editing-tool.md index 993ef9e530b8f..29f71d4aed554 100644 --- a/docs/framework/tools/mage-exe-manifest-generation-and-editing-tool.md +++ b/docs/framework/tools/mage-exe-manifest-generation-and-editing-tool.md @@ -30,7 +30,7 @@ The following table shows the commands supported by *Mage.exe*. For more informa | Command | Description | |---------|-------------| |**-cc, ClearApplicationCache**|Clears the downloaded application cache of all online-only applications.| -|**-n, -New** *fileType [newOptions]*|Creates a new file of the given type. Valid types are:

- `Deployment`: Creates a new deployment manifest.
- `Application`: Creates a new application manifest.

If you do not specify any additional parameters with this command, it will create a file of the appropriate type, with appropriate default tags and attribute values.

Use the **-ToFile** option (see in the following table) to specify the file name and path of the new file.

Use the **-FromDirectory** option (see in the following table) to create an application manifest with all of the assemblies for an application added to the \ section of the manifest.| +|**-n, -New** *fileType [newOptions]*|Creates a new file of the given type. Valid types are:

- `Deployment`: Creates a new deployment manifest.
- `Application`: Creates a new application manifest.

If you do not specify any additional parameters with this command, it will create a file of the appropriate type, with appropriate default tags and attribute values.

Use the **-ToFile** option (see in the following table) to specify the file name and path of the new file.

Use the **-FromDirectory** option (see in the following table) to create an application manifest with all of the assemblies for an application added to the `` section of the manifest.| |**-u, -Update** *[filePath] [updateOptions]*|Makes one or more changes to a manifest file. You do not have to specify the type of file that you are editing. Mage.exe will examine the file by using a set of heuristics and determine whether it is a deployment manifest or an application manifest.

If you have already signed a file with a certificate, **-Update** will remove the key signature block. This is because the key signature contains a hash of the file, and modifying the file renders the hash invalid.

Use the **-ToFile** option (see in the following table) to specify a new file name and path instead of overwriting the existing file.| |**-s, -Sign** `[signOptions]`|Uses a key pair or X509 certificate to sign a file. Signatures are inserted as XML elements inside of the files.

You must be connected to the Internet when signing a manifest that specifies a **-TimestampUri** value.| |**-ver, -Verify** *[manifest-filename]*|Verifies that the manifest is signed correctly. Cannot be combined with other commands.

**Available in .NET Framework 4.7 and later versions.**| diff --git a/docs/framework/tools/mdbg-exe.md b/docs/framework/tools/mdbg-exe.md index 4f547c574743b..510c793755535 100644 --- a/docs/framework/tools/mdbg-exe.md +++ b/docs/framework/tools/mdbg-exe.md @@ -33,7 +33,7 @@ MDbg [ProgramName[arguments]] [options] |-------------|-----------------| |**ap**[**rocess**] [*number*]|Switches to another debugged process or prints available processes. The numbers are not real process IDs (PIDs), but a 0-indexed list.| |**a**[**ttach**] [*pid*]|Attaches to a process or prints available processes.| -|**b**[**reak**] [*ClassName.Method* | *FileName:LineNo*]|Sets a breakpoint at the specified method. Modules are scanned sequentially.

- **break** *FileName:LineNo* sets a breakpoint at a location in the source.
- **break** *~number* sets a breakpoint on a symbol recently displayed with the **x** command.
- **break** *module!ClassName.Method+IlOffset* sets a breakpoint on the fully qualified location.| +|**b**[**reak**] [*ClassName.Method* | *FileName:LineNo*]|Sets a breakpoint at the specified method. Modules are scanned sequentially.

- `break` *FileName:LineNo* sets a breakpoint at a location in the source.
- `break` *~number* sets a breakpoint on a symbol recently displayed with the `x` command.
- `break` *module!ClassName.Method+IlOffset* sets a breakpoint on the fully qualified location.| |**block**[**ingObjects**]|Displays monitor locks, which are blocking threads.| |**ca**[**tch**] [*exceptionType*]|Causes the debugger to break on all exceptions, and not just on the unhandled exceptions.| |**cl**[**earException**]|Marks the current exception as handled so that execution can continue. If the cause of the exception has not been dealt with, the exception may be quickly rethrown.| @@ -44,12 +44,12 @@ MDbg [ProgramName[arguments]] [options] |**echo**|Echoes a message to the console.| |**enableNotif**[**ication**] *typeName* 0|1|Enables (1) or disables (0) custom notifications for the specified type.| |**ex**[**it**] [*exitcode*]|Exits the MDbg.exe shell, and optionally specifies the process exit code.| -|**fo**[**reach**] [*OtherCommand*]|Performs a command on all threads. *OtherCommand* is a valid command that operates on one thread; **foreach** *OtherCommand* performs the same command on all threads.| +|**fo**[**reach**] [*OtherCommand*]|Performs a command on all threads. *OtherCommand* is a valid command that operates on one thread; `foreach` *OtherCommand* performs the same command on all threads.| |**f**[**unceval**] [`-ad` *Num*] *functionName* [*args ...* ]|Performs a function evaluation on the current active thread where the function to evaluate is *functionName*. The function name must be fully qualified, including namespaces.

The `-ad` option specifies the application domain to use to resolve the function. If the `-ad` option is not specified, the application domain for resolution defaults to the application domain where the thread that is used for function evaluation is located.

If the function that is being evaluated is not static, the first parameter passed in should be a `this` pointer. All application domains are searched for arguments to the function evaluation..

To request a value from an application domain, prefix the variable with the module and application domain name; for example, `funceval -ad 0 System.Object.ToString hello.exe#0!MyClass.g_rootRef`. This command evaluates the function `System.Object.ToString` in the application domain `0`. Because the `ToString` method is an instance function, the first parameter must be a `this` pointer.| |**g**[**o**]|Causes the program to continue until it encounters a breakpoint, the program exits, or an event (for example, an unhandled exception) causes the program to stop.| |**h**[**elp**] [*command*]

-or-

**?** [*command*]|Displays a description of all commands or a detailed description of a specified command.| |**ig**[**nore**] [*event*]|Causes the debugger to stop on unhandled exceptions only.| -|**int**[**ercept**] *FrameNumber*|Rolls the debugger back to a specified frame number.

If the debugger encounters an exception, use this command to roll the debugger back to the specified frame number. You can change the program state by using the **set** command and continue by using the **go** command.| +|**int**[**ercept**] *FrameNumber*|Rolls the debugger back to a specified frame number.

If the debugger encounters an exception, use this command to roll the debugger back to the specified frame number. You can change the program state by using the `set` command and continue by using the `go` command.| |**k**[**ill**]|Stops the active process.| |**l**[**ist**] [*modules* | *appdomains* | *assemblies*]|Displays the loaded modules, application domains, or assemblies.| |**lo**[**ad**] *assemblyName*|Loads an extension in the following manner: The specified assembly is loaded and an attempt is then made to run the static method `LoadExtension` from the `Microsoft.Tools.Mdbg.Extension.Extension` type.| @@ -71,20 +71,20 @@ MDbg [ProgramName[arguments]] [options] |**Setip** [`-il`] *number*|Sets the current instruction pointer (IP) in the file to the specified position. If you specify the `-il` option, the number represents a common intermediate language (CIL) offset in the method. Otherwise, the number represents a source line number.| |**sh**[**ow**] [*lines*]|Specifies the number of lines to show.| |**s**[**tep**]|Moves execution into the next function on the current line, or moves to the next line if there is no function to step into.| -|**su**[**spend**] [\* | [~]*threadNumber*]|Suspends the current thread or the thread specified by the *threadNumber* parameter. If *threadNumber* is specified as `*`, the command applies to all threads. If the thread number starts with `~`, the command applies to all threads except the one specified by *threadNumber*. Suspended threads are excluded from running when the process is run by either the **go** or **step** command. If there are no non-suspended threads in the process and you issue the **go** command, the process will not continue. In that case, press CTRL-C to break into the process.| +|**su**[**spend**] [\* | [~]*threadNumber*]|Suspends the current thread or the thread specified by the *threadNumber* parameter. If *threadNumber* is specified as `*`, the command applies to all threads. If the thread number starts with `~`, the command applies to all threads except the one specified by *threadNumber*. Suspended threads are excluded from running when the process is run by either the `go` or `step` command. If there are no non-suspended threads in the process and you issue the `go` command, the process will not continue. In that case, press CTRL-C to break into the process.| |**sy**[**mbol**] *commandName* [*commandValue*]|Specifies one of the following commands:

- `symbol path` [`"value"`] - Displays or sets the current symbol path.
- `symbol addpath` `"value"` - Adds to your current symbol path.
- `symbol reload` [`"module"`] - Reloads either all symbols or the symbols for the specified module.
- `symbol list` [`module`] - Shows the currently loaded symbols for either all modules or the specified module.| -|**t**[**hread**] [*newThread*] [-*nick nickname*`]`|The thread command with no parameters displays all managed threads in the current process. Threads are usually identified by their thread numbers; however, if the thread has an assigned nickname, the nickname is displayed instead. You can use the `-nick` parameter to assign a nickname to a thread.

- **thread** `-nick` *threadName* assigns a nickname to the currently running thread.

Nicknames cannot be numbers. If the current thread already has an assigned nickname, the old nickname is replaced with the new one. If the new nickname is an empty string (""), the nickname for the current thread is deleted and no new nickname is assigned to the thread.| +|**t**[**hread**] [*newThread*] [-*nick nickname*`]`|The thread command with no parameters displays all managed threads in the current process. Threads are usually identified by their thread numbers; however, if the thread has an assigned nickname, the nickname is displayed instead. You can use the `-nick` parameter to assign a nickname to a thread.

- `thread` `-nick` *threadName* assigns a nickname to the currently running thread.

Nicknames cannot be numbers. If the current thread already has an assigned nickname, the old nickname is replaced with the new one. If the new nickname is an empty string (""), the nickname for the current thread is deleted and no new nickname is assigned to the thread.| |**u**[**p**]|Moves the active stack frame up.| |**uwgc**[**handle**] [*var*] | [*address*]|Prints the variable tracked by a handle. The handle can be specified by name or address.| -|**when**|Displays the currently active `when` statements.

**when** **delete all** | `num` [`num` [`num` …]] - Deletes the `when` statement specified by the number, or all `when` statements if `all` is specified.

**when** `stopReason` [`specific_condition`] **do**`cmd` [`cmd` [`cmd` …] ] - The *stopReason* parameter can be one of the following:

`StepComplete`, `ProcessExited`, `ThreadCreated`, `BreakpointHit`, `ModuleLoaded`, `ClassLoaded`, `AssemblyLoaded`, `AssemblyUnloaded`, `ControlCTrapped`, `ExceptionThrown`, `UnhandledExceptionThrown`, `AsyncStop`, `AttachComplete`, `UserBreak`, `EvalComplete`, `EvalException`, `RemapOpportunityReached`, `NativeStop`.

*specific_condition* can be one of the following:

- *number* - For `ThreadCreated` and `BreakpointHit`, triggers action only when stopped by a thread ID/breakpoint number with same value.
- [`!`]*name* - For `ModuleLoaded`, `ClassLoaded`, `AssemblyLoaded`, `AssemblyUnloaded`, `ExceptionThrown`, and `UnhandledExceptionThrown`, triggers action only when the name matches the name of the *stopReason*.

*specific_condition* must be empty for other values of *stopReason*.| -|**w**[**here**] [`-v`] [`-c` *depth*] [*threadID*]|Displays debug information about stack frames.

- The `-v` option provides verbose information about each displayed stack frame.
- Specifying a number for `depth` limits how many frames are displayed. Use the **all** command to display all frames. The default is 100.
- If you specify the *threadID* parameter, you can control which thread is associated with the stack. The default is the current thread only. Use the **all** command to get all threads.| -|**x** [`-c`*numSymbols*] [*module*[`!`*pattern*]]|Displays functions that match the `pattern` for a module.

If *numSymbols* is specified, the output is limited to the specified number. If `!` (indicating a regular expression) is not specified for *pattern*, all functions are displayed. If *module* is not provided, all loaded modules are displayed. Symbols (*~#*) can be used to set breakpoints using the **break** command.| +|**when**|Displays the currently active `when` statements.

`when` **delete all** | `num` [`num` [`num` …]] - Deletes the `when` statement specified by the number, or all `when` statements if `all` is specified.

`when` `stopReason` [`specific_condition`] **do**`cmd` [`cmd` [`cmd` …] ] - The *stopReason* parameter can be one of the following:

`StepComplete`, `ProcessExited`, `ThreadCreated`, `BreakpointHit`, `ModuleLoaded`, `ClassLoaded`, `AssemblyLoaded`, `AssemblyUnloaded`, `ControlCTrapped`, `ExceptionThrown`, `UnhandledExceptionThrown`, `AsyncStop`, `AttachComplete`, `UserBreak`, `EvalComplete`, `EvalException`, `RemapOpportunityReached`, `NativeStop`.

*specific_condition* can be one of the following:

- *number* - For `ThreadCreated` and `BreakpointHit`, triggers action only when stopped by a thread ID/breakpoint number with same value.
- [`!`]*name* - For `ModuleLoaded`, `ClassLoaded`, `AssemblyLoaded`, `AssemblyUnloaded`, `ExceptionThrown`, and `UnhandledExceptionThrown`, triggers action only when the name matches the name of the *stopReason*.

*specific_condition* must be empty for other values of *stopReason*.| +|**w**[**here**] [`-v`] [`-c` *depth*] [*threadID*]|Displays debug information about stack frames.

- The `-v` option provides verbose information about each displayed stack frame.
- Specifying a number for `depth` limits how many frames are displayed. Use the `all` command to display all frames. The default is 100.
- If you specify the *threadID* parameter, you can control which thread is associated with the stack. The default is the current thread only. Use the `all` command to get all threads.| +|**x** [`-c`*numSymbols*] [*module*[`!`*pattern*]]|Displays functions that match the `pattern` for a module.

If *numSymbols* is specified, the output is limited to the specified number. If `!` (indicating a regular expression) is not specified for *pattern*, all functions are displayed. If *module* is not provided, all loaded modules are displayed. Symbols (*~#*) can be used to set breakpoints using the `break` command.| ## Remarks Compile the application to be debugged by using compiler-specific flags that cause your compiler to generate debugging symbols. Refer to your compiler's documentation for more information about these flags. You can debug optimized applications, but some debugging information will be missing. For example, many local variables will not be visible and source lines will be inaccurate. - After you compile your application, type **mdbg** at the command prompt to start a debugging session, as shown in the following example. + After you compile your application, type `mdbg` at the command prompt to start a debugging session, as shown in the following example. ```console C:\Program Files\Microsoft Visual Studio 8\VC>mdbg diff --git a/docs/framework/tools/mgmtclassgen-exe.md b/docs/framework/tools/mgmtclassgen-exe.md index ae4ba6aac554b..866a5e1e1bdb2 100644 --- a/docs/framework/tools/mgmtclassgen-exe.md +++ b/docs/framework/tools/mgmtclassgen-exe.md @@ -2,10 +2,10 @@ title: "Mgmtclassgen.exe (Management Strongly Typed Class Generator)" description: Understand Mgmtclassgen.exe, the Management Strongly Typed Class Generator. This tool lets you quickly generate an early-bound managed class for a WMI class. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "CIM types" - "Management Strongly Typed Class Generator" - "WMI class" @@ -15,137 +15,137 @@ ms.assetid: 02ce6699-49b5-4a0b-b0d5-1003c491232e --- # Mgmtclassgen.exe (Management Strongly Typed Class Generator) -The Management Strongly Typed Class Generator tool enables you to quickly generate an early-bound managed class for a specified Windows Management Instrumentation (WMI) class. The generated class simplifies the code you must write to access an instance of the WMI class. - -## Syntax - -```console +The Management Strongly Typed Class Generator tool enables you to quickly generate an early-bound managed class for a specified Windows Management Instrumentation (WMI) class. The generated class simplifies the code you must write to access an instance of the WMI class. + +## Syntax + +```console mgmtclassgen WMIClass [options] -``` - -|Argument|Description| -|--------------|-----------------| -|*WMIClass*|The Windows Management Instrumentation class for which to generate an early-bound managed class.| - -|Option|Description| -|------------|-----------------| -|**/l** *language*|Specifies the language in which to generate the early-bound managed class. You can specify **CS** (C#; default), **VB** (Visual Basic), **MC** (C++), or **JS** (JScript) as the language argument.| -|**/m** *machine*|Specifies the computer to connect to, where the WMI class resides. The default is the local computer.| -|**/n** *path*|Specifies the path to the WMI namespace that contains the WMI class. If you do not specify this option, the tool generates code for *WMIClass* in the default **Root\cimv2** namespace.| -|**/o** *classnamespace*|Specifies the .NET namespace in which to generate the managed code class. If you do not specify this option, the tool generates the namespace using the WMI namespace and the schema prefix. The schema prefix is the part of the class name preceding the underscore character. For example, for the **Win32_OperatingSystem** class in the **Root\cimv2** namespace, the tool would generate the class in **ROOT.CIMV2.Win32**.| -|**/p** *filepath*|Specifies the path to the file in which to save the generated code. If you do not specify this option, the tool creates the file in the current directory. It names the class and file in which it generates the class using the *WMIClass* argument. The name of the class and the file are the same as the name of the *WMIClass.* If *WMIClass* contains an underscore character, the tool uses the part of the class name following the underscore character. For example, if the *WMIClass* name is in the format **Win32_LogicalDisk**, the generated class and file is named "logicaldisk". If a file already exists, the tool overwrites the existing file.| -|**/pw** *password*|Specifies the password to use when logging on to a computer specified by the **/m** option.| -|**/u** *user name*|Specifies the user name to use when logging on to a computer specified by the **/m** option.| -|**/?**|Displays command syntax and options for the tool.| - -## Remarks - - Mgmtclassgen.exe uses the method. Therefore, you can use any custom code provider to generate code in managed languages other than C#, Visual Basic, and JScript. - - Note that generated classes are bound to the schema for which they are generated. If the underlying schema changes, you must regenerate the class if you want it to reflect changes to the schema. - - The following table shows how WMI Common Information Model (CIM) types map to data types in a generated class: - -|CIM type|Data type in the generated class| -|--------------|--------------------------------------| -|CIM_SINT8|**SByte**| -|CIM_UINT8|**Byte**| -|CIM_SINT16|**Int16**| -|CIM_UINT16|**UInt16**| -|CIM_SINT32|**Int32**| -|SIM_UINT32|**UInt32**| -|CIM_SINT64|**Int64**| -|CIM_UINT64|**UInt64**| -|CIM_REAL32|**Single**| -|CIM_REAL64|**Double**| -|CIM_BOOLEAN|**Boolean**| -|CIM_String|**String**| -|CIM_DATETIME|**DateTime** or **TimeSpan**| -|CIM_REFERENCE|**ManagementPath**| -|CIM_CHAR16|**Char**| -|CIM_OBJECT|**ManagementBaseObject**| -|CIM_IUNKNOWN|**Object**| -|CIM_ARRAY|Array of the above mentioned objects| - - Note the following behaviors when you generate a WMI class: - -- It is possible for a standard public property or method to have the same name as an existing property or method. If this occurs, the tool changes the name of the property or method in the generated class to avoid naming conflicts. - -- It is possible for the name of a property or method in a generated class to be a keyword in the target programming language. If this occurs, the tool changes the name of the property or method in the generated class to avoid naming conflicts. - -- In WMI, qualifiers are modifiers that contain information to describe a class, instance, property, or method. WMI uses standard qualifiers such as **Read**, **Write**, and **Key** to describe a property in a generated class. For example, a property that is modified with a **Read** qualifier is defined only with a property **get** accessor in the generated class. Because a property marked with the **Read** qualifier is intended to be read-only, a **set** accessor is not defined. - -- A numeric property can be modified by the **Values** and **ValueMaps** qualifiers to indicate that the property can be set only to specified permissible values. An enumeration is generated with these **Values** and **ValueMaps** and the property is mapped to the enumeration. - -- The WMI uses the term singleton to describe a class that can have only one instance. Therefore, the parameterless constructor for a singleton class will initialize the class to the only instance of the class. - -- A WMI class can have properties that are objects. When you generate a strongly typed class for this type of WMI class, you should consider generating strongly typed classes for the types of the embedded object properties. This will allow you to access the embedded objects in a strongly typed manner. Note that the generated code might not be able to detect the type of the embedded object. In this case, a comment will be created in the generated code to notify you of this issue. You can then modify the generated code to type the property to the other generated class. - -- In WMI, the data value of the CIM_DATETIME data type can represent either a specific date and time or a time interval. If the data value represents a date and time, the data type in the generated class is **DateTime**. If the data value represents a time interval, the data type in the generated class is **TimeSpan**. - - You can alternately generate a strongly typed class using the Server Explorer Management Extension in Visual Studio .NET. - - For more information about WMI, see the **Windows Management Instrumentation** topic in the Platform SDK documentation. - -## Examples - - The following command generates a managed class in C# code for the **Win32_LogicalDisk** WMI class in the **Root\cimv2** namespace. The tool writes the managed class to the source file at c:\disk.cs in the **ROOT.CIMV2.Win32** namespace. - -```console -mgmtclassgen Win32_LogicalDisk /n root\cimv2 /l CS /p c:\disk.cs -``` - - The following code example shows how to use a generated class programmatically. First, an instance of the class is enumerated and the path is printed. Next, an instance of the generated class to be initialized is created with an instance of WMI. `Process` is the class generated for **Win32_Process** and `LogicalDisk` is the class generated for **Win32_LogicalDisk** in the **Root\cimv2** namespace. - -```vb -Imports System -Imports System.Management -Imports ROOT.CIMV2.Win32 - +``` + +|Argument|Description| +|--------------|-----------------| +|*WMIClass*|The Windows Management Instrumentation class for which to generate an early-bound managed class.| + +|Option|Description| +|------------|-----------------| +|**/l** *language*|Specifies the language in which to generate the early-bound managed class. You can specify `CS` (C#; default), `VB` (Visual Basic), `MC` (C++), or `JS` (JScript) as the language argument.| +|**/m** *machine*|Specifies the computer to connect to, where the WMI class resides. The default is the local computer.| +|**/n** *path*|Specifies the path to the WMI namespace that contains the WMI class. If you do not specify this option, the tool generates code for *WMIClass* in the default **Root\cimv2** namespace.| +|**/o** *classnamespace*|Specifies the .NET namespace in which to generate the managed code class. If you do not specify this option, the tool generates the namespace using the WMI namespace and the schema prefix. The schema prefix is the part of the class name preceding the underscore character. For example, for the **Win32_OperatingSystem** class in the **Root\cimv2** namespace, the tool would generate the class in **ROOT.CIMV2.Win32**.| +|**/p** *filepath*|Specifies the path to the file in which to save the generated code. If you do not specify this option, the tool creates the file in the current directory. It names the class and file in which it generates the class using the *WMIClass* argument. The name of the class and the file are the same as the name of the *WMIClass.* If *WMIClass* contains an underscore character, the tool uses the part of the class name following the underscore character. For example, if the *WMIClass* name is in the format **Win32_LogicalDisk**, the generated class and file is named "logicaldisk". If a file already exists, the tool overwrites the existing file.| +|**/pw** *password*|Specifies the password to use when logging on to a computer specified by the **/m** option.| +|**/u** *user name*|Specifies the user name to use when logging on to a computer specified by the **/m** option.| +|**/?**|Displays command syntax and options for the tool.| + +## Remarks + + Mgmtclassgen.exe uses the method. Therefore, you can use any custom code provider to generate code in managed languages other than C#, Visual Basic, and JScript. + + Note that generated classes are bound to the schema for which they are generated. If the underlying schema changes, you must regenerate the class if you want it to reflect changes to the schema. + + The following table shows how WMI Common Information Model (CIM) types map to data types in a generated class: + +|CIM type|Data type in the generated class| +|--------------|--------------------------------------| +|CIM_SINT8|**SByte**| +|CIM_UINT8|**Byte**| +|CIM_SINT16|**Int16**| +|CIM_UINT16|**UInt16**| +|CIM_SINT32|**Int32**| +|SIM_UINT32|**UInt32**| +|CIM_SINT64|**Int64**| +|CIM_UINT64|**UInt64**| +|CIM_REAL32|**Single**| +|CIM_REAL64|**Double**| +|CIM_BOOLEAN|**Boolean**| +|CIM_String|**String**| +|CIM_DATETIME|**DateTime** or **TimeSpan**| +|CIM_REFERENCE|**ManagementPath**| +|CIM_CHAR16|**Char**| +|CIM_OBJECT|**ManagementBaseObject**| +|CIM_IUNKNOWN|**Object**| +|CIM_ARRAY|Array of the above mentioned objects| + + Note the following behaviors when you generate a WMI class: + +- It is possible for a standard public property or method to have the same name as an existing property or method. If this occurs, the tool changes the name of the property or method in the generated class to avoid naming conflicts. + +- It is possible for the name of a property or method in a generated class to be a keyword in the target programming language. If this occurs, the tool changes the name of the property or method in the generated class to avoid naming conflicts. + +- In WMI, qualifiers are modifiers that contain information to describe a class, instance, property, or method. WMI uses standard qualifiers such as **Read**, **Write**, and `Key` to describe a property in a generated class. For example, a property that is modified with a `Read` qualifier is defined only with a property `get` accessor in the generated class. Because a property marked with the `Read` qualifier is intended to be read-only, a `set` accessor is not defined. + +- A numeric property can be modified by the `Values` and `ValueMaps` qualifiers to indicate that the property can be set only to specified permissible values. An enumeration is generated with these `Values` and `ValueMaps` and the property is mapped to the enumeration. + +- The WMI uses the term singleton to describe a class that can have only one instance. Therefore, the parameterless constructor for a singleton class will initialize the class to the only instance of the class. + +- A WMI class can have properties that are objects. When you generate a strongly typed class for this type of WMI class, you should consider generating strongly typed classes for the types of the embedded object properties. This will allow you to access the embedded objects in a strongly typed manner. Note that the generated code might not be able to detect the type of the embedded object. In this case, a comment will be created in the generated code to notify you of this issue. You can then modify the generated code to type the property to the other generated class. + +- In WMI, the data value of the CIM_DATETIME data type can represent either a specific date and time or a time interval. If the data value represents a date and time, the data type in the generated class is **DateTime**. If the data value represents a time interval, the data type in the generated class is **TimeSpan**. + + You can alternately generate a strongly typed class using the Server Explorer Management Extension in Visual Studio .NET. + + For more information about WMI, see the **Windows Management Instrumentation** topic in the Platform SDK documentation. + +## Examples + + The following command generates a managed class in C# code for the **Win32_LogicalDisk** WMI class in the **Root\cimv2** namespace. The tool writes the managed class to the source file at c:\disk.cs in the **ROOT.CIMV2.Win32** namespace. + +```console +mgmtclassgen Win32_LogicalDisk /n root\cimv2 /l CS /p c:\disk.cs +``` + + The following code example shows how to use a generated class programmatically. First, an instance of the class is enumerated and the path is printed. Next, an instance of the generated class to be initialized is created with an instance of WMI. `Process` is the class generated for **Win32_Process** and `LogicalDisk` is the class generated for **Win32_LogicalDisk** in the **Root\cimv2** namespace. + +```vb +Imports System +Imports System.Management +Imports ROOT.CIMV2.Win32 + Public Class App Public Shared Sub Main() - ' Enumerate instances of the Win32_process. - ' Print the Name property of the instance. + ' Enumerate instances of the Win32_process. + ' Print the Name property of the instance. Dim ps As Process - For Each ps In Process.GetInstances() - Console.WriteLine(ps.Name) - Next ps - - ' Initialize the instance of LogicalDisk with - ' the WMI instance pointing to logical drive d:. - Dim dskD As New LogicalDisk(New _ - ManagementPath("win32_LogicalDisk.DeviceId=""d:""")) - Console.WriteLine(dskD.Caption) - End Sub -End Class -``` - -```csharp -using System; -using System.Management; -using ROOT.CIMV2.Win32; - -public class App -{ - public static void Main() - { - // Enumerate instances of the Win32_process. - // Print the Name property of the instance. - foreach(Process ps in Process.GetInstances()) - { - Console.WriteLine(ps.Name); - } - - // Initialize the instance of LogicalDisk with - // the WMI instance pointing to logical drive d:. - LogicalDisk dskD = new LogicalDisk(new ManagementPath( - "win32_LogicalDisk.DeviceId=\"d:\"")); - Console.WriteLine(dskD.Caption); - } -} -``` - + For Each ps In Process.GetInstances() + Console.WriteLine(ps.Name) + Next ps + + ' Initialize the instance of LogicalDisk with + ' the WMI instance pointing to logical drive d:. + Dim dskD As New LogicalDisk(New _ + ManagementPath("win32_LogicalDisk.DeviceId=""d:""")) + Console.WriteLine(dskD.Caption) + End Sub +End Class +``` + +```csharp +using System; +using System.Management; +using ROOT.CIMV2.Win32; + +public class App +{ + public static void Main() + { + // Enumerate instances of the Win32_process. + // Print the Name property of the instance. + foreach(Process ps in Process.GetInstances()) + { + Console.WriteLine(ps.Name); + } + + // Initialize the instance of LogicalDisk with + // the WMI instance pointing to logical drive d:. + LogicalDisk dskD = new LogicalDisk(new ManagementPath( + "win32_LogicalDisk.DeviceId=\"d:\"")); + Console.WriteLine(dskD.Caption); + } +} +``` + ## See also - diff --git a/docs/framework/tools/tlbexp-exe-type-library-exporter.md b/docs/framework/tools/tlbexp-exe-type-library-exporter.md index e27cfee31d1b3..b3a75f6fca7b3 100644 --- a/docs/framework/tools/tlbexp-exe-type-library-exporter.md +++ b/docs/framework/tools/tlbexp-exe-type-library-exporter.md @@ -11,117 +11,117 @@ helpviewer_keywords: --- # Tlbexp.exe (Type Library Exporter) -The Type Library Exporter generates a type library that describes the types defined in a common language runtime assembly. - +The Type Library Exporter generates a type library that describes the types defined in a common language runtime assembly. + This tool is automatically installed with Visual Studio. To run the tool, use [Visual Studio Developer Command Prompt or Visual Studio Developer PowerShell](/visualstudio/ide/reference/command-prompt-powershell). - - At the command prompt, type the following: - -## Syntax - -```console -tlbexp assemblyName [options] -``` - -## Parameters - -|Argument|Description| -|--------------|-----------------| -|*assemblyName*|The assembly for which to export a type library.| - -|Option|Description| -|------------|-----------------| -|**/asmpath:** *directory*|Specifies the location to search for assemblies. If you use this option, you must explicitly specify the locations to search for referenced assemblies, including the current directory.

When you use the **asmpath** option, the Type Library Exporter will not look for an assembly in the global assembly cache (GAC).| -|**/help**|Displays command syntax and options for the tool.| -|**/names:** *filename*|Specifies the capitalization of names in a type library. The *filename* argument is a text file. Each line in the file specifies the capitalization of one name in the type library.| -|**/nologo**|Suppresses the Microsoft startup banner display.| -|**/oldnames**|Forces Tlbexp.exe to export decorated type names if there is a type name conflict. Note that this was the default behavior in versions prior to .NET Framework version 2.0.| -|**/out:** *file*|Specifies the name of the type library file to generate. If you omit this option, Tlbexp.exe generates a type library with the same name as the assembly (the actual assembly name, which might not necessarily be the same as the file containing the assembly) and a .tlb extension.| -|**/silence:** `warningnumber`|Suppresses the display of the specified warning. This option cannot be used with **/silent**.| -|**/silent**|Suppresses the display of success messages. This option cannot be used with **/silence**.| -|**/tlbreference:** *typelibraryname*|Forces Tlbexp.exe to explicitly resolve type library references without consulting the registry. For example, if assembly B references assembly A, you can use this option to provide an explicit type library reference, rather than relying on the type library specified in the registry. Tlbexp.exe performs a version check to ensure that the type library version matches the assembly version; otherwise, it generates an error.

Note that the **tlbreference** option still consults the registry in cases where the attribute is applied to an interface that is then implemented by another type.| -|**/tlbrefpath:** *path*|Fully qualified path to a referenced type library.| -|**/win32**|When compiling on a 64-bit computer, this option specifies that Tlbexp.exe generates a 32-bit type library.| -|**/win64**|When compiling on a 32-bit computer, this option specifies that Tlbexp.exe generates a 64-bit type library.| -|**/verbose**|Specifies verbose mode; displays a list of any referenced assemblies for which a type library needs to be generated.| -|**/?**|Displays command syntax and options for the tool.| - + + At the command prompt, type the following: + +## Syntax + +```console +tlbexp assemblyName [options] +``` + +## Parameters + +|Argument|Description| +|--------------|-----------------| +|*assemblyName*|The assembly for which to export a type library.| + +|Option|Description| +|------------|-----------------| +|**/asmpath:** *directory*|Specifies the location to search for assemblies. If you use this option, you must explicitly specify the locations to search for referenced assemblies, including the current directory.

When you use the `asmpath` option, the Type Library Exporter will not look for an assembly in the global assembly cache (GAC).| +|**/help**|Displays command syntax and options for the tool.| +|**/names:** *filename*|Specifies the capitalization of names in a type library. The *filename* argument is a text file. Each line in the file specifies the capitalization of one name in the type library.| +|**/nologo**|Suppresses the Microsoft startup banner display.| +|**/oldnames**|Forces Tlbexp.exe to export decorated type names if there is a type name conflict. Note that this was the default behavior in versions prior to .NET Framework version 2.0.| +|**/out:** *file*|Specifies the name of the type library file to generate. If you omit this option, Tlbexp.exe generates a type library with the same name as the assembly (the actual assembly name, which might not necessarily be the same as the file containing the assembly) and a .tlb extension.| +|**/silence:** `warningnumber`|Suppresses the display of the specified warning. This option cannot be used with **/silent**.| +|**/silent**|Suppresses the display of success messages. This option cannot be used with **/silence**.| +|**/tlbreference:** *typelibraryname*|Forces Tlbexp.exe to explicitly resolve type library references without consulting the registry. For example, if assembly B references assembly A, you can use this option to provide an explicit type library reference, rather than relying on the type library specified in the registry. Tlbexp.exe performs a version check to ensure that the type library version matches the assembly version; otherwise, it generates an error.

Note that the `tlbreference` option still consults the registry in cases where the attribute is applied to an interface that is then implemented by another type.| +|**/tlbrefpath:** *path*|Fully qualified path to a referenced type library.| +|**/win32**|When compiling on a 64-bit computer, this option specifies that Tlbexp.exe generates a 32-bit type library.| +|**/win64**|When compiling on a 32-bit computer, this option specifies that Tlbexp.exe generates a 64-bit type library.| +|**/verbose**|Specifies verbose mode; displays a list of any referenced assemblies for which a type library needs to be generated.| +|**/?**|Displays command syntax and options for the tool.| + > [!NOTE] -> The command-line options for Tlbexp.exe are case-insensitive and can be supplied in any order. You only need to specify enough of the option to uniquely identify it. For example, **/n** is equivalent to **/nologo**, and **/o:** *outfile.tlb* is equivalent to **/out:** *outfile.tlb*. - -## Remarks +> The command-line options for Tlbexp.exe are case-insensitive and can be supplied in any order. You only need to specify enough of the option to uniquely identify it. For example, **/n** is equivalent to **/nologo**, and **/o:** *outfile.tlb* is equivalent to **/out:** *outfile.tlb*. + +## Remarks + + Tlbexp.exe generates a type library that contains definitions of the types defined in the assembly. Applications such as Visual Basic 6.0 can use the generated type library to bind to the .NET types defined in the assembly. - Tlbexp.exe generates a type library that contains definitions of the types defined in the assembly. Applications such as Visual Basic 6.0 can use the generated type library to bind to the .NET types defined in the assembly. - > [!IMPORTANT] -> You cannot use Tlbexp.exe to export Windows metadata (.winmd) files. Exporting Windows Runtime assemblies is not supported. - - The entire assembly is converted at once. You cannot use Tlbexp.exe to generate type information for a subset of the types defined in an assembly. - - You cannot use Tlbexp.exe to produce a type library from an assembly that was imported using the [Type Library Importer (Tlbimp.exe)](tlbimp-exe-type-library-importer.md). Instead, you should refer to the original type library that was imported with Tlbimp.exe. You can export a type library from an assembly that references assemblies that were imported using Tlbimp.exe. See the examples section below. - - Tlbexp.exe places generated type libraries in the current working directory or the directory specified for the output file. A single assembly might cause several type libraries to be generated. - - Tlbexp.exe generates a type library but does not register it. This is in contrast to the [Assembly Registration tool (Regasm.exe)](regasm-exe-assembly-registration-tool.md), which both generates and registers a type library. To generate and register a type library with COM, use Regasm.exe. - - If you do not specify either the `/win32` or `/win64` option, Tlbexp.exe generates a 32-bit or 64-bit type library that corresponds to the type of computer on which you are performing the compilation (32-bit or 64-bit computer). For cross-compilation purposes, you can use the `/win64` option on a 32-bit computer to generate a 64-bit type library and you can use the `/win32` option on a 64-bit computer to generate a 32-bit type library. In 32-bit type libraries, the value is set to . In 64-bit type libraries, the value is set to . All data type transformations (for example, pointer-sized data types such as `IntPtr` and `UIntPtr`) are converted appropriately. - - If you use the attribute to specify a value of `VT_UNKNOWN` or `VT_DISPATCH`, Tlbexp.exe ignores any subsequent use of the field. For example, given the following signatures: - +> You cannot use Tlbexp.exe to export Windows metadata (.winmd) files. Exporting Windows Runtime assemblies is not supported. + + The entire assembly is converted at once. You cannot use Tlbexp.exe to generate type information for a subset of the types defined in an assembly. + + You cannot use Tlbexp.exe to produce a type library from an assembly that was imported using the [Type Library Importer (Tlbimp.exe)](tlbimp-exe-type-library-importer.md). Instead, you should refer to the original type library that was imported with Tlbimp.exe. You can export a type library from an assembly that references assemblies that were imported using Tlbimp.exe. See the examples section below. + + Tlbexp.exe places generated type libraries in the current working directory or the directory specified for the output file. A single assembly might cause several type libraries to be generated. + + Tlbexp.exe generates a type library but does not register it. This is in contrast to the [Assembly Registration tool (Regasm.exe)](regasm-exe-assembly-registration-tool.md), which both generates and registers a type library. To generate and register a type library with COM, use Regasm.exe. + + If you do not specify either the `/win32` or `/win64` option, Tlbexp.exe generates a 32-bit or 64-bit type library that corresponds to the type of computer on which you are performing the compilation (32-bit or 64-bit computer). For cross-compilation purposes, you can use the `/win64` option on a 32-bit computer to generate a 64-bit type library and you can use the `/win32` option on a 64-bit computer to generate a 32-bit type library. In 32-bit type libraries, the value is set to . In 64-bit type libraries, the value is set to . All data type transformations (for example, pointer-sized data types such as `IntPtr` and `UIntPtr`) are converted appropriately. + + If you use the attribute to specify a value of `VT_UNKNOWN` or `VT_DISPATCH`, Tlbexp.exe ignores any subsequent use of the field. For example, given the following signatures: + ```csharp -[return:MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_UNKNOWN, SafeArrayUserDefinedSubType=typeof(ConsoleKeyInfo))] public Array StructUnkSafe(){return null;} -[return:MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_DISPATCH, SafeArrayUserDefinedSubType=typeof(ConsoleKeyInfo))] public Array StructDispSafe(){return null;} -``` - - the following type library is generated: - +[return:MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_UNKNOWN, SafeArrayUserDefinedSubType=typeof(ConsoleKeyInfo))] public Array StructUnkSafe(){return null;} +[return:MarshalAs(UnmanagedType.SafeArray, SafeArraySubType=VarEnum.VT_DISPATCH, SafeArrayUserDefinedSubType=typeof(ConsoleKeyInfo))] public Array StructDispSafe(){return null;} +``` + + the following type library is generated: + ```cpp -[id(0x60020004)] -HRESULT StructUnkSafe([out, retval] SAFEARRAY(IUnknown*)* pRetVal); -[id(0x60020005)] -HRESULT StructDispSafe([out, retval] SAFEARRAY(IDispatch*)* pRetVal); -``` - - Note that Tlbexp.exe ignores the field. - - Because type libraries cannot accommodate all the information found in assemblies, Tlbexp.exe might discard some data during the export process. For an explanation of the transformation process and identification of the source of each piece of information emitted to a type library, see the [Assembly to Type Library Conversion Summary](/previous-versions/dotnet/netframework-4.0/xk1120c3(v=vs.100)). - +[id(0x60020004)] +HRESULT StructUnkSafe([out, retval] SAFEARRAY(IUnknown*)* pRetVal); +[id(0x60020005)] +HRESULT StructDispSafe([out, retval] SAFEARRAY(IDispatch*)* pRetVal); +``` + + Note that Tlbexp.exe ignores the field. + + Because type libraries cannot accommodate all the information found in assemblies, Tlbexp.exe might discard some data during the export process. For an explanation of the transformation process and identification of the source of each piece of information emitted to a type library, see the [Assembly to Type Library Conversion Summary](/previous-versions/dotnet/netframework-4.0/xk1120c3(v=vs.100)). + Note that the Type Library Exporter exports methods that have parameters as `VARIANT`, even though the object has no meaning in unmanaged code. When you export methods that have parameters, the Type Library Exporter will not generate a warning or error and unmanaged code that uses the resulting type library will not run properly. - -## Examples - - The following command generates a type library with the same name as the assembly found in `myTest.dll`. - -```console -tlbexp myTest.dll -``` - - The following command generates a type library with the name `clipper.tlb`. - -```console -tlbexp myTest.dll /out:clipper.tlb -``` - - The following example illustrates using Tlbexp.exe to export a type library from an assembly that references assemblies that were imported using Tlbimp.exe. - - First use Tlbimp.exe to import the type library `myLib.tlb` and save it as `myLib.dll`. - -```console -tlbimp myLib.tlb /out:myLib.dll -``` - - The following command uses the C# compiler to compile the `Sample.dll`, which references `myLib.dll` created in the previous example. - -```console -CSC Sample.cs /reference:myLib.dll /out:Sample.dll -``` - - The following command generates a type library for `Sample.dll` that references `myLib.dll`. - -```console -tlbexp Sample.dll -``` - + +## Examples + + The following command generates a type library with the same name as the assembly found in `myTest.dll`. + +```console +tlbexp myTest.dll +``` + + The following command generates a type library with the name `clipper.tlb`. + +```console +tlbexp myTest.dll /out:clipper.tlb +``` + + The following example illustrates using Tlbexp.exe to export a type library from an assembly that references assemblies that were imported using Tlbimp.exe. + + First use Tlbimp.exe to import the type library `myLib.tlb` and save it as `myLib.dll`. + +```console +tlbimp myLib.tlb /out:myLib.dll +``` + + The following command uses the C# compiler to compile the `Sample.dll`, which references `myLib.dll` created in the previous example. + +```console +CSC Sample.cs /reference:myLib.dll /out:Sample.dll +``` + + The following command generates a type library for `Sample.dll` that references `myLib.dll`. + +```console +tlbexp Sample.dll +``` + ## See also - diff --git a/docs/framework/tools/tlbimp-exe-type-library-importer.md b/docs/framework/tools/tlbimp-exe-type-library-importer.md index e8837725a9d7a..a790a3b2ff42e 100644 --- a/docs/framework/tools/tlbimp-exe-type-library-importer.md +++ b/docs/framework/tools/tlbimp-exe-type-library-importer.md @@ -2,7 +2,7 @@ title: "Tlbimp.exe (Type Library Importer)" description: Use Tlbimp.exe, the Type Library Importer. This tool converts type definitions found within a COM type library into equivalent definitions in a CLR assembly. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "type libraries [.NET Framework], importing" - "importing type library" - "Tlbimp.exe" @@ -14,115 +14,115 @@ ms.assetid: ec0a8d63-11b3-4acd-b398-da1e37e97382 --- # Tlbimp.exe (Type Library Importer) -The Type Library Importer converts the type definitions found within a COM type library into equivalent definitions in a common language runtime assembly. The output of Tlbimp.exe is a binary file (an assembly) that contains runtime metadata for the types defined within the original type library. You can examine this file with tools such as [Ildasm.exe](ildasm-exe-il-disassembler.md). - +The Type Library Importer converts the type definitions found within a COM type library into equivalent definitions in a common language runtime assembly. The output of Tlbimp.exe is a binary file (an assembly) that contains runtime metadata for the types defined within the original type library. You can examine this file with tools such as [Ildasm.exe](ildasm-exe-il-disassembler.md). + This tool is automatically installed with Visual Studio. To run the tool, use [Visual Studio Developer Command Prompt or Visual Studio Developer PowerShell](/visualstudio/ide/reference/command-prompt-powershell). - - At the command prompt, type the following: - -## Syntax - -```console -tlbimp tlbFile [options] -``` - -## Parameters - -|Argument|Description| -|--------------|-----------------| -|*tlbFile*|The name of any file that contains a COM type library.| - -|Option|Description| -|------------|-----------------| -|**/asmversion:** *versionnumber*|Specifies the version number of the assembly to produce. Specify *versionnumber* in the format *major.minor.build.revision*.| -|**/company:** `companyinformation`|Adds company information to the output assembly.| -|**/copyright:** `copyrightinformation`|Adds copyright information to the output assembly. This information can be viewed in the **File Properties** dialog box for the assembly.| -|**/delaysign**|Specifies to Tlbimp.exe to sign the resulting assembly with a strong name using delayed signing. You must specify this option with either the **/keycontainer:**, **/keyfile:**, or **/publickey:** option. For more information on the delayed signing process, see [Delay Signing an Assembly](../../standard/assembly/delay-sign.md).| -|**/help**|Displays command syntax and options for the tool.| -|**/keycontainer:** *containername*|Signs the resulting assembly with a strong name using the public/private key pair found in the key container specified by *containername*.| -|**/keyfile:** *filename*|Signs the resulting assembly with a strong name using the publisher's official public/private key pair found in *filename*.| -|**/machine:** `machinetype`|Creates an assembly that targets the specified machine type (microprocessor). Supported machine types: x86, x64, Itanium, and Agnostic.| -|**/namespace:** *namespace*|Specifies the namespace in which to produce the assembly.| -|**/noclassmembers**|Prevents Tlbimp.exe from adding members to classes. This avoids a potential .| -|**/nologo**|Suppresses the Microsoft startup banner display.| -|**/out:** *filename*|Specifies the name of the output file, assembly, and namespace in which to write the metadata definitions. The **/out** option has no effect on the assembly's namespace if the type library specifies the Interface Definition Language (IDL) custom attribute that explicitly controls the assembly's namespace. If you do not specify this option, Tlbimp.exe writes the metadata to a file with the same name as the actual type library defined within the input file and assigns it a .dll extension. If the output file is the same name as the input file, the tool generates an error to prevent overwriting the type library.| -|**/primary**|Produces a primary interop assembly for the specified type library. Information is added to the assembly indicating that the publisher of the type library produced the assembly. By specifying a primary interop assembly, you differentiate a publisher's assembly from any other assemblies that are created from the type library using Tlbimp.exe. You should only use the **/primary** option if you are the publisher of the type library that you are importing with Tlbimp.exe. Note that you must sign a primary interop assembly with a [strong name](../../standard/assembly/strong-named.md). For more information, see [Primary Interop Assemblies](/previous-versions/dotnet/netframework-4.0/aax7sdch(v=vs.100)).| -|**/product:** `productinformation`|Adds product information to the output assembly. This information can be viewed in the **File Properties** dialog box for the assembly.| -|**/productversion:** `productversioninformation`|Adds product version information to the output assembly. There are no format restrictions. This information can be viewed in the **File Properties** dialog box for the assembly.| -|**/publickey:** *filename*|Specifies the file containing the public key to use to sign the resulting assembly. If you specify the **/keyfile:** or **/keycontainer:** option instead of **/publickey:**, Tlbimp.exe generates the public key from the public/private key pair supplied with **/keyfile:** or **/keycontainer:**. The **/publickey:** option supports test key and delay signing scenarios. The file is in the format generated by Sn.exe. For more information, see the **-p** option of Sn.exe in [Strong Name Tool (Sn.exe)](sn-exe-strong-name-tool.md).| -|**/reference:** *filename*|Specifies the assembly file to use to resolve references to types defined outside the current type library. If you do not specify the **/reference** option, Tlbimp.exe automatically recursively imports any external type library that the type library being imported references. If you specify the **/reference** option, the tool attempts to resolve external types in the referenced assemblies before it imports other type libraries.| -|**/silence:** `warningnumber`|Suppresses the display of the specified warning. This option cannot be used with **/silent**.| -|**/silent**|Suppresses the display of success messages. This option cannot be used with **/silence**.| -|**/strictref**|Does not import a type library if the tool cannot resolve all references within the current assembly, the assemblies specified with the **/reference** option, or registered primary interop assemblies (PIAs).| -|**/strictref:nopia**|Same as **/strictref**, but ignores PIAs.| -|**/sysarray**|Specifies to the tool to import a COM style SafeArray as a managed type.| -|**/tlbreference:** *filename*|Specifies the type library file to use to resolve type library references without consulting the registry.

Note that this option will not load some older type library formats. However, you can still load older type library formats implicitly through the registry or current directory.| -|**/trademark:** `trademarkinformation`|Adds trademark information to the output assembly. This information can be viewed in the **File Properties** dialog box for the assembly.| -|**/transform:** *transformname*|Transforms metadata as specified by the *transformname* parameter.

Specify **dispret** for the *transformname* parameter to transform [out, retval] parameters of methods on dispatch-only interfaces (dispinterfaces) into return values.

For more information about this option, see the examples later in this topic.| -|**/unsafe**|Produces interfaces without .NET Framework security checks. Calling a method that is exposed in this way might pose a security risk. You should not use this option unless you are aware of the risks of exposing such code.| -|**/verbose**|Specifies verbose mode; displays additional information about the imported type library.| -|**/VariantBoolFieldToBool**|Converts `VARIANT_BOOL` fields in structures to .| -|**/?**|Displays command syntax and options for the tool.| - + + At the command prompt, type the following: + +## Syntax + +```console +tlbimp tlbFile [options] +``` + +## Parameters + +|Argument|Description| +|--------------|-----------------| +|*tlbFile*|The name of any file that contains a COM type library.| + +|Option|Description| +|------------|-----------------| +|**/asmversion:** *versionnumber*|Specifies the version number of the assembly to produce. Specify *versionnumber* in the format *major.minor.build.revision*.| +|**/company:** `companyinformation`|Adds company information to the output assembly.| +|**/copyright:** `copyrightinformation`|Adds copyright information to the output assembly. This information can be viewed in the **File Properties** dialog box for the assembly.| +|**/delaysign**|Specifies to Tlbimp.exe to sign the resulting assembly with a strong name using delayed signing. You must specify this option with either the **/keycontainer:**, **/keyfile:**, or **/publickey:** option. For more information on the delayed signing process, see [Delay Signing an Assembly](../../standard/assembly/delay-sign.md).| +|**/help**|Displays command syntax and options for the tool.| +|**/keycontainer:** *containername*|Signs the resulting assembly with a strong name using the public/private key pair found in the key container specified by *containername*.| +|**/keyfile:** *filename*|Signs the resulting assembly with a strong name using the publisher's official public/private key pair found in *filename*.| +|**/machine:** `machinetype`|Creates an assembly that targets the specified machine type (microprocessor). Supported machine types: x86, x64, Itanium, and Agnostic.| +|**/namespace:** *namespace*|Specifies the namespace in which to produce the assembly.| +|**/noclassmembers**|Prevents Tlbimp.exe from adding members to classes. This avoids a potential .| +|**/nologo**|Suppresses the Microsoft startup banner display.| +|**/out:** *filename*|Specifies the name of the output file, assembly, and namespace in which to write the metadata definitions. The **/out** option has no effect on the assembly's namespace if the type library specifies the Interface Definition Language (IDL) custom attribute that explicitly controls the assembly's namespace. If you do not specify this option, Tlbimp.exe writes the metadata to a file with the same name as the actual type library defined within the input file and assigns it a .dll extension. If the output file is the same name as the input file, the tool generates an error to prevent overwriting the type library.| +|**/primary**|Produces a primary interop assembly for the specified type library. Information is added to the assembly indicating that the publisher of the type library produced the assembly. By specifying a primary interop assembly, you differentiate a publisher's assembly from any other assemblies that are created from the type library using Tlbimp.exe. You should only use the **/primary** option if you are the publisher of the type library that you are importing with Tlbimp.exe. Note that you must sign a primary interop assembly with a [strong name](../../standard/assembly/strong-named.md). For more information, see [Primary Interop Assemblies](/previous-versions/dotnet/netframework-4.0/aax7sdch(v=vs.100)).| +|**/product:** `productinformation`|Adds product information to the output assembly. This information can be viewed in the **File Properties** dialog box for the assembly.| +|**/productversion:** `productversioninformation`|Adds product version information to the output assembly. There are no format restrictions. This information can be viewed in the **File Properties** dialog box for the assembly.| +|**/publickey:** *filename*|Specifies the file containing the public key to use to sign the resulting assembly. If you specify the **/keyfile:** or **/keycontainer:** option instead of **/publickey:**, Tlbimp.exe generates the public key from the public/private key pair supplied with **/keyfile:** or **/keycontainer:**. The **/publickey:** option supports test key and delay signing scenarios. The file is in the format generated by Sn.exe. For more information, see the **-p** option of Sn.exe in [Strong Name Tool (Sn.exe)](sn-exe-strong-name-tool.md).| +|**/reference:** *filename*|Specifies the assembly file to use to resolve references to types defined outside the current type library. If you do not specify the **/reference** option, Tlbimp.exe automatically recursively imports any external type library that the type library being imported references. If you specify the **/reference** option, the tool attempts to resolve external types in the referenced assemblies before it imports other type libraries.| +|**/silence:** `warningnumber`|Suppresses the display of the specified warning. This option cannot be used with **/silent**.| +|**/silent**|Suppresses the display of success messages. This option cannot be used with **/silence**.| +|**/strictref**|Does not import a type library if the tool cannot resolve all references within the current assembly, the assemblies specified with the **/reference** option, or registered primary interop assemblies (PIAs).| +|**/strictref:nopia**|Same as **/strictref**, but ignores PIAs.| +|**/sysarray**|Specifies to the tool to import a COM style SafeArray as a managed type.| +|**/tlbreference:** *filename*|Specifies the type library file to use to resolve type library references without consulting the registry.

Note that this option will not load some older type library formats. However, you can still load older type library formats implicitly through the registry or current directory.| +|**/trademark:** `trademarkinformation`|Adds trademark information to the output assembly. This information can be viewed in the **File Properties** dialog box for the assembly.| +|**/transform:** *transformname*|Transforms metadata as specified by the *transformname* parameter.

Specify `dispret` for the *transformname* parameter to transform [out, retval] parameters of methods on dispatch-only interfaces (dispinterfaces) into return values.

For more information about this option, see the examples later in this topic.| +|**/unsafe**|Produces interfaces without .NET Framework security checks. Calling a method that is exposed in this way might pose a security risk. You should not use this option unless you are aware of the risks of exposing such code.| +|**/verbose**|Specifies verbose mode; displays additional information about the imported type library.| +|**/VariantBoolFieldToBool**|Converts `VARIANT_BOOL` fields in structures to .| +|**/?**|Displays command syntax and options for the tool.| + > [!NOTE] -> The command-line options for Tlbimp.exe are case-insensitive and can be supplied in any order. You only need to specify enough of the option to uniquely identify it. Therefore, **/n** is equivalent to **/nologo** and **/ou:** *outfile.dll* is equivalent to **/out:** *outfile.dll*. - -## Remarks - - Tlbimp.exe performs conversions on an entire type library at one time. You cannot use the tool to generate type information for a subset of the types defined within a single type library. - - It is often useful or necessary to be able to assign [strong names](../../standard/assembly/strong-named.md) to assemblies. Therefore, Tlbimp.exe includes options for supplying the information necessary to generate strongly named assemblies. Both the **/keyfile:** and **/keycontainer:** options sign assemblies with strong names. Therefore, it is logical to supply only one of these options at a time. - +> The command-line options for Tlbimp.exe are case-insensitive and can be supplied in any order. You only need to specify enough of the option to uniquely identify it. Therefore, **/n** is equivalent to **/nologo** and **/ou:** *outfile.dll* is equivalent to **/out:** *outfile.dll*. + +## Remarks + + Tlbimp.exe performs conversions on an entire type library at one time. You cannot use the tool to generate type information for a subset of the types defined within a single type library. + + It is often useful or necessary to be able to assign [strong names](../../standard/assembly/strong-named.md) to assemblies. Therefore, Tlbimp.exe includes options for supplying the information necessary to generate strongly named assemblies. Both the **/keyfile:** and **/keycontainer:** options sign assemblies with strong names. Therefore, it is logical to supply only one of these options at a time. + You can specify multiple reference assemblies by using the **/reference** option multiple times. Due to the way in which Tlbimp.exe generates assemblies, it is not possible to retarget an assembly to a different `mscorlib` version. For example, if you desire to generate an assembly that targets .NET Framework 2.0, the Tlbimp.exe shipped with the .NET Framework 2.0/3.0/3.5 SDK must be used. In order to target .NET Framework 4.x, the Tlbimp.exe shipped with a .NET Framework 4.x SDK should be used. - A resource ID can optionally be appended to a type library file when importing a type library from a module containing multiple type libraries. Tlbimp.exe is able to locate this file only if it is in the current directory or if you specify the full path. See the example later in this topic. - -## Examples + A resource ID can optionally be appended to a type library file when importing a type library from a module containing multiple type libraries. Tlbimp.exe is able to locate this file only if it is in the current directory or if you specify the full path. See the example later in this topic. + +## Examples + + The following command generates an assembly with the same name as the type library found in `myTest.tlb` and with the .dll extension. - The following command generates an assembly with the same name as the type library found in `myTest.tlb` and with the .dll extension. - -```console +```console tlbimp myTest.tlb -``` - - The following command generates an assembly with the name `myTest.dll`. - -```console -tlbimp myTest.tlb /out:myTest.dll -``` - - The following command generates an assembly with the same name as the type library specified by `MyModule.dll\1` and with the .dll extension. `MyModule.dll\1` must be located in the current directory. - -```console -tlbimp MyModule.dll\1 -``` - - The following command generates an assembly with the name `myTestLib.dll` for the type library `TestLib.dll`. The **/transform:dispret** option transforms any [out, retval] parameters of methods on dispinterfaces in the type library into return values in the managed library. - -```console -tlbimp TestLib.dll /transform:dispret /out:myTestLib.dll -``` - - The type library `TestLib.dll`, in the preceding example, includes a dispinterface method named `SomeMethod` that returns void and has an [out, retval] parameter. The following code is the input type library method signature for `SomeMethod` in `TestLib.dll`. - -```cpp -void SomeMethod([out, retval] VARIANT_BOOL*); -``` - - Specifying the **/transform:dispret** option causes Tlbimp.exe to transform the `[out, retval]` parameter of `SomeMethod` into a `bool` return value. The following is the method signature that Tlbimp.exe produces for `SomeMethod` in the managed library `myTestLib.dll` when the **/transform:dispret** option is specified. - -```csharp -bool SomeMethod(); -``` - - If you use Tlbimp.exe to produce a managed library for `TestLib.dll` without specifying the **/transform:dispret**, the tool produces the following method signature for `SomeMethod` in the managed library `myTestLib.dll`. - -```csharp -void SomeMethod(out bool x); -``` - +``` + + The following command generates an assembly with the name `myTest.dll`. + +```console +tlbimp myTest.tlb /out:myTest.dll +``` + + The following command generates an assembly with the same name as the type library specified by `MyModule.dll\1` and with the .dll extension. `MyModule.dll\1` must be located in the current directory. + +```console +tlbimp MyModule.dll\1 +``` + + The following command generates an assembly with the name `myTestLib.dll` for the type library `TestLib.dll`. The **/transform:dispret** option transforms any [out, retval] parameters of methods on dispinterfaces in the type library into return values in the managed library. + +```console +tlbimp TestLib.dll /transform:dispret /out:myTestLib.dll +``` + + The type library `TestLib.dll`, in the preceding example, includes a dispinterface method named `SomeMethod` that returns void and has an [out, retval] parameter. The following code is the input type library method signature for `SomeMethod` in `TestLib.dll`. + +```cpp +void SomeMethod([out, retval] VARIANT_BOOL*); +``` + + Specifying the **/transform:dispret** option causes Tlbimp.exe to transform the `[out, retval]` parameter of `SomeMethod` into a `bool` return value. The following is the method signature that Tlbimp.exe produces for `SomeMethod` in the managed library `myTestLib.dll` when the **/transform:dispret** option is specified. + +```csharp +bool SomeMethod(); +``` + + If you use Tlbimp.exe to produce a managed library for `TestLib.dll` without specifying the **/transform:dispret**, the tool produces the following method signature for `SomeMethod` in the managed library `myTestLib.dll`. + +```csharp +void SomeMethod(out bool x); +``` + ## See also - [Tools](index.md) diff --git a/docs/framework/tools/winres-exe-windows-forms-resource-editor.md b/docs/framework/tools/winres-exe-windows-forms-resource-editor.md index 683595d96f10f..e09812c0fd141 100644 --- a/docs/framework/tools/winres-exe-windows-forms-resource-editor.md +++ b/docs/framework/tools/winres-exe-windows-forms-resource-editor.md @@ -51,21 +51,21 @@ Also see [Hierarchical Organization of Resources for Localization](/previous-ver Winres.exe cannot convert a .resx file into its corresponding .resources file; use the Resgen.exe tool instead. For more information about Resgen.exe, see [Resgen.exe (Resource File Generator)](resgen-exe-resource-file-generator.md). -Winres.exe is a graphical application that recreates a design-time version of a Windows Forms form from just the resource file, without having access to the source code. Winres.exe hosts Visual Studio's **Windows Forms Form Designer** and **Properties** window. These features enable visual editing of a .resources or .resx file containing a Windows Forms form. Typically, localizers use Winres.exe to edit control labels and adjust the location and size of controls to accommodate the labels for the target culture. +Winres.exe is a graphical application that recreates a design-time version of a Windows Forms form from just the resource file, without having access to the source code. Winres.exe hosts Visual Studio's **Windows Forms Form Designer** and `Properties` window. These features enable visual editing of a .resources or .resx file containing a Windows Forms form. Typically, localizers use Winres.exe to edit control labels and adjust the location and size of controls to accommodate the labels for the target culture. -If Winres.exe cannot resolve the type of a control, it creates a placeholder control in the localized .resx or .resources file. The placeholder control appears on the Windows Forms form as a hatched window. The size and position of the hatched window matches that of the actual control. All the available localizable properties for the placeholder control appear in the **Properties** window. Any changes that you make to the placeholder control are saved for the actual control. +If Winres.exe cannot resolve the type of a control, it creates a placeholder control in the localized .resx or .resources file. The placeholder control appears on the Windows Forms form as a hatched window. The size and position of the hatched window matches that of the actual control. All the available localizable properties for the placeholder control appear in the `Properties` window. Any changes that you make to the placeholder control are saved for the actual control. ## Winres.exe versus Visual Studio In general, before you begin to localize an application's Windows Forms forms, you should decide whether you want to use Visual Studio or Winres.exe as the localization tool. Version compatibility, as described later, may prevent you from switching from one tool to the other. -The advantage of Visual Studio is that you can use it to both develop and localize an application. To localize a form, after development is complete, set the form's (the **Localizable** property in the **Properties** editor) to `true` and change its **Language** property to the desired target culture. Then, edit strings and adjust the location and size of controls to accommodate the strings for the target culture. When you save the localized .resx file, Visual Studio writes only the localizable properties (properties that changed in the target culture) to the file. Visual Studio automatically creates a satellite assembly for the localized .resx file in the correct directory location. +The advantage of Visual Studio is that you can use it to both develop and localize an application. To localize a form, after development is complete, set the form's (the `Localizable` property in the `Properties` editor) to `true` and change its `Language` property to the desired target culture. Then, edit strings and adjust the location and size of controls to accommodate the strings for the target culture. When you save the localized .resx file, Visual Studio writes only the localizable properties (properties that changed in the target culture) to the file. Visual Studio automatically creates a satellite assembly for the localized .resx file in the correct directory location. Although Visual Studio provides an integrated development and localization environment, Winres.exe is the recommended tool to use if localization is done by third-party localizers. Because Winres.exe is a localization tool only, it allows for a cleaner separation of an application's code from the forms to be localized, which is more practical for managing large projects. ## Using Winres.exe -To localize using Winres.exe, you must first develop an application using a visual designer like the **Windows Forms Designer** in Visual Studio. When development is complete, set the form's (the **Localizable** property in the **Properties** editor) to `true`, and then hand off the .resx file for the default culture to a third-party localizer. This .resx file contains extra information that Winres.exe uses to recreate a design-time version of the original form. +To localize using Winres.exe, you must first develop an application using a visual designer like the **Windows Forms Designer** in Visual Studio. When development is complete, set the form's (the `Localizable` property in the `Properties` editor) to `true`, and then hand off the .resx file for the default culture to a third-party localizer. This .resx file contains extra information that Winres.exe uses to recreate a design-time version of the original form. > [!NOTE] > Winres.exe cannot be used to edit the default resource file. Winres.exe interprets all changed properties as localized properties and saves them to the target culture resource file. @@ -78,7 +78,7 @@ Winres.exe has the following features and capabilities: - An error-reporting window, docked to the bottom-left of the main window. -- Hotkeys can be checked for duplicates: from the **Format** menu, click the **Check HotKeys** command. +- Hotkeys can be checked for duplicates: from the `Format` menu, click the **Check HotKeys** command. ## Version compatibility @@ -123,7 +123,7 @@ You should use the version of Winres.exe that was released with the .NET Framewo 3. Select controls on the form and change their and other properties to reflect the localized culture and its language. Move or resize controls as necessary to accommodate the localized text. -4. To save the localized version of the .resx or .resources file, click the **Save** icon or select **File > Save**. The tool displays the **Select Culture** window. +4. To save the localized version of the .resx or .resources file, click the `Save` icon or select **File > Save**. The tool displays the **Select Culture** window. 5. Select the appropriate culture and file mode then click **OK**. diff --git a/docs/framework/unmanaged-api/authenticode/axlrsakeyvaluetopublickeytoken-function.md b/docs/framework/unmanaged-api/authenticode/axlrsakeyvaluetopublickeytoken-function.md index 9c7f0854a79fa..497b64b6a053f 100644 --- a/docs/framework/unmanaged-api/authenticode/axlrsakeyvaluetopublickeytoken-function.md +++ b/docs/framework/unmanaged-api/authenticode/axlrsakeyvaluetopublickeytoken-function.md @@ -9,7 +9,7 @@ api_location: api_type: - "DLLExport" ms.assetid: d60f19fe-7bec-47ba-b60e-ba9ce66abf8c -topic_type: +topic_type: - "apiref" --- # \_AxlRSAKeyValueToPublicKeyToken function @@ -29,10 +29,10 @@ HRESULT _AxlRSAKeyValueToPublicKeyToken ( ## Parameters `pModulusBlob`\ - [in] The base64-encoded Modulus blob (from the \ element). See the [CRYPTOAPI_BLOB](/windows/win32/api/dpapi/ns-dpapi-crypt_integer_blob) structure. + [in] The base64-encoded Modulus blob (from the `` element). See the [CRYPTOAPI_BLOB](/windows/win32/api/dpapi/ns-dpapi-crypt_integer_blob) structure. `pExponentBlob`\ - [in] The base64-encoded Exponent blob (from the \ element). See the [CRYPTOAPI_BLOB](/windows/win32/api/dpapi/ns-dpapi-crypt_integer_blob) structure. + [in] The base64-encoded Exponent blob (from the `` element). See the [CRYPTOAPI_BLOB](/windows/win32/api/dpapi/ns-dpapi-crypt_integer_blob) structure. `ppwszPublicKeyToken`\ [out] A pointer to WCHAR * to receive the hex-encoded public key token. diff --git a/docs/framework/unmanaged-api/diagnostics/isymunmanagedasyncmethodpropertieswriter-definecatchhandleriloffset-method.md b/docs/framework/unmanaged-api/diagnostics/isymunmanagedasyncmethodpropertieswriter-definecatchhandleriloffset-method.md index c3c5e41db2593..1bf3c3aab4547 100644 --- a/docs/framework/unmanaged-api/diagnostics/isymunmanagedasyncmethodpropertieswriter-definecatchhandleriloffset-method.md +++ b/docs/framework/unmanaged-api/diagnostics/isymunmanagedasyncmethodpropertieswriter-definecatchhandleriloffset-method.md @@ -6,30 +6,30 @@ ms.assetid: 92af7896-2201-408d-8b1b-23e28001eeac --- # ISymUnmanagedAsyncMethodPropertiesWriter::DefineCatchHandlerILOffset Method -Sets the IL offset for the compiler-generated catch handler that wraps an async method. - - The IL offset of the generated catch is used by the debugger to handle the catch as if it were non-user code even though it might occur in a user code method. In particular, it is used in response to a **CatchHandlerFound** exception event. - -## Syntax - -```idl -HRESULT DefineCatchHandlerILOffset( [in] ULONG32 catchHandlerOffset); -``` - -## Parameters - -|Parameter|Description| -|---------------|-----------------| -|`catchHandlerOffset`|| - -## Return Value - - Returns `HRESULT`. - -## Requirements - - **Header:** CorSym.idl, CorSym.h - +Sets the IL offset for the compiler-generated catch handler that wraps an async method. + + The IL offset of the generated catch is used by the debugger to handle the catch as if it were non-user code even though it might occur in a user code method. In particular, it is used in response to a `CatchHandlerFound` exception event. + +## Syntax + +```idl +HRESULT DefineCatchHandlerILOffset( [in] ULONG32 catchHandlerOffset); +``` + +## Parameters + +|Parameter|Description| +|---------------|-----------------| +|`catchHandlerOffset`|| + +## Return Value + + Returns `HRESULT`. + +## Requirements + + **Header:** CorSym.idl, CorSym.h + ## See also - [ISymUnmanagedAsyncMethodPropertiesWriter Interface](isymunmanagedasyncmethodpropertieswriter-interface.md) diff --git a/docs/framework/unmanaged-api/diagnostics/isymunmanagedasyncmethodpropertieswriter-interface.md b/docs/framework/unmanaged-api/diagnostics/isymunmanagedasyncmethodpropertieswriter-interface.md index 0c255c1deb5fd..f2378dcd3aa96 100644 --- a/docs/framework/unmanaged-api/diagnostics/isymunmanagedasyncmethodpropertieswriter-interface.md +++ b/docs/framework/unmanaged-api/diagnostics/isymunmanagedasyncmethodpropertieswriter-interface.md @@ -6,28 +6,28 @@ ms.assetid: caa71820-8058-4b6a-93a2-25ee757d92d3 --- # ISymUnmanagedAsyncMethodPropertiesWriter Interface -Allows you to define optional async method information for each method symbol. Always use with an opened method; that is, between calls to the [OpenMethod Method](isymunmanagedwriter-openmethod-method.md) and the [CloseMethod Method](isymunmanagedwriter-closemethod-method.md). - -## Syntax - -```idl -[object,uuid(FC073774-1739-4232-BD56-A027294BEC15),pointer_default(unique)]interface ISymUnmanagedAsyncMethodPropertiesWriter : IUnknown -``` - -## Methods - - This interface contains the following methods: - -|Method|Description| -|------------|-----------------| -|[DefineAsyncStepInfo Method](isymunmanagedasyncmethodpropertieswriter-defineasyncstepinfo-method.md)|Define a group of async await operations in the current method.

Each yield offset matches an await's return instruction, identifying a potential yield. Each `breakpointMethod`/`breakpointOffset` pair identifies where the asynchronous operation will resume; it may be in a different method.| -|[DefineCatchHandlerILOffset Method](isymunmanagedasyncmethodpropertieswriter-definecatchhandleriloffset-method.md)|Sets the IL offset for the compiler-generated catch handler that wraps an async method.

The IL offset of the generated catch is used by the debugger to handle the catch as if it were non-user code, even though it may occur in a user code method. In particular, it is used in response to a **CatchHandlerFound** exception event.| -|[DefineKickoffMethod Method](isymunmanagedasyncmethodpropertieswriter-definekickoffmethod-method.md)|Sets the starting method that initiates the async operation.| - -## Requirements - - **Header:** CorSym.idl, CorSym.h - +Allows you to define optional async method information for each method symbol. Always use with an opened method; that is, between calls to the [OpenMethod Method](isymunmanagedwriter-openmethod-method.md) and the [CloseMethod Method](isymunmanagedwriter-closemethod-method.md). + +## Syntax + +```idl +[object,uuid(FC073774-1739-4232-BD56-A027294BEC15),pointer_default(unique)]interface ISymUnmanagedAsyncMethodPropertiesWriter : IUnknown +``` + +## Methods + + This interface contains the following methods: + +|Method|Description| +|------------|-----------------| +|[DefineAsyncStepInfo Method](isymunmanagedasyncmethodpropertieswriter-defineasyncstepinfo-method.md)|Define a group of async await operations in the current method.

Each yield offset matches an await's return instruction, identifying a potential yield. Each `breakpointMethod`/`breakpointOffset` pair identifies where the asynchronous operation will resume; it may be in a different method.| +|[DefineCatchHandlerILOffset Method](isymunmanagedasyncmethodpropertieswriter-definecatchhandleriloffset-method.md)|Sets the IL offset for the compiler-generated catch handler that wraps an async method.

The IL offset of the generated catch is used by the debugger to handle the catch as if it were non-user code, even though it may occur in a user code method. In particular, it is used in response to a `CatchHandlerFound` exception event.| +|[DefineKickoffMethod Method](isymunmanagedasyncmethodpropertieswriter-definekickoffmethod-method.md)|Sets the starting method that initiates the async operation.| + +## Requirements + + **Header:** CorSym.idl, CorSym.h + ## See also - [Diagnostics Symbol Store Interfaces](diagnostics-symbol-store-interfaces.md) diff --git a/docs/framework/unmanaged-api/hosting/iclrappdomainresourcemonitor-interface.md b/docs/framework/unmanaged-api/hosting/iclrappdomainresourcemonitor-interface.md index f8f9f50d47d78..6a458fc48516b 100644 --- a/docs/framework/unmanaged-api/hosting/iclrappdomainresourcemonitor-interface.md +++ b/docs/framework/unmanaged-api/hosting/iclrappdomainresourcemonitor-interface.md @@ -2,59 +2,59 @@ description: "Learn more about: ICLRAppDomainResourceMonitor Interface" title: "ICLRAppDomainResourceMonitor Interface" ms.date: "03/30/2017" -api_name: +api_name: - "ICLRAppDomainResourceMonitor" -api_location: +api_location: - "mscoree.dll" -api_type: +api_type: - "COM" -f1_keywords: +f1_keywords: - "ICLRAppDomainResourceMonitor" -helpviewer_keywords: +helpviewer_keywords: - "ICLRAppDomainResourceMonitor interface [.NET Framework hosting]" ms.assetid: 72fa83a1-8997-41d7-b355-ab177a24a303 -topic_type: +topic_type: - "apiref" --- # ICLRAppDomainResourceMonitor Interface -Provides methods that inspect an application domain's memory and CPU usage. - -## Methods - -|Method|Description| -|------------|-----------------| -|[GetCurrentAllocated Method](iclrappdomainresourcemonitor-getcurrentallocated-method.md)|Gets the total size, in bytes, of all memory allocations that have been made by the application domain since it was created, without subtracting memory that has been garbage-collected.| -|[GetCurrentSurvived Method](iclrappdomainresourcemonitor-getcurrentsurvived-method.md)|Gets the number of bytes that survived the last full, blocking garbage collection and that are referenced by the current application domain.| -|[GetCurrentCpuTime Method](iclrappdomainresourcemonitor-getcurrentcputime-method.md)|Gets the total processor time that has been used by all threads while executing in the current application domain, since the application domain was created.| - -## Remarks - - The `ICLRAppDomainResourceMonitor` interface provides functionality that is similar to the following managed properties: - -- - -- - -- - -- - -- - -## Requirements - - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** MetaHost.h - - **Library:** Included as a resource in MSCorEE.dll - - **.NET Framework Versions:** [!INCLUDE[net_current_v40plus](../../../../includes/net-current-v40plus-md.md)] - +Provides methods that inspect an application domain's memory and CPU usage. + +## Methods + +|Method|Description| +|------------|-----------------| +|[GetCurrentAllocated Method](iclrappdomainresourcemonitor-getcurrentallocated-method.md)|Gets the total size, in bytes, of all memory allocations that have been made by the application domain since it was created, without subtracting memory that has been garbage-collected.| +|[GetCurrentSurvived Method](iclrappdomainresourcemonitor-getcurrentsurvived-method.md)|Gets the number of bytes that survived the last full, blocking garbage collection and that are referenced by the current application domain.| +|[GetCurrentCpuTime Method](iclrappdomainresourcemonitor-getcurrentcputime-method.md)|Gets the total processor time that has been used by all threads while executing in the current application domain, since the application domain was created.| + +## Remarks + + The `ICLRAppDomainResourceMonitor` interface provides functionality that is similar to the following managed properties: + +- + +- + +- + +- + +- + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** MetaHost.h + + **Library:** Included as a resource in MSCorEE.dll + + **.NET Framework Versions:** [!INCLUDE[net_current_v40plus](../../../../includes/net-current-v40plus-md.md)] + ## See also -- [\ Element](../../configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md) +- [`` Element](../../configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md) - [Application Domain Resource Monitoring](../../../standard/garbage-collection/app-domain-resource-monitoring.md) - [Hosting Interfaces](hosting-interfaces.md) - [Hosting](index.md) diff --git a/docs/framework/unmanaged-api/hosting/iclrmetahost-interface.md b/docs/framework/unmanaged-api/hosting/iclrmetahost-interface.md index 4aab578cdebae..3933638fd07d9 100644 --- a/docs/framework/unmanaged-api/hosting/iclrmetahost-interface.md +++ b/docs/framework/unmanaged-api/hosting/iclrmetahost-interface.md @@ -2,56 +2,56 @@ description: "Learn more about: ICLRMetaHost Interface" title: "ICLRMetaHost Interface" ms.date: "03/30/2017" -api_name: +api_name: - "ICLRMetaHost" -api_location: +api_location: - "mscoree.dll" -api_type: +api_type: - "COM" -f1_keywords: +f1_keywords: - "ICLRMetaHost" -helpviewer_keywords: +helpviewer_keywords: - "ICLRMetaHost interface [.NET Framework hosting]" ms.assetid: c627fcdd-fc4f-4b1c-8e91-df8536f627d8 -topic_type: +topic_type: - "apiref" --- # ICLRMetaHost Interface -Provides methods that return a specific version of the common language runtime (CLR) based on its version number, list all installed CLRs, list all runtimes that are loaded in a specified process, discover the CLR version used to compile an assembly, exit a process with a clean runtime shutdown, and query legacy API binding. - -## Methods - -|Method|Description| -|------------|-----------------| -|[EnumerateInstalledRuntimes Method](iclrmetahost-enumerateinstalledruntimes-method.md)|Returns an enumeration that contains a valid [ICLRRuntimeInfo](iclrruntimeinfo-interface.md) interface pointer for each CLR version that is installed on a computer.| -|[EnumerateLoadedRuntimes Method](iclrmetahost-enumerateloadedruntimes-method.md)|Returns an enumeration that contains a valid [ICLRRuntimeInfo](iclrruntimeinfo-interface.md) interface pointer for each CLR that is loaded in a given process. This method supersedes [GetVersionFromProcess](getversionfromprocess-function.md).| -|[ExitProcess Method](iclrmetahost-exitprocess-method.md)|Attempts to shut down all loaded runtimes gracefully and then terminates the process. Supersedes the [CorExitProcess](corexitprocess-function.md) function.| -|[GetRuntime Method](iclrmetahost-getruntime-method.md)|Gets the [ICLRRuntimeInfo](iclrruntimeinfo-interface.md) interface that corresponds to a particular CLR version. This method supersedes the [CorBindToRuntimeEx](corbindtoruntimeex-function.md) function used with the [STARTUP_LOADER_SAFEMODE](startup-flags-enumeration.md) flag.| -|[GetVersionFromFile Method](iclrmetahost-getversionfromfile-method.md)|Gets the assembly's original .NET Framework compilation version (stored in the metadata), given its file path. This method supersedes [GetFileVersion](getfileversion-function.md).| -|[QueryLegacyV2RuntimeBinding Method](iclrmetahost-querylegacyv2runtimebinding-method.md)|Returns an interface that represents a runtime to which legacy activation policy has been bound, for example by using the `useLegacyV2RuntimeActivationPolicy` attribute on the [\ Element](../../configure-apps/file-schema/startup/startup-element.md) configuration file entry, by direct use of the legacy activation APIs, or by calling the [ICLRRuntimeInfo::BindAsLegacyV2Runtime](iclrruntimeinfo-bindaslegacyv2runtime-method.md) method.| -|[RequestRuntimeLoadedNotification Method](iclrmetahost-requestruntimeloadednotification-method.md)|Guarantees a callback to the specified function pointer when a CLR version is first loaded, but not yet started. This method supersedes [LockClrVersion](lockclrversion-function.md)| - -## Remarks - - The only way to get an instance of this interface is by calling the [CLRCreateInstance](clrcreateinstance-function.md) function as follows: - -```cpp -ICLRMetaHost *pMetaHost = NULL; -HRESULT hr = CLRCreateInstance(CLSID_CLRMetaHost, - IID_ICLRMetaHost, (LPVOID*)&pMetaHost); -``` - -## Requirements - - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** MetaHost.h - - **Library:** Included as a resource in MSCorEE.dll - - **.NET Framework Versions:** [!INCLUDE[net_current_v40plus](../../../../includes/net-current-v40plus-md.md)] - +Provides methods that return a specific version of the common language runtime (CLR) based on its version number, list all installed CLRs, list all runtimes that are loaded in a specified process, discover the CLR version used to compile an assembly, exit a process with a clean runtime shutdown, and query legacy API binding. + +## Methods + +|Method|Description| +|------------|-----------------| +|[EnumerateInstalledRuntimes Method](iclrmetahost-enumerateinstalledruntimes-method.md)|Returns an enumeration that contains a valid [ICLRRuntimeInfo](iclrruntimeinfo-interface.md) interface pointer for each CLR version that is installed on a computer.| +|[EnumerateLoadedRuntimes Method](iclrmetahost-enumerateloadedruntimes-method.md)|Returns an enumeration that contains a valid [ICLRRuntimeInfo](iclrruntimeinfo-interface.md) interface pointer for each CLR that is loaded in a given process. This method supersedes [GetVersionFromProcess](getversionfromprocess-function.md).| +|[ExitProcess Method](iclrmetahost-exitprocess-method.md)|Attempts to shut down all loaded runtimes gracefully and then terminates the process. Supersedes the [CorExitProcess](corexitprocess-function.md) function.| +|[GetRuntime Method](iclrmetahost-getruntime-method.md)|Gets the [ICLRRuntimeInfo](iclrruntimeinfo-interface.md) interface that corresponds to a particular CLR version. This method supersedes the [CorBindToRuntimeEx](corbindtoruntimeex-function.md) function used with the [STARTUP_LOADER_SAFEMODE](startup-flags-enumeration.md) flag.| +|[GetVersionFromFile Method](iclrmetahost-getversionfromfile-method.md)|Gets the assembly's original .NET Framework compilation version (stored in the metadata), given its file path. This method supersedes [GetFileVersion](getfileversion-function.md).| +|[QueryLegacyV2RuntimeBinding Method](iclrmetahost-querylegacyv2runtimebinding-method.md)|Returns an interface that represents a runtime to which legacy activation policy has been bound, for example by using the `useLegacyV2RuntimeActivationPolicy` attribute on the [`` Element](../../configure-apps/file-schema/startup/startup-element.md) configuration file entry, by direct use of the legacy activation APIs, or by calling the [ICLRRuntimeInfo::BindAsLegacyV2Runtime](iclrruntimeinfo-bindaslegacyv2runtime-method.md) method.| +|[RequestRuntimeLoadedNotification Method](iclrmetahost-requestruntimeloadednotification-method.md)|Guarantees a callback to the specified function pointer when a CLR version is first loaded, but not yet started. This method supersedes [LockClrVersion](lockclrversion-function.md)| + +## Remarks + + The only way to get an instance of this interface is by calling the [CLRCreateInstance](clrcreateinstance-function.md) function as follows: + +```cpp +ICLRMetaHost *pMetaHost = NULL; +HRESULT hr = CLRCreateInstance(CLSID_CLRMetaHost, + IID_ICLRMetaHost, (LPVOID*)&pMetaHost); +``` + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** MetaHost.h + + **Library:** Included as a resource in MSCorEE.dll + + **.NET Framework Versions:** [!INCLUDE[net_current_v40plus](../../../../includes/net-current-v40plus-md.md)] + ## See also - [Hosting Interfaces](hosting-interfaces.md) diff --git a/docs/framework/unmanaged-api/hosting/iclrmetahost-querylegacyv2runtimebinding-method.md b/docs/framework/unmanaged-api/hosting/iclrmetahost-querylegacyv2runtimebinding-method.md index d3fcf10076862..fecf95b43f821 100644 --- a/docs/framework/unmanaged-api/hosting/iclrmetahost-querylegacyv2runtimebinding-method.md +++ b/docs/framework/unmanaged-api/hosting/iclrmetahost-querylegacyv2runtimebinding-method.md @@ -2,63 +2,63 @@ description: "Learn more about: ICLRMetaHost::QueryLegacyV2RuntimeBinding Method" title: "ICLRMetaHost::QueryLegacyV2RuntimeBinding Method" ms.date: "03/30/2017" -api_name: +api_name: - "ICLRMetaHost.RequestRuntimeLoadedNotification" -api_location: +api_location: - "mscoree.dll" -api_type: +api_type: - "COM" -f1_keywords: +f1_keywords: - "ICLRMetaHost::QueryLegacyV2RuntimeBinding" -helpviewer_keywords: +helpviewer_keywords: - "QueryLegacyV2RuntimeBinding method [.NET Framework hosting]" - "ICLRMetaHost::QueryLegacyV2RuntimeBinding method [.NET Framework hosting]" ms.assetid: 9929817e-acc9-40b7-960c-598664e04b60 -topic_type: +topic_type: - "apiref" --- # ICLRMetaHost::QueryLegacyV2RuntimeBinding Method -Returns an interface that represents a runtime to which legacy activation policy has been bound, for example, by using the `useLegacyV2RuntimeActivationPolicy` attribute on the [\ element](../../configure-apps/file-schema/startup/startup-element.md) configuration file entry, by direct use of the legacy activation APIs, or by calling the [ICLRRuntimeInfo::BindAsLegacyV2Runtime](iclrruntimeinfo-bindaslegacyv2runtime-method.md) method. - -## Syntax - -```cpp -HRESULT QueryLegacyV2RuntimeBinding ( - [in] REFIID riid, - [out, iid_is(riid), retval] LPVOID *ppUnk); -``` - -## Parameters - - `riid` - [in] Required.Currently the only valid value for this parameter is `IID_ICLRRuntimeInfo`. - - `ppUnk` - [out] Required. When this method returns, contains a pointer to the [ICLRRuntimeInfo](iclrruntimeinfo-interface.md) interface that represents a runtime that has been bound to legacy activation policy. - -## Return Value - - This method returns the following specific HRESULTs as well as HRESULT errors that indicate method failure. - -|HRESULT|Description| -|-------------|-----------------| -|S_OK|The method completed successfully and returned a runtime that was bound to legacy activation policy.| -|S_FALSE|The method completed successfully, but a legacy runtime has not yet been bound.| -|E_NOINTERFACE|The method found a runtime that was bound to legacy activation policy, but `riid` is not supported by that runtime.| - -## Remarks - -## Requirements - - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** MetaHost.h - - **Library:** Included as a resource in MSCorEE.dll - - **.NET Framework Versions:** [!INCLUDE[net_current_v40plus](../../../../includes/net-current-v40plus-md.md)] - +Returns an interface that represents a runtime to which legacy activation policy has been bound, for example, by using the `useLegacyV2RuntimeActivationPolicy` attribute on the [`` element](../../configure-apps/file-schema/startup/startup-element.md) configuration file entry, by direct use of the legacy activation APIs, or by calling the [ICLRRuntimeInfo::BindAsLegacyV2Runtime](iclrruntimeinfo-bindaslegacyv2runtime-method.md) method. + +## Syntax + +```cpp +HRESULT QueryLegacyV2RuntimeBinding ( + [in] REFIID riid, + [out, iid_is(riid), retval] LPVOID *ppUnk); +``` + +## Parameters + + `riid` + [in] Required.Currently the only valid value for this parameter is `IID_ICLRRuntimeInfo`. + + `ppUnk` + [out] Required. When this method returns, contains a pointer to the [ICLRRuntimeInfo](iclrruntimeinfo-interface.md) interface that represents a runtime that has been bound to legacy activation policy. + +## Return Value + + This method returns the following specific HRESULTs as well as HRESULT errors that indicate method failure. + +|HRESULT|Description| +|-------------|-----------------| +|S_OK|The method completed successfully and returned a runtime that was bound to legacy activation policy.| +|S_FALSE|The method completed successfully, but a legacy runtime has not yet been bound.| +|E_NOINTERFACE|The method found a runtime that was bound to legacy activation policy, but `riid` is not supported by that runtime.| + +## Remarks + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** MetaHost.h + + **Library:** Included as a resource in MSCorEE.dll + + **.NET Framework Versions:** [!INCLUDE[net_current_v40plus](../../../../includes/net-current-v40plus-md.md)] + ## See also - [ICLRMetaHost Interface](iclrmetahost-interface.md) diff --git a/docs/framework/unmanaged-api/hosting/iclrruntimeinfo-bindaslegacyv2runtime-method.md b/docs/framework/unmanaged-api/hosting/iclrruntimeinfo-bindaslegacyv2runtime-method.md index a69824369b18a..1a75caaf465c9 100644 --- a/docs/framework/unmanaged-api/hosting/iclrruntimeinfo-bindaslegacyv2runtime-method.md +++ b/docs/framework/unmanaged-api/hosting/iclrruntimeinfo-bindaslegacyv2runtime-method.md @@ -2,57 +2,57 @@ description: "Learn more about: ICLRRuntimeInfo::BindAsLegacyV2Runtime Method" title: "ICLRRuntimeInfo::BindAsLegacyV2Runtime Method" ms.date: "03/30/2017" -api_name: +api_name: - "ICLRRuntimeInfo.BindAsLegacyV2Runtime" -api_location: +api_location: - "mscoree.dll" -api_type: +api_type: - "COM" -f1_keywords: +f1_keywords: - "ICLRRuntimeInfo::BindAsLegacyV2Runtime" -helpviewer_keywords: +helpviewer_keywords: - "ICLRRuntimeInfo::BindAsLegacyV2Runtime method [.NET Framework hosting]" - "BindAsLegacyV2Runtime method [.NET Framework hosting]" ms.assetid: 65fd55ac-4a24-4479-9384-a2e8013bfb2b -topic_type: +topic_type: - "apiref" --- # ICLRRuntimeInfo::BindAsLegacyV2Runtime Method -Binds the current runtime for all legacy common language runtime (CLR) version 2 activation policy decisions. - -## Syntax - -```cpp -HRESULT BindAsLegacyV2Runtime (); -``` - -## Return Value - - This method returns the following specific HRESULTs: - -|HRESULT|Description| -|-------------|-----------------| -|S_OK|Either binding succeeded, or this runtime was already bound as the legacy CLR version 2 activation policy runtime.| -|CLR_E_SHIM_LEGACYRUNTIMEALREADYBOUND|A different runtime was already bound to the legacy CLR version 2 activation policy.| - -## Remarks - - If the current runtime is already bound for all legacy CLR version 2 activation policy decisions (for example, by using the `useLegacyV2RuntimeActivationPolicy` attribute on the [\ element](../../configure-apps/file-schema/startup/startup-element.md) in the configuration file), this method does not return an error result; instead, the result is S_OK, just as it would be if the method had successfully bound legacy activation policy. - -## Requirements - - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** MetaHost.h - - **Library:** Included as a resource in MSCorEE.dll - - **.NET Framework Versions:** [!INCLUDE[net_current_v40plus](../../../../includes/net-current-v40plus-md.md)] - +Binds the current runtime for all legacy common language runtime (CLR) version 2 activation policy decisions. + +## Syntax + +```cpp +HRESULT BindAsLegacyV2Runtime (); +``` + +## Return Value + + This method returns the following specific HRESULTs: + +|HRESULT|Description| +|-------------|-----------------| +|S_OK|Either binding succeeded, or this runtime was already bound as the legacy CLR version 2 activation policy runtime.| +|CLR_E_SHIM_LEGACYRUNTIMEALREADYBOUND|A different runtime was already bound to the legacy CLR version 2 activation policy.| + +## Remarks + + If the current runtime is already bound for all legacy CLR version 2 activation policy decisions (for example, by using the `useLegacyV2RuntimeActivationPolicy` attribute on the [`` element](../../configure-apps/file-schema/startup/startup-element.md) in the configuration file), this method does not return an error result; instead, the result is S_OK, just as it would be if the method had successfully bound legacy activation policy. + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** MetaHost.h + + **Library:** Included as a resource in MSCorEE.dll + + **.NET Framework Versions:** [!INCLUDE[net_current_v40plus](../../../../includes/net-current-v40plus-md.md)] + ## See also - [ICLRRuntimeInfo Interface](iclrruntimeinfo-interface.md) - [Hosting Interfaces](hosting-interfaces.md) - [Hosting](index.md) -- [\ Element](../../configure-apps/file-schema/startup/startup-element.md) +- [`` Element](../../configure-apps/file-schema/startup/startup-element.md) diff --git a/docs/framework/unmanaged-api/hosting/metahost-config-flags-enumeration.md b/docs/framework/unmanaged-api/hosting/metahost-config-flags-enumeration.md index b61054e6a4089..0c18dc7f2f4c5 100644 --- a/docs/framework/unmanaged-api/hosting/metahost-config-flags-enumeration.md +++ b/docs/framework/unmanaged-api/hosting/metahost-config-flags-enumeration.md @@ -2,58 +2,58 @@ description: "Learn more about: METAHOST_CONFIG_FLAGS Enumeration" title: "METAHOST_CONFIG_FLAGS Enumeration" ms.date: "03/30/2017" -api_name: +api_name: - "METAHOST_CONFIG_FLAGS" -api_location: +api_location: - "mscoree.dll" -api_type: +api_type: - "COM" -f1_keywords: +f1_keywords: - "METAHOST_CONFIG_FLAGS" -helpviewer_keywords: +helpviewer_keywords: - "METAHOST_CONFIG_FLAGS enumeration [.NET Framework hosting]" ms.assetid: 6f1e389f-ed99-4d6a-a0ba-72d7d869a01d -topic_type: +topic_type: - "apiref" --- # METAHOST_CONFIG_FLAGS Enumeration -Describes the possible flags returned in the `pdwConfigFlags` parameter of the [ICLRMetaHostPolicy::GetRequestedRuntime](iclrmetahostpolicy-getrequestedruntime-method.md) method, indicating the presence and setting of the `useLegacyV2RuntimeActivationPolicy` attribute in the [\ element](../../configure-apps/file-schema/startup/startup-element.md) of the configuration file. - -## Syntax - -```cpp -typedef enum { - METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_UNSET = 0x00, - METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_TRUE = 0x01, - METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_FALSE = 0x02, - METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_MASK = 0x03 -} METAHOST_CONFIG_FLAGS; -``` - -## Members - -|Member|Description| -|------------|-----------------| -|`METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_UNSET`|The `useLegacyV2RuntimeActivationPolicy` attribute was not present in the [\ Element](../../configure-apps/file-schema/startup/startup-element.md).| -|`METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_TRUE`|The `useLegacyV2RuntimeActivationPolicy` attribute was present and set to `true`.| -|`METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_FALSE`|The `useLegacyV2RuntimeActivationPolicy` attribute was present and set to `false`.| -|`METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_MASK`|Apply this mask to the value returned in `pdwConfigFlags` to get the values relevant to `useLegacyV2RuntimeActivationPolicy`.| - -## Remarks - -## Requirements - - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** Metahost.h - - **Library:** Included as a resource in MSCorEE.dll - - **.NET Framework Versions:** [!INCLUDE[net_current_v40plus](../../../../includes/net-current-v40plus-md.md)] - +Describes the possible flags returned in the `pdwConfigFlags` parameter of the [ICLRMetaHostPolicy::GetRequestedRuntime](iclrmetahostpolicy-getrequestedruntime-method.md) method, indicating the presence and setting of the `useLegacyV2RuntimeActivationPolicy` attribute in the [`` element](../../configure-apps/file-schema/startup/startup-element.md) of the configuration file. + +## Syntax + +```cpp +typedef enum { + METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_UNSET = 0x00, + METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_TRUE = 0x01, + METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_FALSE = 0x02, + METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_MASK = 0x03 +} METAHOST_CONFIG_FLAGS; +``` + +## Members + +|Member|Description| +|------------|-----------------| +|`METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_UNSET`|The `useLegacyV2RuntimeActivationPolicy` attribute was not present in the [`` Element](../../configure-apps/file-schema/startup/startup-element.md).| +|`METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_TRUE`|The `useLegacyV2RuntimeActivationPolicy` attribute was present and set to `true`.| +|`METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_FALSE`|The `useLegacyV2RuntimeActivationPolicy` attribute was present and set to `false`.| +|`METAHOST_CONFIG_FLAGS_LEGACY_V2_ACTIVATION_POLICY_MASK`|Apply this mask to the value returned in `pdwConfigFlags` to get the values relevant to `useLegacyV2RuntimeActivationPolicy`.| + +## Remarks + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** Metahost.h + + **Library:** Included as a resource in MSCorEE.dll + + **.NET Framework Versions:** [!INCLUDE[net_current_v40plus](../../../../includes/net-current-v40plus-md.md)] + ## See also - [Hosting Enumerations](hosting-enumerations.md) - [GetRequestedRuntime Method](iclrmetahostpolicy-getrequestedruntime-method.md) -- [\ Element](../../configure-apps/file-schema/startup/startup-element.md) +- [`` Element](../../configure-apps/file-schema/startup/startup-element.md) diff --git a/docs/framework/unmanaged-api/hosting/startup-flags-enumeration.md b/docs/framework/unmanaged-api/hosting/startup-flags-enumeration.md index 5356440fe38f3..daee3da34a3e0 100644 --- a/docs/framework/unmanaged-api/hosting/startup-flags-enumeration.md +++ b/docs/framework/unmanaged-api/hosting/startup-flags-enumeration.md @@ -2,82 +2,82 @@ description: "Learn more about: STARTUP_FLAGS Enumeration" title: "STARTUP_FLAGS Enumeration" ms.date: "03/30/2017" -api_name: +api_name: - "STARTUP_FLAGS" -api_location: +api_location: - "mscoree.dll" -api_type: +api_type: - "COM" -f1_keywords: +f1_keywords: - "STARTUP_FLAGS" -helpviewer_keywords: +helpviewer_keywords: - "STARTUP_FLAGS enumeration [.NET Framework hosting]" ms.assetid: 4f043594-0c45-4bc6-988e-a6793f0d8d06 -topic_type: +topic_type: - "apiref" --- # STARTUP_FLAGS Enumeration -Contains values that indicate the startup behavior of the common language runtime (CLR). By default, garbage collection is non-concurrent, and only the base class library is loaded into the domain-neutral area. - -## Syntax - -```cpp -typedef enum { - STARTUP_CONCURRENT_GC = 0x1, - STARTUP_LOADER_OPTIMIZATION_MASK = 0x3<<1, - STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN = 0x1<<1, - STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN = 0x2<<1, - STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN_HOST = 0x3<<1, - - STARTUP_LOADER_SAFEMODE = 0x10, - STARTUP_LOADER_SETPREFERENCE = 0x100, - - STARTUP_SERVER_GC = 0x1000, - STARTUP_HOARD_GC_VM = 0x2000, - - STARTUP_SINGLE_VERSION_HOSTING_INTERFACE = 0x4000, - STARTUP_LEGACY_IMPERSONATION = 0x10000, - STARTUP_DISABLE_COMMITTHREADSTACK = 0x20000, - STARTUP_ALWAYSFLOW_IMPERSONATION = 0x40000, - STARTUP_TRIM_GC_COMMIT = 0x80000, - - STARTUP_ETW = 0x100000, - STARTUP_ARM = 0x400000 -} STARTUP_FLAGS; -``` - -## Members - -|Member|Description| -|------------|-----------------| -|`STARTUP_CONCURRENT_GC`|Specifies that concurrent garbage collection should be used. If the caller asks for the server build and concurrent garbage collection on a single-processor machine, the workstation build and non-concurrent garbage collection are run instead. **Note:** Concurrent garbage collection is not supported in applications that are running the WOW64 x86 emulator on 64-bit systems that implement the Intel Itanium architecture (formerly called IA-64). For more information about using WOW64 on 64-bit Windows systems, see [Running 32-bit Applications](/windows/desktop/WinProg64/running-32-bit-applications).| -|`STARTUP_LOADER_OPTIMIZATION_MASK`|Specifies that loader optimization shall occur.| -|`STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN`|Specifies that no assemblies are loaded as domain-neutral.| -|`STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN`|Specifies that all assemblies are loaded as domain-neutral.| -|`STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN_HOST`|Specifies that all strong-named assemblies are loaded as domain-neutral.| -|`STARTUP_LOADER_SAFEMODE`|Specifies that CLR version policy will not be applied to the version passed in. The exact version specified of the CLR will be loaded. The shim does not evaluate policy to determine the latest compatible version.| -|`STARTUP_LOADER_SETPREFERENCE`|Specifies that the preferred runtime will be set, but not actually started.| -|`STARTUP_SERVER_GC`|Specifies that the server garbage collection will be used.| -|`STARTUP_HOARD_GC_VM`|Specifies that garbage collection will keep the virtual address used.| -|`STARTUP_SINGLE_VERSION_HOSTING_INTERFACE`|Specifies that mixing a hosting interface will not be allowed.| -|`STARTUP_LEGACY_IMPERSONATION`|Specifies that impersonation should not flow across asynchronous points by default.| -|`STARTUP_DISABLE_COMMITTHREADSTACK`|Specifies that the full thread stack should not be committed when the thread starts running.| -|`STARTUP_ALWAYSFLOW_IMPERSONATION`|Specifies that managed impersonations and impersonations achieved through platform invoke will flow across asynchronous points. By default, only managed impersonations will flow across asynchronous points.| -|`STARTUP_TRIM_GC_COMMIT`|Specifies that garbage collection will use less committed space when system memory is low. See `gcTrimCommitOnLowMemory` in [Optimization for Shared Web Hosting](../../../standard/garbage-collection/optimization-for-shared-web-hosting.md).| -|`STARTUP_ETW`|Specifies that event tracing for Windows (ETW) is enabled for common language runtime events. Beginning with Windows Vista, event tracing is always enabled, so this flag has no effect. See [Controlling .NET Framework Logging](../../performance/controlling-logging.md).| -|`STARTUP_ARM`|Specifies that application domain resource monitoring is enabled. See the property and [\ Element](../../configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md).| - -## Requirements - - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** MSCorEE.h - - **Library:** MSCorEE.dll - - **.NET Framework Versions:** [!INCLUDE[net_current_v20plus](../../../../includes/net-current-v20plus-md.md)] - +Contains values that indicate the startup behavior of the common language runtime (CLR). By default, garbage collection is non-concurrent, and only the base class library is loaded into the domain-neutral area. + +## Syntax + +```cpp +typedef enum { + STARTUP_CONCURRENT_GC = 0x1, + STARTUP_LOADER_OPTIMIZATION_MASK = 0x3<<1, + STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN = 0x1<<1, + STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN = 0x2<<1, + STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN_HOST = 0x3<<1, + + STARTUP_LOADER_SAFEMODE = 0x10, + STARTUP_LOADER_SETPREFERENCE = 0x100, + + STARTUP_SERVER_GC = 0x1000, + STARTUP_HOARD_GC_VM = 0x2000, + + STARTUP_SINGLE_VERSION_HOSTING_INTERFACE = 0x4000, + STARTUP_LEGACY_IMPERSONATION = 0x10000, + STARTUP_DISABLE_COMMITTHREADSTACK = 0x20000, + STARTUP_ALWAYSFLOW_IMPERSONATION = 0x40000, + STARTUP_TRIM_GC_COMMIT = 0x80000, + + STARTUP_ETW = 0x100000, + STARTUP_ARM = 0x400000 +} STARTUP_FLAGS; +``` + +## Members + +|Member|Description| +|------------|-----------------| +|`STARTUP_CONCURRENT_GC`|Specifies that concurrent garbage collection should be used. If the caller asks for the server build and concurrent garbage collection on a single-processor machine, the workstation build and non-concurrent garbage collection are run instead. **Note:** Concurrent garbage collection is not supported in applications that are running the WOW64 x86 emulator on 64-bit systems that implement the Intel Itanium architecture (formerly called IA-64). For more information about using WOW64 on 64-bit Windows systems, see [Running 32-bit Applications](/windows/desktop/WinProg64/running-32-bit-applications).| +|`STARTUP_LOADER_OPTIMIZATION_MASK`|Specifies that loader optimization shall occur.| +|`STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN`|Specifies that no assemblies are loaded as domain-neutral.| +|`STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN`|Specifies that all assemblies are loaded as domain-neutral.| +|`STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN_HOST`|Specifies that all strong-named assemblies are loaded as domain-neutral.| +|`STARTUP_LOADER_SAFEMODE`|Specifies that CLR version policy will not be applied to the version passed in. The exact version specified of the CLR will be loaded. The shim does not evaluate policy to determine the latest compatible version.| +|`STARTUP_LOADER_SETPREFERENCE`|Specifies that the preferred runtime will be set, but not actually started.| +|`STARTUP_SERVER_GC`|Specifies that the server garbage collection will be used.| +|`STARTUP_HOARD_GC_VM`|Specifies that garbage collection will keep the virtual address used.| +|`STARTUP_SINGLE_VERSION_HOSTING_INTERFACE`|Specifies that mixing a hosting interface will not be allowed.| +|`STARTUP_LEGACY_IMPERSONATION`|Specifies that impersonation should not flow across asynchronous points by default.| +|`STARTUP_DISABLE_COMMITTHREADSTACK`|Specifies that the full thread stack should not be committed when the thread starts running.| +|`STARTUP_ALWAYSFLOW_IMPERSONATION`|Specifies that managed impersonations and impersonations achieved through platform invoke will flow across asynchronous points. By default, only managed impersonations will flow across asynchronous points.| +|`STARTUP_TRIM_GC_COMMIT`|Specifies that garbage collection will use less committed space when system memory is low. See `gcTrimCommitOnLowMemory` in [Optimization for Shared Web Hosting](../../../standard/garbage-collection/optimization-for-shared-web-hosting.md).| +|`STARTUP_ETW`|Specifies that event tracing for Windows (ETW) is enabled for common language runtime events. Beginning with Windows Vista, event tracing is always enabled, so this flag has no effect. See [Controlling .NET Framework Logging](../../performance/controlling-logging.md).| +|`STARTUP_ARM`|Specifies that application domain resource monitoring is enabled. See the property and [`` Element](../../configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md).| + +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** MSCorEE.h + + **Library:** MSCorEE.dll + + **.NET Framework Versions:** [!INCLUDE[net_current_v20plus](../../../../includes/net-current-v20plus-md.md)] + ## See also - [Hosting Enumerations](hosting-enumerations.md) diff --git a/docs/framework/unmanaged-api/wmi/putinstancewmi.md b/docs/framework/unmanaged-api/wmi/putinstancewmi.md index 8776fe319bb18..c621acfe09d58 100644 --- a/docs/framework/unmanaged-api/wmi/putinstancewmi.md +++ b/docs/framework/unmanaged-api/wmi/putinstancewmi.md @@ -43,7 +43,7 @@ HRESULT PutInstanceWmi ( |Constant |Value |Description | |---------|---------|---------| -| `WBEM_FLAG_USE_AMENDED_QUALIFIERS` | 0x20000 | If set, WMI does not store any qualifiers with the **Amended** flavor.
If not set, it is assumed that this object is not localized, and all qualifiers are stored with this instance. | +| `WBEM_FLAG_USE_AMENDED_QUALIFIERS` | 0x20000 | If set, WMI does not store any qualifiers with the `Amended` flavor.
If not set, it is assumed that this object is not localized, and all qualifiers are stored with this instance. | | `WBEM_FLAG_CREATE_OR_UPDATE` | 0 | Create the instance if it does not exist, or overwrite it if it exists already. | | `WBEM_FLAG_UPDATE_ONLY` | 1 | Update the instance. The instance must exist for the call to be successful. | | `WBEM_FLAG_CREATE_ONLY` | 2 | Create the instance. The call fails if the instance already exists. | @@ -64,7 +64,7 @@ The following values returned by this function are defined in the *WbemCli.h* he | `WBEM_E_ACCESS_DENIED` | 0x80041003 | The user does not have permission to update an instance of the specified class. | | `WBEM_E_FAILED` | 0x80041001 | An unspecified error has occurred. | | `WBEM_E_INVALID_CLASS` | 0x80041010 | The class supporting this instance is not valid. | -| `WBEM_E_ILLEGAL_NULL` | 0x80041028 | a `null` was specified for a property that cannot be `null`, such as one that is marked by an **Indexed** or **Not_Null** qualifier. | +| `WBEM_E_ILLEGAL_NULL` | 0x80041028 | a `null` was specified for a property that cannot be `null`, such as one that is marked by an `Indexed` or `Not_Null` qualifier. | | `WBEM_E_INVALID_OBJECT` | 0x8004100f | The specified instance is not valid. (For example, calling `PutInstanceWmi` with a class returns this value.) | | `WBEM_E_INVALID_PARAMETER` | 0x80041008 | A parameter is not valid. | | `WBEM_E_ALREADY_EXISTS` | 0x80041019 | The `WBEM_FLAG_CREATE_ONLY` flag was specified, but the instance already exists. | @@ -83,7 +83,7 @@ The `PutInstanceWmi` function supports creating instances and updating instances When the instance pointed to by `pInst` belongs to a subclass, Windows Management calls all the providers responsible for the classes from which the subclass derives. All of these providers must succeed for the original `PutInstanceWmi` request to succeed. The provider supporting the topmost class in the hierarchy is called first. The calling order continues with the subclass of the topmost class and proceeds from top to bottom until Windows Management reaches the provider for the class owning the instance pointed to by `pInst`. Windows Management does not call the providers for any of the child classes of an instance. -When an application must update an instance that belongs to a class hierarchy, the `pInst` parameter must point to the instance containing the properties to be modified. That is, consider a target instance that belongs to **ClassB**. The **ClassB** instance derives from **ClassA**, and **ClassA** defines the property **PropA**. If an application wants to make a change to the value of **PropA** in the **ClassB** instance, it must set `pInst` to that instance rather than an instance of **ClassA**. +When an application must update an instance that belongs to a class hierarchy, the `pInst` parameter must point to the instance containing the properties to be modified. That is, consider a target instance that belongs to **ClassB**. The `ClassB` instance derives from **ClassA**, and `ClassA` defines the property **PropA**. If an application wants to make a change to the value of `PropA` in the `ClassB` instance, it must set `pInst` to that instance rather than an instance of **ClassA**. Calling `PutInstanceWmi` on an instance of an abstract class is not allowed. diff --git a/docs/framework/unmanaged-api/wmi/putmethod.md b/docs/framework/unmanaged-api/wmi/putmethod.md index 7cec153de670b..f3503fb7f866e 100644 --- a/docs/framework/unmanaged-api/wmi/putmethod.md +++ b/docs/framework/unmanaged-api/wmi/putmethod.md @@ -2,17 +2,17 @@ title: PutMethod function (Unmanaged API Reference) description: The PutMethod function creates a method. ms.date: "11/06/2017" -api_name: +api_name: - "PutMethod" -api_location: +api_location: - "WMINet_Utils.dll" -api_type: +api_type: - "DLLExport" -f1_keywords: +f1_keywords: - "PutMethod" -helpviewer_keywords: +helpviewer_keywords: - "PutMethod function [.NET WMI and performance counters]" -topic_type: +topic_type: - "Reference" --- # PutMethod function @@ -21,9 +21,9 @@ Creates a method. [!INCLUDE[internalonly-unmanaged](../../../../includes/internalonly-unmanaged.md)] -## Syntax - -```cpp +## Syntax + +```cpp HRESULT PutMethod ( [in] int vFunc, [in] IWbemClassObject* ptr, @@ -32,26 +32,26 @@ HRESULT PutMethod ( [in] IWbemClassObject* pInSignature, [in] IWbemClassObject* pOutSignature ); -``` +``` ## Parameters -`vFunc` +`vFunc` [in] This parameter is unused. -`ptr` +`ptr` [in] A pointer to an [IWbemClassObject](/windows/desktop/api/wbemcli/nn-wbemcli-iwbemclassobject) instance. -`wszName` +`wszName` [in] The name of the method to create. -`lFlags` +`lFlags` [in] Reserved. This parameter must be 0. -`pSignatureIn` -[in] A pointer to a copy of the [__Parameters system class](/windows/desktop/WmiSdk/--parameters) that contains the `in` parameters for the method. This parameter is ignored if set to `null`. +`pSignatureIn` +[in] A pointer to a copy of the [__Parameters system class](/windows/desktop/WmiSdk/--parameters) that contains the `in` parameters for the method. This parameter is ignored if set to `null`. -`pSignatureOut` +`pSignatureOut` [in] A pointer to a copy of the [__Parameters system class](/windows/desktop/WmiSdk/--parameters) that contains the `out` parameters for the method. This parameter is ignored if set to `null`. ## Return value @@ -62,12 +62,12 @@ The following values returned by this function are defined in the *WbemCli.h* he |----------------------------|------------|---------------------------------------| | `WBEM_E_INVALID_PARAMETER` | 0x80041008 | One or more parameters are not valid. | | `WBEM_E_INVALID_DUPLICATE_PARAMETER` | 0x80041043 | The `[in, out]` method parameter specified in both the *pInSignature* and *pOutSignature* objects have different qualifiers. | -| `WBEM_E_MISSING_PARAMETER_ID` | 0x80041036 | A method parameter is missing the specification of the **ID** qualifier. | +| `WBEM_E_MISSING_PARAMETER_ID` | 0x80041036 | A method parameter is missing the specification of the `ID` qualifier. | | `WBEM_E_NONCONSECUTIVE_PARAMETER_IDS` | 0x80041038 | The ID series that is assigned to the method parameters is not consecutive or does not start at 0. | -| `WBEM_E_PARAMETER_ID_ON_RETVAL` | 0x80041039 | The return value for a method has an **ID** qualifier. | +| `WBEM_E_PARAMETER_ID_ON_RETVAL` | 0x80041039 | The return value for a method has an `ID` qualifier. | | `WBEM_E_PROPAGATED_METHOD` | 0x80041034 | An attempt was made to reuse an existing method name from a parent class, and the signatures did not match. | | `WBEM_S_NO_ERROR` | 0 | The function call was successful. | - + ## Remarks This function wraps a call to the [IWbemClassObject::PutMethod](/windows/desktop/api/wbemcli/nf-wbemcli-iwbemclassobject-putmethod) method. @@ -78,22 +78,22 @@ Users cannot create methods with names that begin or end with an underscore. Thi For a method, the `in` and `out` parameters are described as properties in [IWbemClassObject](/windows/desktop/api/wbemcli/nn-wbemcli-iwbemclassobject) objects. -An `[in/out]` parameter can be defined by adding the same property to both objects pointed to by the `pInSignature` and `pOutSignature` parameters. In this case, the properties share the same **ID** qualifier value. +An `[in/out]` parameter can be defined by adding the same property to both objects pointed to by the `pInSignature` and `pOutSignature` parameters. In this case, the properties share the same `ID` qualifier value. -Each property in a [__Parameters](/windows/desktop/WmiSdk/--parameters) class object other than `ReturnValue` must have an **ID** qualifier, a zero-based numeric value that identifies the order in which the parameters appear. No two parameters can have the same **ID** value, and no **ID** value can be skipped. If either condition occurs, the `PutMethod` function returns `WBEM_E_NONCONSECUTIVE_PARAMETER_IDS`. +Each property in a [__Parameters](/windows/desktop/WmiSdk/--parameters) class object other than `ReturnValue` must have an `ID` qualifier, a zero-based numeric value that identifies the order in which the parameters appear. No two parameters can have the same `ID` value, and no `ID` value can be skipped. If either condition occurs, the `PutMethod` function returns `WBEM_E_NONCONSECUTIVE_PARAMETER_IDS`. ## Example For an example, see the [IWbemClassObject::PutMethod](/windows/desktop/api/wbemcli/nf-wbemcli-iwbemclassobject-putmethod) method. -## Requirements +## Requirements + + **Platforms:** See [System Requirements](../../get-started/system-requirements.md). + + **Header:** WMINet_Utils.idl + + **.NET Framework Versions:** [!INCLUDE[net_current_v472plus](../../../../includes/net-current-v472plus.md)] - **Platforms:** See [System Requirements](../../get-started/system-requirements.md). - - **Header:** WMINet_Utils.idl - - **.NET Framework Versions:** [!INCLUDE[net_current_v472plus](../../../../includes/net-current-v472plus.md)] - ## See also - [WMI and Performance Counters (Unmanaged API Reference)](index.md) diff --git a/docs/framework/unmanaged-api/wmi/qualifierset-put.md b/docs/framework/unmanaged-api/wmi/qualifierset-put.md index 278f718813a45..f71a0e2385215 100644 --- a/docs/framework/unmanaged-api/wmi/qualifierset-put.md +++ b/docs/framework/unmanaged-api/wmi/qualifierset-put.md @@ -65,7 +65,7 @@ The following values returned by this function are defined in the *WbemCli.h* he |Constant |Value |Description | |---------|---------|---------| -| `WBEM_E_CANNOT_BE_KEY` | 0x8004101f | There was an illegal attempt to specify the **Key** qualifier on a property that cannot be a key. The keys are specified in the class definition for an object and cannot be altered on a per-instance basis. | +| `WBEM_E_CANNOT_BE_KEY` | 0x8004101f | There was an illegal attempt to specify the `Key` qualifier on a property that cannot be a key. The keys are specified in the class definition for an object and cannot be altered on a per-instance basis. | | `WBEM_E_INVALID_PARAMETER` | 0x80041008 | A parameter is not valid. | | `WBEM_E_INVALID_QUALIFIER_TYPE` | 0x80041029 | The `pVal` parameter is not of a legal qualifier type. | | `WBEM_E_OVERRIDE_NOT_ALLOWED` | 0x8004101a | It is not possible to call the `QualifierSet_Put` method on the qualifier because the owning object does not permit overrides. | diff --git a/docs/framework/wcf/diagnostics/etw/216-messagesentbytransport.md b/docs/framework/wcf/diagnostics/etw/216-messagesentbytransport.md index 4f8500864d48a..546c51ec0296f 100644 --- a/docs/framework/wcf/diagnostics/etw/216-messagesentbytransport.md +++ b/docs/framework/wcf/diagnostics/etw/216-messagesentbytransport.md @@ -10,23 +10,23 @@ ms.assetid: 150c3167-4154-4225-8d94-57cc94341233 | Property | Value | | - | - | -|ID|216| -|Keywords|Troubleshooting, ServiceModel| -|Level|Information| -|Channel|Microsoft-Windows-Application Server-Applications/Analytic| - -## Description - - This event occurs when a TCP-based transport sends a message. Note that at the transport level multiple messages can be exchanged between clients and services for a single operation. This may be due to infrastructure behavior, security being a good example. Therefore, the number of **MessageSentByTransport** events that are emitted vary based on your service's binding and its configuration. - -## Message - - The transport sent a message to '%1'. - -## Details - -|Data Item Name|Data Item Type|Description| -|--------------------|--------------------|-----------------| -|DestinationAddress|`xs:string`|The address that the request message was sent to.| -|HostReference|xs:string|For Web-hosted services, this field uniquely identifies the service in the Web hierarchy. Its format is defined as 'Web Site Name Application Virtual Path|Service Virtual Path|ServiceName'. Example: 'Default Web Site/CalculatorApplication|/CalculatorService.svc|CalculatorService'.| +|ID|216| +|Keywords|Troubleshooting, ServiceModel| +|Level|Information| +|Channel|Microsoft-Windows-Application Server-Applications/Analytic| + +## Description + + This event occurs when a TCP-based transport sends a message. Note that at the transport level multiple messages can be exchanged between clients and services for a single operation. This may be due to infrastructure behavior, security being a good example. Therefore, the number of `MessageSentByTransport` events that are emitted vary based on your service's binding and its configuration. + +## Message + + The transport sent a message to '%1'. + +## Details + +|Data Item Name|Data Item Type|Description| +|--------------------|--------------------|-----------------| +|DestinationAddress|`xs:string`|The address that the request message was sent to.| +|HostReference|xs:string|For Web-hosted services, this field uniquely identifies the service in the Web hierarchy. Its format is defined as 'Web Site Name Application Virtual Path|Service Virtual Path|ServiceName'. Example: 'Default Web Site/CalculatorApplication|/CalculatorService.svc|CalculatorService'.| |AppDomain|`xs:string`|The string returned by AppDomain.CurrentDomain.FriendlyName.| diff --git a/docs/framework/wcf/how-to-specify-client-credential-values.md b/docs/framework/wcf/how-to-specify-client-credential-values.md index e97ea75550b9b..1b91b267cf8bd 100644 --- a/docs/framework/wcf/how-to-specify-client-credential-values.md +++ b/docs/framework/wcf/how-to-specify-client-credential-values.md @@ -17,11 +17,11 @@ Using Windows Communication Foundation (WCF), the service can specify how a clie 2. Open the XML configuration file. If you use the Svcutil.exe tool, the default name of the file is Output.config. -3. Find the **\** element with the **mode** attribute (**\** where `MessageOrTransport` is set to one of the security modes. +3. Find the **\** element with the `mode` attribute (**\** where `MessageOrTransport` is set to one of the security modes. 4. Find the child element that matches the mode value. For example, if the mode is set to **Message**, find the **\** element contained in the **\** element. -5. Note the value assigned to the **clientCredentialType** attribute. The actual value depends on which mode is used, transport or message. +5. Note the value assigned to the `clientCredentialType` attribute. The actual value depends on which mode is used, transport or message. The following XML code shows configuration for a client using message security and requiring a certificate to authenticate the client. diff --git a/docs/framework/whats-new/index.md b/docs/framework/whats-new/index.md index 1a4f72c3e64a7..8dce626ae2a20 100644 --- a/docs/framework/whats-new/index.md +++ b/docs/framework/whats-new/index.md @@ -764,11 +764,11 @@ In .NET Framework 4.7, ASP.NET includes the following new features: Starting with .NET Framework 4.7, ASP.NET adds a new set of APIs that allow developers to replace the default ASP.NET implementations for in-memory object caching and memory monitoring. Developers can now replace any of the following three components if the ASP.NET implementation is not adequate: -- **Object Cache Store**. By using the new cache providers configuration section, developers can plug in new implementations of an object cache for an ASP.NET application by using the new **ICacheStoreProvider** interface. +- **Object Cache Store**. By using the new cache providers configuration section, developers can plug in new implementations of an object cache for an ASP.NET application by using the new `ICacheStoreProvider` interface. - **Memory monitoring**. The default memory monitor in ASP.NET notifies applications when they are running close to the configured private bytes limit for the process, or when the machine is low on total available physical RAM. When these limits are near, notifications are fired. For some applications, notifications are fired too close to the configured limits to allow for useful reactions. Developers can now write their own memory monitors to replace the default by using the property. -- **Memory Limit Reactions**. By default, ASP.NET attempts to trim the object cache and periodically call when the private byte process limit is near. For some applications, the frequency of calls to or the amount of cache that is trimmed are inefficient. Developers can now replace or supplement the default behavior by subscribing **IObserver** implementations to the application's memory monitor. +- **Memory Limit Reactions**. By default, ASP.NET attempts to trim the object cache and periodically call when the private byte process limit is near. For some applications, the frequency of calls to or the amount of cache that is trimmed are inefficient. Developers can now replace or supplement the default behavior by subscribing `IObserver` implementations to the application's memory monitor. @@ -791,7 +791,7 @@ Starting with .NET Framework 4.7, WCF allows you to configure TLS 1.1 or TLS 1.2 WCF includes a number of code changes that eliminate race conditions, thereby improving performance and the reliability of serialization options. These include: - Better support for mixing asynchronous and synchronous code in calls to **SocketConnection.BeginRead** and **SocketConnection.Read**. -- Improved reliability when aborting a connection with **SharedConnectionListener** and **DuplexChannelBinder**. +- Improved reliability when aborting a connection with `SharedConnectionListener` and **DuplexChannelBinder**. - Improved reliability of serialization operations when calling the method. - Improved reliability when removing a waiter by calling the **ChannelSynchronizer.RemoveWaiter** method. @@ -1924,7 +1924,7 @@ Improvements to Windows Forms include: - - Some aspects of the (see [new features in 4.5.2](#v452) for additional controls supported) - To enable this feature, add a new \ element to the configuration file (app.config) and set the `EnableWindowsFormsHighDpiAutoResizing` element to `true`: + To enable this feature, add a new `` element to the configuration file (app.config) and set the `EnableWindowsFormsHighDpiAutoResizing` element to `true`: ```xml @@ -1954,7 +1954,7 @@ For new features in ASP.NET 4.5.1, see [ASP.NET and Web Tools for Visual Studio - Ability to reduce system restarts by detecting and closing .NET Framework 4 applications during deployment. See [Reducing System Restarts During .NET Framework 4.5 Installations](../deployment/reducing-system-restarts.md). -- Support for arrays that are larger than 2 gigabytes (GB) on 64-bit platforms. This feature can be enabled in the application configuration file. See the [\ element](../configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md), which also lists other restrictions on object size and array size. +- Support for arrays that are larger than 2 gigabytes (GB) on 64-bit platforms. This feature can be enabled in the application configuration file. See the [`` element](../configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md), which also lists other restrictions on object size and array size. - Better performance through background garbage collection for servers. When you use server garbage collection in .NET Framework 4.5, background garbage collection is automatically enabled. See the Background Server Garbage Collection section of the [Fundamentals of Garbage Collection](../../standard/garbage-collection/fundamentals.md) topic. @@ -1978,7 +1978,7 @@ For new features in ASP.NET 4.5.1, see [ASP.NET and Web Tools for Visual Studio - Delegation of string comparison to the operating system, which implements Unicode 6.0, when the .NET Framework is used on Windows 8. When running on other platforms, the .NET Framework includes its own string comparison data, which implements Unicode 5.x. See the class and the Remarks section of the class. -- Ability to compute the hash codes for strings on a per application domain basis. See [\ Element](../configure-apps/file-schema/runtime/userandomizedstringhashalgorithm-element.md). +- Ability to compute the hash codes for strings on a per application domain basis. See [`` Element](../configure-apps/file-schema/runtime/userandomizedstringhashalgorithm-element.md). - Type reflection support split between and classes. See [Reflection in the .NET Framework for Windows Store Apps](../reflection-and-codedom/reflection-for-windows-store-apps.md). diff --git a/docs/framework/whats-new/whats-new-in-accessibility.md b/docs/framework/whats-new/whats-new-in-accessibility.md index 8a0274f8f0ff5..6d6a051f61cca 100644 --- a/docs/framework/whats-new/whats-new-in-accessibility.md +++ b/docs/framework/whats-new/whats-new-in-accessibility.md @@ -500,17 +500,17 @@ Screen readers such as Narrator help people read the UI contents of an applicati To support live regions, the following APIs have been added to WPF: -- The and fields, which identify the **LiveSetting** property and the **LiveRegionChanged** event. They can be set by using XAML. +- The and fields, which identify the `LiveSetting` property and the `LiveRegionChanged` event. They can be set by using XAML. - The **AutomationProperties.LiveSetting** attached property, which informs the screen reader of the importance of the UI change to the user. - The property, which identifies the **AutomationProperties.LiveSetting** attached property. -- The method, which can be overridden to provide a **LiveSetting** value. +- The method, which can be overridden to provide a `LiveSetting` value. -- The and methods, which get and set a **LiveSetting** value. +- The and methods, which get and set a `LiveSetting` value. -- The enumeration, which defines the following possible **LiveSetting** values: +- The enumeration, which defines the following possible `LiveSetting` values: - . The element does not send notifications if the content of the live region has changed. - . The element sends non-interruptive notifications if the content of the live region has changed. diff --git a/docs/framework/whats-new/whats-obsolete.md b/docs/framework/whats-new/whats-obsolete.md index 55902647eff33..e87f2847a9ba5 100644 --- a/docs/framework/whats-new/whats-obsolete.md +++ b/docs/framework/whats-new/whats-obsolete.md @@ -2,7 +2,7 @@ title: What's obsolete in .NET Framework description: See how the .NET Framework class library marks members as obsolete. Understand the ObsoleteAttribute attribute, how to handle obsolete types and members, and more. ms.date: 04/26/2023 -helpviewer_keywords: +helpviewer_keywords: - "obsolete [.NET Framework]" - "what's obsolete [.NET Framework]" - "deprecated [.NET Framework]" @@ -77,4 +77,4 @@ To target a specific version of .NET Framework, assign one of the following stri ## See also -- [\ Element](../configure-apps/file-schema/startup/supportedruntime-element.md) +- [`` Element](../configure-apps/file-schema/startup/supportedruntime-element.md) diff --git a/docs/fsharp/language-reference/xml-documentation.md b/docs/fsharp/language-reference/xml-documentation.md index 1dbf384215a13..b234a8f94b431 100644 --- a/docs/fsharp/language-reference/xml-documentation.md +++ b/docs/fsharp/language-reference/xml-documentation.md @@ -90,7 +90,7 @@ The following table describes the tags for use inside description sections: ### User-defined tags The previous tags represent those that are recognized by the F# compiler and typical F# editor tooling. However, a user is free to define their own tags. -Tools like fsdocs bring support for extra tags like [\](https://github.com/fsharp/fslang-design/blob/main/tooling/FST-1031-xmldoc-extensions.md). +Tools like fsdocs bring support for extra tags like [``](https://github.com/fsharp/fslang-design/blob/main/tooling/FST-1031-xmldoc-extensions.md). Custom or in-house documentation generation tools can also be used with the standard tags and multiple output formats from HTML to PDF can be supported. ## Compile-time checking diff --git a/docs/fundamentals/code-analysis/configuration-options.md b/docs/fundamentals/code-analysis/configuration-options.md index 662aac41be0bd..4f4dea4cc960f 100644 --- a/docs/fundamentals/code-analysis/configuration-options.md +++ b/docs/fundamentals/code-analysis/configuration-options.md @@ -30,7 +30,7 @@ For additional options, see [Code analysis properties](../../core/project-sdk/ms ### Analysis mode -While the .NET SDK includes all code analysis rules, only some of them are [enabled by default](https://github.com/dotnet/roslyn-analyzers/blob/main/src/NetAnalyzers/Core/AnalyzerReleases.Shipped.md). The *analysis mode* determines which, if any, set of rules to enable. You can choose a more aggressive analysis mode where most or all rules are enabled. Or you can choose a more conservative analysis mode where most or all rules are disabled, and you can then opt-in to specific rules as needed. Set your analysis mode by adding the [\](../../core/project-sdk/msbuild-props.md#analysismode) MSBuild property to your project file. +While the .NET SDK includes all code analysis rules, only some of them are [enabled by default](https://github.com/dotnet/roslyn-analyzers/blob/main/src/NetAnalyzers/Core/AnalyzerReleases.Shipped.md). The *analysis mode* determines which, if any, set of rules to enable. You can choose a more aggressive analysis mode where most or all rules are enabled. Or you can choose a more conservative analysis mode where most or all rules are disabled, and you can then opt-in to specific rules as needed. Set your analysis mode by adding the [``](../../core/project-sdk/msbuild-props.md#analysismode) MSBuild property to your project file. ```xml @@ -116,7 +116,7 @@ The following table shows the different rule severities that you can configure f ``` > [!IMPORTANT] -> When you configure the severity level for multiple rules with a single entry, either for a *category* of rules or for *all* rules, the severity only applies to rules that are [enabled by default](https://github.com/dotnet/roslyn-analyzers/blob/main/src/NetAnalyzers/Core/AnalyzerReleases.Shipped.md). And if you enable all rules by using the MSBuild properties [\](../../core/project-sdk/msbuild-props.md#analysismode) or [\](../../core/project-sdk/msbuild-props.md#analysislevel), any bulk `dotnet_analyzer_diagnostic` options are ignored. For this reason, it's better to enable a category of rules by setting [\>](../../core/project-sdk/msbuild-props.md#analysismodecategory) to `All`. +> When you configure the severity level for multiple rules with a single entry, either for a *category* of rules or for *all* rules, the severity only applies to rules that are [enabled by default](https://github.com/dotnet/roslyn-analyzers/blob/main/src/NetAnalyzers/Core/AnalyzerReleases.Shipped.md). And if you enable all rules by using the MSBuild properties [``](../../core/project-sdk/msbuild-props.md#analysismode) or [``](../../core/project-sdk/msbuild-props.md#analysislevel), any bulk `dotnet_analyzer_diagnostic` options are ignored. For this reason, it's better to enable a category of rules by setting [\>](../../core/project-sdk/msbuild-props.md#analysismodecategory) to `All`. > [!NOTE] > The prefix for setting severity for a single rule, `dotnet_diagnostic`, is slightly different than the prefix for configuring severity via category or for all rules, `dotnet_analyzer_diagnostic`. diff --git a/docs/fundamentals/code-analysis/overview.md b/docs/fundamentals/code-analysis/overview.md index 9e8ecc5df9b0d..287238ca16612 100644 --- a/docs/fundamentals/code-analysis/overview.md +++ b/docs/fundamentals/code-analysis/overview.md @@ -250,7 +250,7 @@ If your project uses the legacy project file format, that is, it doesn't referen ## Third-party analyzers -In addition to the official .NET analyzers, you can also install third party analyzers, such as [StyleCop](https://www.nuget.org/packages/StyleCop.Analyzers/), [Roslynator](https://www.nuget.org/packages/Roslynator.Analyzers/), [XUnit Analyzers](https://www.nuget.org/packages/xunit.analyzers/), and [Sonar Analyzer](https://www.nuget.org/packages/SonarAnalyzer.CSharp/). +In addition to the official .NET analyzers, you can also install third party analyzers, such as [StyleCop](https://www.nuget.org/packages/StyleCop.Analyzers/), [Roslynator](https://www.nuget.org/packages/Roslynator.Analyzers/), [Meziantou.Analyzer](https://www.nuget.org/packages/Meziantou.Analyzer/), [XUnit Analyzers](https://www.nuget.org/packages/xunit.analyzers/), and [Sonar Analyzer](https://www.nuget.org/packages/SonarAnalyzer.CSharp/). ## See also diff --git a/docs/fundamentals/code-analysis/style-rules/language-rules.md b/docs/fundamentals/code-analysis/style-rules/language-rules.md index 6ca1f966d419c..5c79b335515a6 100644 --- a/docs/fundamentals/code-analysis/style-rules/language-rules.md +++ b/docs/fundamentals/code-analysis/style-rules/language-rules.md @@ -46,7 +46,7 @@ or If you're using the .NET 8 SDK or an earlier version and you want the severity to be respected at build time, you can do so in one of two ways: - - Set the [\](../../../core/project-sdk/msbuild-props.md#analysislevel) or `` property to `9.0` or higher, or to `preview`. + - Set the [``](../../../core/project-sdk/msbuild-props.md#analysislevel) or `` property to `9.0` or higher, or to `preview`. - Set the severity by using the rule ID-based severity configuration syntax for analyzers instead. The syntax takes the form `dotnet_diagnostic..severity = `, for example, `dotnet_diagnostic.IDE0040.severity = warning`. For more information, see [severity level](../configuration-options.md#severity-level). > [!TIP] diff --git a/docs/fundamentals/code-analysis/style-rules/naming-rules.md b/docs/fundamentals/code-analysis/style-rules/naming-rules.md index 5f392c2412d9d..6990ce5609044 100644 --- a/docs/fundamentals/code-analysis/style-rules/naming-rules.md +++ b/docs/fundamentals/code-analysis/style-rules/naming-rules.md @@ -40,17 +40,17 @@ Each property should only be set once, but some settings allow multiple, comma-s The order of the properties is not important. -## \ values +## `` values **\** specifies which kind of entity is being defined—naming rule, symbol group, or naming style—and must be one of the following: -| To set a property for | Use the \ value | Example | +| To set a property for | Use the `` value | Example | | --- | --- | -- | | Naming rule | `dotnet_naming_rule` | `dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion` | | Symbol group | `dotnet_naming_symbols` | `dotnet_naming_symbols.interface.applicable_kinds = interface` | | Naming style | `dotnet_naming_style` | `dotnet_naming_style.pascal_case.capitalization = pascal_case` | -## \ +## `` **\** is a descriptive name you choose that associates multiple property settings into a single definition. For example, the following properties produce two symbol group definitions, `interface` and `types`, each of which has two properties set on it. @@ -62,7 +62,7 @@ dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum, d dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected ``` -## \ and \ +## `` and `` Each kind of entity—[naming rule](#naming-rule-properties), [symbol group](#symbol-group-properties), or [naming style](#naming-style-properties)—has its own supported properties, as described in the following sections. diff --git a/docs/fundamentals/runtime-libraries/system-appcontext.md b/docs/fundamentals/runtime-libraries/system-appcontext.md index 52e213a3e4a14..643607ce24129 100644 --- a/docs/fundamentals/runtime-libraries/system-appcontext.md +++ b/docs/fundamentals/runtime-libraries/system-appcontext.md @@ -26,7 +26,7 @@ It's beneficial to use a consistent format for switch names, since they're a for - *Switch*.*namespace*.*switchname* - *Switch*.*library*.*switchname* -Once you define and document the switch, callers can use it by calling the method programmatically. .NET Framework apps can also use the switch by adding an [\](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) element to their application configuration file or by using the registry. For more information about how callers use and set the value of configuration switches, see the [AppContext for library consumers](#appcontext-for-library-consumers) section. +Once you define and document the switch, callers can use it by calling the method programmatically. .NET Framework apps can also use the switch by adding an [``](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) element to their application configuration file or by using the registry. For more information about how callers use and set the value of configuration switches, see the [AppContext for library consumers](#appcontext-for-library-consumers) section. In .NET Framework, when the common language runtime runs an application, it automatically reads the registry's compatibility settings and loads the application configuration file to populate the application's instance. Because the instance is populated either programmatically by the caller or by the runtime, .NET Framework apps don't have to take any action, such as calling the method, to configure the instance. @@ -90,9 +90,9 @@ You can set the value of a switch by calling the ` element to the [\](../../framework/configure-apps/file-schema/runtime/runtime-element.md) section of the app.config file. The switch has a single attribute, `value`, whose value is a string that represents a key/value pair containing both the switch name and its value. +- By adding an `` element to the [``](../../framework/configure-apps/file-schema/runtime/runtime-element.md) section of the app.config file. The switch has a single attribute, `value`, whose value is a string that represents a key/value pair containing both the switch name and its value. - To define multiple switches, separate each switch's key/value pair in the [\](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) element's `value` attribute with a semicolon. In that case, the `` element has the following format: + To define multiple switches, separate each switch's key/value pair in the [``](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) element's `value` attribute with a semicolon. In that case, the `` element has the following format: ```xml @@ -101,7 +101,7 @@ You can set the value of a switch by calling the ` element to define a configuration setting has application scope; that is, it affects only the application. > [!NOTE] - > For information on the switches defined by .NET Framework, see [\ element](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md). + > For information on the switches defined by .NET Framework, see [`` element](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md). - By adding an entry to the registry. Add a new string value to the **HKLM\SOFTWARE\Microsoft\\.NETFramework\AppContext** subkey. Set the name of the entry to the name of the switch. Set its value to one of the following options: `True`, `true`, `False`, or `false`. If the runtime encounters any other value, it ignores the switch. @@ -109,7 +109,7 @@ You can set the value of a switch by calling the switch has machine scope; that is, it affects every application running on the machine. -For ASP.NET and ASP.NET Core applications, you set a switch by adding an [\](../../framework/configure-apps/file-schema/appsettings/add-element-for-appsettings.md) element to the [\](../../framework/configure-apps/file-schema/appsettings/index.md) section of the web.config file. For example: +For ASP.NET and ASP.NET Core applications, you set a switch by adding an [``](../../framework/configure-apps/file-schema/appsettings/add-element-for-appsettings.md) element to the [``](../../framework/configure-apps/file-schema/appsettings/index.md) section of the web.config file. For example: ```xml diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md index 9ffc3aae85cdf..78a7e5451ca3d 100644 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md +++ b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md @@ -196,7 +196,7 @@ Because the main assembly that contains an app's default resources is separate f For more information about versioning support for satellite assemblies, see the article [Retrieving Resources](/dotnet/framework/resources/retrieving-resources-in-desktop-apps). -### \ configuration file node +### `` configuration file node > [!NOTE] > This section is specific to .NET Framework apps. diff --git a/docs/fundamentals/runtime-libraries/system-resources-satellitecontractversionattribute.md b/docs/fundamentals/runtime-libraries/system-resources-satellitecontractversionattribute.md index 9c36e7512992d..2766876648f52 100644 --- a/docs/fundamentals/runtime-libraries/system-resources-satellitecontractversionattribute.md +++ b/docs/fundamentals/runtime-libraries/system-resources-satellitecontractversionattribute.md @@ -13,7 +13,7 @@ When you update the main assembly, you increment its assembly version number. Ho If you want to revise a satellite assembly but not the main assembly, increment the version number on your satellite. In this case, ship a publisher policy assembly along with your satellite assembly stating that your new satellite assembly has backward compatibility with your old satellite assembly. The resource manager will still use the old contract number written into your main assembly based on the attribute; however, the loader will bind to the satellite assembly version that is specified by the policy assembly. -A vendor of a shared component uses a publisher policy assembly to make a compatibility statement about a particular version of a released assembly. A publisher policy assembly is a strongly named assembly that has a name in the format `policy...`, and is registered in the [Global Assembly Cache (GAC)](../../framework/app-domains/gac.md). The publisher policy is generated from an XML configuration file (see the [\ Element](../../framework/configure-apps/file-schema/runtime/bindingredirect-element.md)) by using the [Al.exe (Assembly Linker)](../../framework/tools/al-exe-assembly-linker.md) tool. The Assembly Linker is used with the `/link` option to link the XML configuration file to a manifest assembly, which is then stored in the global assembly cache. The publisher policy assemblies can be used when a vendor ships a maintenance release (service pack) that contains bug fixes. +A vendor of a shared component uses a publisher policy assembly to make a compatibility statement about a particular version of a released assembly. A publisher policy assembly is a strongly named assembly that has a name in the format `policy...`, and is registered in the [Global Assembly Cache (GAC)](../../framework/app-domains/gac.md). The publisher policy is generated from an XML configuration file (see the [`` Element](../../framework/configure-apps/file-schema/runtime/bindingredirect-element.md)) by using the [Al.exe (Assembly Linker)](../../framework/tools/al-exe-assembly-linker.md) tool. The Assembly Linker is used with the `/link` option to link the XML configuration file to a manifest assembly, which is then stored in the global assembly cache. The publisher policy assemblies can be used when a vendor ships a maintenance release (service pack) that contains bug fixes. ## Windows 8.x Store apps diff --git a/docs/fundamentals/runtime-libraries/system-xml-schema-xmlschemaset.md b/docs/fundamentals/runtime-libraries/system-xml-schema-xmlschemaset.md index 0e573dfe7a37b..83327f11acfdf 100644 --- a/docs/fundamentals/runtime-libraries/system-xml-schema-xmlschemaset.md +++ b/docs/fundamentals/runtime-libraries/system-xml-schema-xmlschemaset.md @@ -31,9 +31,9 @@ dev_langs: The following example validates an XML file using schemas stored in the . The namespace in the XML file, `urn:bookstore-schema`, identifies which schema in the to use for validation. Output from the example shows that the XML file has two schema violations: -- The first \ element contains an \ element but no \ or \<price> element. +- The first `<book>` element contains an `<author>` element but no `<title>` or `<price>` element. -- The \<author> element in the last \<book> element is missing a \<first-name> and \<last-name> element and instead has an invalid \<name> element. +- The `<author>` element in the last `<book>` element is missing a `<first-name>` and `<last-name>` element and instead has an invalid `<name>` element. :::code language="csharp" source="./snippets/System.Xml/XmlReaderSettings/ValidationType/csharp/validschemaset.cs" id="Snippet1"::: :::code language="vb" source="./snippets/System.Xml.Schema/XmlSchemaSet/Overview/vb/validschemaset.vb" id="Snippet1"::: diff --git a/docs/standard/analyzers/platform-compat-analyzer.md b/docs/standard/analyzers/platform-compat-analyzer.md index 875bba35e5625..fbe380085633d 100644 --- a/docs/standard/analyzers/platform-compat-analyzer.md +++ b/docs/standard/analyzers/platform-compat-analyzer.md @@ -37,7 +37,7 @@ The platform compatibility analyzer is one of the Roslyn code quality analyzers. - If the platform is a [subset of another platform](#platform-inclusion), the attribute implies that the superset platform is also unsupported. For example, `[UnsupportedOSPlatform("iOS")]` implies that the API is unsupported on `iOS` and also on its superset platform, `MacCatalyst`. - The analyzer produces a **warning** only if the `platform` is effective for the call site: - **Warns** if the project targets the platform that's attributed as unsupported (for example, if the API is attributed with `[UnsupportedOSPlatform("windows")]` and the call site targets `<TargetFramework>net5.0-windows</TargetFramework>`). - - **Warns** if the project is multi-targeted and the `platform` is included in the default [MSBuild `<SupportedPlatform>`](https://github.com/dotnet/sdk/blob/main/src/Tasks/Microsoft.NET.Build.Tasks/targets/Microsoft.NET.SupportedPlatforms.props) items group, or the `platform` is manually included within the `MSBuild` \<SupportedPlatform> items group: + - **Warns** if the project is multi-targeted and the `platform` is included in the default [MSBuild `<SupportedPlatform>`](https://github.com/dotnet/sdk/blob/main/src/Tasks/Microsoft.NET.Build.Tasks/targets/Microsoft.NET.SupportedPlatforms.props) items group, or the `platform` is manually included within the `MSBuild` `<SupportedPlatform>` items group: ```xml <ItemGroup> diff --git a/docs/standard/assembly/disable-strong-name-bypass-feature.md b/docs/standard/assembly/disable-strong-name-bypass-feature.md index 36636d28ae758..82029c24aedcb 100644 --- a/docs/standard/assembly/disable-strong-name-bypass-feature.md +++ b/docs/standard/assembly/disable-strong-name-bypass-feature.md @@ -2,53 +2,53 @@ title: "How to: Disable the strong-name bypass feature" description: Strong-name bypass skips signature validation in fully trusted domains in .NET. You can override this feature for a single application or all applications. ms.date: "08/20/2019" -helpviewer_keywords: +helpviewer_keywords: - "strong-name bypass feature" - "strong-named assemblies, loading into trusted application domains" ms.topic: how-to --- # How to: Disable the strong-name bypass feature -Starting with the .NET Framework version 3.5 Service Pack 1 (SP1), strong-name signatures are not validated when an assembly is loaded into a full-trust <xref:System.AppDomain> object, such as the default <xref:System.AppDomain> for the `MyComputer` zone. This is referred to as the strong-name bypass feature. In a full-trust environment, demands for <xref:System.Security.Permissions.StrongNameIdentityPermission> always succeed for signed, full-trust assemblies regardless of their signature. The only restriction is that the assembly must be fully trusted because its zone is fully trusted. Because the strong name is not a determining factor under these conditions, there is no reason for it to be validated. Bypassing the validation of strong-name signatures provides significant performance improvements. - - The bypass feature applies to any full-trust assembly that is not delay-signed and that is loaded into any full-trust <xref:System.AppDomain> from the directory specified by its <xref:System.AppDomainSetup.ApplicationBase%2A> property. - - You can override the bypass feature for all applications on a computer by setting a registry key value. You can override the setting for a single application by using an application configuration file. You cannot reinstate the bypass feature for a single application if it has been disabled by the registry key. - - When you override the bypass feature, the strong name is validated only for correctness; it is not checked for a <xref:System.Security.Permissions.StrongNameIdentityPermission>. If you want to confirm a specific strong name, you have to perform that check separately. - +Starting with the .NET Framework version 3.5 Service Pack 1 (SP1), strong-name signatures are not validated when an assembly is loaded into a full-trust <xref:System.AppDomain> object, such as the default <xref:System.AppDomain> for the `MyComputer` zone. This is referred to as the strong-name bypass feature. In a full-trust environment, demands for <xref:System.Security.Permissions.StrongNameIdentityPermission> always succeed for signed, full-trust assemblies regardless of their signature. The only restriction is that the assembly must be fully trusted because its zone is fully trusted. Because the strong name is not a determining factor under these conditions, there is no reason for it to be validated. Bypassing the validation of strong-name signatures provides significant performance improvements. + + The bypass feature applies to any full-trust assembly that is not delay-signed and that is loaded into any full-trust <xref:System.AppDomain> from the directory specified by its <xref:System.AppDomainSetup.ApplicationBase%2A> property. + + You can override the bypass feature for all applications on a computer by setting a registry key value. You can override the setting for a single application by using an application configuration file. You cannot reinstate the bypass feature for a single application if it has been disabled by the registry key. + + When you override the bypass feature, the strong name is validated only for correctness; it is not checked for a <xref:System.Security.Permissions.StrongNameIdentityPermission>. If you want to confirm a specific strong name, you have to perform that check separately. + > [!IMPORTANT] -> The ability to force strong-name validation depends on a registry key, as described in the following procedure. If an application is running under an account that does not have access control list (ACL) permission to access that registry key, the setting is ineffective. You must ensure that ACL rights are configured for this key so that it can be read for all assemblies. - -## Disable the strong-name bypass feature for all applications - -- On 32-bit computers, in the system registry, create a DWORD entry with a value of 0 named `AllowStrongNameBypass` under the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\\.NETFramework key. - -- On 64-bit computers, in the system registry, create a DWORD entry with a value of 0 named `AllowStrongNameBypass` under the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\\.NETFramework and HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\\.NETFramework keys. - -## Disable the strong-name bypass feature for a single application - -1. Open or create the application configuration file. - - For more information about this file, see the Application Configuration Files section in [Configure apps](../../framework/configure-apps/index.md). - -2. Add the following entry: - - ```xml - <configuration> - <runtime> - <bypassTrustedAppStrongNames enabled="false" /> - </runtime> - </configuration> - ``` - - You can restore the bypass feature for the application by removing the configuration file setting or by setting the attribute to `true`. - +> The ability to force strong-name validation depends on a registry key, as described in the following procedure. If an application is running under an account that does not have access control list (ACL) permission to access that registry key, the setting is ineffective. You must ensure that ACL rights are configured for this key so that it can be read for all assemblies. + +## Disable the strong-name bypass feature for all applications + +- On 32-bit computers, in the system registry, create a DWORD entry with a value of 0 named `AllowStrongNameBypass` under the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\\.NETFramework key. + +- On 64-bit computers, in the system registry, create a DWORD entry with a value of 0 named `AllowStrongNameBypass` under the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\\.NETFramework and HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\\.NETFramework keys. + +## Disable the strong-name bypass feature for a single application + +1. Open or create the application configuration file. + + For more information about this file, see the Application Configuration Files section in [Configure apps](../../framework/configure-apps/index.md). + +2. Add the following entry: + + ```xml + <configuration> + <runtime> + <bypassTrustedAppStrongNames enabled="false" /> + </runtime> + </configuration> + ``` + + You can restore the bypass feature for the application by removing the configuration file setting or by setting the attribute to `true`. + > [!NOTE] -> You can turn strong-name validation on and off for an application only if the bypass feature is enabled for the computer. If the bypass feature has been turned off for the computer, strong names are validated for all applications and you cannot bypass validation for a single application. - +> You can turn strong-name validation on and off for an application only if the bypass feature is enabled for the computer. If the bypass feature has been turned off for the computer, strong names are validated for all applications and you cannot bypass validation for a single application. + ## See also - [Sn.exe (Strong Name Tool)](../../framework/tools/sn-exe-strong-name-tool.md) -- [\<bypassTrustedAppStrongNames> element](../../framework/configure-apps/file-schema/runtime/bypasstrustedappstrongnames-element.md) +- [`<bypassTrustedAppStrongNames>` element](../../framework/configure-apps/file-schema/runtime/bypasstrustedappstrongnames-element.md) - [Create and use strong-named assemblies](create-use-strong-named.md) diff --git a/docs/standard/assembly/index.md b/docs/standard/assembly/index.md index 8b90636687084..59f180512dcc2 100644 --- a/docs/standard/assembly/index.md +++ b/docs/standard/assembly/index.md @@ -85,7 +85,7 @@ To use an assembly in an application, you must add a reference to it. When an as > [!NOTE] > Most assemblies from the .NET Class Library are referenced automatically. If a system assembly isn't automatically referenced, add a reference in one of the following ways: > -> - For .NET and .NET Core, add a reference to the NuGet package that contains the assembly. Either use the NuGet Package Manager in Visual Studio or add a [\<PackageReference>](../../core/tools/dependencies.md#the-packagereference-element) element for the assembly to the *.csproj* or *.vbproj* project. +> - For .NET and .NET Core, add a reference to the NuGet package that contains the assembly. Either use the NuGet Package Manager in Visual Studio or add a [`<PackageReference>`](../../core/tools/dependencies.md#the-packagereference-element) element for the assembly to the *.csproj* or *.vbproj* project. > - For .NET Framework, add a reference to the assembly using the **Add Reference** dialog in Visual Studio or the `-reference` command line option for the [C#](../../csharp/language-reference/compiler-options/inputs.md#references) or [Visual Basic](../../visual-basic/reference/command-line-compiler/reference.md) compilers. In C#, you can use two versions of the same assembly in a single application. For more information, see [extern alias](../../csharp/language-reference/keywords/extern-alias.md). diff --git a/docs/standard/garbage-collection/app-domain-resource-monitoring.md b/docs/standard/garbage-collection/app-domain-resource-monitoring.md index 96155cd900fdf..c2f7429689566 100644 --- a/docs/standard/garbage-collection/app-domain-resource-monitoring.md +++ b/docs/standard/garbage-collection/app-domain-resource-monitoring.md @@ -23,7 +23,7 @@ ARM can be enabled in four ways: by supplying a configuration file when the comm As soon as ARM is enabled, it begins collecting data on all application domains in the process.If an application domain was created before ARM is enabled, cumulative data starts when ARM is enabled, not when the application domain was created.Once it is enabled, ARM cannot be disabled. -- You can enable ARM at CLR startup by adding the [\<appDomainResourceMonitoring>](../../framework/configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md) element to the configuration file, and setting the `enabled` attribute to `true`. A value of `false` (the default) means only that ARM is not enabled at startup; you can activate it later by using one of the other activation mechanisms. +- You can enable ARM at CLR startup by adding the [`<appDomainResourceMonitoring>`](../../framework/configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md) element to the configuration file, and setting the `enabled` attribute to `true`. A value of `false` (the default) means only that ARM is not enabled at startup; you can activate it later by using one of the other activation mechanisms. - The host can enable ARM by requesting the [ICLRAppDomainResourceMonitor](../../framework/unmanaged-api/hosting/iclrappdomainresourcemonitor-interface.md) hosting interface. Once this interface is successfully obtained, ARM is enabled. @@ -85,5 +85,5 @@ If you use the unmanaged hosting API, your host must pass the CLR an implementat - <xref:System.AppDomain.MonitoringIsEnabled%2A?displayProperty=nameWithType> - [ICLRAppDomainResourceMonitor Interface](../../framework/unmanaged-api/hosting/iclrappdomainresourcemonitor-interface.md) -- [\<appDomainResourceMonitoring>](../../framework/configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md) +- [`<appDomainResourceMonitoring>`](../../framework/configure-apps/file-schema/runtime/appdomainresourcemonitoring-element.md) - [CLR ETW Events](../../framework/performance/clr-etw-events.md) diff --git a/docs/standard/garbage-collection/notifications.md b/docs/standard/garbage-collection/notifications.md index acc46095c52a2..6a11b4752f13a 100644 --- a/docs/standard/garbage-collection/notifications.md +++ b/docs/standard/garbage-collection/notifications.md @@ -15,7 +15,7 @@ There are situations in which a full garbage collection (that is, a generation 2 The <xref:System.GC.RegisterForFullGCNotification%2A> method registers for a notification to be raised when the runtime senses that a full garbage collection is approaching. There are two parts to this notification: when the full garbage collection is approaching and when the full garbage collection has completed. > [!WARNING] -> When the [\<gcConcurrent>](../../framework/configure-apps/file-schema/runtime/gcconcurrent-element.md) configuration element is enabled, <xref:System.GC.WaitForFullGCComplete%2A> may return `NotApplicable` <xref:System.GCNotificationStatus> if the full GC was done as a background GC. +> When the [`<gcConcurrent>`](../../framework/configure-apps/file-schema/runtime/gcconcurrent-element.md) configuration element is enabled, <xref:System.GC.WaitForFullGCComplete%2A> may return `NotApplicable` <xref:System.GCNotificationStatus> if the full GC was done as a background GC. To determine when a notification has been raised, use the <xref:System.GC.WaitForFullGCApproach%2A> and <xref:System.GC.WaitForFullGCComplete%2A> methods. Typically, you use these methods in a `while` loop to continually obtain a <xref:System.GCNotificationStatus> enumeration that shows the status of the notification. If that value is <xref:System.GCNotificationStatus.Succeeded>, you can do the following: diff --git a/docs/standard/security/security-and-user-input.md b/docs/standard/security/security-and-user-input.md index 0c80704adc184..9847ea5bdc780 100644 --- a/docs/standard/security/security-and-user-input.md +++ b/docs/standard/security/security-and-user-input.md @@ -17,7 +17,7 @@ These are among the subtlest and hardest security bugs to find because, although Some important considerations involving user data include the following: -- Any user data in a server response runs in the context of the server's site on the client. If your Web server takes user data and inserts it into the returned Web page, it might, for example, include a **\<script>** tag and run as if from the server. +- Any user data in a server response runs in the context of the server's site on the client. If your Web server takes user data and inserts it into the returned Web page, it might, for example, include a `<script>` tag and run as if from the server. - Remember that the client can request any URL. diff --git a/docs/standard/serialization/add-element-for-schemaimporterextensions.md b/docs/standard/serialization/add-element-for-schemaimporterextensions.md index 18e2594bd64ba..a6e46e804b113 100644 --- a/docs/standard/serialization/add-element-for-schemaimporterextensions.md +++ b/docs/standard/serialization/add-element-for-schemaimporterextensions.md @@ -1,66 +1,66 @@ --- title: "<add> Element for <schemaImporterExtensions>" -description: The <add> element adds types used by the XmlSchemaImporter class for mapping XSD types to .NET types. +description: The <add> element adds types used by the XmlSchemaImporter class for mapping XSD types to .NET types. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "XML serialization, configuration" - "<add> element for <schemaImporterExtensions> element" ms.topic: reference --- -# \<add> Element for \<schemaImporterExtensions> - -Adds types used by the <xref:System.Xml.Serialization.XmlSchemaImporter> for mapping XSD types to .NET types. For more information about configuration files, see [Configuration File Schema](../../framework/configure-apps/file-schema/index.md). - -\<configuration> -\<system.xml.serialization> -\<schemaImporterExtensions> -\<add> - -## Syntax - -```xml -<add name = "typeName" type="fully qualified type [,Version=version number] [,Culture=culture] [,PublicKeyToken= token]"/> -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**name**|A simple name that is used to find the instance.| -|**type**|Required. Specifies the schema extension class to add. The **type** attribute value must be on one line, and include the fully qualified type name. When the assembly is placed in the Global Assembly Cache (GAC), it must also include the version, culture, and public key token of the signed assembly.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|\<schemaImporterExtensions>|Contains the types that are used by the <xref:System.Xml.Serialization.XmlSchemaImporter>.| - -## Example - - The following code example adds an extension type that the XmlSchemaImporter can use when mapping types. - -```xml -<configuration> - <system.xml.serialization> - <schemaImporterExtensions> +# `<add>` Element for `<schemaImporterExtensions>` + +Adds types used by the <xref:System.Xml.Serialization.XmlSchemaImporter> for mapping XSD types to .NET types. For more information about configuration files, see [Configuration File Schema](../../framework/configure-apps/file-schema/index.md). + +\<configuration> +\<system.xml.serialization> +\<schemaImporterExtensions> +\<add> + +## Syntax + +```xml +<add name = "typeName" type="fully qualified type [,Version=version number] [,Culture=culture] [,PublicKeyToken= token]"/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|**name**|A simple name that is used to find the instance.| +|**type**|Required. Specifies the schema extension class to add. The **type** attribute value must be on one line, and include the fully qualified type name. When the assembly is placed in the Global Assembly Cache (GAC), it must also include the version, culture, and public key token of the signed assembly.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|\<schemaImporterExtensions>|Contains the types that are used by the <xref:System.Xml.Serialization.XmlSchemaImporter>.| + +## Example + + The following code example adds an extension type that the XmlSchemaImporter can use when mapping types. + +```xml +<configuration> + <system.xml.serialization> + <schemaImporterExtensions> <add name="contoso" type="System.Web.Mobile.MobileCapabilities, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> - </schemaImporterExtensions> - </system.xml.serialization> -</configuration> -``` - + </schemaImporterExtensions> + </system.xml.serialization> +</configuration> +``` + ## See also - <xref:System.Xml.Serialization.XmlSchemaImporter> -- [\<system.xml.serialization> Element](system-xml-serialization-element.md) -- [\<schemaImporterExtensions> Element](schemaimporterextensions-element.md) +- [`<system.xml.serialization>` Element](system-xml-serialization-element.md) +- [`<schemaImporterExtensions>` Element](schemaimporterextensions-element.md) diff --git a/docs/standard/serialization/datetimeserialization-element.md b/docs/standard/serialization/datetimeserialization-element.md index 89aa16cee5a20..fed1e5ecd7bb3 100644 --- a/docs/standard/serialization/datetimeserialization-element.md +++ b/docs/standard/serialization/datetimeserialization-element.md @@ -2,59 +2,59 @@ title: "<dateTimeSerialization> Element" description: This article describes the <dateTimeSerialization> element, which determines the serialization mode of DateTime objects. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "dateTimeSerialization element" - "XML serialization, configuration" - "<dateTimeSerialization> element" ms.topic: reference --- -# \<dateTimeSerialization> Element - -Determines the serialization mode of <xref:System.DateTime> objects. - - \<configuration> -\<dateTimeSerialization> - -## Syntax - -```xml -<dateTimeSerialization - mode = "Roundtrip|Local" -/> -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attributes|Description| -|----------------|-----------------| -|`mode`|Optional. Specifies the serialization mode. Set to one of the <xref:System.Xml.Serialization.Configuration.DateTimeSerializationSection.DateTimeSerializationMode> values. The default is **RoundTrip**.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|system.xml.serialization|The top-level element for controlling XML serialization.| - -## Remarks +# `<dateTimeSerialization>` Element + +Determines the serialization mode of <xref:System.DateTime> objects. + + `<configuration>` +`<dateTimeSerialization>` + +## Syntax + +```xml +<dateTimeSerialization + mode = "Roundtrip|Local" +/> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attributes|Description| +|----------------|-----------------| +|`mode`|Optional. Specifies the serialization mode. Set to one of the <xref:System.Xml.Serialization.Configuration.DateTimeSerializationSection.DateTimeSerializationMode> values. The default is **RoundTrip**.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|system.xml.serialization|The top-level element for controlling XML serialization.| + +## Remarks When this property is set to **Local**, <xref:System.DateTime> objects are always formatted as the local time. That is, local time zone information is always included with the serialized data. - -When this property is set to **Roundtrip**, <xref:System.DateTime> objects are examined to determine whether they are in the local, UTC, or an unspecified time zone. The <xref:System.DateTime> objects are then serialized in such a way that this information is preserved. This is the default behavior and is the recommended behavior for all new applications that do not communicate with older versions of the framework. - + +When this property is set to **Roundtrip**, <xref:System.DateTime> objects are examined to determine whether they are in the local, UTC, or an unspecified time zone. The <xref:System.DateTime> objects are then serialized in such a way that this information is preserved. This is the default behavior and is the recommended behavior for all new applications that do not communicate with older versions of the framework. + ## See also - <xref:System.DateTime> - <xref:System.Xml.Serialization.XmlSchemaImporter> - <xref:System.Xml.Serialization.Configuration.DateTimeSerializationSection.DateTimeSerializationMode> - [Configuration File Schema](../../framework/configure-apps/file-schema/index.md) -- [\<schemaImporterExtensions> Element](schemaimporterextensions-element.md) -- [\<add> Element for \<schemaImporterExtensions>](add-element-for-schemaimporterextensions.md) -- [\<system.xml.serialization> Element](system-xml-serialization-element.md) +- [`<schemaImporterExtensions>` Element](schemaimporterextensions-element.md) +- [`<add>` Element for `<schemaImporterExtensions>`](add-element-for-schemaimporterextensions.md) +- [`<system.xml.serialization>` Element](system-xml-serialization-element.md) diff --git a/docs/standard/serialization/how-to-specify-an-alternate-element-name-for-an-xml-stream.md b/docs/standard/serialization/how-to-specify-an-alternate-element-name-for-an-xml-stream.md index b9a583abde069..8223b0cc7b865 100644 --- a/docs/standard/serialization/how-to-specify-an-alternate-element-name-for-an-xml-stream.md +++ b/docs/standard/serialization/how-to-specify-an-alternate-element-name-for-an-xml-stream.md @@ -2,10 +2,10 @@ title: "How to: Specify an Alternate Element Name for an XML Stream" description: Learn how to create an XML stream with an alternate element name, for instance, for XML Web services that require the same information with slight differences. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "XML serialization, overriding" - "serialization, overriding" - "XML stream, specifying alternate element name for" @@ -15,77 +15,77 @@ helpviewer_keywords: ms.assetid: 5cc1c0b0-f94b-4525-9a41-88a582cd6668 --- # How to: Specify an Alternate Element Name for an XML Stream - -Using the <xref:System.Xml.Serialization.XmlSerializer>, you can generate more than one XML stream with the same set of classes. You might want to do this because two different XML Web services require the same basic information, with only slight differences. For example, imagine two XML Web services that process orders for books, and thus both require ISBN numbers. One service uses the tag \<ISBN> while the second uses the tag \<BookID>. You have a class named `Book` that contains a field named `ISBN`. When an instance of the `Book` class is serialized, it will, by default, use the member name (ISBN) as the tag element name. For the first XML Web service, this is as expected. But to send the XML stream to the second XML Web service, you must override the serialization so that the tag's element name is `BookID`. - -## To create an XML stream with an alternate element name - -1. Create an instance of the <xref:System.Xml.Serialization.XmlElementAttribute> class. - -2. Set the <xref:System.Xml.Serialization.XmlElementAttribute.ElementName%2A> of the <xref:System.Xml.Serialization.XmlElementAttribute> to "BookID". - -3. Create an instance of the <xref:System.Xml.Serialization.XmlAttributes> class. - -4. Add the `XmlElementAttribute` object to the collection accessed through the <xref:System.Xml.Serialization.XmlAttributes.XmlElements%2A> property of <xref:System.Xml.Serialization.XmlAttributes> . - -5. Create an instance of the <xref:System.Xml.Serialization.XmlAttributeOverrides> class. - -6. Add the `XmlAttributes` to the <xref:System.Xml.Serialization.XmlAttributeOverrides>, passing the type of the object to override and the name of the member being overridden. - -7. Create an instance of the `XmlSerializer` class with `XmlAttributeOverrides`. - -8. Create an instance of the `Book` class, and serialize or deserialize it. - -## Example - -```vb -Public Function SerializeOverride() - ' Creates an XmlElementAttribute with the alternate name. - Dim myElementAttribute As XmlElementAttribute = _ - New XmlElementAttribute() - myElementAttribute.ElementName = "BookID" - Dim myAttributes As XmlAttributes = New XmlAttributes() - myAttributes.XmlElements.Add(myElementAttribute) - Dim myOverrides As XmlAttributeOverrides = New XmlAttributeOverrides() - myOverrides.Add(typeof(Book), "ISBN", myAttributes) - Dim mySerializer As XmlSerializer = _ - New XmlSerializer(GetType(Book), myOverrides) - Dim b As Book = New Book() - b.ISBN = "123456789" - ' Creates a StreamWriter to write the XML stream to. - Dim writer As StreamWriter = New StreamWriter("Book.xml") - mySerializer.Serialize(writer, b); -End Class -``` - -```csharp -public void SerializeOverride() -{ - // Creates an XmlElementAttribute with the alternate name. - XmlElementAttribute myElementAttribute = new XmlElementAttribute(); - myElementAttribute.ElementName = "BookID"; - XmlAttributes myAttributes = new XmlAttributes(); - myAttributes.XmlElements.Add(myElementAttribute); - XmlAttributeOverrides myOverrides = new XmlAttributeOverrides(); - myOverrides.Add(typeof(Book), "ISBN", myAttributes); + +Using the <xref:System.Xml.Serialization.XmlSerializer>, you can generate more than one XML stream with the same set of classes. You might want to do this because two different XML Web services require the same basic information, with only slight differences. For example, imagine two XML Web services that process orders for books, and thus both require ISBN numbers. One service uses the tag `<ISBN>` while the second uses the tag `<BookID>`. You have a class named `Book` that contains a field named `ISBN`. When an instance of the `Book` class is serialized, it will, by default, use the member name (ISBN) as the tag element name. For the first XML Web service, this is as expected. But to send the XML stream to the second XML Web service, you must override the serialization so that the tag's element name is `BookID`. + +## To create an XML stream with an alternate element name + +1. Create an instance of the <xref:System.Xml.Serialization.XmlElementAttribute> class. + +2. Set the <xref:System.Xml.Serialization.XmlElementAttribute.ElementName%2A> of the <xref:System.Xml.Serialization.XmlElementAttribute> to "BookID". + +3. Create an instance of the <xref:System.Xml.Serialization.XmlAttributes> class. + +4. Add the `XmlElementAttribute` object to the collection accessed through the <xref:System.Xml.Serialization.XmlAttributes.XmlElements%2A> property of <xref:System.Xml.Serialization.XmlAttributes> . + +5. Create an instance of the <xref:System.Xml.Serialization.XmlAttributeOverrides> class. + +6. Add the `XmlAttributes` to the <xref:System.Xml.Serialization.XmlAttributeOverrides>, passing the type of the object to override and the name of the member being overridden. + +7. Create an instance of the `XmlSerializer` class with `XmlAttributeOverrides`. + +8. Create an instance of the `Book` class, and serialize or deserialize it. + +## Example + +```vb +Public Function SerializeOverride() + ' Creates an XmlElementAttribute with the alternate name. + Dim myElementAttribute As XmlElementAttribute = _ + New XmlElementAttribute() + myElementAttribute.ElementName = "BookID" + Dim myAttributes As XmlAttributes = New XmlAttributes() + myAttributes.XmlElements.Add(myElementAttribute) + Dim myOverrides As XmlAttributeOverrides = New XmlAttributeOverrides() + myOverrides.Add(typeof(Book), "ISBN", myAttributes) + Dim mySerializer As XmlSerializer = _ + New XmlSerializer(GetType(Book), myOverrides) + Dim b As Book = New Book() + b.ISBN = "123456789" + ' Creates a StreamWriter to write the XML stream to. + Dim writer As StreamWriter = New StreamWriter("Book.xml") + mySerializer.Serialize(writer, b); +End Class +``` + +```csharp +public void SerializeOverride() +{ + // Creates an XmlElementAttribute with the alternate name. + XmlElementAttribute myElementAttribute = new XmlElementAttribute(); + myElementAttribute.ElementName = "BookID"; + XmlAttributes myAttributes = new XmlAttributes(); + myAttributes.XmlElements.Add(myElementAttribute); + XmlAttributeOverrides myOverrides = new XmlAttributeOverrides(); + myOverrides.Add(typeof(Book), "ISBN", myAttributes); XmlSerializer mySerializer = new XmlSerializer(typeof(Book), myOverrides); - Book b = new Book(); + Book b = new Book(); b.ISBN = "123456789"; - // Creates a StreamWriter to write the XML stream to. - StreamWriter writer = new StreamWriter("Book.xml"); - mySerializer.Serialize(writer, b); -} -``` - - The XML stream might resemble the following. - -```xml -<Book> - <BookID>123456789</BookID> -</Book> -``` - + // Creates a StreamWriter to write the XML stream to. + StreamWriter writer = new StreamWriter("Book.xml"); + mySerializer.Serialize(writer, b); +} +``` + + The XML stream might resemble the following. + +```xml +<Book> + <BookID>123456789</BookID> +</Book> +``` + ## See also - <xref:System.Xml.Serialization.XmlElementAttribute> diff --git a/docs/standard/serialization/schemaimporterextensions-element.md b/docs/standard/serialization/schemaimporterextensions-element.md index 065343f816c32..a908758eee013 100644 --- a/docs/standard/serialization/schemaimporterextensions-element.md +++ b/docs/standard/serialization/schemaimporterextensions-element.md @@ -2,56 +2,56 @@ title: "<schemaImporterExtensions> Element" description: The <schemaImporterExtensions> element contains types that are used by the XmlSchemaImporter for mapping of XSD types to .NET types. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "XML serialization, configuration" - "schemaImporterExtensions element" - "<schemaImporterExtensions> element" ms.topic: reference --- -# \<schemaImporterExtensions> element - -Contains types that are used by the <xref:System.Xml.Serialization.XmlSchemaImporter> for mapping of XSD types to .NET types. For more information about configuration files, see [Configuration File Schema](../../framework/configure-apps/file-schema/index.md). - -## Syntax - -```xml -<schemaImporterExtensions> - <!-- Add types --> -</schemaImporterExtensions> -``` - -## Child Elements - -|Element|Description| -|-------------|-----------------| -|[\<add> Element for \<schemaImporterExtensions>](add-element-for-schemaimporterextensions.md)|Adds types that are used by the <xref:System.Xml.Serialization.XmlSchemaImporter> to create mappings.| - -## Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\<system.xml.serialization> Element](system-xml-serialization-element.md)|The top-level element for controlling XML serialization.| - -## Example - - The following code example illustrates how to add types that are used by the <xref:System.Xml.Serialization.XmlSchemaImporter> when mapping XSD types to .NET types. - -```xml -<system.xml.serialization> - <schemaImporterExtensions> +# `<schemaImporterExtensions>` element + +Contains types that are used by the <xref:System.Xml.Serialization.XmlSchemaImporter> for mapping of XSD types to .NET types. For more information about configuration files, see [Configuration File Schema](../../framework/configure-apps/file-schema/index.md). + +## Syntax + +```xml +<schemaImporterExtensions> + <!-- Add types --> +</schemaImporterExtensions> +``` + +## Child Elements + +|Element|Description| +|-------------|-----------------| +|[\<add> Element for `<schemaImporterExtensions>`](add-element-for-schemaimporterextensions.md)|Adds types that are used by the <xref:System.Xml.Serialization.XmlSchemaImporter> to create mappings.| + +## Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\<system.xml.serialization> Element](system-xml-serialization-element.md)|The top-level element for controlling XML serialization.| + +## Example + + The following code example illustrates how to add types that are used by the <xref:System.Xml.Serialization.XmlSchemaImporter> when mapping XSD types to .NET types. + +```xml +<system.xml.serialization> + <schemaImporterExtensions> <add name = "MobileCapabilities" type = "System.Web.Mobile.MobileCapabilities, System.Web.Mobile, Version - 2.0.0.0, Culture = neutral, - PublicKeyToken = b03f5f6f11d40a3a" /> - </schemaImporterExtensions> -</system.xml.serialization> -``` - + PublicKeyToken = b03f5f6f11d40a3a" /> + </schemaImporterExtensions> +</system.xml.serialization> +``` + ## See also - <xref:System.Xml.Serialization.XmlSchemaImporter> - <xref:System.Xml.Serialization.Configuration.DateTimeSerializationSection.DateTimeSerializationMode> - [Configuration File Schema](../../framework/configure-apps/file-schema/index.md) -- [\<dateTimeSerialization> Element](datetimeserialization-element.md) -- [\<add> Element for \<schemaImporterExtensions>](add-element-for-schemaimporterextensions.md) -- [\<system.xml.serialization> Element](system-xml-serialization-element.md) +- [`<dateTimeSerialization>` Element](datetimeserialization-element.md) +- [`<add>` Element for `<schemaImporterExtensions>`](add-element-for-schemaimporterextensions.md) +- [`<system.xml.serialization>` Element](system-xml-serialization-element.md) diff --git a/docs/standard/serialization/system-xml-serialization-element.md b/docs/standard/serialization/system-xml-serialization-element.md index 5345a1dd595a1..6a9f42337d6a7 100644 --- a/docs/standard/serialization/system-xml-serialization-element.md +++ b/docs/standard/serialization/system-xml-serialization-element.md @@ -8,7 +8,7 @@ helpviewer_keywords: - "<system.xml.serialization> element" ms.topic: reference --- -# \<system.xml.serialization> Element +# `<system.xml.serialization>` Element The top-level element for controlling XML serialization. For more information about configuration files, see [Configuration File Schema](../../framework/configure-apps/file-schema/index.md). @@ -66,6 +66,6 @@ The following code example illustrates how to specify the serialization mode of - <xref:System.Xml.Serialization.XmlSchemaImporter> - <xref:System.Xml.Serialization.Configuration.DateTimeSerializationSection.DateTimeSerializationMode> - [Configuration File Schema](../../framework/configure-apps/file-schema/index.md) -- [\<dateTimeSerialization> Element](datetimeserialization-element.md) -- [\<schemaImporterExtensions> Element](schemaimporterextensions-element.md) -- [\<add> Element for \<schemaImporterExtensions>](add-element-for-schemaimporterextensions.md) +- [`<dateTimeSerialization>` Element](datetimeserialization-element.md) +- [`<schemaImporterExtensions>` Element](schemaimporterextensions-element.md) +- [`<add>` Element for `<schemaImporterExtensions>`](add-element-for-schemaimporterextensions.md) diff --git a/docs/standard/serialization/xml-schema-definition-tool-xsd-exe.md b/docs/standard/serialization/xml-schema-definition-tool-xsd-exe.md index b445e4a1d1b4d..d0973f7248e76 100644 --- a/docs/standard/serialization/xml-schema-definition-tool-xsd-exe.md +++ b/docs/standard/serialization/xml-schema-definition-tool-xsd-exe.md @@ -24,7 +24,7 @@ xsd file.xsd {/classes | /dataset} [/element:element] [/parameters:file.xml] xsd {file.dll | file.exe} [-outputdir:directory] [/type:typename [...]][/parameters:file.xml] ``` - + > [!TIP] > For .NET Framework tools to function properly, you must set your `Path`, `Include`, and `Lib` environment variables correctly. Set these environment variables by running SDKVars.bat, which is located in the \<SDK>\\\<version>\Bin directory. SDKVars.bat must be executed in every command shell. @@ -148,7 +148,7 @@ To generate a code file, use the `<generateClasses>` element. The following exam |-------------|-----------------| |\<element>|Specifies an element in the .xsd file to generate code for.| |\<schemaImporterExtensions>|Specifies a type derived from the <xref:System.Xml.Serialization.Advanced.SchemaImporterExtension> class.| -|\<schema>|Specifies a XML Schema file to generate code for. Multiple XML Schema files can be specified using multiple \<schema> elements.| +|\<schema>|Specifies a XML Schema file to generate code for. Multiple XML Schema files can be specified using multiple `<schema>` elements.| The following table shows the attributes that can also be used with the `<generateClasses>` element. @@ -171,7 +171,7 @@ Options you can set for the `<generateDataSet>` element include the following. |Element|Description| |-------------|-----------------| -|\<schema>|Specifies an XML Schema file to generate code for. Multiple XML Schema files can be specified using multiple \<schema> elements.| +|\<schema>|Specifies an XML Schema file to generate code for. Multiple XML Schema files can be specified using multiple `<schema>` elements.| The following table shows the attributes that can be used with the `<generateDataSet>` element. diff --git a/docs/standard/serialization/xmlserializer-element.md b/docs/standard/serialization/xmlserializer-element.md index 048d98b298645..904470b9c6fe2 100644 --- a/docs/standard/serialization/xmlserializer-element.md +++ b/docs/standard/serialization/xmlserializer-element.md @@ -2,66 +2,66 @@ title: "<xmlSerializer> Element" description: The <xmlSerializer> element specifies whether an additional check of progress of the XmlSerializer is done. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "<xmlSerializer> element" - "XML serialization, configuration" - "xmlSerializer element" ms.topic: reference --- -# \<xmlSerializer> Element - -Specifies whether an additional check of progress of the <xref:System.Xml.Serialization.XmlSerializer> is done. - - \<configuration> -\<system.xml.serialization> - -## Syntax - -```xml -<xmlSerializer checkDeserializerAdvance = "true|false" /> -``` - -## Attributes and Elements - - The following sections describe attributes, child elements, and parent elements. - -### Attributes - -|Attribute|Description| -|---------------|-----------------| -|**checkDeserializeAdvances**|Specifies whether the progress of the <xref:System.Xml.Serialization.XmlSerializer> is checked. Set the attribute to "true" or "false". The default is "true".| -|**useLegacySerializationGeneration**|Specifies whether the <xref:System.Xml.Serialization.XmlSerializer> uses legacy serialization generation which generates assemblies by writing C# code to a file and then compiling it to an assembly. The default is **false**.| - -### Child Elements - - None. - -### Parent Elements - -|Element|Description| -|-------------|-----------------| -|[\<system.xml.serialization> Element](system-xml-serialization-element.md)|Contains configuration settings for the <xref:System.Xml.Serialization.XmlSerializer> and <xref:System.Xml.Serialization.XmlSchemaImporter> classes.| - -## Remarks - - By default, the <xref:System.Xml.Serialization.XmlSerializer> provides an additional layer of security against potential denial of service attacks when deserializing untrusted data. It does so by attempting to detect infinite loops during deserialization. If such a condition is detected, an exception is thrown with the following message: "Internal error: deserialization failed to advance over underlying stream." - - Receiving this message does not necessarily indicate that a denial of service attack is in progress. In some rare circumstances, the infinite loop detection mechanism produces a false positive and the exception is thrown for a legitimate incoming message. If you find that in your particular application legitimate messages are being rejected by this extra layer of protection, set **checkDeserializeAdvances** attribute to "false". - -## Example - - The following code example sets the **checkDeserializeAdvances** attribute to "false". - -```xml -<configuration> - <system.xml.serialization> - <xmlSerializer checkDeserializeAdvances="false" /> - </system.xml.serialization> -</configuration> -``` - +# `<xmlSerializer>` Element + +Specifies whether an additional check of progress of the <xref:System.Xml.Serialization.XmlSerializer> is done. + + `<configuration>` + `<system.xml.serialization>` + +## Syntax + +```xml +<xmlSerializer checkDeserializerAdvance = "true|false" /> +``` + +## Attributes and Elements + + The following sections describe attributes, child elements, and parent elements. + +### Attributes + +|Attribute|Description| +|---------------|-----------------| +|**checkDeserializeAdvances**|Specifies whether the progress of the <xref:System.Xml.Serialization.XmlSerializer> is checked. Set the attribute to "true" or "false". The default is "true".| +|**useLegacySerializationGeneration**|Specifies whether the <xref:System.Xml.Serialization.XmlSerializer> uses legacy serialization generation which generates assemblies by writing C# code to a file and then compiling it to an assembly. The default is **false**.| + +### Child Elements + + None. + +### Parent Elements + +|Element|Description| +|-------------|-----------------| +|[\<system.xml.serialization> Element](system-xml-serialization-element.md)|Contains configuration settings for the <xref:System.Xml.Serialization.XmlSerializer> and <xref:System.Xml.Serialization.XmlSchemaImporter> classes.| + +## Remarks + + By default, the <xref:System.Xml.Serialization.XmlSerializer> provides an additional layer of security against potential denial of service attacks when deserializing untrusted data. It does so by attempting to detect infinite loops during deserialization. If such a condition is detected, an exception is thrown with the following message: "Internal error: deserialization failed to advance over underlying stream." + + Receiving this message does not necessarily indicate that a denial of service attack is in progress. In some rare circumstances, the infinite loop detection mechanism produces a false positive and the exception is thrown for a legitimate incoming message. If you find that in your particular application legitimate messages are being rejected by this extra layer of protection, set **checkDeserializeAdvances** attribute to "false". + +## Example + + The following code example sets the **checkDeserializeAdvances** attribute to "false". + +```xml +<configuration> + <system.xml.serialization> + <xmlSerializer checkDeserializeAdvances="false" /> + </system.xml.serialization> +</configuration> +``` + ## See also - <xref:System.Xml.Serialization.XmlSerializer> -- [\<system.xml.serialization> Element](system-xml-serialization-element.md) +- [`<system.xml.serialization>` Element](system-xml-serialization-element.md) - [XML and SOAP Serialization](xml-and-soap-serialization.md) diff --git a/docs/visual-basic/developing-apps/customizing-extending-my/packaging-and-deploying-custom-my-extensions.md b/docs/visual-basic/developing-apps/customizing-extending-my/packaging-and-deploying-custom-my-extensions.md index ecc9768b7b029..b648e644ff81a 100644 --- a/docs/visual-basic/developing-apps/customizing-extending-my/packaging-and-deploying-custom-my-extensions.md +++ b/docs/visual-basic/developing-apps/customizing-extending-my/packaging-and-deploying-custom-my-extensions.md @@ -59,7 +59,7 @@ The CustomData file contains a <`VBMyExtensionTemplate>` element that has attrib |`Version`|Required. A version number for the item template.| |`AssemblyFullName`|Optional. An assembly name. When a reference to this assembly is added to the project, the user will be prompted to add the `My` extension from this item template.| -### Add the \<CustomDataSignature> element to the .vstemplate file +### Add the `<CustomDataSignature>` element to the .vstemplate file To identify your Visual Studio item template as a `My` namespace extension, you must also modify the .vstemplate file for your item template. You must add a `<CustomDataSignature>` element to the `<TemplateData>` element. The `<CustomDataSignature>` element must contain the text `Microsoft.VisualBasic.MyExtension`, as shown in the following example. diff --git a/docs/visual-basic/developing-apps/programming/log-info/how-to-write-event-information-to-a-text-file.md b/docs/visual-basic/developing-apps/programming/log-info/how-to-write-event-information-to-a-text-file.md index 692888206d8b1..c9b3a738c1c49 100644 --- a/docs/visual-basic/developing-apps/programming/log-info/how-to-write-event-information-to-a-text-file.md +++ b/docs/visual-basic/developing-apps/programming/log-info/how-to-write-event-information-to-a-text-file.md @@ -28,7 +28,7 @@ You can use the `My.Application.Log` and `My.Log` objects to log information abo 2. Locate the `<listeners>` section in the application configuration file. - You will find the \<listeners> section in the \<source> section with the name attribute "DefaultSource", which is nested under the \<system.diagnostics> section, which is nested under the top-level \<configuration> section. + You will find the `<listeners>` section in the `<source>` section with the name attribute "DefaultSource", which is nested under the `<system.diagnostics>` section, which is nested under the top-level `<configuration>` section. 3. Add this element to that `<listeners>` section: diff --git a/docs/visual-basic/programming-guide/language-features/xml/how-to-modify-xml-literals.md b/docs/visual-basic/programming-guide/language-features/xml/how-to-modify-xml-literals.md index 19e2308f262bd..c03679304e0ba 100644 --- a/docs/visual-basic/programming-guide/language-features/xml/how-to-modify-xml-literals.md +++ b/docs/visual-basic/programming-guide/language-features/xml/how-to-modify-xml-literals.md @@ -17,7 +17,7 @@ Visual Basic provides convenient ways to modify XML literals. You can add or del 1. To modify the value of an XML literal, obtain a reference to the XML literal and set the `Value` property to the desired value. - The following code example updates the value of all the \<Price> elements in an XML document. + The following code example updates the value of all the `<Price>` elements in an XML document. [!code-vb[VbXmlSamples2#4](~/samples/snippets/visualbasic/VS_Snippets_VBCSharp/VbXmlSamples2/VB/Module2.vb#4)] @@ -214,7 +214,7 @@ Visual Basic provides convenient ways to modify XML literals. You can add or del If the element that you are replacing has sub-elements that must be preserved, set the value of the new <xref:System.Xml.Linq.XElement> object to the <xref:System.Xml.Linq.XContainer.Nodes%2A> property of the existing element. This will set the value of the new element to the inner XML of the existing element. Otherwise, you can set the value of the new element to the `Value` property of the existing element. - The following code example replaces all \<Description> elements with an \<Abstract> element. The content of the \<Description> element is preserved in the new \<Abstract> element by using the <xref:System.Xml.Linq.XContainer.Nodes%2A> property of the \<Description> <xref:System.Xml.Linq.XElement> object. + The following code example replaces all `<Description>` elements with an `<Abstract>` element. The content of the `<Description>` element is preserved in the new `<Abstract>` element by using the <xref:System.Xml.Linq.XContainer.Nodes%2A> property of the `<Description>` <xref:System.Xml.Linq.XElement> object. [!code-vb[VbXmlSamples2#8](~/samples/snippets/visualbasic/VS_Snippets_VBCSharp/VbXmlSamples2/VB/Module2.vb#8)] diff --git a/docs/visual-basic/programming-guide/language-features/xml/how-to-transform-xml-by-using-linq.md b/docs/visual-basic/programming-guide/language-features/xml/how-to-transform-xml-by-using-linq.md index 83e0dda309f47..152765392a407 100644 --- a/docs/visual-basic/programming-guide/language-features/xml/how-to-transform-xml-by-using-linq.md +++ b/docs/visual-basic/programming-guide/language-features/xml/how-to-transform-xml-by-using-linq.md @@ -55,7 +55,7 @@ The example in this topic transforms content from an XML source document to HTML [How to: Load XML from a File, String, or Stream](how-to-load-xml-from-a-file-string-or-stream.md). -3. After the code to create the source XML document, add the following code to retrieve all the \<Book> elements from the object and transform them into an HTML document. The list of \<Book> elements is created by using a LINQ query that returns a collection of <xref:System.Xml.Linq.XElement> objects that contain the transformed HTML. You can use embedded expressions to put the values from the source document in the new XML format. +3. After the code to create the source XML document, add the following code to retrieve all the `<Book>` elements from the object and transform them into an HTML document. The list of `<Book>` elements is created by using a LINQ query that returns a collection of <xref:System.Xml.Linq.XElement> objects that contain the transformed HTML. You can use embedded expressions to put the values from the source document in the new XML format. The resulting HTML document is written to a file by using the <xref:System.Xml.Linq.XElement.Save%2A> method. @@ -78,9 +78,9 @@ The example in this topic transforms content from an XML source document to HTML htmlOutput.Save("BookDescription.html") ``` -4. After `Sub Main` of `Module1`, add a new method (`Sub`) to transform a \<Description> node into the specified HTML format. This method is called by the code in the previous step and is used to preserve the format of the \<Description> elements. +4. After `Sub Main` of `Module1`, add a new method (`Sub`) to transform a `<Description>` node into the specified HTML format. This method is called by the code in the previous step and is used to preserve the format of the `<Description>` elements. - This method replaces sub-elements of the \<Description> element with HTML. The `ReplaceWith` method is used to preserve the location of the sub-elements. The transformed content of the \<Description> element is included in an HTML paragraph (\<p>) element. The <xref:System.Xml.Linq.XContainer.Nodes%2A> property is used to retrieve the transformed content of the \<Description> element. This ensures that sub-elements are included in the transformed content. + This method replaces sub-elements of the `<Description>` element with HTML. The `ReplaceWith` method is used to preserve the location of the sub-elements. The transformed content of the `<Description>` element is included in an HTML paragraph (\<p>) element. The <xref:System.Xml.Linq.XContainer.Nodes%2A> property is used to retrieve the transformed content of the `<Description>` element. This ensures that sub-elements are included in the transformed content. Add the following code after `Sub Main` of `Module1`. diff --git a/docs/visual-basic/programming-guide/program-structure/documenting-your-code-with-xml.md b/docs/visual-basic/programming-guide/program-structure/documenting-your-code-with-xml.md index 734a2223bcdfa..58096fc228d8b 100644 --- a/docs/visual-basic/programming-guide/program-structure/documenting-your-code-with-xml.md +++ b/docs/visual-basic/programming-guide/program-structure/documenting-your-code-with-xml.md @@ -24,11 +24,11 @@ XML documentation starts with `'''`. The processing of these comments has some r - Developers are free to create their own set of tags. There is a recommended set of tags (see [XML Comment Tags](../../language-reference/xmldoc/index.md)). Some of the recommended tags have special meanings: - - The \<param> tag is used to describe parameters. If used, the compiler will verify that the parameter exists and that all parameters are described in the documentation. If the verification fails, the compiler issues a warning. + - The `<param>` tag is used to describe parameters. If used, the compiler will verify that the parameter exists and that all parameters are described in the documentation. If the verification fails, the compiler issues a warning. - The `cref` attribute can be attached to any tag to provide a reference to a code element. The compiler verifies that this code element exists. If the verification fails, the compiler issues a warning. The compiler also respects any `Imports` statements when looking for a type described in the `cref` attribute. - - The \<summary> tag is used by IntelliSense in Visual Studio to display additional information about a type or member. + - The `<summary>` tag is used by IntelliSense in Visual Studio to display additional information about a type or member. ## Related sections diff --git a/docs/visual-basic/programming-guide/program-structure/how-to-create-xml-documentation.md b/docs/visual-basic/programming-guide/program-structure/how-to-create-xml-documentation.md index 2b3a4b5ebd834..95bc475a3dca3 100644 --- a/docs/visual-basic/programming-guide/program-structure/how-to-create-xml-documentation.md +++ b/docs/visual-basic/programming-guide/program-structure/how-to-create-xml-documentation.md @@ -28,7 +28,7 @@ This example shows how to add XML documentation comments to your code. 4. Add additional code that uses the type or member with the new XML documentation comments. - IntelliSense displays the text from the \<summary> tag for the type or member. + IntelliSense displays the text from the `<summary>` tag for the type or member. 5. Compile the code to generate an XML file containing the documentation comments. For more information, see [-doc](../../reference/command-line-compiler/doc.md). diff --git a/samples/snippets/csharp/getting-started/console-linq/Program.cs b/samples/snippets/csharp/getting-started/console-linq/Program.cs deleted file mode 100644 index 5898f400b8b84..0000000000000 --- a/samples/snippets/csharp/getting-started/console-linq/Program.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace LinqFaroShuffle -{ - #region snippet2 - public enum Suit - { - Clubs, - Diamonds, - Hearts, - Spades - } - #endregion - - #region snippet3 - public enum Rank - { - Two, - Three, - Four, - Five, - Six, - Seven, - Eight, - Nine, - Ten, - Jack, - Queen, - King, - Ace - } - #endregion - - public class Program - { - #region snippet4 - static IEnumerable<Suit> Suits() => (Enum.GetValues(typeof(Suit)) as IEnumerable<Suit>)!; - #endregion - - #region snippet5 - static IEnumerable<Rank> Ranks() => (Enum.GetValues(typeof(Rank)) as IEnumerable<Rank>)!; - #endregion - - #region snippet1 - public static void Main(string[] args) - { - IEnumerable<Suit>? suits = Suits(); - IEnumerable<Rank>? ranks = Ranks(); - - if ((suits is null) || (ranks is null)) - return; - - var startingDeck = (from s in suits.LogQuery("Suit Generation") - from r in ranks.LogQuery("Value Generation") - select new { Suit = s, Rank = r }) - .LogQuery("Starting Deck") - .ToArray(); - - foreach (var c in startingDeck) - { - Console.WriteLine(c); - } - - Console.WriteLine(); - - var times = 0; - var shuffle = startingDeck; - - do - { - /* - shuffle = shuffle.Take(26) - .LogQuery("Top Half") - .InterleaveSequenceWith(shuffle.Skip(26).LogQuery("Bottom Half")) - .LogQuery("Shuffle") - .ToArray(); - */ - - shuffle = shuffle.Skip(26) - .LogQuery("Bottom Half") - .InterleaveSequenceWith(shuffle.Take(26).LogQuery("Top Half")) - .LogQuery("Shuffle") - .ToArray(); - - foreach (var c in shuffle) - { - Console.WriteLine(c); - } - - times++; - Console.WriteLine(times); - } while (!startingDeck.SequenceEquals(shuffle)); - - Console.WriteLine(times); - } - #endregion - } -} diff --git a/samples/snippets/csharp/getting-started/console-linq/playingcard.cs b/samples/snippets/csharp/getting-started/console-linq/playingcard.cs deleted file mode 100644 index 033c0259ac39b..0000000000000 --- a/samples/snippets/csharp/getting-started/console-linq/playingcard.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace LinqFaroShuffle -{ - #region snippet1 - public class PlayingCard - { - public Suit CardSuit { get; } - public Rank CardRank { get; } - - public PlayingCard(Suit s, Rank r) - { - CardSuit = s; - CardRank = r; - } - - public override string ToString() - { - return $"{CardRank} of {CardSuit}"; - } - } - #endregion -} \ No newline at end of file