diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 6c3778e4be667..66dcfa3a48de6 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -71,6 +71,6 @@ jobs: # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" - uses: github/codeql-action/upload-sarif@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15 + uses: github/codeql-action/upload-sarif@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16 with: sarif_file: results.sarif diff --git a/docs/azure/includes/dotnet-all.md b/docs/azure/includes/dotnet-all.md index 7f410b6419e81..b0686814d0f8e 100644 --- a/docs/azure/includes/dotnet-all.md +++ b/docs/azure/includes/dotnet-all.md @@ -444,7 +444,7 @@ | LUIS Authoring | NuGet [3.1.0](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring/3.1.0)
NuGet [3.2.0-preview.5](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring/3.2.0-preview.5) | | GitHub [3.1.0](https://github.com/Azure/azure-sdk-for-net/tree/Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring_3.2.0-preview.3/sdk/cognitiveservices/Language.LUIS.Authoring) | | LUIS Runtime | NuGet [3.1.0-preview.1](https://www.nuget.org/packages/Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime/3.1.0-preview.1) | | GitHub [3.1.0-preview.1](https://github.com/Azure/azure-sdk-for-net/tree/Microsoft.Azure.CognitiveServices.Language.LUIS.Runtime_3.1.0-preview.1/sdk/cognitiveservices/Language.LUIS.Runtime) | | Media Live Video Analytics Edge | NuGet [1.0.4-preview.1](https://www.nuget.org/packages/Microsoft.Azure.Media.LiveVideoAnalytics.Edge/1.0.4-preview.1) | | GitHub [1.0.4-preview.1](https://github.com/Azure/azure-sdk-for-net/tree/Microsoft.Azure.Media.LiveVideoAnalytics.Edge_1.0.4-preview.1/sdk/mediaservices/Microsoft.Azure.Media.LiveVideoAnalytics.Edge) | -| Microsoft.Azure.Amqp | NuGet [2.6.9](https://www.nuget.org/packages/Microsoft.Azure.Amqp/2.6.9) | | | +| Microsoft.Azure.Amqp | NuGet [2.6.11](https://www.nuget.org/packages/Microsoft.Azure.Amqp/2.6.11) | | | | Microsoft.Azure.Devices | NuGet [1.40.0](https://www.nuget.org/packages/Microsoft.Azure.Devices/1.40.0)
NuGet [2.0.0-preview007](https://www.nuget.org/packages/Microsoft.Azure.Devices/2.0.0-preview007) | | | | Microsoft.Azure.Devices.Authentication | NuGet [2.0.0-preview001](https://www.nuget.org/packages/Microsoft.Azure.Devices.Authentication/2.0.0-preview001) | | | | Microsoft.Azure.Devices.Client.PCL | NuGet [1.0.16](https://www.nuget.org/packages/Microsoft.Azure.Devices.Client.PCL/1.0.16) | | | @@ -552,11 +552,11 @@ | Microsoft.Azure.Functions.Worker.Extensions.ServiceBus | NuGet [5.22.2](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.ServiceBus/5.22.2) | | | | Microsoft.Azure.Functions.Worker.Extensions.SignalRService | NuGet [2.0.1](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.SignalRService/2.0.1) | | | | Microsoft.Azure.Functions.Worker.Extensions.Sql | NuGet [3.1.376](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Sql/3.1.376) | | | -| Microsoft.Azure.Functions.Worker.Extensions.Storage | NuGet [6.6.1](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Storage/6.6.1) | | | -| Microsoft.Azure.Functions.Worker.Extensions.Storage.Blobs | NuGet [6.6.1](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Storage.Blobs/6.6.1) | | | -| Microsoft.Azure.Functions.Worker.Extensions.Storage.Queues | NuGet [5.5.1](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Storage.Queues/5.5.1) | | | +| Microsoft.Azure.Functions.Worker.Extensions.Storage | NuGet [6.7.0](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Storage/6.7.0) | | | +| Microsoft.Azure.Functions.Worker.Extensions.Storage.Blobs | NuGet [6.7.0](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Storage.Blobs/6.7.0) | | | +| Microsoft.Azure.Functions.Worker.Extensions.Storage.Queues | NuGet [5.5.2](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Storage.Queues/5.5.2) | | | | Microsoft.Azure.Functions.Worker.Extensions.Storage.Tables | NuGet [1.0.0-preview1](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Storage.Tables/1.0.0-preview1) | | | -| Microsoft.Azure.Functions.Worker.Extensions.Tables | NuGet [1.4.2](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Tables/1.4.2) | | | +| Microsoft.Azure.Functions.Worker.Extensions.Tables | NuGet [1.4.3](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Tables/1.4.3) | | | | Microsoft.Azure.Functions.Worker.Extensions.Timer | NuGet [4.3.1](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Timer/4.3.1) | | | | Microsoft.Azure.Functions.Worker.Extensions.Warmup | NuGet [4.0.2](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Extensions.Warmup/4.0.2) | | | | Microsoft.Azure.Functions.Worker.Grpc | NuGet [2.0.0](https://www.nuget.org/packages/Microsoft.Azure.Functions.Worker.Grpc/2.0.0) | | | diff --git a/docs/core/compatibility/10.0.md b/docs/core/compatibility/10.0.md index 7380d328c6e5e..e9ac7d2247509 100644 --- a/docs/core/compatibility/10.0.md +++ b/docs/core/compatibility/10.0.md @@ -2,7 +2,7 @@ title: Breaking changes in .NET 10 titleSuffix: "" description: Navigate to the breaking changes in .NET 10. -ms.date: 04/08/2025 +ms.date: 04/21/2025 ai-usage: ai-assisted no-loc: [Blazor, Razor, Kestrel] --- @@ -29,6 +29,7 @@ If you're migrating an app to .NET 10, the breaking changes listed here might af | [ActivitySource.CreateActivity and ActivitySource.StartActivity behavior change](core-libraries/10.0/activity-sampling.md) | Behavioral change | Preview 1 | | [C# 14 overload resolution with span parameters](core-libraries/10.0/csharp-overload-resolution.md) | Behavioral change | Preview 1 | | [Consistent shift behavior in generic math](core-libraries/10.0/generic-math.md) | Behavioral change | Preview 1 | +| [Default trace context propagator updated to W3C standard](core-libraries/10.0/default-trace-context-propagator.md) | Behavioral change | Preview 4 | | [LDAP DirectoryControl parsing is now more stringent](core-libraries/10.0/ldap-directorycontrol-parsing.md) | Behavioral change | Preview 1 | | [MacCatalyst version normalization](core-libraries/10.0/maccatalyst-version-normalization.md) | Behavioral change | Preview 1 | | [System.Linq.AsyncEnumerable included in core libraries](core-libraries/10.0/asyncenumerable.md) | Source incompatible | Preview 1 | diff --git a/docs/core/compatibility/core-libraries/10.0/default-trace-context-propagator.md b/docs/core/compatibility/core-libraries/10.0/default-trace-context-propagator.md new file mode 100644 index 0000000000000..5a7394ef77805 --- /dev/null +++ b/docs/core/compatibility/core-libraries/10.0/default-trace-context-propagator.md @@ -0,0 +1,55 @@ +--- +title: "Breaking change - Default trace context propagator updated to W3C standard" +description: "Learn about the breaking change in .NET 10 where the default trace context propagator is switched from Legacy to W3C." +ms.date: 4/21/2025 +ai-usage: ai-assisted +ms.custom: https://github.com/dotnet/docs/issues/45793 +--- + +# Default trace context propagator updated to W3C standard + +The default trace context propagator has been switched from the legacy propagator to the W3C propagator. The new propagator uses the `baggage` header instead of `Correlation-Context`, enforces W3C-compliant encoding, and supports only W3C-formatted trace parent IDs. + +## Version introduced + +.NET 10 Preview 4 + +## Previous behavior + +The method returned an instance of the legacy propagator. By default, was set to this legacy instance. + +## New behavior + +The method now returns an instance of the W3C propagator. By default, is set to this W3C instance. + +Example of setting the default propagator to the legacy propagator: + +```csharp +DistributedContextPropagator.Current = DistributedContextPropagator.CreatePreW3CPropagator(); +``` + +## Type of breaking change + +This is a [behavioral change](../../categories.md#behavioral-change). + +## Reason for change + +This change ensures full compliance with the W3C Trace Context and Baggage specifications. The W3C propagator enforces strict formatting for trace parent, trace state, and baggage keys and values, aligning with the W3C standards. The legacy propagator was more lenient and used the non-standard `Correlation-Context` header for baggage propagation. + +For more details, see the following GitHub issues: + +- [Pull Request #114583](https://github.com/dotnet/runtime/pull/114583) +- [Issue #114584](https://github.com/dotnet/runtime/issues/114584) + +## Recommended action + +If you need to retain the legacy behavior, use the `DistributedContextPropagator.CreatePreW3CPropagator()` method to retrieve the legacy propagator instance. Set it as the current propagator as shown below: + +```csharp +DistributedContextPropagator.Current = DistributedContextPropagator.CreatePreW3CPropagator(); +``` + +## Affected APIs + +- +- diff --git a/docs/core/compatibility/toc.yml b/docs/core/compatibility/toc.yml index 74a1a6e83698c..9a68a1eeca6c4 100644 --- a/docs/core/compatibility/toc.yml +++ b/docs/core/compatibility/toc.yml @@ -22,6 +22,8 @@ items: href: core-libraries/10.0/csharp-overload-resolution.md - name: Consistent shift behavior in generic math href: core-libraries/10.0/generic-math.md + - name: Default trace context propagator updated to W3C Standard + href: core-libraries/10.0/default-trace-context-propagator.md - name: LDAP DirectoryControl parsing is now more stringent href: core-libraries/10.0/ldap-directorycontrol-parsing.md - name: MacCatalyst version normalization @@ -1390,6 +1392,8 @@ items: href: core-libraries/10.0/csharp-overload-resolution.md - name: Consistent shift behavior in generic math href: core-libraries/10.0/generic-math.md + - name: Default trace context propagator updated to W3C Standard + href: core-libraries/10.0/default-trace-context-propagator.md - name: LDAP DirectoryControl parsing is now more stringent href: core-libraries/10.0/ldap-directorycontrol-parsing.md - name: MacCatalyst version normalization diff --git a/docs/core/containers/publish-configuration.md b/docs/core/containers/publish-configuration.md index 2d56e9f4b3daa..9ef1af1e5f691 100644 --- a/docs/core/containers/publish-configuration.md +++ b/docs/core/containers/publish-configuration.md @@ -2,19 +2,19 @@ title: Containerize a .NET app reference description: Reference material for containerizing a .NET app and configuring the container image. ms.topic: reference -ms.date: 01/27/2025 +ms.date: 04/22/2025 --- # Containerize a .NET app reference -In this reference article, you learn how to configure the container image that's generated when you publish a .NET app as a container. This article covers the various properties that you can set to control the image, the execution environment, and the commands that are run when the container starts. +In this reference article, you learn how to configure the container image generated when you publish a .NET app as a container. This article covers the various properties that you can set to control the image, the execution environment, and the commands that are run when the container starts. ## Configure container image You can control many aspects of the generated container through MSBuild properties. In general, if you can use a command in a _Dockerfile_ to set some configuration, you can do the same via MSBuild. > [!NOTE] -> The only exceptions to this are `RUN` commands. Due to the way containers are built, those can't be emulated. If you need this functionality, you might consider using a _Dockerfile_ to build your container images. +> The only exceptions to this are `RUN` commands. Due to the way containers are built, those commands can't be emulated. If you need this functionality, consider using a _Dockerfile_ to build your container images. There's no way of performing `RUN` commands with the .NET SDK. These commands are often used to install some OS packages or create a new OS user, or any number of arbitrary things. If you would like to keep using the .NET SDK container building feature, you can instead create a custom base image with these changes and then using this base image. For more information, see [`ContainerBaseImage`](#containerbaseimage). @@ -98,6 +98,18 @@ The preceding project configuration results in a final tag of `8.0-alpine` for a This field is free-form, and often can be used to select different operating system distributions, default package configurations, or any other _flavor_ of changes to a base image. This field is ignored when `ContainerBaseImage` is set. For more information, see [.NET container images](../docker/container-images.md). +### `ContainerPublishInParallel` + +For multi-RID containers, certain project types (like Blazor WebAssembly) may encounter build race conditions. To address this, starting with .NET SDK versions 8.0.408, 9.0.300, and 10.0, you can control the parallelism of the publish process using the `ContainerPublishInParallel` property. By default, publishing occurs in parallel for each Runtime Identifier (RID). Setting this property to `false` ensures sequential publishing, which increases stability but may take longer. + +```xml + + false + +``` + +For more information on multi-RID publishing, see [ContainerRuntimeIdentifier(s)](#containerruntimeidentifiers). + ### `ContainerRuntimeIdentifier(s)` The `ContainerRuntimeIdentifier` property specifies the OS and architecture for your container if the `ContainerBaseImage` supports multiple platforms. For example, the `mcr.microsoft.com/dotnet/runtime` image supports `linux-x64`, `linux-arm`, `linux-arm64`, and `win10-x64`. By default, this is set to the `RuntimeIdentifier` used when publishing the container. Typically, you don't need to set this property explicitly; instead, use the `-r` option with the `dotnet publish` command. If the chosen image doesn't support the specified `RuntimeIdentifier`, an error indicates the supported identifiers. @@ -118,11 +130,16 @@ To specify multiple container runtime identifiers for multi-architecture images, ``` +> [!IMPORTANT] +> The `ContainerRuntimeIdentifiers` property must be a subset of the `RuntimeIdentifiers` property. If this condition isn't met, critical parts of the build pipeline may fail. +> +> Setting multiple `ContainerRuntimeIdentifiers` results in a multi-architecture image being created. For more information, see [Multi-architecture images](#multi-architecture-images). + For more information regarding the runtime identifiers supported by .NET, see [RID catalog](../rid-catalog.md). ### `ContainerRegistry` -The container registry property controls the destination registry, the place that the newly created image will be pushed to. By default it's pushed to the local Docker daemon, but you can also specify a remote registry. When using a remote registry that requires authentication, you authenticate using the well-known `docker login` mechanisms. For more information, See [authenticating to container registries](https://aka.ms/dotnet/containers/auth) for more details. For a concrete example of using this property, consider the following XML example: +The container registry property controls the destination registry, the place that the newly created image is to be pushed to. By default it's pushed to the local Docker daemon, but you can also specify a remote registry. When using a remote registry that requires authentication, you authenticate using the well-known `docker login` mechanisms. For more information, See [authenticating to container registries](https://aka.ms/dotnet/containers/auth) for more details. For a concrete example of using this property, consider the following XML example: ```xml @@ -154,18 +171,33 @@ The container repository is the name of the image itself, for example, `dotnet/r Image names consist of one or more slash-delimited segments, each of which can only contain lowercase alphanumeric characters, periods, underscores, and dashes, and must start with a letter or number. Any other characters result in an error being thrown. -### `ContainerImageTag(s)` +### `ContainerImageFormat` + +Starting with .NET 8.0.405, you can use the `ContainerImageFormat` MSBuild property to specify the image format as either `Docker` or `OCI`. By default, the .NET tooling infers the format from the base image. For example, .NET base images use the Docker-specific format `application/vnd.docker.distribution.manifest.v2+json`. However, many modern tools prefer the OCI format `application/vnd.oci.image.manifest.v1+json`. To force a specific format, set the property as shown: + +```xml + + OCI + +``` + +Both formats are largely interchangeable without loss of information. + +> [!NOTE] +> When building a multi-architecture image, the resulting image format is always OCI. + +### `ContainerImageTag` The container image tag property controls the tags that are generated for the image. To specify a single tag use `ContainerImageTag` and for multiple tags use `ContainerImageTags`. > [!IMPORTANT] -> When you use `ContainerImageTags`, you'll end up with multiple images, one per unique tag. +> When you use `ContainerImageTags`, you end up with multiple images, one per unique tag. Tags are often used to refer to different versions of an app, but they can also refer to different operating system distributions, or even different configurations. Starting with .NET 8, when a tag isn't provided the default is `latest`. -To override the default, specify either of the following: +To override the default, specify either of the following properties: ```xml @@ -184,7 +216,7 @@ To specify multiple tags, use a semicolon-delimited set of tags in the `Containe Tags can only contain up to 127 alphanumeric characters, periods, underscores, and dashes. They must start with an alphanumeric character or an underscore. Any other form results in an error being thrown. > [!NOTE] -> When using `ContainerImageTags` or any MSBuild property that needs to configure `;` delimited values. If you're calling `dotnet publish` from the command line (as is the case with most CI/CD environments), you need to understand the limitations of the environment's inability to disambiguate delimiters and quotations, thus requiring proper escaping. This differs between PowerShell and Bash. Consider the following `dotnet publish` commands in their respective environments: +> When using `ContainerImageTags` or any MSBuild property requiring `;`-delimited values, ensure proper escaping when calling `dotnet publish` from the command line, especially in CI/CD environments. Escaping rules differ between PowerShell and Bash. For example: > > ```powershell > dotnet publish --os linux --arch x64 /t:PublishContainer /p:ContainerImageTags=`"1.2.3-alpha2`;latest`" @@ -283,6 +315,23 @@ For more information, see [.NET environment variables](../tools/dotnet-environme > [!NOTE] > It's currently not possible to set environment variables from the .NET CLI when publishing a container image. For more information, see [GitHub: .NET SDK container builds](https://github.com/dotnet/sdk-container-builds/issues/451). +### `LocalRegistry` + +The `LocalRegistry` MSBuild property specifies the local container tooling to use when pushing to local sources. Supported values are `docker` and `podman`. If not set, the SDK determines the tool based on availability: + +- If both `docker` and `podman` exist, and `docker` is an alias for `podman`, then `podman` is used. +- If only `docker` exists, `docker` is used. +- If only `podman` exists, `podman` is used. +- If neither exists, an error is thrown. + +To explicitly set the local registry tool, use the following configuration: + +```xml + + podman + +``` + ## Configure container commands By default, the container tools launch your app using either the generated AppHost binary for your app (if your app uses an AppHost), or the `dotnet` command plus your app's DLL. @@ -293,7 +342,7 @@ These different configuration points exist because different base images use dif - Identify the binary to run and set it as `ContainerAppCommand` - Identify which arguments are _required_ for your application to run and set them as `ContainerAppCommandArgs` -- Identify which arguments (if any) are _optional_ and could be overridden by a user and set them as `ContainerDefaultArgs` +- Identify which arguments (if any) are _optional_ and are able to be overridden by a user and set them as `ContainerDefaultArgs` - Set `ContainerAppCommandInstruction` to `DefaultArgs` For more information, see the following configuration items. @@ -317,7 +366,7 @@ The `ContainerAppCommand` configuration has a single `Include` property, which r ### `ContainerAppCommandArgs` -This app command args configuration item represents any logically required arguments for your app that should be applied to the `ContainerAppCommand`. By default, none are generated for an app. When present, the args are applied to your container when it's run. +This app command args configuration item represents any logically required arguments for your app that should be applied to the `ContainerAppCommand`. By default, none are generated for an app. When present, the args are applied to your container when it runs. The `ContainerAppCommandArgs` configuration has a single `Include` property, which represents the option or argument to apply to the `ContainerAppCommand` command. @@ -427,10 +476,26 @@ Where possible, existing MSBuild properties provide the values for these labels. | `org.opencontainers.image.licenses` | | `ContainerLicenseExpression` | `PackageLicenseExpression` | `ContainerGenerateLabelsImageLicenses` | | | `org.opencontainers.image.title` | | `ContainerTitle` | `Title` | `ContainerGenerateLabelsImageTitle` | | | `org.opencontainers.image.base.name` | | `ContainerBaseImage` | | `ContainerGenerateLabelsImageBaseName` | | -| `org.opencontainers.image.base.digest` | | | | `ContainerGenerateLabelsImageBaseDigest` | This will be the SHA digest of the chosen base image. Available from .NET SDK 9.0.100 onwards. | +| `org.opencontainers.image.base.digest` | | | | `ContainerGenerateLabelsImageBaseDigest` | This is the SHA digest of the chosen base image. Available from .NET SDK 9.0.100 onwards. | | `org.opencontainers.image.source` | | `PrivateRepositoryUrl` | | `ContainerGenerateLabelsImageSource` | Only written if `PublishRepositoryUrl` is `true`. Also relies on Sourcelink infrastructure being part of the build. | | `org.opencontainers.image.revision` | | `SourceRevisionId` | | `ContainerGenerateLabelsImageRevision` | Only written if `PublishRepositoryUrl` is `true`. Also relies on Sourcelink infrastructure being part of the build. | +## Multi-architecture images + +Multi-architecture images enable a single container image to support multiple architectures, simplifying cross-platform development and deployment. The .NET SDK supports this through the `ContainerRuntimeIdentifiers` property. + +Beginning with SDK versions 8.0.405, 9.0.102, and 9.0.2xx, multi-RID container publishing is supported. When publishing with `/t:PublishContainer`: + +- If a single `RuntimeIdentifier` or `ContainerRuntimeIdentifier` is specified, a single-architecture container is generated as before. +- If no single `RuntimeIdentifier` is specified but multiple `RuntimeIdentifiers` or `ContainerRuntimeIdentifiers` are set, the SDK publishes the app for each specified RID and combines the resulting images into an [OCI Image Index](https://specs.opencontainers.org/image-spec/image-index/). This index allows multiple architecture-specific images to share a single name. + +> [!NOTE] +> The `ContainerRuntimeIdentifiers` property must be a subset of the `RuntimeIdentifiers` property. For more information, see [ContainerRuntimeIdentifiers](#containerruntimeidentifiers). + +This feature streamlines container workflows in mixed-architecture environments. For example, a developer on a `linux-x64` host can publish a container supporting both `linux-x64` and `linux-arm64`, enabling deployment to either architecture without changing image names or labels. + +The generated OCI Image Index is widely supported with modern container tooling, enhancing compatibility and ease of use. + ## See also - [Containerize a .NET app with dotnet publish](sdk-publish.md) diff --git a/docs/core/testing/mstest-analyzers/mstest0042.md b/docs/core/testing/mstest-analyzers/mstest0042.md new file mode 100644 index 0000000000000..f4a05e30dd534 --- /dev/null +++ b/docs/core/testing/mstest-analyzers/mstest0042.md @@ -0,0 +1,41 @@ +--- +title: "MSTEST0042: Avoid duplicated 'DataRow' entries" +description: "Learn about code analysis rule MSTEST0042: Avoid duplicated 'DataRow' entries" +ms.date: 04/11/2025 +f1_keywords: +- MSTEST0042 +- DuplicateDataRowAnalyzer +helpviewer_keywords: +- DuplicateDataRowAnalyzer +- MSTEST0042 +author: Youssef1313 +ms.author: ygerges +--- +# MSTEST0042: Avoid duplicated 'DataRow' entries + +| Property | Value | +|-------------------------------------|------------------------------------------------------------------------| +| **Rule ID** | MSTEST0042 | +| **Title** | Avoid duplicated 'DataRow' entries | +| **Category** | Usage | +| **Fix is breaking or non-breaking** | Non-breaking | +| **Enabled by default** | Yes | +| **Default severity** | Warning | +| **Introduced in version** | 3.9.0 | +| **Is there a code fix** | No | + +## Cause + +A test method has two or more [DataRow](xref:Microsoft.VisualStudio.TestTools.UnitTesting.DataRowAttribute) attributes that are equivalent. + +## Rule description + + is used to denote inputs to test methods. It's not expected that a test will intentionally run twice with the exact same data. Duplicated `DataRow`s are often a copy/paste error. + +## How to fix violations + +Either remove the duplicate `DataRow` attribute, or fix it to make unique. + +## When to suppress warnings + +Do not suppress a warning from this rule, unless you intended to use the same input more than once. diff --git a/docs/core/testing/mstest-analyzers/mstest0043.md b/docs/core/testing/mstest-analyzers/mstest0043.md new file mode 100644 index 0000000000000..914e17e0d4128 --- /dev/null +++ b/docs/core/testing/mstest-analyzers/mstest0043.md @@ -0,0 +1,41 @@ +--- +title: "MSTEST0043: Use retry attribute on test method" +description: "Learn about code analysis rule MSTEST0043: Use retry attribute on test method" +ms.date: 04/11/2025 +f1_keywords: +- MSTEST0043 +- UseRetryWithTestMethodAnalyzer +helpviewer_keywords: +- UseRetryWithTestMethodAnalyzer +- MSTEST0043 +author: Youssef1313 +ms.author: ygerges +--- +# MSTEST0043: Use retry attribute on test method + +| Property | Value | +|-------------------------------------|------------------------------------------------------------------------------------------| +| **Rule ID** | MSTEST0043 | +| **Title** | Use retry attribute on test method | +| **Category** | Usage | +| **Fix is breaking or non-breaking** | Non-breaking | +| **Enabled by default** | Yes | +| **Default severity** | Warning (escalated to Error when setting `MSTestAnalysisMode` to `Recommended` or `All`) | +| **Introduced in version** | 3.9.0 | +| **Is there a code fix** | No | + +## Cause + +A method has an attribute that derives from and does not have an attribute that derives from . + +## Rule description + + only applies to test methods. + +## How to fix violations + +Add to the method, or remove the . + +## When to suppress warnings + +Do not suppress a warning from this rule. diff --git a/docs/core/testing/mstest-analyzers/overview.md b/docs/core/testing/mstest-analyzers/overview.md index d8bd11d084fe9..04df8a6d0c1b9 100644 --- a/docs/core/testing/mstest-analyzers/overview.md +++ b/docs/core/testing/mstest-analyzers/overview.md @@ -49,11 +49,17 @@ This setting follows the default documented behavior for each rule. ### `Recommended` -This is the mode we expect most developers to use. Rules that are enabled by default with Info (`suggestion`) severity are escalated to warnings. Moreover, certain rules might be escalated to errors in both `Recommended` and `All` modes. For example, [MSTEST0003: Test methods should have valid layout](mstest0003.md) is escalated to error in `Recommended` and `All` modes. +This is the mode most developers are expected to use. Rules that are enabled by default with Info (`suggestion`) severity are escalated to warnings. The following rules are escalated to errors in both `Recommended` and `All` modes: + +- [MSTEST0003: Test methods should have valid layout](mstest0003.md). +- [MSTEST0043: Use retry attribute on test method](mstest0043.md). ### `All` -This mode is more aggressive than `Recommended`. All rules are enabled as warnings. As mentioned for `Recommended` mode, certain rules might be escalated to errors in both `Recommended` and `All` modes. For example, [MSTEST0003: Test methods should have valid layout](./mstest0003.md) is escalated to error in `Recommended` and `All` modes. +This mode is more aggressive than `Recommended`. All rules are enabled as warnings. In addition, the following rules are escalated to errors: + +- [MSTEST0003: Test methods should have valid layout](mstest0003.md). +- [MSTEST0043: Use retry attribute on test method](mstest0043.md). > [!NOTE] > The following rules are completely opt-in and are not enabled in `Default`, `Recommended`, or `All` modes: diff --git a/docs/core/testing/mstest-analyzers/usage-rules.md b/docs/core/testing/mstest-analyzers/usage-rules.md index 120458aad2c48..8f6723072467a 100644 --- a/docs/core/testing/mstest-analyzers/usage-rules.md +++ b/docs/core/testing/mstest-analyzers/usage-rules.md @@ -38,3 +38,5 @@ Identifier | Name | Description [MSTEST0039](mstest0039.md) | UseNewerAssertThrowsAnalyzer | Use newer 'Assert.Throws' methods [MSTEST0040](mstest0040.md) | AvoidUsingAssertsInAsyncVoidContextAnalyzer | Do not assert inside 'async void' contexts [MSTEST0041](mstest0041.md) | UseConditionBaseWithTestClassAnalyzer | Use 'ConditionBaseAttribute' on test classes +[MSTEST0042](mstest0042.md) | DuplicateDataRowAnalyzer | Avoid duplicated 'DataRow' entries +[MSTEST0043](mstest0043.md) | UseRetryWithTestMethodAnalyzer | Use retry attribute on test method diff --git a/docs/csharp/programming-guide/classes-and-structs/extension-methods.md b/docs/csharp/programming-guide/classes-and-structs/extension-methods.md index 9b0d992b25127..c568b72a3d92e 100644 --- a/docs/csharp/programming-guide/classes-and-structs/extension-methods.md +++ b/docs/csharp/programming-guide/classes-and-structs/extension-methods.md @@ -12,9 +12,9 @@ helpviewer_keywords: Extension members enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. -<< Introduce both types. >> +Beginning with C# 14, there are two syntaxes you use to define extension methods. C# 14 adds [`extension`](../../language-reference/keywords/extension.md) containers, where you define multiple extension members for a type or an instance of a type. Before C# 14, you add the [`this`](../../language-reference/keywords/this.md) modifier to the first parameter of a static method to indicate that the method appears as a member of an instance of the parameter type. -<< Add Extension member lowering here>>. Extension methods are static methods, but they're called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there's no apparent difference between calling an extension method and the methods defined in a type. +Extension methods are static methods, but they're called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there's no apparent difference between calling an extension method and the methods defined in a type. Both forms of extension methods are compiled to the same IL (Intermediate Language). Consumers of extension members don't need to know which syntax was used to define extension methods. The most common extension members are the LINQ standard query operators that add query functionality to the existing and types. To use the standard query operators, first bring them into scope with a `using System.Linq` directive. Then any type that implements appears to have instance methods such as , , , and so on. You can see these extra methods in IntelliSense statement completion when you type "dot" after an instance of an type such as or . @@ -134,13 +134,13 @@ For more information on derived types, see [Inheritance](../../fundamentals/obje If you do implement extension methods for a given type, remember the following points: - An extension method isn't called if it has the same signature as a method defined in the type. -- Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named `Extensions`, they'll all be brought into scope by the `using Extensions;` directive. +- Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named `Extensions`, all of them are brought into scope by the `using Extensions;` directive. For a class library that you implemented, you shouldn't use extension methods to avoid incrementing the version number of an assembly. If you want to add significant functionality to a library for which you own the source code, follow the .NET guidelines for assembly versioning. For more information, see [Assembly Versioning](../../../standard/assembly/versioning.md). ## See also -- [Parallel Programming Samples (these include many example extension methods)](/samples/browse/?products=dotnet&term=parallel) +- [Parallel Programming Samples (many examples demonstrate extension methods)](/samples/browse/?products=dotnet&term=parallel) - [Lambda Expressions](../../language-reference/operators/lambda-expressions.md) - [Standard Query Operators Overview](../../linq/standard-query-operators/index.md) - [Conversion rules for Instance parameters and their impact](/archive/blogs/sreekarc/conversion-rules-for-instance-parameters-and-their-impact) diff --git a/docs/framework/interop/marshalling-classes-structures-and-unions.md b/docs/framework/interop/marshalling-classes-structures-and-unions.md index 1e732e3c9cb6f..edcf08b258b96 100644 --- a/docs/framework/interop/marshalling-classes-structures-and-unions.md +++ b/docs/framework/interop/marshalling-classes-structures-and-unions.md @@ -2,11 +2,11 @@ title: "Marshalling Classes, Structures, and Unions" description: Review how to marshal classes, structures, and unions. View samples of marshalling classes, structures with nested structures, arrays of structures, and unions. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "data marshalling, classes" - "marshaling, unions" - "marshaling, structures" @@ -42,8 +42,8 @@ The following table lists marshalling options for classes, structures, and union ## Structures sample -This sample demonstrates how to pass a structure that points to a second structure, pass a structure with an embedded structure, and pass a structure with an embedded array. - +This sample demonstrates how to pass a structure that points to a second structure, pass a structure with an embedded structure, and pass a structure with an embedded array. + The Structs sample uses the following unmanaged functions, shown with their original function declaration: - **TestStructInStruct** exported from PinvokeLib.dll. @@ -222,7 +222,7 @@ The `NativeMethods` class contains the prototypes for the `TestUnion` and `TestU In some scenarios, `struct` and `union` layouts can differ depending on the targeted platform. For example, consider the [`STRRET`](/windows/win32/api/shtypes/ns-shtypes-strret) type when defined in a COM scenario: -```c++ +```cpp #include /* Defines the packing of the struct */ typedef struct _STRRET { diff --git a/docs/fundamentals/reflection/accessing-custom-attributes.md b/docs/fundamentals/reflection/accessing-custom-attributes.md index 4db97c19a6490..20cbf5f901a4a 100644 --- a/docs/fundamentals/reflection/accessing-custom-attributes.md +++ b/docs/fundamentals/reflection/accessing-custom-attributes.md @@ -5,12 +5,10 @@ ms.date: 03/27/2024 dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "custom attributes, accessibility" - "attributes [.NET], accessing" - "reflection, custom attributes" -ms.assetid: 1d8e3398-00d8-47d5-a084-214f9859d3d7 --- # Access custom attributes @@ -61,7 +59,6 @@ The custom attribute reflection model could leak instances of user-defined types The following example demonstrates the basic way of using reflection to get access to custom attributes. -[!code-cpp[CustomAttributeData#2](../../../samples/snippets/cpp/VS_Snippets_CLR/CustomAttributeData/CPP/source2.cpp#2)] [!code-csharp[CustomAttributeData#2](../../../samples/snippets/csharp/VS_Snippets_CLR/CustomAttributeData/CS/source2.cs#2)] [!code-vb[CustomAttributeData#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/CustomAttributeData/VB/source2.vb#2)] diff --git a/docs/fundamentals/reflection/dynamically-loading-and-using-types.md b/docs/fundamentals/reflection/dynamically-loading-and-using-types.md index c6dcb8d173c4c..64a91283bce27 100644 --- a/docs/fundamentals/reflection/dynamically-loading-and-using-types.md +++ b/docs/fundamentals/reflection/dynamically-loading-and-using-types.md @@ -5,14 +5,12 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "late binding, about late binding" - "early binding" - "dynamically loading and using types" - "implicit late binding" - "reflection, dynamically using types" -ms.assetid: db985bec-5942-40ec-b13a-771ae98623dc --- # Dynamically load and use types @@ -44,7 +42,6 @@ Using custom binding, you can load an assembly at run time, obtain information a The following example demonstrates a simple custom binder that provides no argument type conversion. Code for `Simple_Type.dll` precedes the main example. Be sure to build `Simple_Type.dll` and then include a reference to it in the project at build time. -[!code-cpp[Conceptual.Types.Dynamic#1](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.dynamic/cpp/source1.cpp#1)] [!code-csharp[Conceptual.Types.Dynamic#1](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.dynamic/cs/source1.cs#1)] [!code-vb[Conceptual.Types.Dynamic#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.types.dynamic/vb/source1.vb#1)] @@ -54,7 +51,6 @@ Use to invoke a The following example shows the three possible combinations of argument coercion (type conversion) and member selection. In Case 1, no argument coercion or member selection is needed. In Case 2, only member selection is needed. In Case 3, only argument coercion is needed. -[!code-cpp[Conceptual.Types.Dynamic#2](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.dynamic/cpp/source2.cpp#2)] [!code-csharp[Conceptual.Types.Dynamic#2](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.dynamic/cs/source2.cs#2)] [!code-vb[Conceptual.Types.Dynamic#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.types.dynamic/vb/source2.vb#2)] diff --git a/docs/fundamentals/reflection/get-type-member-information.md b/docs/fundamentals/reflection/get-type-member-information.md index 2fd0e4f4cafee..b1c83e1c36eef 100644 --- a/docs/fundamentals/reflection/get-type-member-information.md +++ b/docs/fundamentals/reflection/get-type-member-information.md @@ -6,9 +6,7 @@ ms.topic: how-to helpviewer_keywords: - "reflection, obtaining member information" - "types [.NET], obtaining member information from" -ms.assetid: 348ae651-ccda-4f13-8eda-19e8337e9438 dev_langs: - - "cpp" - "csharp" - "vb" --- @@ -20,7 +18,6 @@ The namespace contains many methods for obtaining infor The following example obtains type and member information by using reflection: -[!code-cpp[Get type members](../../../samples/snippets/standard/reflection/memberinfo/gettypemembers.cpp)] [!code-csharp[Get type members](../../../samples/snippets/standard/reflection/memberinfo/gettypemembers.cs)] [!code-vb[Get type members](../../../samples/snippets/standard/reflection/memberinfo/gettypemembers.vb)] diff --git a/docs/fundamentals/reflection/how-to-define-a-generic-type-with-reflection-emit.md b/docs/fundamentals/reflection/how-to-define-a-generic-type-with-reflection-emit.md index 3b41e829dbe32..ab135521f8f2e 100644 --- a/docs/fundamentals/reflection/how-to-define-a-generic-type-with-reflection-emit.md +++ b/docs/fundamentals/reflection/how-to-define-a-generic-type-with-reflection-emit.md @@ -5,12 +5,10 @@ ms.date: 03/27/2024 dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "generics [.NET], reflection emit" - "generics [.NET], dynamic types" - "reflection emit, generic types" -ms.assetid: 07d5f01a-7b5b-40ea-9b15-f21561098fe4 --- # How to: Define a generic type with reflection emit @@ -23,19 +21,16 @@ This article shows how to create a simple generic type with two type parameters, 1. Define a dynamic assembly named `GenericEmitExample1`. In this example, the assembly is executed and saved to disk, so is specified. - [!code-cpp[EmitGenericType#2](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#2)] [!code-csharp[EmitGenericType#2](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#2)] [!code-vb[EmitGenericType#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#2)] 1. Define a dynamic module. An assembly is made up of executable modules. For a single-module assembly, the module name is the same as the assembly name, and the file name is the module name plus an extension. - [!code-cpp[EmitGenericType#3](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#3)] [!code-csharp[EmitGenericType#3](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#3)] [!code-vb[EmitGenericType#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#3)] 1. Define a class. In this example, the class is named `Sample`. - [!code-cpp[EmitGenericType#4](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#4)] [!code-csharp[EmitGenericType#4](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#4)] [!code-vb[EmitGenericType#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#4)] @@ -43,31 +38,26 @@ This article shows how to create a simple generic type with two type parameters, In the following code, `Sample` becomes a generic type with type parameters `TFirst` and `TSecond`. To make the code easier to read, each is placed in a variable with the same name as the type parameter. - [!code-cpp[EmitGenericType#5](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#5)] [!code-csharp[EmitGenericType#5](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#5)] [!code-vb[EmitGenericType#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#5)] 1. Add special constraints to the type parameters. In this example, type parameter `TFirst` is constrained to types that have parameterless constructors, and to reference types. - [!code-cpp[EmitGenericType#6](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#6)] [!code-csharp[EmitGenericType#6](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#6)] [!code-vb[EmitGenericType#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#6)] 1. Optionally add class and interface constraints to the type parameters. In this example, type parameter `TFirst` is constrained to types that derive from the base class represented by the object contained in the variable `baseType`, and that implement the interfaces whose types are contained in the variables `interfaceA` and `interfaceB`. See the code example for the declaration and assignment of these variables. - [!code-cpp[EmitGenericType#7](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#7)] [!code-csharp[EmitGenericType#7](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#7)] [!code-vb[EmitGenericType#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#7)] 1. Define a field. In this example, the type of the field is specified by type parameter `TFirst`. derives from , so you can use generic type parameters anywhere a type can be used. - [!code-cpp[EmitGenericType#21](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#21)] [!code-csharp[EmitGenericType#21](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#21)] [!code-vb[EmitGenericType#21](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#21)] 1. Define a method that uses the type parameters of the generic type. Note that such methods are not generic unless they have their own type parameter lists. The following code defines a `static` method (`Shared` in Visual Basic) that takes an array of `TFirst` and returns a `List` (`List(Of TFirst)` in Visual Basic) containing all the elements of the array. To define this method, it is necessary to create the type `List` by calling on the generic type definition, `List`. (The `T` is omitted when you use the `typeof` operator (`GetType` in Visual Basic) to get the generic type definition.) The parameter type is created by using the method. - [!code-cpp[EmitGenericType#22](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#22)] [!code-csharp[EmitGenericType#22](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#22)] [!code-vb[EmitGenericType#22](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#22)] @@ -82,25 +72,21 @@ This article shows how to create a simple generic type with two type parameters, Now it is possible to get the constructor of `List` by calling on the generic type definition. To convert this constructor to the corresponding constructor of `List`, pass `List` and the constructor from `List` to the static method. - [!code-cpp[EmitGenericType#23](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#23)] [!code-csharp[EmitGenericType#23](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#23)] [!code-vb[EmitGenericType#23](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#23)] 1. Create the type and save the file. - [!code-cpp[EmitGenericType#8](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#8)] [!code-csharp[EmitGenericType#8](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#8)] [!code-vb[EmitGenericType#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#8)] 1. Invoke the method. `ExampleMethod` is not generic, but the type it belongs to is generic, so to get a that can be invoked, it's necessary to create a constructed type from the type definition for `Sample`. The constructed type uses the `Example` class, which satisfies the constraints on `TFirst` because it is a reference type and has a default parameterless constructor, and the `ExampleDerived` class which satisfies the constraints on `TSecond`. (The code for `ExampleDerived` can be found in the example code section.) These two types are passed to to create the constructed type. The is then obtained using the method. - [!code-cpp[EmitGenericType#9](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#9)] [!code-csharp[EmitGenericType#9](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#9)] [!code-vb[EmitGenericType#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#9)] 1. The following code creates an array of `Example` objects, places that array in an array of type representing the arguments of the method to be invoked, and passes them to the method. The first argument of the method is a null reference because the method is `static`. - [!code-cpp[EmitGenericType#10](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#10)] [!code-csharp[EmitGenericType#10](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#10)] [!code-vb[EmitGenericType#10](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#10)] @@ -118,7 +104,6 @@ The program includes a method that lists information about a generic type, and a The program saves the finished module to disk as `GenericEmitExample1.dll`, so you can open it with the [Ildasm.exe (IL Disassembler)](../../framework/tools/ildasm-exe-il-disassembler.md) and examine the CIL for the `Sample` class. -[!code-cpp[EmitGenericType#1](../../../samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp#1)] [!code-csharp[EmitGenericType#1](../../../samples/snippets/csharp/VS_Snippets_CLR/EmitGenericType/CS/source.cs#1)] [!code-vb[EmitGenericType#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/EmitGenericType/VB/source.vb#1)] diff --git a/docs/fundamentals/reflection/how-to-define-and-execute-dynamic-methods.md b/docs/fundamentals/reflection/how-to-define-and-execute-dynamic-methods.md index 7025750fcf7a7..39026225aa5ca 100644 --- a/docs/fundamentals/reflection/how-to-define-and-execute-dynamic-methods.md +++ b/docs/fundamentals/reflection/how-to-define-and-execute-dynamic-methods.md @@ -5,11 +5,9 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "reflection emit, dynamic methods" - "dynamic methods" -ms.assetid: 07d08a99-62c5-4254-bce2-2a75e55a18ab --- # How to: Define and execute dynamic methods @@ -17,13 +15,11 @@ The following procedures show how to define and execute a simple dynamic method 1. Declare a delegate type to execute the method. Consider using a generic delegate to minimize the number of delegate types you need to declare. The following code declares two delegate types that could be used for the `SquareIt` method, and one of them is generic. - [!code-cpp[DynamicMethodHowTo#2](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#2)] [!code-csharp[DynamicMethodHowTo#2](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#2)] [!code-vb[DynamicMethodHowTo#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#2)] 1. Create an array that specifies the parameter types for the dynamic method. In this example, the only parameter is an `int` (`Integer` in Visual Basic), so the array has only one element. - [!code-cpp[DynamicMethodHowTo#3](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#3)] [!code-csharp[DynamicMethodHowTo#3](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#3)] [!code-vb[DynamicMethodHowTo#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#3)] @@ -34,7 +30,6 @@ The following procedures show how to define and execute a simple dynamic method The type of the return value is specified as `long`. The method is associated with the module that contains the `Example` class, which contains the example code. Any loaded module could be specified. The dynamic method acts like a module-level `static` method (`Shared` in Visual Basic). - [!code-cpp[DynamicMethodHowTo#4](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#4)] [!code-csharp[DynamicMethodHowTo#4](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#4)] [!code-vb[DynamicMethodHowTo#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#4)] @@ -42,31 +37,26 @@ The following procedures show how to define and execute a simple dynamic method The CIL in this example loads the argument, which is an `int`, onto the stack, converts it to a `long`, duplicates the `long`, and multiplies the two numbers. This leaves the squared result on the stack, and all the method has to do is return. - [!code-cpp[DynamicMethodHowTo#5](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#5)] [!code-csharp[DynamicMethodHowTo#5](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#5)] [!code-vb[DynamicMethodHowTo#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#5)] 1. Create an instance of the delegate (declared in step 1) that represents the dynamic method by calling the method. Creating the delegate completes the method, and any further attempts to change the method — for example, adding more CIL — are ignored. The following code creates the delegate and invokes it, using a generic delegate. - [!code-cpp[DynamicMethodHowTo#6](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#6)] [!code-csharp[DynamicMethodHowTo#6](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#6)] [!code-vb[DynamicMethodHowTo#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#6)] 1. Declare a delegate type to execute the method. Consider using a generic delegate to minimize the number of delegate types you need to declare. The following code declares a generic delegate type that can be used to execute any method with one parameter and a return value, or a method with two parameters and a return value if the delegate is bound to an object. - [!code-cpp[DynamicMethodHowTo#12](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#12)] [!code-csharp[DynamicMethodHowTo#12](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#12)] [!code-vb[DynamicMethodHowTo#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#12)] 1. Create an array that specifies the parameter types for the dynamic method. If the delegate representing the method is to be bound to an object, the first parameter must match the type the delegate is bound to. In this example, there are two parameters, of type `Example` and type `int` (`Integer` in Visual Basic). - [!code-cpp[DynamicMethodHowTo#13](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#13)] [!code-csharp[DynamicMethodHowTo#13](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#13)] [!code-vb[DynamicMethodHowTo#13](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#13)] 1. Create a . In this example the method has no name. The type of the return value is specified as `int` (`Integer` in Visual Basic). The method has access to the private and protected members of the `Example` class. - [!code-cpp[DynamicMethodHowTo#14](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#14)] [!code-csharp[DynamicMethodHowTo#14](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#14)] [!code-vb[DynamicMethodHowTo#14](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#14)] @@ -74,7 +64,6 @@ The following procedures show how to define and execute a simple dynamic method The CIL in this example loads the first argument, which is an instance of the `Example` class, and uses it to load the value of a private instance field of type `int`. The second argument is loaded, and the two numbers are multiplied. If the result is larger than `int`, the value is truncated and the most significant bits are discarded. The method returns, with the return value on the stack. - [!code-cpp[DynamicMethodHowTo#15](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#15)] [!code-csharp[DynamicMethodHowTo#15](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#15)] [!code-vb[DynamicMethodHowTo#15](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#15)] @@ -87,7 +76,6 @@ The following procedures show how to define and execute a simple dynamic method The delegate `OneParameter` is used because the first parameter of the method always receives the instance of `Example`. When the delegate is invoked, only the second parameter is required. - [!code-cpp[DynamicMethodHowTo#16](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#16)] [!code-csharp[DynamicMethodHowTo#16](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#16)] [!code-vb[DynamicMethodHowTo#16](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#16)] @@ -101,7 +89,6 @@ The second dynamic method has two parameters, of type `Example` and type `int` ( The code example defines delegates that can be used to execute the methods. -[!code-cpp[DynamicMethodHowTo#1](../../../samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp#1)] [!code-csharp[DynamicMethodHowTo#1](../../../samples/snippets/csharp/VS_Snippets_CLR/DynamicMethodHowTo/cs/source.cs#1)] [!code-vb[DynamicMethodHowTo#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/DynamicMethodHowTo/vb/source.vb#1)] diff --git a/docs/fundamentals/reflection/how-to-hook-up-a-delegate-using-reflection.md b/docs/fundamentals/reflection/how-to-hook-up-a-delegate-using-reflection.md index b796fddb8e5b0..0b4616478458d 100644 --- a/docs/fundamentals/reflection/how-to-hook-up-a-delegate-using-reflection.md +++ b/docs/fundamentals/reflection/how-to-hook-up-a-delegate-using-reflection.md @@ -5,12 +5,10 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "events [.NET], adding event handlers with reflection" - "reflection, adding event-handler delegates" - "delegates [.NET], adding event handlers with reflection" -ms.assetid: 076ee62d-a964-449e-a447-c31b33518b81 --- # How to: Hook up a delegate using reflection @@ -23,43 +21,36 @@ When you use reflection to load and run assemblies, you can't use language featu 1. Load an assembly that contains a type that raises events. Assemblies are usually loaded with the method. To keep this example simple, a derived form in the current assembly is used, so the method is used to load the current assembly. - [!code-cpp[HookUpDelegate#3](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#3)] [!code-csharp[HookUpDelegate#3](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#3)] [!code-vb[HookUpDelegate#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#3)] 2. Get a object representing the type, and create an instance of the type. The method is used in the following code because the form has a parameterless constructor. There are several other overloads of the method that you can use if the type you are creating does not have a parameterless constructor. The new instance is stored as type to maintain the fiction that nothing is known about the assembly. (Reflection allows you to get the types in an assembly without knowing their names in advance.) - [!code-cpp[HookUpDelegate#4](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#4)] [!code-csharp[HookUpDelegate#4](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#4)] [!code-vb[HookUpDelegate#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#4)] 3. Get an object representing the event, and use the property to get the type of delegate used to handle the event. In the following code, an for the event is obtained. - [!code-cpp[HookUpDelegate#5](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#5)] [!code-csharp[HookUpDelegate#5](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#5)] [!code-vb[HookUpDelegate#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#5)] 4. Get a object representing the method that handles the event. The complete program code in the Example section later in this article contains a method that matches the signature of the delegate, which handles the event, but you can also generate dynamic methods at run time. For details, see the accompanying procedure, for generating an event handler at run time by using a dynamic method. - [!code-cpp[HookUpDelegate#6](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#6)] [!code-csharp[HookUpDelegate#6](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#6)] [!code-vb[HookUpDelegate#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#6)] 5. Create an instance of the delegate, using the method. This method is static (`Shared` in Visual Basic), so the delegate type must be supplied. Using the overloads of that take a is recommended. - [!code-cpp[HookUpDelegate#7](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#7)] [!code-csharp[HookUpDelegate#7](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#7)] [!code-vb[HookUpDelegate#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#7)] 6. Get the `add` accessor method and invoke it to hook up the event. All events have an `add` accessor and a `remove` accessor, which are hidden by the syntax of high-level languages. For example, C# uses the `+=` operator to hook up events, and Visual Basic uses the [AddHandler statement](../../visual-basic/language-reference/statements/addhandler-statement.md). The following code gets the `add` accessor of the event and invokes it late-bound, passing in the delegate instance. The arguments must be passed as an array. - [!code-cpp[HookUpDelegate#8](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#8)] [!code-csharp[HookUpDelegate#8](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#8)] [!code-vb[HookUpDelegate#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#8)] 7. Test the event. The following code shows the form defined in the code example. Clicking the form invokes the event handler. - [!code-cpp[HookUpDelegate#12](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#12)] [!code-csharp[HookUpDelegate#12](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#12)] [!code-vb[HookUpDelegate#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#12)] @@ -69,25 +60,21 @@ When you use reflection to load and run assemblies, you can't use language featu It is not necessary to name a , so the empty string can be used. In the following code, the last argument associates the dynamic method with the current type, giving the delegate access to all the public and private members of the `Example` class. - [!code-cpp[HookUpDelegate#9](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#9)] [!code-csharp[HookUpDelegate#9](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#9)] [!code-vb[HookUpDelegate#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#9)] 2. Generate a method body. This method loads a string, calls the overload of the method that takes a string, pops the return value off the stack (because the handler has no return type), and returns. To learn more about emitting dynamic methods, see [How to: Define and Execute Dynamic Methods](how-to-define-and-execute-dynamic-methods.md). - [!code-cpp[HookUpDelegate#10](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#10)] [!code-csharp[HookUpDelegate#10](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#10)] [!code-vb[HookUpDelegate#10](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#10)] 3. Complete the dynamic method by calling its method. Use the `add` accessor to add the delegate to the invocation list for the event. - [!code-cpp[HookUpDelegate#11](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#11)] [!code-csharp[HookUpDelegate#11](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#11)] [!code-vb[HookUpDelegate#11](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#11)] 4. Test the event. The following code loads the form defined in the code example. Clicking the form invokes both the predefined event handler and the emitted event handler. - [!code-cpp[HookUpDelegate#12](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#12)] [!code-csharp[HookUpDelegate#12](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#12)] [!code-vb[HookUpDelegate#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#12)] @@ -95,7 +82,6 @@ When you use reflection to load and run assemblies, you can't use language featu The following code example shows how to hook up an existing method to an event using reflection, and also how to use the class to emit a method at run time and hook it up to an event. -[!code-cpp[HookUpDelegate#1](../../../samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp#1)] [!code-csharp[HookUpDelegate#1](../../../samples/snippets/csharp/VS_Snippets_CLR/HookUpDelegate/cs/source.cs#1)] [!code-vb[HookUpDelegate#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HookUpDelegate/vb/source.vb#1)] diff --git a/docs/fundamentals/reflection/reflection-and-generic-types.md b/docs/fundamentals/reflection/reflection-and-generic-types.md index c7f30a2223851..af39e27832a44 100644 --- a/docs/fundamentals/reflection/reflection-and-generic-types.md +++ b/docs/fundamentals/reflection/reflection-and-generic-types.md @@ -5,7 +5,6 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "generics [.NET], reflection emit" - "reflection emit, generic types" @@ -16,7 +15,6 @@ helpviewer_keywords: - "type information, viewing" - "types, generic" - "type parameters" -ms.assetid: f7180fc5-dd41-42d4-8a8e-1b34288e06de --- # Reflection and generic types @@ -88,11 +86,6 @@ Class D(Of V, W) End Class ``` -```cpp -generic ref class B {}; -generic ref class D : B {}; -``` - If you obtain a object representing `D` and use the property to obtain its base type, the resulting `type B` is open, but it's not a generic type definition. ### Source of a generic parameter diff --git a/docs/fundamentals/reflection/viewing-type-information.md b/docs/fundamentals/reflection/viewing-type-information.md index 20ea9422180ba..e28cb3076f91d 100644 --- a/docs/fundamentals/reflection/viewing-type-information.md +++ b/docs/fundamentals/reflection/viewing-type-information.md @@ -5,13 +5,11 @@ ms.date: 03/27/2024 dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "types, viewing type information" - "Type object" - "viewing type information" - "reflection, viewing type information" -ms.assetid: 7e7303a9-4064-4738-b4e7-b75974ed70d2 --- # View type information @@ -24,13 +22,11 @@ Use or The following example shows the syntax necessary to get the object and module for an assembly. -[!code-cpp[Conceptual.Types.ViewInfo#6](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source5.cpp#6)] [!code-csharp[Conceptual.Types.ViewInfo#6](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source5.cs#6)] [!code-vb[Conceptual.Types.ViewInfo#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.types.viewinfo/vb/source5.vb#6)] The following example demonstrates getting `Type` objects from a loaded assembly. -[!code-cpp[Conceptual.Types.ViewInfo#7](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source5.cpp#7)] [!code-csharp[Conceptual.Types.ViewInfo#7](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source5.cs#7)] [!code-vb[Conceptual.Types.ViewInfo#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.types.viewinfo/vb/source5.vb#7)] @@ -44,7 +40,6 @@ If you have a `Type`, you can use the class. -[!code-cpp[Conceptual.Types.ViewInfo#1](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source1.cpp#1)] [!code-csharp[Conceptual.Types.ViewInfo#1](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source1.cs#1)] [!code-vb[Conceptual.Types.ViewInfo#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.types.viewinfo/vb/source1.vb#1)] @@ -54,18 +49,15 @@ Obtain information about the type's methods, properties, events, and fields usin The following example uses `MemberInfo` to list the number of members in the `System.IO.File` class and uses the property to determine the visibility of the class. -[!code-cpp[Conceptual.Types.ViewInfo#2](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source2.cpp#2)] [!code-csharp[Conceptual.Types.ViewInfo#2](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source2.cs#2)] [!code-vb[Conceptual.Types.ViewInfo#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.types.viewinfo/vb/source2.vb#2)] The following example investigates the type of the specified member. It performs reflection on a member of the `MemberInfo` class, and lists its type. -[!code-cpp[Conceptual.Types.ViewInfo#3](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source3.cpp#3)] [!code-csharp[Conceptual.Types.ViewInfo#3](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source3.cs#3)] [!code-vb[Conceptual.Types.ViewInfo#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.types.viewinfo/vb/source3.vb#3)] The following example uses all the Reflection `*Info` classes along with to list all the members (constructors, fields, properties, events, and methods) of the specified class, dividing the members into static and instance categories. -[!code-cpp[Conceptual.Types.ViewInfo#4](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source4.cpp#4)] [!code-csharp[Conceptual.Types.ViewInfo#4](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.types.viewinfo/cs/source4.cs#4)] [!code-vb[Conceptual.Types.ViewInfo#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.types.viewinfo/vb/source4.vb#4)] diff --git a/docs/navigate/devops-testing/toc.yml b/docs/navigate/devops-testing/toc.yml index 03a0fff1e4bb1..96cf78d381915 100644 --- a/docs/navigate/devops-testing/toc.yml +++ b/docs/navigate/devops-testing/toc.yml @@ -207,6 +207,10 @@ items: href: ../../core/testing/mstest-analyzers/mstest0040.md - name: MSTEST0041 href: ../../core/testing/mstest-analyzers/mstest0041.md + - name: MSTEST0042 + href: ../../core/testing/mstest-analyzers/mstest0042.md + - name: MSTEST0043 + href: ../../core/testing/mstest-analyzers/mstest0043.md - name: Test platforms items: - name: Microsoft.Testing.Platform diff --git a/docs/standard/assembly/find-fully-qualified-name.md b/docs/standard/assembly/find-fully-qualified-name.md index c7c1b7a85ebf1..4b1ac4b558f1b 100644 --- a/docs/standard/assembly/find-fully-qualified-name.md +++ b/docs/standard/assembly/find-fully-qualified-name.md @@ -10,7 +10,6 @@ ms.topic: how-to dev_langs: - "csharp" - "vb" - - "cpp" --- # How to: Find an assembly's fully qualified name @@ -59,31 +58,6 @@ For more information about setting assembly attributes such as version, culture, The following example shows how to display the fully qualified name of an assembly containing a specified class to the console. It uses the property to retrieve a reference to an assembly from a type that's defined in that assembly. -```cpp -#using -#using - -using namespace System; -using namespace System::Reflection; - -ref class asmname -{ -public: - static void Main() - { - Type^ t = System::Data::DataSet::typeid; - String^ s = t->Assembly->FullName->ToString(); - Console::WriteLine("The fully qualified assembly name " + - "containing the specified class is {0}.", s); - } -}; - -int main() -{ - asmname::Main(); -} -``` - ```csharp using System; using System.Reflection; diff --git a/docs/standard/assembly/view-contents.md b/docs/standard/assembly/view-contents.md index ad4b040cdb025..07dedf77feb79 100644 --- a/docs/standard/assembly/view-contents.md +++ b/docs/standard/assembly/view-contents.md @@ -14,7 +14,6 @@ ms.topic: how-to dev_langs: - "csharp" - "vb" - - "cpp" --- # How to: View assembly contents @@ -32,24 +31,6 @@ To view assembly manifest information, double-click the **Manifest** icon in the The following example starts with a basic "Hello World" program. After compiling the program, use *Ildasm.exe* to disassemble the *Hello.exe* assembly and view the assembly manifest. -```cpp -using namespace System; - -class MainApp -{ -public: - static void Main() - { - Console::WriteLine("Hello World using C++/CLI!"); - } -}; - -int main() -{ - MainApp::Main(); -} -``` - ```csharp using System; diff --git a/docs/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously.md b/docs/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously.md index 18587a893e8f2..3fe054610315a 100644 --- a/docs/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously.md +++ b/docs/standard/asynchronous-programming-patterns/calling-synchronous-methods-asynchronously.md @@ -5,7 +5,6 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "asynchronous programming, delegates" - "asynchronous delegates" @@ -19,7 +18,6 @@ helpviewer_keywords: - "synchronous calling in asynchronous manner" - "waiting for asynchronous calls" - "status information [.NET], asynchronous operations" -ms.assetid: 41972034-92ed-450a-9664-ab93fcc6f1fb --- # Calling Synchronous Methods Asynchronously @@ -54,7 +52,6 @@ The code examples in this topic demonstrate four common ways to use `BeginInvoke The following code example shows the definition of `TestMethod` and the delegate named `AsyncMethodCaller` that can be used to call `TestMethod` asynchronously. To compile the code examples, you must include the definitions for `TestMethod` and the `AsyncMethodCaller` delegate. - [!code-cpp[AsyncDelegateExamples#1](../../../samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/TestMethod.cpp#1)] [!code-csharp[AsyncDelegateExamples#1](../../../samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/TestMethod.cs#1)] [!code-vb[AsyncDelegateExamples#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/AsyncDelegateExamples/VB/TestMethod.vb#1)] @@ -65,7 +62,6 @@ The code examples in this topic demonstrate four common ways to use `BeginInvoke > [!IMPORTANT] > Because `EndInvoke` might block, you should never call it from threads that service the user interface. - [!code-cpp[AsyncDelegateExamples#2](../../../samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/EndInvoke.cpp#2)] [!code-csharp[AsyncDelegateExamples#2](../../../samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/EndInvoke.cs#2)] [!code-vb[AsyncDelegateExamples#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/AsyncDelegateExamples/VB/EndInvoke.vb#2)] @@ -78,7 +74,6 @@ The code examples in this topic demonstrate four common ways to use `BeginInvoke > [!NOTE] > The wait handle is not closed automatically when you call `EndInvoke`. If you release all references to the wait handle, system resources are freed when garbage collection reclaims the wait handle. To free the system resources as soon as you are finished using the wait handle, dispose of it by calling the method. Garbage collection works more efficiently when disposable objects are explicitly disposed. - [!code-cpp[AsyncDelegateExamples#3](../../../samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/waithandle.cpp#3)] [!code-csharp[AsyncDelegateExamples#3](../../../samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/waithandle.cs#3)] [!code-vb[AsyncDelegateExamples#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/AsyncDelegateExamples/VB/WaitHandle.vb#3)] @@ -86,7 +81,6 @@ The code examples in this topic demonstrate four common ways to use `BeginInvoke You can use the property of the returned by `BeginInvoke` to discover when the asynchronous call completes. You might do this when making the asynchronous call from a thread that services the user interface. Polling for completion allows the calling thread to continue executing while the asynchronous call executes on a thread. - [!code-cpp[AsyncDelegateExamples#4](../../../samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/polling.cpp#4)] [!code-csharp[AsyncDelegateExamples#4](../../../samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/polling.cs#4)] [!code-vb[AsyncDelegateExamples#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/AsyncDelegateExamples/VB/polling.vb#4)] @@ -104,7 +98,6 @@ The code examples in this topic demonstrate four common ways to use `BeginInvoke - The callback is made on a thread. threads are background threads, which do not keep the application running if the main thread ends, so the main thread of the example has to sleep long enough for the callback to finish. - [!code-cpp[AsyncDelegateExamples#5](../../../samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/callback.cpp#5)] [!code-csharp[AsyncDelegateExamples#5](../../../samples/snippets/csharp/VS_Snippets_CLR/AsyncDelegateExamples/CS/callback.cs#5)] [!code-vb[AsyncDelegateExamples#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/AsyncDelegateExamples/VB/callback.vb#5)] diff --git a/docs/standard/attributes/applying-attributes.md b/docs/standard/attributes/applying-attributes.md index 398d8a18511da..e3567ff3dd90d 100644 --- a/docs/standard/attributes/applying-attributes.md +++ b/docs/standard/attributes/applying-attributes.md @@ -5,7 +5,6 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "assemblies [.NET], attributes" - "attributes [.NET], applying" @@ -31,17 +30,15 @@ Use the following process to apply an attribute to an element of your code. ## Apply an attribute to a method - The following code example shows how to use **System.ObsoleteAttribute**, which marks code as obsolete. The string `"Will be removed in next version"` is passed to the attribute. This attribute causes a compiler warning that displays the passed string when code that the attribute describes is called. + The following code example shows how to use , which marks code as obsolete. The string `"Will be removed in next version"` is passed to the attribute. This attribute causes a compiler warning that displays the passed string when code that the attribute describes is called. - [!code-cpp[Conceptual.Attributes.Usage#3](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source1.cpp#3)] [!code-csharp[Conceptual.Attributes.Usage#3](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source1.cs#3)] [!code-vb[Conceptual.Attributes.Usage#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source1.vb#3)] ## Apply attributes at the assembly level - If you want to apply an attribute at the assembly level, use the `assembly` (`Assembly` in Visual Basic) keyword. The following code shows the **AssemblyTitleAttribute** applied at the assembly level. + If you want to apply an attribute at the assembly level, use the `assembly` (`Assembly` in Visual Basic) keyword. The following code shows the applied at the assembly level. - [!code-cpp[Conceptual.Attributes.Usage#2](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source1.cpp#2)] [!code-csharp[Conceptual.Attributes.Usage#2](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source1.cs#2)] [!code-vb[Conceptual.Attributes.Usage#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source1.vb#2)] diff --git a/docs/standard/attributes/retrieving-information-stored-in-attributes.md b/docs/standard/attributes/retrieving-information-stored-in-attributes.md index f178f234fbb17..aaf3ad3038bc2 100644 --- a/docs/standard/attributes/retrieving-information-stored-in-attributes.md +++ b/docs/standard/attributes/retrieving-information-stored-in-attributes.md @@ -3,11 +3,10 @@ title: "Retrieving Information Stored in Attributes" description: Learn to retrieve information stored in attributes, including for an attribute instance, multiple instances for the same scope, multiple instances for different scopes, and attributes applied to class members. ms.date: "08/05/2022" ms.custom: devdivchpfy22 -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "retrieving attributes" - "multiple attribute instances" - "attributes [.NET], retrieving" @@ -15,76 +14,73 @@ ms.topic: how-to --- # Retrieving Information Stored in Attributes -Retrieving a custom attribute is a simple process. First, declare an instance of the attribute you want to retrieve. Then, use the method to initialize the new attribute to the value of the attribute you want to retrieve. Once the new attribute is initialized, you can use its properties to get the values. - +Retrieving a custom attribute is a simple process. First, declare an instance of the attribute you want to retrieve. Then, use the method to initialize the new attribute to the value of the attribute you want to retrieve. Once the new attribute is initialized, you can use its properties to get the values. + > [!IMPORTANT] -> This article describes how to retrieve attributes for code loaded into the execution context. To retrieve attributes for code loaded into the reflection-only context, you must use the class, as shown in [How to: Load Assemblies into the Reflection-Only Context](../../framework/reflection-and-codedom/how-to-load-assemblies-into-the-reflection-only-context.md). - - This section describes the following ways to retrieve attributes: - -- [Retrieving a single instance of an attribute](#cpconretrievingsingleinstanceofattribute) - -- [Retrieving multiple instances of an attribute applied to the same scope](#cpconretrievingmultipleinstancesofattributeappliedtosamescope) - -- [Retrieving multiple instances of an attribute applied to different scopes](#cpconretrievingmultipleinstancesofattributeappliedtodifferentscopes) - +> This article describes how to retrieve attributes for code loaded into the execution context. To retrieve attributes for code loaded into the reflection-only context, you must use the class, as shown in [How to: Load Assemblies into the Reflection-Only Context](../../framework/reflection-and-codedom/how-to-load-assemblies-into-the-reflection-only-context.md). + + This section describes the following ways to retrieve attributes: + +- [Retrieving a single instance of an attribute](#cpconretrievingsingleinstanceofattribute) + +- [Retrieving multiple instances of an attribute applied to the same scope](#cpconretrievingmultipleinstancesofattributeappliedtosamescope) + +- [Retrieving multiple instances of an attribute applied to different scopes](#cpconretrievingmultipleinstancesofattributeappliedtodifferentscopes) + -## Retrieving a Single Instance of an Attribute +## Retrieving a Single Instance of an Attribute + + In the following example, the `DeveloperAttribute` (described in the previous section) is applied to the `MainApp` class on the class level. The `GetAttribute` method uses `GetCustomAttribute` to retrieve the values stored in `DeveloperAttribute` on the class level before displaying them to the console. - In the following example, the `DeveloperAttribute` (described in the previous section) is applied to the `MainApp` class on the class level. The `GetAttribute` method uses `GetCustomAttribute` to retrieve the values stored in `DeveloperAttribute` on the class level before displaying them to the console. - - [!code-cpp[Conceptual.Attributes.Usage#18](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source3.cpp#18)] [!code-csharp[Conceptual.Attributes.Usage#18](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source3.cs#18)] - [!code-vb[Conceptual.Attributes.Usage#18](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source3.vb#18)] - + [!code-vb[Conceptual.Attributes.Usage#18](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source3.vb#18)] + The execution of the preceding program displays the following text: - -```console -The Name Attribute is: Joan Smith. -The Level Attribute is: 42. -The Reviewed Attribute is: True. -``` - + +```console +The Name Attribute is: Joan Smith. +The Level Attribute is: 42. +The Reviewed Attribute is: True. +``` + If the attribute isn't found, the `GetCustomAttribute` method initializes `MyAttribute` to a null value. This example checks `MyAttribute` for such an instance and notifies the user if the attribute isn't found. If `DeveloperAttribute` isn't found in the class scope, the console displays the following message: - -```console + +```console The attribute was not found. -``` - - The preceding example assumes that the attribute definition is in the current namespace. Remember to import the namespace in which the attribute definition resides if it isn't in the current namespace. - +``` + + The preceding example assumes that the attribute definition is in the current namespace. Remember to import the namespace in which the attribute definition resides if it isn't in the current namespace. + -## Retrieving Multiple Instances of an Attribute Applied to the Same Scope +## Retrieving Multiple Instances of an Attribute Applied to the Same Scope + + In the preceding example, the class to inspect and the specific attribute to find are passed to the method. That code works well if only one instance of an attribute is applied on the class level. However, if multiple instances of an attribute are applied on the same class level, the `GetCustomAttribute` method doesn't retrieve all the information. In cases where multiple instances of the same attribute are applied to the same scope, you can use method to place all instances of an attribute into an array. For example, if two instances of `DeveloperAttribute` are applied on the class level of the same class, the `GetAttribute` method can be modified to display the information found in both attributes. Remember, to apply multiple attributes on the same level. The attribute must be defined with the `AllowMultiple` property set to `true` in the class. + + The following code example shows how to use the `GetCustomAttributes` method to create an array that references all instances of `DeveloperAttribute` in any given class. The code then outputs the values of all the attributes to the console. - In the preceding example, the class to inspect and the specific attribute to find are passed to the method. That code works well if only one instance of an attribute is applied on the class level. However, if multiple instances of an attribute are applied on the same class level, the `GetCustomAttribute` method doesn't retrieve all the information. In cases where multiple instances of the same attribute are applied to the same scope, you can use method to place all instances of an attribute into an array. For example, if two instances of `DeveloperAttribute` are applied on the class level of the same class, the `GetAttribute` method can be modified to display the information found in both attributes. Remember, to apply multiple attributes on the same level. The attribute must be defined with the `AllowMultiple` property set to `true` in the class. - - The following code example shows how to use the `GetCustomAttributes` method to create an array that references all instances of `DeveloperAttribute` in any given class. The code then outputs the values of all the attributes to the console. - - [!code-cpp[Conceptual.Attributes.Usage#19](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source3.cpp#19)] [!code-csharp[Conceptual.Attributes.Usage#19](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source3.cs#19)] - [!code-vb[Conceptual.Attributes.Usage#19](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source3.vb#19)] - - If no attributes are found, this code alerts the user. Otherwise, the information contained in both instances of `DeveloperAttribute` is displayed. - + [!code-vb[Conceptual.Attributes.Usage#19](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source3.vb#19)] + + If no attributes are found, this code alerts the user. Otherwise, the information contained in both instances of `DeveloperAttribute` is displayed. + -## Retrieving Multiple Instances of an Attribute Applied to Different Scopes +## Retrieving Multiple Instances of an Attribute Applied to Different Scopes + + The and methods don't search an entire class and return all instances of an attribute in that class. Rather, they search only one specified method or member at a time. If you have a class with the same attribute applied to every member and you want to retrieve the values in all the attributes applied to those members, you must supply every method or member individually to `GetCustomAttributes` and `GetCustomAttribute`. - The and methods don't search an entire class and return all instances of an attribute in that class. Rather, they search only one specified method or member at a time. If you have a class with the same attribute applied to every member and you want to retrieve the values in all the attributes applied to those members, you must supply every method or member individually to `GetCustomAttributes` and `GetCustomAttribute`. - The following code example takes a class as a parameter and searches for the `DeveloperAttribute` (defined previously) on the class level and on every individual method of that class: - - [!code-cpp[Conceptual.Attributes.Usage#20](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source3.cpp#20)] + [!code-csharp[Conceptual.Attributes.Usage#20](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source3.cs#20)] - [!code-vb[Conceptual.Attributes.Usage#20](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source3.vb#20)] - - If no instances of the `DeveloperAttribute` are found on the method level or class level, the `GetAttribute` method notifies the user that no attributes were found and displays the name of the method or class that doesn't contain the attribute. If an attribute is found, the console displays the `Name`, `Level`, and `Reviewed` fields. - + [!code-vb[Conceptual.Attributes.Usage#20](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source3.vb#20)] + + If no instances of the `DeveloperAttribute` are found on the method level or class level, the `GetAttribute` method notifies the user that no attributes were found and displays the name of the method or class that doesn't contain the attribute. If an attribute is found, the console displays the `Name`, `Level`, and `Reviewed` fields. + You can use the members of the class to get the individual methods and members in the passed class. This example first queries the `Type` object to get attribute information for the class level. Next, it uses to place instances of all methods into an array of objects to retrieve attribute information for the method level. You can also use the method to check for attributes on the property level or to check for attributes on the constructor level. -## Retrieving Attributes from Class Members +## Retrieving Attributes from Class Members In addition to retrieving attributes at the class level, attributes can also be applied to individual members such as methods, properties, and fields. The `GetCustomAttribute` and `GetCustomAttributes` methods can be used to retrieve these attributes. @@ -93,7 +89,7 @@ In addition to retrieving attributes at the class level, attributes can also be The following example demonstrates how to retrieve an attribute applied to a method: [!code-csharp[Conceptual.Attributes.Usage#21](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source4.cs#21)] - + ## See also - diff --git a/docs/standard/attributes/writing-custom-attributes.md b/docs/standard/attributes/writing-custom-attributes.md index feff372cd49df..d0d1545b77e04 100644 --- a/docs/standard/attributes/writing-custom-attributes.md +++ b/docs/standard/attributes/writing-custom-attributes.md @@ -3,11 +3,10 @@ title: "Writing Custom Attributes" description: Design your own custom attributes in .NET. Custom attributes are essentially classes derived directly or indirectly from System.Attribute. ms.date: "08/05/2022" ms.custom: devdivchpfy22 -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "multiple attribute instances" - "AttributeTargets enumeration" - "attributes [.NET], custom" @@ -16,143 +15,129 @@ helpviewer_keywords: - "AttributeUsageAttribute class, custom attributes" - "Inherited property" - "attribute classes, declaring" -ms.assetid: 97216f69-bde8-49fd-ac40-f18c500ef5dc --- # Write custom attributes -To design custom attributes, you don't need to learn many new concepts. If you're familiar with object-oriented programming and know how to design classes, you already have most of the knowledge needed. Custom attributes are traditional classes that derive directly or indirectly from the class. Just like traditional classes, custom attributes contain methods that store and retrieve data. - - The primary steps to properly design custom attribute classes are as follows: - -- [Applying the AttributeUsageAttribute](#applying-the-attributeusageattribute) - -- [Declaring the attribute class](#declaring-the-attribute-class) - -- [Declaring constructors](#declaring-constructors) - -- [Declaring properties](#declaring-properties) - +To design custom attributes, you don't need to learn many new concepts. If you're familiar with object-oriented programming and know how to design classes, you already have most of the knowledge needed. Custom attributes are traditional classes that derive directly or indirectly from the class. Just like traditional classes, custom attributes contain methods that store and retrieve data. + + The primary steps to properly design custom attribute classes are as follows: + +- [Applying the AttributeUsageAttribute](#applying-the-attributeusageattribute) + +- [Declaring the attribute class](#declaring-the-attribute-class) + +- [Declaring constructors](#declaring-constructors) + +- [Declaring properties](#declaring-properties) + This section describes each of these steps and concludes with a [custom attribute example](#custom-attribute-example). - -## Applying the AttributeUsageAttribute - A custom attribute declaration begins with the attribute, which defines some of the key characteristics of your attribute class. For example, you can specify whether your attribute can be inherited by other classes or which elements the attribute can be applied to. The following code fragment demonstrates how to use the : - - [!code-cpp[Conceptual.Attributes.Usage#5](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#5)] +## Applying the AttributeUsageAttribute + + A custom attribute declaration begins with the attribute, which defines some of the key characteristics of your attribute class. For example, you can specify whether your attribute can be inherited by other classes or which elements the attribute can be applied to. The following code fragment demonstrates how to use the : + [!code-csharp[Conceptual.Attributes.Usage#5](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#5)] - [!code-vb[Conceptual.Attributes.Usage#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#5)] - - The has three members that are important for the creation of custom attributes: [AttributeTargets](#attributetargets-member), [Inherited](#inherited-property), and [AllowMultiple](#allowmultiple-property). - -### AttributeTargets Member - - In the preceding example, is specified, indicating that this attribute can be applied to all program elements. Alternatively, you can specify , indicating that your attribute can be applied only to a class, or , indicating that your attribute can be applied only to a method. All program elements can be marked for description by a custom attribute in this manner. - + [!code-vb[Conceptual.Attributes.Usage#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#5)] + + The has three members that are important for the creation of custom attributes: [AttributeTargets](#attributetargets-member), [Inherited](#inherited-property), and [AllowMultiple](#allowmultiple-property). + +### AttributeTargets Member + + In the preceding example, is specified, indicating that this attribute can be applied to all program elements. Alternatively, you can specify , indicating that your attribute can be applied only to a class, or , indicating that your attribute can be applied only to a method. All program elements can be marked for description by a custom attribute in this manner. + You can also pass multiple values. The following code fragment specifies that a custom attribute can be applied to any class or method: - - [!code-cpp[Conceptual.Attributes.Usage#6](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#6)] + [!code-csharp[Conceptual.Attributes.Usage#6](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#6)] - [!code-vb[Conceptual.Attributes.Usage#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#6)] - -### Inherited Property + [!code-vb[Conceptual.Attributes.Usage#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#6)] + +### Inherited Property + + The property indicates whether your attribute can be inherited by classes that are derived from the classes to which your attribute is applied. This property takes either a `true` (the default) or `false` flag. In the following example, `MyAttribute` has a default value of `true`, while `YourAttribute` has an value of `false`: - The property indicates whether your attribute can be inherited by classes that are derived from the classes to which your attribute is applied. This property takes either a `true` (the default) or `false` flag. In the following example, `MyAttribute` has a default value of `true`, while `YourAttribute` has an value of `false`: - - [!code-cpp[Conceptual.Attributes.Usage#7](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#7)] [!code-csharp[Conceptual.Attributes.Usage#7](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#7)] - [!code-vb[Conceptual.Attributes.Usage#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#7)] - + [!code-vb[Conceptual.Attributes.Usage#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#7)] + The two attributes are then applied to a method in the base class `MyClass`: - - [!code-cpp[Conceptual.Attributes.Usage#9](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#9)] + [!code-csharp[Conceptual.Attributes.Usage#9](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#9)] - [!code-vb[Conceptual.Attributes.Usage#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#9)] - + [!code-vb[Conceptual.Attributes.Usage#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#9)] + Finally, the class `YourClass` is inherited from the base class `MyClass`. The method `MyMethod` shows `MyAttribute` but not `YourAttribute`: - - [!code-cpp[Conceptual.Attributes.Usage#10](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#10)] + [!code-csharp[Conceptual.Attributes.Usage#10](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#10)] - [!code-vb[Conceptual.Attributes.Usage#10](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#10)] - -### AllowMultiple Property + [!code-vb[Conceptual.Attributes.Usage#10](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#10)] + +### AllowMultiple Property + + The property indicates whether multiple instances of your attribute can exist on an element. If set to `true`, multiple instances are allowed. If set to `false` (the default), only one instance is allowed. - The property indicates whether multiple instances of your attribute can exist on an element. If set to `true`, multiple instances are allowed. If set to `false` (the default), only one instance is allowed. - In the following example, `MyAttribute` has a default value of `false`, while `YourAttribute` has a value of `true`: - - [!code-cpp[Conceptual.Attributes.Usage#11](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#11)] + [!code-csharp[Conceptual.Attributes.Usage#11](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#11)] - [!code-vb[Conceptual.Attributes.Usage#11](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#11)] - + [!code-vb[Conceptual.Attributes.Usage#11](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#11)] + When multiple instances of these attributes are applied, `MyAttribute` produces a compiler error. The following code example shows the valid use of `YourAttribute` and the invalid use of `MyAttribute`: - - [!code-cpp[Conceptual.Attributes.Usage#13](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#13)] + [!code-csharp[Conceptual.Attributes.Usage#13](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#13)] - [!code-vb[Conceptual.Attributes.Usage#13](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#13)] - - If both the property and the property are set to `true`, a class that's inherited from another class can inherit an attribute and have another instance of the same attribute applied in the same child class. If is set to `false`, the values of any attributes in the parent class will be overwritten by new instances of the same attribute in the child class. - -## Declaring the Attribute Class + [!code-vb[Conceptual.Attributes.Usage#13](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#13)] + + If both the property and the property are set to `true`, a class that's inherited from another class can inherit an attribute and have another instance of the same attribute applied in the same child class. If is set to `false`, the values of any attributes in the parent class will be overwritten by new instances of the same attribute in the child class. + +## Declaring the Attribute Class After you apply the , start defining the specifics of your attribute. The declaration of an attribute class looks similar to the declaration of a traditional class, as demonstrated by the following code: - - [!code-cpp[Conceptual.Attributes.Usage#14](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#14)] + [!code-csharp[Conceptual.Attributes.Usage#14](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#14)] - [!code-vb[Conceptual.Attributes.Usage#14](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#14)] - - This attribute definition demonstrates the following points: - -- Attribute classes must be declared as public classes. - -- By convention, the name of the attribute class ends with the word **Attribute**. While not required, this convention is recommended for readability. When the attribute is applied, the inclusion of the word Attribute is optional. - -- All attribute classes must inherit directly or indirectly from the class. - -- In Microsoft Visual Basic, all custom attribute classes must have the attribute. - -## Declaring Constructors + [!code-vb[Conceptual.Attributes.Usage#14](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#14)] + + This attribute definition demonstrates the following points: + +- Attribute classes must be declared as public classes. + +- By convention, the name of the attribute class ends with the word **Attribute**. While not required, this convention is recommended for readability. When the attribute is applied, the inclusion of the word Attribute is optional. + +- All attribute classes must inherit directly or indirectly from the class. + +- In Microsoft Visual Basic, all custom attribute classes must have the attribute. + +## Declaring Constructors Just like traditional classes, attributes are initialized with constructors. The following code fragment illustrates a typical attribute constructor. This public constructor takes a parameter and sets a member variable equal to its value. - - [!code-cpp[Conceptual.Attributes.Usage#15](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#15)] + [!code-csharp[Conceptual.Attributes.Usage#15](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#15)] - [!code-vb[Conceptual.Attributes.Usage#15](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#15)] - + [!code-vb[Conceptual.Attributes.Usage#15](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#15)] + You can overload the constructor to accommodate different combinations of values. If you also define a [property](/previous-versions/visualstudio/visual-studio-2013/65zdfbdt(v=vs.120)) for your custom attribute class, you can use a combination of named and positional parameters when initializing the attribute. Typically, you define all required parameters as positional and all optional parameters as named. In this case, the attribute can't be initialized without the required parameter. All other parameters are optional. > [!NOTE] -> In Visual Basic, constructors for an attribute class shouldn't use a `ParamArray` argument. - - The following code example shows how an attribute that uses the previous constructor can be applied using optional and required parameters. It assumes that the attribute has one required Boolean value and one optional string property. - - [!code-cpp[Conceptual.Attributes.Usage#17](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#17)] +> In Visual Basic, constructors for an attribute class shouldn't use a `ParamArray` argument. + + The following code example shows how an attribute that uses the previous constructor can be applied using optional and required parameters. It assumes that the attribute has one required Boolean value and one optional string property. + [!code-csharp[Conceptual.Attributes.Usage#17](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#17)] - [!code-vb[Conceptual.Attributes.Usage#17](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#17)] - -## Declaring Properties + [!code-vb[Conceptual.Attributes.Usage#17](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#17)] + +## Declaring Properties If you want to define a named parameter or provide an easy way to return the values stored by your attribute, declare a [property](/previous-versions/visualstudio/visual-studio-2013/65zdfbdt(v=vs.120)). Attribute properties should be declared as public entities with a description of the data type that will be returned. Define the variable that will hold the value of your property and associate it with the `get` and `set` methods. The following code example demonstrates how to implement a property in your attribute: - - [!code-cpp[Conceptual.Attributes.Usage#16](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#16)] + [!code-csharp[Conceptual.Attributes.Usage#16](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#16)] - [!code-vb[Conceptual.Attributes.Usage#16](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#16)] - -## Custom Attribute Example + [!code-vb[Conceptual.Attributes.Usage#16](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#16)] + +## Custom Attribute Example + + This section incorporates the previous information and shows how to design an attribute that documents information about the author of a section of code. The attribute in this example stores the name and level of the programmer, and whether the code has been reviewed. It uses three private variables to store the actual values to save. Each variable is represented by a public property that gets and sets the values. Finally, the constructor is defined with two required parameters: - This section incorporates the previous information and shows how to design an attribute that documents information about the author of a section of code. The attribute in this example stores the name and level of the programmer, and whether the code has been reviewed. It uses three private variables to store the actual values to save. Each variable is represented by a public property that gets and sets the values. Finally, the constructor is defined with two required parameters: - - [!code-cpp[Conceptual.Attributes.Usage#4](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#4)] [!code-csharp[Conceptual.Attributes.Usage#4](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#4)] - [!code-vb[Conceptual.Attributes.Usage#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#4)] - - You can apply this attribute using the full name, `DeveloperAttribute`, or using the abbreviated name, `Developer`, in one of the following ways: - - [!code-cpp[Conceptual.Attributes.Usage#12](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp#12)] + [!code-vb[Conceptual.Attributes.Usage#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#4)] + + You can apply this attribute using the full name, `DeveloperAttribute`, or using the abbreviated name, `Developer`, in one of the following ways: + [!code-csharp[Conceptual.Attributes.Usage#12](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.attributes.usage/cs/source2.cs#12)] - [!code-vb[Conceptual.Attributes.Usage#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#12)] - + [!code-vb[Conceptual.Attributes.Usage#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.attributes.usage/vb/source2.vb#12)] + The first example shows the attribute applied with only the required named parameters. The second example shows the attribute applied with both the required and optional parameters. - + ## See also - diff --git a/docs/standard/base-types/comparing.md b/docs/standard/base-types/comparing.md index fe41082558ee2..97213ffcd01e3 100644 --- a/docs/standard/base-types/comparing.md +++ b/docs/standard/base-types/comparing.md @@ -6,7 +6,6 @@ ms.topic: conceptual dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "value comparisons of strings" - "LastIndexOf method" @@ -18,7 +17,6 @@ helpviewer_keywords: - "EndsWith method" - "Equals method" - "StartsWith method" -ms.assetid: 977dc094-fe19-4955-98ec-d2294d04a4ba --- # Compare strings in .NET @@ -52,7 +50,6 @@ The static method p The following example uses the method to determine the relative values of two strings. - [!code-cpp[Conceptual.String.BasicOps#6](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp#6)] [!code-csharp[Conceptual.String.BasicOps#6](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/compare.cs#6)] [!code-vb[Conceptual.String.BasicOps#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/compare.vb#6)] @@ -69,7 +66,6 @@ The method c The following example uses the `CompareOrdinal` method to compare the values of two strings. - [!code-cpp[Conceptual.String.BasicOps#7](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp#7)] [!code-csharp[Conceptual.String.BasicOps#7](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/compare.cs#7)] [!code-vb[Conceptual.String.BasicOps#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/compare.vb#7)] @@ -84,7 +80,6 @@ The method compar The following example uses the method to compare the `string1` object to the `string2` object. - [!code-cpp[Conceptual.String.BasicOps#8](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp#8)] [!code-csharp[Conceptual.String.BasicOps#8](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/compare.cs#8)] [!code-vb[Conceptual.String.BasicOps#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/compare.vb#8)] @@ -96,7 +91,6 @@ The method compar The method can easily determine if two strings are the same. This case-sensitive method returns a `true` or `false` Boolean value. It can be used from an existing class, as illustrated in the next example. The following example uses the `Equals` method to determine whether a string object contains the phrase "Hello World". - [!code-cpp[Conceptual.String.BasicOps#9](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp#9)] [!code-csharp[Conceptual.String.BasicOps#9](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/compare.cs#9)] [!code-vb[Conceptual.String.BasicOps#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/compare.vb#9)] @@ -104,7 +98,6 @@ The method can easil This method can also be used as a static method. The following example compares two string objects using a static method. - [!code-cpp[Conceptual.String.BasicOps#10](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp#10)] [!code-csharp[Conceptual.String.BasicOps#10](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/compare.cs#10)] [!code-vb[Conceptual.String.BasicOps#10](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/compare.vb#10)] @@ -114,7 +107,6 @@ The method can easil You can use the method to determine whether a string object begins with the same characters that encompass another string. This case-sensitive method returns `true` if the current string object begins with the passed string and `false` if it does not. The following example uses this method to determine if a string object begins with "Hello". - [!code-cpp[Conceptual.String.BasicOps#11](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp#11)] [!code-csharp[Conceptual.String.BasicOps#11](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/compare.cs#11)] [!code-vb[Conceptual.String.BasicOps#11](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/compare.vb#11)] @@ -122,7 +114,6 @@ You can use the The method compares a passed string to the characters that exist at the end of the current string object. It also returns a Boolean value. The following example checks the end of a string using the `EndsWith` method. - [!code-cpp[Conceptual.String.BasicOps#12](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp#12)] [!code-csharp[Conceptual.String.BasicOps#12](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/compare.cs#12)] [!code-vb[Conceptual.String.BasicOps#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/compare.vb#12)] @@ -134,7 +125,6 @@ You can use the met The following example uses the `IndexOf` method to search for the first occurrence of the '`l`' character in a string. - [!code-cpp[Conceptual.String.BasicOps#13](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp#13)] [!code-csharp[Conceptual.String.BasicOps#13](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/compare.cs#13)] [!code-vb[Conceptual.String.BasicOps#13](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/compare.vb#13)] @@ -144,7 +134,6 @@ The following example uses the `IndexOf` method to search for the first occurren The following example uses the `LastIndexOf` method to search for the last occurrence of the '`l`' character in a string. - [!code-cpp[Conceptual.String.BasicOps#14](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp#14)] [!code-csharp[Conceptual.String.BasicOps#14](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/compare.cs#14)] [!code-vb[Conceptual.String.BasicOps#14](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/compare.vb#14)] diff --git a/docs/standard/base-types/custom-numeric-format-strings.md b/docs/standard/base-types/custom-numeric-format-strings.md index d92e9cc668991..b02326ca0fb78 100644 --- a/docs/standard/base-types/custom-numeric-format-strings.md +++ b/docs/standard/base-types/custom-numeric-format-strings.md @@ -6,7 +6,6 @@ ms.topic: reference dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "numeric format strings [.NET]" - "formatting [.NET], numbers" @@ -16,7 +15,6 @@ helpviewer_keywords: - "format specifiers, numeric" - "formatting numbers [.NET]" - "format specifiers, custom numeric format strings" -ms.assetid: 6f74fd32-6c6b-48ed-8241-3c2b86dea5f4 --- # Custom numeric format strings @@ -57,7 +55,6 @@ The "00" specifier causes the value to be rounded to the nearest digit preceding The following example displays several values that are formatted by using custom format strings that include zero placeholders. -[!code-cpp[Formatting.Numeric.Custom#1](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp#1)] [!code-csharp[Formatting.Numeric.Custom#1](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/custom.cs#1)] [!code-vb[Formatting.Numeric.Custom#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/Custom.vb#1)] @@ -75,13 +72,11 @@ The "##" format string causes the value to be rounded to the nearest digit prece The following example displays several values that are formatted by using custom format strings that include digit placeholders. -[!code-cpp[Formatting.Numeric.Custom#2](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp#2)] [!code-csharp[Formatting.Numeric.Custom#2](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/custom.cs#2)] [!code-vb[Formatting.Numeric.Custom#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/Custom.vb#2)] To return a result string in which absent digits or leading zeroes are replaced by spaces, use the [composite formatting feature](composite-formatting.md) and specify a field width, as the following example illustrates. -[!code-cpp[Formatting.Numeric.Custom#12](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/SpaceOrDigit1.cpp#12)] [!code-csharp[Formatting.Numeric.Custom#12](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/SpaceOrDigit1.cs#12)] [!code-vb[Formatting.Numeric.Custom#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/SpaceOrDigit1.vb#12)] @@ -97,7 +92,6 @@ The character that is used as the decimal separator in the result string is not The following example uses the "." format specifier to define the location of the decimal point in several result strings. -[!code-cpp[Formatting.Numeric.Custom#3](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp#3)] [!code-csharp[Formatting.Numeric.Custom#3](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/custom.cs#3)] [!code-vb[Formatting.Numeric.Custom#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/Custom.vb#3)] @@ -119,13 +113,11 @@ You can use group separator and number scaling specifiers in the same format str The following example illustrates the use of the comma as a group separator. -[!code-cpp[Formatting.Numeric.Custom#4](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp#4)] [!code-csharp[Formatting.Numeric.Custom#4](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/custom.cs#4)] [!code-vb[Formatting.Numeric.Custom#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/Custom.vb#4)] The following example illustrates the use of the comma as a specifier for number scaling. -[!code-cpp[Formatting.Numeric.Custom#5](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp#5)] [!code-csharp[Formatting.Numeric.Custom#5](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/custom.cs#5)] [!code-vb[Formatting.Numeric.Custom#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/Custom.vb#5)] @@ -139,7 +131,6 @@ A percent sign (%) in a format string causes a number to be multiplied by 100 be The following example defines several custom format strings that include the "%" custom specifier. -[!code-cpp[Formatting.Numeric.Custom#6](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp#6)] [!code-csharp[Formatting.Numeric.Custom#6](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/custom.cs#6)] [!code-vb[Formatting.Numeric.Custom#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/Custom.vb#6)] @@ -153,7 +144,6 @@ A per mille character (‰ or \u2030) in a format string causes a number to be m The following example defines a custom format string that includes the "‰" custom specifier. -[!code-cpp[Formatting.Numeric.Custom#9](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp#9)] [!code-csharp[Formatting.Numeric.Custom#9](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/custom.cs#9)] [!code-vb[Formatting.Numeric.Custom#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/Custom.vb#9)] @@ -167,7 +157,6 @@ If any of the strings "E", "E+", "E-", "e", "e+", or "e-" are present in the for The following example formats several numeric values using the specifiers for scientific notation. -[!code-cpp[Formatting.Numeric.Custom#7](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp#7)] [!code-csharp[Formatting.Numeric.Custom#7](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/custom.cs#7)] [!code-vb[Formatting.Numeric.Custom#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/Custom.vb#7)] @@ -188,7 +177,6 @@ To include a backslash in a result string, you must escape it with another backs The following example uses the escape character to prevent the formatting operation from interpreting the "#", "0", and "\\" characters as either escape characters or format specifiers. The C# examples uses an additional backslash to ensure that a backslash is interpreted as a literal character. -[!code-cpp[Formatting.Numeric.Custom#11](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/escape1.cpp#11)] [!code-csharp-interactive[Formatting.Numeric.Custom#11](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/escape1.cs#11)] [!code-vb[Formatting.Numeric.Custom#11](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/escape1.vb#11)] @@ -210,7 +198,6 @@ Section separators ignore any preexisting formatting associated with a number wh The following example uses the ";" format specifier to format positive, negative, and zero numbers differently. -[!code-cpp[Formatting.Numeric.Custom#8](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp#8)] [!code-csharp-interactive[Formatting.Numeric.Custom#8](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/custom.cs#8)] [!code-vb[Formatting.Numeric.Custom#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/Custom.vb#8)] @@ -274,7 +261,6 @@ For fixed-point format strings (that is, format strings that do not contain scie The following example demonstrates two custom numeric format strings. In both cases, the digit placeholder (`#`) displays the numeric data, and all other characters are copied to the result string. -[!code-cpp[Formatting.Numeric.Custom#10](../../../samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/example1.cpp#10)] [!code-csharp-interactive[Formatting.Numeric.Custom#10](../../../samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/example1.cs#10)] [!code-vb[Formatting.Numeric.Custom#10](../../../samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/example1.vb#10)] diff --git a/docs/standard/base-types/padding.md b/docs/standard/base-types/padding.md index 5dfd5938720f1..8d2b88941495b 100644 --- a/docs/standard/base-types/padding.md +++ b/docs/standard/base-types/padding.md @@ -2,47 +2,43 @@ title: "Padding Strings in .NET" description: Learn how to pad strings in .NET. Use the String.PadLeft and String.PadRight methods to add leading or trailing characters to achieve a specified total length. ms.date: "03/15/2018" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "strings [.NET], padding" - "white space" - "PadRight method" - "PadLeft method" - "padding strings" -ms.assetid: 84a9f142-3244-4c90-ba02-21af9bbaff71 --- -# Padding Strings in .NET +# Pad strings in .NET Use one of the following methods to create a new string that consists of an original string that is padded with leading or trailing characters to a specified total length. The padding character can be a space or a specified character. The resulting string appears to be either right-aligned or left-aligned. If the original string's length is already equal to or greater than the desired total length, the padding methods return the original string unchanged; for more information, see the **Returns** sections of the two overloads of the and methods. - -|Method name|Use| -|-----------------|---------| -||Pads a string with leading characters to a specified total length.| -||Pads a string with trailing characters to a specified total length.| - -## PadLeft - - The method creates a new string by concatenating enough leading pad characters to an original string to achieve a specified total length. The method uses white space as the padding character and the method enables you to specify your own padding character. - - The following code example uses the method to create a new string that is twenty characters long. The example displays "`--------Hello World!`" to the console. - - [!code-cpp[Conceptual.String.BasicOps#3](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/padding.cpp#3)] + +|Method name|Use| +|-----------------|---------| +||Pads a string with leading characters to a specified total length.| +||Pads a string with trailing characters to a specified total length.| + +## PadLeft + + The method creates a new string by concatenating enough leading pad characters to an original string to achieve a specified total length. The method uses white space as the padding character and the method enables you to specify your own padding character. + + The following code example uses the method to create a new string that is twenty characters long. The example displays "`--------Hello World!`" to the console. + [!code-csharp[Conceptual.String.BasicOps#3](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/padding.cs#3)] - [!code-vb[Conceptual.String.BasicOps#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/padding.vb#3)] - -## PadRight - - The method creates a new string by concatenating enough trailing pad characters to an original string to achieve a specified total length. The method uses white space as the padding character and the method enables you to specify your own padding character. - - The following code example uses the method to create a new string that is twenty characters long. The example displays "`Hello World!--------`" to the console. - - [!code-cpp[Conceptual.String.BasicOps#4](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/padding.cpp#4)] + [!code-vb[Conceptual.String.BasicOps#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/padding.vb#3)] + +## PadRight + + The method creates a new string by concatenating enough trailing pad characters to an original string to achieve a specified total length. The method uses white space as the padding character and the method enables you to specify your own padding character. + + The following code example uses the method to create a new string that is twenty characters long. The example displays "`Hello World!--------`" to the console. + [!code-csharp[Conceptual.String.BasicOps#4](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/padding.cs#4)] - [!code-vb[Conceptual.String.BasicOps#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/padding.vb#4)] - + [!code-vb[Conceptual.String.BasicOps#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/padding.vb#4)] + ## See also - [Basic String Operations](basic-string-operations.md) diff --git a/docs/standard/base-types/parsing-other.md b/docs/standard/base-types/parsing-other.md index ed5b0704ca7f7..e83def37fd03c 100644 --- a/docs/standard/base-types/parsing-other.md +++ b/docs/standard/base-types/parsing-other.md @@ -2,50 +2,45 @@ description: "Learn more about: Parsing Other Strings in .NET" title: "Parsing Other Strings in .NET" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "Char data type, parsing strings" - "enumerations [.NET], parsing strings" - "base types, parsing strings" - "parsing strings, other strings" - "Boolean data type, parsing strings" -ms.assetid: d139bc00-3c4e-4d78-ac9a-5c951b258d28 --- -# Parsing Other Strings in .NET +# Parse other strings in .NET -In addition to numeric and strings, you can also parse strings that represent the types , , and into data types. - -## Char +In addition to numeric and strings, you can also parse strings that represent the types , , and into data types. + +## Char + + The static parse method associated with the **Char** data type is useful for converting a string that contains a single character into its Unicode value. The following code example parses a string into a Unicode character. - The static parse method associated with the **Char** data type is useful for converting a string that contains a single character into its Unicode value. The following code example parses a string into a Unicode character. - - [!code-cpp[Conceptual.String.Parse#2](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.parse/cpp/parse.cpp#2)] [!code-csharp[Conceptual.String.Parse#2](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.parse/cs/parse.cs#2)] - [!code-vb[Conceptual.String.Parse#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.parse/vb/parse.vb#2)] - -## Boolean - - The **Boolean** data type contains a **Parse** method that you can use to convert a string that represents a Boolean value into an actual **Boolean** type. This method is not case-sensitive and can successfully parse a string containing "True" or "False." The **Parse** method associated with the **Boolean** type can also parse strings that are surrounded by white spaces. If any other string is passed, a is thrown. - - The following code example uses the **Parse** method to convert a string into a Boolean value. - - [!code-cpp[Conceptual.String.Parse#3](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.parse/cpp/parse.cpp#3)] + [!code-vb[Conceptual.String.Parse#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.parse/vb/parse.vb#2)] + +## Boolean + + The **Boolean** data type contains a **Parse** method that you can use to convert a string that represents a Boolean value into an actual **Boolean** type. This method is not case-sensitive and can successfully parse a string containing "True" or "False." The **Parse** method associated with the **Boolean** type can also parse strings that are surrounded by white spaces. If any other string is passed, a is thrown. + + The following code example uses the **Parse** method to convert a string into a Boolean value. + [!code-csharp[Conceptual.String.Parse#3](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.parse/cs/parse.cs#3)] - [!code-vb[Conceptual.String.Parse#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.parse/vb/parse.vb#3)] - -## Enumeration - - You can use the static **Parse** method to initialize an enumeration type to the value of a string. This method accepts the enumeration type you are parsing, the string to parse, and an optional Boolean flag indicating whether or not the parse is case-sensitive. The string you are parsing can contain several values separated by commas, which can be preceded or followed by one or more empty spaces (also called white spaces). When the string contains multiple values, the value of the returned object is the value of all specified values combined with a bitwise OR operation. - - The following example uses the **Parse** method to convert a string representation into an enumeration value. The enumeration is initialized to **Thursday** from a string. - - [!code-cpp[Conceptual.String.Parse#4](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.parse/cpp/parse.cpp#4)] + [!code-vb[Conceptual.String.Parse#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.parse/vb/parse.vb#3)] + +## Enumeration + + You can use the static **Parse** method to initialize an enumeration type to the value of a string. This method accepts the enumeration type you are parsing, the string to parse, and an optional Boolean flag indicating whether or not the parse is case-sensitive. The string you are parsing can contain several values separated by commas, which can be preceded or followed by one or more empty spaces (also called white spaces). When the string contains multiple values, the value of the returned object is the value of all specified values combined with a bitwise OR operation. + + The following example uses the **Parse** method to convert a string representation into an enumeration value. The enumeration is initialized to **Thursday** from a string. + [!code-csharp[Conceptual.String.Parse#4](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.parse/cs/parse.cs#4)] - [!code-vb[Conceptual.String.Parse#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.parse/vb/parse.vb#4)] - + [!code-vb[Conceptual.String.Parse#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.parse/vb/parse.vb#4)] + ## See also - [Parsing Strings](parsing-strings.md) diff --git a/docs/standard/base-types/standard-numeric-format-strings.md b/docs/standard/base-types/standard-numeric-format-strings.md index 199aca156878d..2d88f76072324 100644 --- a/docs/standard/base-types/standard-numeric-format-strings.md +++ b/docs/standard/base-types/standard-numeric-format-strings.md @@ -6,7 +6,6 @@ ms.topic: reference dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "numeric format strings [.NET]" - "formatting [.NET], numbers" @@ -74,19 +73,16 @@ A standard numeric format string can be used to define the formatting of a numer - It can be passed to the `TryFormat` method or an overload of the `ToString` method that has a `format` parameter. The following example formats a numeric value as a currency string in the current culture (in this case, the en-US culture). - [!code-cpp[Formatting.Numeric.Standard#10](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/standardusage1.cpp#10)] [!code-csharp-interactive[Formatting.Numeric.Standard#10](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/standardusage1.cs#10)] [!code-vb[Formatting.Numeric.Standard#10](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/standardusage1.vb#10)] - It can be supplied as the `formatString` argument in a format item used with such methods as , , and . For more information, see [Composite Formatting](composite-formatting.md). The following example uses a format item to insert a currency value in a string. - [!code-cpp[Formatting.Numeric.Standard#11](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/standardusage1.cpp#11)] [!code-csharp-interactive[Formatting.Numeric.Standard#11](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/standardusage1.cs#11)] [!code-vb[Formatting.Numeric.Standard#11](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/standardusage1.vb#11)] Optionally, you can supply an `alignment` argument to specify the width of the numeric field and whether its value is right- or left-aligned. The following example left-aligns a currency value in a 28-character field, and it right-aligns a currency value in a 14-character field. - [!code-cpp[Formatting.Numeric.Standard#12](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/standardusage1.cpp#12)] [!code-csharp-interactive[Formatting.Numeric.Standard#12](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/standardusage1.cs#12)] [!code-vb[Formatting.Numeric.Standard#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/standardusage1.vb#12)] @@ -126,8 +122,6 @@ The result string is affected by the formatting information of the current |Defines the number of integer digits that appear in a group.| The following example formats a value with the currency format specifier: - -[!code-cpp[Formatting.Numeric.Standard#1](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp#1)] [!code-csharp[Formatting.Numeric.Standard#1](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/Standard.cs#1)] [!code-vb[Formatting.Numeric.Standard#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb#1)] @@ -146,8 +140,6 @@ The result string is affected by the formatting information of the current |Defines the string that indicates that a number is negative.| The following example formats an value with the decimal format specifier. - -[!code-cpp[Formatting.Numeric.Standard#2](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp#2)] [!code-csharp-interactive[Formatting.Numeric.Standard#2](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/Standard.cs#2)] [!code-vb[Formatting.Numeric.Standard#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb#2)] @@ -170,8 +162,6 @@ The result string is affected by the formatting information of the current |Defines the string that indicates that an exponent is positive.| The following example formats a value with the exponential format specifier: - -[!code-cpp[Formatting.Numeric.Standard#3](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp#3)] [!code-csharp[Formatting.Numeric.Standard#3](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/Standard.cs#3)] [!code-vb[Formatting.Numeric.Standard#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb#3)] @@ -192,8 +182,6 @@ The result string is affected by the formatting information of the current |Defines the default number of decimal digits. This value can be overridden by using the precision specifier.| The following example formats a and an value with the fixed-point format specifier: - -[!code-cpp[Formatting.Numeric.Standard#4](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp#4)] [!code-csharp[Formatting.Numeric.Standard#4](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/Standard.cs#4)] [!code-vb[Formatting.Numeric.Standard#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb#4)] @@ -235,8 +223,6 @@ The result string is affected by the formatting information of the current |Defines the string that indicates that an exponent is positive.| The following example formats assorted floating-point values with the general format specifier: - -[!code-cpp[Formatting.Numeric.Standard#5](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp#5)] [!code-csharp[Formatting.Numeric.Standard#5](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/Standard.cs#5)] [!code-vb[Formatting.Numeric.Standard#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb#5)] @@ -258,8 +244,6 @@ The result string is affected by the formatting information of the current |Defines the default number of decimal digits. This value can be overridden by using a precision specifier.| The following example formats assorted floating-point values with the number format specifier: - -[!code-cpp[Formatting.Numeric.Standard#6](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp#6)] [!code-csharp[Formatting.Numeric.Standard#6](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/Standard.cs#6)] [!code-vb[Formatting.Numeric.Standard#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb#6)] @@ -283,8 +267,6 @@ The following table lists the prope ||Defines the number of integer digits that appear in a group.| The following example formats floating-point values with the percent format specifier: - -[!code-cpp[Formatting.Numeric.Standard#7](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp#7)] [!code-csharp[Formatting.Numeric.Standard#7](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/Standard.cs#7)] [!code-vb[Formatting.Numeric.Standard#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb#7)] @@ -308,8 +290,6 @@ The result string is affected by the formatting information of the current |Defines the string that indicates that an exponent is positive.| The following example formats a value with the round-trip format specifier. - -[!code-cpp[R format specifier with a BigInteger](../../../samples/snippets/standard/base-types/format-strings/biginteger-r.cpp)] [!code-csharp[R format specifier with a BigInteger](../../../samples/snippets/standard/base-types/format-strings/biginteger-r.cs)] [!code-vb[R format specifier with a BigInteger](../../../samples/snippets/standard/base-types/format-strings/biginteger-r.vb)] @@ -332,8 +312,6 @@ The precision specifier indicates the minimum number of digits desired in the re The result string is not affected by the formatting information of the current object. The following example formats values with the hexadecimal format specifier. - -[!code-cpp[Formatting.Numeric.Standard#9](../../../samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp#9)] [!code-csharp-interactive[Formatting.Numeric.Standard#9](../../../samples/snippets/csharp/VS_Snippets_CLR/Formatting.Numeric.Standard/cs/Standard.cs#9)] [!code-vb[Formatting.Numeric.Standard#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Formatting.Numeric.Standard/vb/Standard.vb#9)] diff --git a/docs/standard/base-types/stringbuilder.md b/docs/standard/base-types/stringbuilder.md index dc07b09d28c96..889f9e59f9a92 100644 --- a/docs/standard/base-types/stringbuilder.md +++ b/docs/standard/base-types/stringbuilder.md @@ -5,7 +5,6 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "Remove method" - "strings [.NET], capacities" @@ -15,7 +14,6 @@ helpviewer_keywords: - "Append method" - "Insert method" - "strings [.NET], StringBuilder object" -ms.assetid: 5c14867c-9a99-45bc-ae7f-2686700d377a --- # Using the StringBuilder Class in .NET @@ -24,30 +22,22 @@ The object is immutable. Every time you use one of the meth ## Importing the System.Text Namespace The class is found in the namespace. To avoid having to provide a fully qualified type name in your code, you can import the namespace: - - [!code-cpp[Conceptual.StringBuilder#11](../../../samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp#11)] [!code-csharp[Conceptual.StringBuilder#11](../../../samples/snippets/csharp/VS_Snippets_CLR/Conceptual.StringBuilder/cs/Example.cs#11)] [!code-vb[Conceptual.StringBuilder#11](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb#11)] ## Instantiating a StringBuilder Object You can create a new instance of the class by initializing your variable with one of the overloaded constructor methods, as illustrated in the following example. - - [!code-cpp[Conceptual.StringBuilder#1](../../../samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp#1)] [!code-csharp[Conceptual.StringBuilder#1](../../../samples/snippets/csharp/VS_Snippets_CLR/Conceptual.StringBuilder/cs/Example.cs#1)] [!code-vb[Conceptual.StringBuilder#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb#1)] ## Setting the Capacity and Length Although the is a dynamic object that allows you to expand the number of characters in the string that it encapsulates, you can specify a value for the maximum number of characters that it can hold. This value is called the capacity of the object and should not be confused with the length of the string that the current holds. For example, you might create a new instance of the class with the string "Hello", which has a length of 5, and you might specify that the object has a maximum capacity of 25. When you modify the , it does not reallocate size for itself until the capacity is reached. When this occurs, the new space is allocated automatically and the capacity is doubled. You can specify the capacity of the class using one of the overloaded constructors. The following example specifies that the `myStringBuilder` object can be expanded to a maximum of 25 spaces. - - [!code-cpp[Conceptual.StringBuilder#2](../../../samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp#2)] [!code-csharp[Conceptual.StringBuilder#2](../../../samples/snippets/csharp/VS_Snippets_CLR/Conceptual.StringBuilder/cs/Example.cs#2)] [!code-vb[Conceptual.StringBuilder#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb#2)] Additionally, you can use the read/write property to set the maximum length of your object. The following example uses the **Capacity** property to define the maximum object length. - - [!code-cpp[Conceptual.StringBuilder#3](../../../samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp#3)] [!code-csharp[Conceptual.StringBuilder#3](../../../samples/snippets/csharp/VS_Snippets_CLR/Conceptual.StringBuilder/cs/Example.cs#3)] [!code-vb[Conceptual.StringBuilder#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb#3)] @@ -70,40 +60,30 @@ The object is immutable. Every time you use one of the meth ### Append The **Append** method can be used to add text or a string representation of an object to the end of a string represented by the current **StringBuilder**. The following example initializes a **StringBuilder** to "Hello World" and then appends some text to the end of the object. Space is allocated automatically as needed. - - [!code-cpp[Conceptual.StringBuilder#4](../../../samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp#4)] [!code-csharp[Conceptual.StringBuilder#4](../../../samples/snippets/csharp/VS_Snippets_CLR/Conceptual.StringBuilder/cs/Example.cs#4)] [!code-vb[Conceptual.StringBuilder#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb#4)] ### AppendFormat The method adds text to the end of the object. It supports the [composite formatting feature](composite-formatting.md) by calling the implementation of the object or objects to be formatted. Therefore, it accepts the standard format strings for numeric, date and time, and enumeration values, the custom format strings for numeric and date and time values, and the format strings defined for custom types. (For information about formatting, see [Formatting Types](formatting-types.md).) You can use this method to customize the format of variables and append those values to a . The following example uses the method to place an integer value formatted as a currency value at the end of a object. - - [!code-cpp[Conceptual.StringBuilder#5](../../../samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp#5)] [!code-csharp[Conceptual.StringBuilder#5](../../../samples/snippets/csharp/VS_Snippets_CLR/Conceptual.StringBuilder/cs/Example.cs#5)] [!code-vb[Conceptual.StringBuilder#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb#5)] ### Insert The method adds a string or object to a specified position in the current object. The following example uses this method to insert a word into the sixth position of a object. - - [!code-cpp[Conceptual.StringBuilder#6](../../../samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp#6)] [!code-csharp[Conceptual.StringBuilder#6](../../../samples/snippets/csharp/VS_Snippets_CLR/Conceptual.StringBuilder/cs/Example.cs#6)] [!code-vb[Conceptual.StringBuilder#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb#6)] ### Remove You can use the **Remove** method to remove a specified number of characters from the current object, beginning at a specified zero-based index. The following example uses the **Remove** method to shorten a object. - - [!code-cpp[Conceptual.StringBuilder#7](../../../samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp#7)] [!code-csharp[Conceptual.StringBuilder#7](../../../samples/snippets/csharp/VS_Snippets_CLR/Conceptual.StringBuilder/cs/Example.cs#7)] [!code-vb[Conceptual.StringBuilder#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb#7)] ### Replace The **Replace** method can be used to replace characters within the object with another specified character. The following example uses the **Replace** method to search a object for all instances of the exclamation point character (!) and replace them with the question mark character (?). - - [!code-cpp[Conceptual.StringBuilder#8](../../../samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp#8)] [!code-csharp[Conceptual.StringBuilder#8](../../../samples/snippets/csharp/VS_Snippets_CLR/Conceptual.StringBuilder/cs/Example.cs#8)] [!code-vb[Conceptual.StringBuilder#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Conceptual.StringBuilder/vb/Example.vb#8)] diff --git a/docs/standard/base-types/trimming.md b/docs/standard/base-types/trimming.md index 73948aee292b3..df8c187405df3 100644 --- a/docs/standard/base-types/trimming.md +++ b/docs/standard/base-types/trimming.md @@ -3,11 +3,10 @@ title: "Trimming and Removing Characters from Strings in .NET" description: Learn to trim blank spaces from the beginning or end of a string, or remove any number of spaces or characters from a specified position in the string in .NET. ms.date: "07/22/2022" ms.custom: devdivchpfy22 -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "strings [.NET], removing characters" - "Remove method" - "TrimEnd method" @@ -15,81 +14,70 @@ helpviewer_keywords: - "trimming characters" - "TrimStart method" - "removing characters" -ms.assetid: ab248dab-70d4-4413-81c6-542d153fd195 --- # Trim and remove characters from strings in .NET If you're parsing a sentence into individual words, you might end up with words that have blank spaces (also called white spaces) on either end of the word. In this situation, you can use one of the trim methods in the `System.String` class to remove any number of spaces or other characters from a specified position in the string. The following table describes the available trim methods: - -|Method name|Use| -|-----------------|---------| -||Removes white spaces or characters specified in an array of characters from the beginning and end of a string.| -||Removes characters specified in an array of characters from the end of a string.| -||Removes characters specified in an array of characters from the beginning of a string.| -||Removes a specified number of characters from a specified index position in a string.| - + +|Method name|Use| +|-----------------|---------| +||Removes white spaces or characters specified in an array of characters from the beginning and end of a string.| +||Removes characters specified in an array of characters from the end of a string.| +||Removes characters specified in an array of characters from the beginning of a string.| +||Removes a specified number of characters from a specified index position in a string.| + ## Trim You can easily remove white spaces from both ends of a string by using the method, as shown in the following example: - - [!code-cpp[Conceptual.String.BasicOps#17](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/trimming.cpp#17)] [!code-csharp[Conceptual.String.BasicOps#17](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/trimming.cs#17)] - [!code-vb[Conceptual.String.BasicOps#17](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trimming.vb#17)] - + [!code-vb[Conceptual.String.BasicOps#17](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trimming.vb#17)] + You can also remove characters that you specify in a character array from the beginning and end of a string. The following example removes white-space characters, periods, and asterisks: - + [!code-csharp[Conceptual.String.BasicOps#22](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/trim2.cs#22)] - [!code-vb[Conceptual.String.BasicOps#22](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trim2.vb#22)] - + [!code-vb[Conceptual.String.BasicOps#22](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trim2.vb#22)] + ## TrimEnd The `String.TrimEnd` method removes characters from the end of a string, creating a new string object. An array of characters is passed to this method to specify the characters to be removed. The order of the elements in the character array doesn't affect the trim operation. The trim stops when a character not specified in the array is found. - + The following example removes the last letters of a string using the `TrimEnd` method. In this example, the position of the `'r'` character and the `'W'` character are reversed to illustrate that the order of characters in the array doesn't matter. Notice that this code removes the last word of `MyString` plus part of the first. - - [!code-cpp[Conceptual.String.BasicOps#18](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/trimming.cpp#18)] [!code-csharp[Conceptual.String.BasicOps#18](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/trimming.cs#18)] - [!code-vb[Conceptual.String.BasicOps#18](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trimming.vb#18)] - + [!code-vb[Conceptual.String.BasicOps#18](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trimming.vb#18)] + This code displays `He` to the console. - + The following example removes the last word of a string using the `TrimEnd` method. In this code, a comma follows the word `Hello` and because the comma isn't specified in the array of characters to trim, the trim ends at the comma. - - [!code-cpp[Conceptual.String.BasicOps#19](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/trimming.cpp#19)] [!code-csharp[Conceptual.String.BasicOps#19](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/trimming.cs#19)] - [!code-vb[Conceptual.String.BasicOps#19](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trimming.vb#19)] - + [!code-vb[Conceptual.String.BasicOps#19](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trimming.vb#19)] + This code displays `Hello,` to the console. - + ## TrimStart The `String.TrimStart` method is similar to the `String.TrimEnd` method except that it creates a new string by removing characters from the beginning of an existing string object. An array of characters is passed to the `TrimStart` method to specify the characters to be removed. As with the `TrimEnd` method, the order of the elements in the character array doesn't affect the trim operation. The trim stops when a character not specified in the array is found. - + The following example removes the first word of a string. In this example, the position of the `'l'` character and the `'H'` character are reversed to illustrate that the order of characters in the array doesn't matter. - - [!code-cpp[Conceptual.String.BasicOps#20](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/trimming.cpp#20)] [!code-csharp[Conceptual.String.BasicOps#20](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/trimming.cs#20)] - [!code-vb[Conceptual.String.BasicOps#20](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trimming.vb#20)] - + [!code-vb[Conceptual.String.BasicOps#20](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trimming.vb#20)] + This code displays `World!` to the console. - + ## Remove The method removes a specified number of characters that begin at a specified position in an existing string. This method assumes a zero-based index. - + The following example removes 10 characters from a string beginning at position five of a zero-based index of the string. - - [!code-cpp[Conceptual.String.BasicOps#21](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/trimming.cpp#21)] [!code-csharp[Conceptual.String.BasicOps#21](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/trimming.cs#21)] - [!code-vb[Conceptual.String.BasicOps#21](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trimming.vb#21)] - + [!code-vb[Conceptual.String.BasicOps#21](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/trimming.vb#21)] + ## Replace You can also remove a specified character or substring from a string by calling the method and specifying an empty string () as the replacement. The following example removes all commas from a string: - + [!code-csharp[Conceptual.String.BasicOps#23](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.string.basicops/cs/replace1.cs#23)] - [!code-vb[Conceptual.String.BasicOps#23](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/replace1.vb#23)] - + [!code-vb[Conceptual.String.BasicOps#23](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.string.basicops/vb/replace1.vb#23)] + ## See also - [Basic String Operations](basic-string-operations.md) diff --git a/docs/standard/data/xml/building-xml-schemas.md b/docs/standard/data/xml/building-xml-schemas.md index 7ef68fe0b216d..d5254975adbbc 100644 --- a/docs/standard/data/xml/building-xml-schemas.md +++ b/docs/standard/data/xml/building-xml-schemas.md @@ -2,89 +2,79 @@ description: "Learn more about: Building XML Schemas" title: "Building XML Schemas" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: 8a5ea56c-0140-4b51-8997-875ae6a8e0cb --- -# Building XML Schemas +# Build XML schemas -The classes in the namespace map to the structures defined in the World Wide Web Consortium (W3C) XML Schema Recommendation and can be used to build XML schemas in-memory. - -## Building an XML Schema +The classes in the namespace map to the structures defined in the World Wide Web Consortium (W3C) XML Schema Recommendation and can be used to build XML schemas in-memory. - In the code examples that follow, the SOM API is used to build a customer XML schema in-memory. - -### Creating Element and Attributes +## Building an XML Schema - The code examples build the customer schema from the bottom up, creating the child elements, attributes, and their corresponding types first, and then the top-level elements. - - In the following code example, the `FirstName` and `LastName` elements, as well as the `CustomerId` attribute of the customer schema are created using the and classes of the SOM. Apart from the properties of the and classes, which correspond to the "name" attribute of the `` and `` elements in an XML schema, all other attributes allowed by the schema (`defaultValue`, `fixedValue`, `form`, and so on) have corresponding properties in the and classes. - - [!code-cpp[XmlSchemaCreateExample#2](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaCreateExample/CPP/XmlSchemaCreateExample.cpp#2)] + In the code examples that follow, the SOM API is used to build a customer XML schema in-memory. + +### Creating Element and Attributes + + The code examples build the customer schema from the bottom up, creating the child elements, attributes, and their corresponding types first, and then the top-level elements. + + In the following code example, the `FirstName` and `LastName` elements, as well as the `CustomerId` attribute of the customer schema are created using the and classes of the SOM. Apart from the properties of the and classes, which correspond to the "name" attribute of the `` and `` elements in an XML schema, all other attributes allowed by the schema (`defaultValue`, `fixedValue`, `form`, and so on) have corresponding properties in the and classes. [!code-csharp[XmlSchemaCreateExample#2](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaCreateExample/CS/XmlSchemaCreateExample.cs#2)] - [!code-vb[XmlSchemaCreateExample#2](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaCreateExample/VB/XmlSchemaCreateExample.vb#2)] - -### Creating Schema Types + [!code-vb[XmlSchemaCreateExample#2](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaCreateExample/VB/XmlSchemaCreateExample.vb#2)] + +### Creating Schema Types + + The content of elements and attributes is defined by their types. To create elements and attributes whose types are one of the built-in schema types, the property of the or classes are set with the corresponding qualified name of the built-in type using the class. To create a user-defined type for elements and attributes, a new simple or complex type is created using the or class. - The content of elements and attributes is defined by their types. To create elements and attributes whose types are one of the built-in schema types, the property of the or classes are set with the corresponding qualified name of the built-in type using the class. To create a user-defined type for elements and attributes, a new simple or complex type is created using the or class. - > [!NOTE] -> To create unnamed simple or complex types that are anonymous children of an element or attribute (only simple types apply for attributes), set the property of the or classes to the unnamed simple or complex type, instead of the property of the or classes. - - XML schemas allow both anonymous and named simple types to be derived by restriction from other simple types (built-in or user-defined) or constructed as a list or union of other simple types. The class is used to create a simple type by restricting the built-in `xs:string` type. You can also use the or classes to create list or union types. The property denotes whether it is a simple type restriction, list, or union. - - In the following code example, the `FirstName` element's type is the built-in type `xs:string`, the `LastName` element's type is a named simple type that is a restriction of the built-in type `xs:string`, with a `MaxLength` facet value of 20, and the `CustomerId` attribute's type is the built-in type `xs:positiveInteger`. The `Customer` element is an anonymous complex type whose particle is the sequence of the `FirstName` and `LastName` elements and whose attributes contains the `CustomerId` attribute. - +> To create unnamed simple or complex types that are anonymous children of an element or attribute (only simple types apply for attributes), set the property of the or classes to the unnamed simple or complex type, instead of the property of the or classes. + + XML schemas allow both anonymous and named simple types to be derived by restriction from other simple types (built-in or user-defined) or constructed as a list or union of other simple types. The class is used to create a simple type by restricting the built-in `xs:string` type. You can also use the or classes to create list or union types. The property denotes whether it is a simple type restriction, list, or union. + + In the following code example, the `FirstName` element's type is the built-in type `xs:string`, the `LastName` element's type is a named simple type that is a restriction of the built-in type `xs:string`, with a `MaxLength` facet value of 20, and the `CustomerId` attribute's type is the built-in type `xs:positiveInteger`. The `Customer` element is an anonymous complex type whose particle is the sequence of the `FirstName` and `LastName` elements and whose attributes contains the `CustomerId` attribute. + > [!NOTE] -> You can also use the or classes as the particle of the complex type to replicate `` or `` semantics. - - [!code-cpp[XmlSchemaCreateExample#3](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaCreateExample/CPP/XmlSchemaCreateExample.cpp#3)] +> You can also use the or classes as the particle of the complex type to replicate `` or `` semantics. [!code-csharp[XmlSchemaCreateExample#3](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaCreateExample/CS/XmlSchemaCreateExample.cs#3)] - [!code-vb[XmlSchemaCreateExample#3](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaCreateExample/VB/XmlSchemaCreateExample.vb#3)] - -### Creating and Compiling Schemas + [!code-vb[XmlSchemaCreateExample#3](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaCreateExample/VB/XmlSchemaCreateExample.vb#3)] - At this point, the child elements and attributes, their corresponding types, and the top-level `Customer` element have been created in-memory using the SOM API. In the following code example, the schema element is created using the class, the top-level elements and types are added to it using the property and the complete schema is compiled using the class and written to the console. - - [!code-cpp[XmlSchemaCreateExample#4](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaCreateExample/CPP/XmlSchemaCreateExample.cpp#4)] +### Creating and Compiling Schemas + + At this point, the child elements and attributes, their corresponding types, and the top-level `Customer` element have been created in-memory using the SOM API. In the following code example, the schema element is created using the class, the top-level elements and types are added to it using the property and the complete schema is compiled using the class and written to the console. [!code-csharp[XmlSchemaCreateExample#4](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaCreateExample/CS/XmlSchemaCreateExample.cs#4)] - [!code-vb[XmlSchemaCreateExample#4](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaCreateExample/VB/XmlSchemaCreateExample.vb#4)] - - The method validates the customer schema against the rules for an XML schema and makes post-schema-compilation properties available. - + [!code-vb[XmlSchemaCreateExample#4](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaCreateExample/VB/XmlSchemaCreateExample.vb#4)] + + The method validates the customer schema against the rules for an XML schema and makes post-schema-compilation properties available. + > [!NOTE] -> All post-schema-compilation properties in the SOM API differ from the Post-Schema-Validation-Infoset. - - The added to the is a delegate that calls the callback method `ValidationCallback` to handle schema validation warnings and errors. - - The following is the complete code example, and the customer schema written to the console. - - [!code-cpp[XmlSchemaCreateExample#1](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaCreateExample/CPP/XmlSchemaCreateExample.cpp#1)] +> All post-schema-compilation properties in the SOM API differ from the Post-Schema-Validation-Infoset. + + The added to the is a delegate that calls the callback method `ValidationCallback` to handle schema validation warnings and errors. + + The following is the complete code example, and the customer schema written to the console. [!code-csharp[XmlSchemaCreateExample#1](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaCreateExample/CS/XmlSchemaCreateExample.cs#1)] - [!code-vb[XmlSchemaCreateExample#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaCreateExample/VB/XmlSchemaCreateExample.vb#1)] - -```xml - - - - - - - - - - - - - - - - - -``` - + [!code-vb[XmlSchemaCreateExample#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaCreateExample/VB/XmlSchemaCreateExample.vb#1)] + +```xml + + + + + + + + + + + + + + + + + +``` + ## See also - [XML Schema Object Model Overview](xml-schema-object-model-overview.md) diff --git a/docs/standard/data/xml/editing-xml-schemas.md b/docs/standard/data/xml/editing-xml-schemas.md index b8cc7b133a7fa..b456994d8a949 100644 --- a/docs/standard/data/xml/editing-xml-schemas.md +++ b/docs/standard/data/xml/editing-xml-schemas.md @@ -5,10 +5,8 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: fa09c8e5-c2b9-49d2-bb0d-40330cd13e4d --- -# Editing XML Schemas +# Edit XML schemas Editing an XML schema is one of the most important features of the Schema Object Model (SOM). All of the pre-schema-compilation properties of the SOM can be used to change the existing values in an XML schema. The XML schema can then be recompiled to reflect the changes. @@ -37,8 +35,6 @@ This first code example adds a new `PhoneNumber` element to the `Customer` eleme 7. Finally, reprocesses and compiles the modified object using the and methods of the class and writes it to the console. The following is the complete code example. - -[!code-cpp[XmlSchemaEditExample1#1](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaEditExample1/CPP/XmlSchemaEditExample1.cpp#1)] [!code-csharp[XmlSchemaEditExample1#1](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaEditExample1/CS/XmlSchemaEditExample1.cs#1)] [!code-vb[XmlSchemaEditExample1#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaEditExample1/VB/XmlSchemaEditExample1.vb#1)] @@ -101,8 +97,6 @@ The code example edits the customer schema in the following steps. 4. Finally, reprocesses and compiles the modified object using the and methods of the class and writes it to the console. The following is the complete code example. - -[!code-cpp[XmlSchemaEditExample2#1](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaEditExample2/CPP/XmlSchemaEditExample2.cpp#1)] [!code-csharp[XmlSchemaEditExample2#1](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaEditExample2/CS/XmlSchemaEditExample2.cs#1)] [!code-vb[XmlSchemaEditExample2#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaEditExample2/VB/XmlSchemaEditExample2.vb#1)] diff --git a/docs/standard/data/xml/including-or-importing-xml-schemas.md b/docs/standard/data/xml/including-or-importing-xml-schemas.md index c99b5dbef5daf..16a8c3d79ecd0 100644 --- a/docs/standard/data/xml/including-or-importing-xml-schemas.md +++ b/docs/standard/data/xml/including-or-importing-xml-schemas.md @@ -2,97 +2,93 @@ description: "Learn more about: Including or Importing XML Schemas" title: "Including or Importing XML Schemas" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: fe1b4a11-37f4-4e1a-93c9-239f4fe736c0 --- -# Including or Importing XML Schemas +# Include or import XML schemas -An XML schema may contain ``, ``, and `` elements. These schema elements refer to other XML schemas that can be used to supplement the structure of the schema that includes or imports them. The , and classes, map to these elements in the Schema Object Model (SOM) API. - -## Including or Importing an XML Schema +An XML schema may contain ``, ``, and `` elements. These schema elements refer to other XML schemas that can be used to supplement the structure of the schema that includes or imports them. The , and classes, map to these elements in the Schema Object Model (SOM) API. - The following code example supplements the customer schema created in the [Building XML Schemas](building-xml-schemas.md) topic with the address schema. Supplementing the customer schema with the address schema makes address types available in the customer schema. - - The address schema can be incorporated using either `` or `` elements to use the components of the address schema as-is, or using an `` element to modify any of its components to suit the need of the customer schema. Because the address schema has a `targetNamespace` that is different from that of the customer schema, the `` element and therefore import semantics is used. - - The code example includes the address schema in the following steps. - -1. Adds the customer schema and the address schema to a new object and then compiles them. Any schema validation warnings and errors encountered reading or compiling the schemas are handled by the delegate. - -2. Retrieves the compiled objects for both the customer and address schemas from the by iterating over the property. Because the schemas are compiled, Post-Schema-Compilation-Infoset (PSCI) properties are accessible. - -3. Creates an object, sets the property of the import to the namespace of the address schema, sets the property of the import to the object of the address schema, and adds the import to the property of the customer schema. - -4. Reprocesses and compiles the modified object of the customer schema using the and methods of the class and writes it to the console. - -5. Finally, recursively writes all of the schemas imported into the customer schema to the console using the property of the customer schema. The property provides access to all the includes, imports, or redefines added to a schema. - - The following is the complete code example and the customer and address schemas written to the console. - - [!code-cpp[XmlSchemaImportExample#1](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaImportExample/CPP/XmlSchemaImportExample.cpp#1)] +## Including or Importing an XML Schema + + The following code example supplements the customer schema created in the [Building XML Schemas](building-xml-schemas.md) topic with the address schema. Supplementing the customer schema with the address schema makes address types available in the customer schema. + + The address schema can be incorporated using either `` or `` elements to use the components of the address schema as-is, or using an `` element to modify any of its components to suit the need of the customer schema. Because the address schema has a `targetNamespace` that is different from that of the customer schema, the `` element and therefore import semantics is used. + + The code example includes the address schema in the following steps. + +1. Adds the customer schema and the address schema to a new object and then compiles them. Any schema validation warnings and errors encountered reading or compiling the schemas are handled by the delegate. + +2. Retrieves the compiled objects for both the customer and address schemas from the by iterating over the property. Because the schemas are compiled, Post-Schema-Compilation-Infoset (PSCI) properties are accessible. + +3. Creates an object, sets the property of the import to the namespace of the address schema, sets the property of the import to the object of the address schema, and adds the import to the property of the customer schema. + +4. Reprocesses and compiles the modified object of the customer schema using the and methods of the class and writes it to the console. + +5. Finally, recursively writes all of the schemas imported into the customer schema to the console using the property of the customer schema. The property provides access to all the includes, imports, or redefines added to a schema. + + The following is the complete code example and the customer and address schemas written to the console. [!code-csharp[XmlSchemaImportExample#1](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaImportExample/CS/XmlSchemaImportExample.cs#1)] - [!code-vb[XmlSchemaImportExample#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaImportExample/VB/XmlSchemaImportExample.vb#1)] - -```xml - - - - - - - - - - - - - - - - - - - - - - Addresses for International Purchase order schema - Copyright 2000 Example.com. All rights reserved. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -``` - - For more information about the ``, ``, and `` elements and the , and classes, see the [W3C XML Schema](https://www.w3.org/XML/Schema) and the namespace class reference documentation. - + [!code-vb[XmlSchemaImportExample#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaImportExample/VB/XmlSchemaImportExample.vb#1)] + +```xml + + + + + + + + + + + + + + + + + + + + + + Addresses for International Purchase order schema + Copyright 2000 Example.com. All rights reserved. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + + For more information about the ``, ``, and `` elements and the , and classes, see the [W3C XML Schema](https://www.w3.org/XML/Schema) and the namespace class reference documentation. + ## See also - [XML Schema Object Model Overview](xml-schema-object-model-overview.md) diff --git a/docs/standard/data/xml/inferring-schemas-from-xml-documents.md b/docs/standard/data/xml/inferring-schemas-from-xml-documents.md index 2402a83e5650a..8a8ac504b3586 100644 --- a/docs/standard/data/xml/inferring-schemas-from-xml-documents.md +++ b/docs/standard/data/xml/inferring-schemas-from-xml-documents.md @@ -2,83 +2,79 @@ description: "Learn more about: Inferring Schemas from XML Documents" title: "Inferring Schemas from XML Documents" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: f3d97d53-614d-4a04-a174-87965b7405f6 --- -# Inferring Schemas from XML Documents - -This topic describes how to use the class to infer an XML Schema definition language (XSD) schema from the structure of an XML document. - -## The Schema Inference Process - - The class of the namespace is used to generate one or more XML Schema definition language (XSD) schemas from the structure of an XML document. The generated schemas may be used to validate the original XML document. - - As an XML document is processed by the class, the class makes assumptions about the schema components that describe the elements and attributes in the XML document. The class also infers schema components in a constrained way by inferring the most restrictive type for a particular element or attribute. As more information about the XML document is gathered, these constraints are loosened by inferring less restrictive types. The least restrictive type that can be inferred is `xs:string`. - - Take, for example, the following piece of an XML document. - -```xml - - One - Two - +# Infer schemas from XML documents + +This topic describes how to use the class to infer an XML Schema definition language (XSD) schema from the structure of an XML document. + +## The Schema Inference Process + + The class of the namespace is used to generate one or more XML Schema definition language (XSD) schemas from the structure of an XML document. The generated schemas may be used to validate the original XML document. + + As an XML document is processed by the class, the class makes assumptions about the schema components that describe the elements and attributes in the XML document. The class also infers schema components in a constrained way by inferring the most restrictive type for a particular element or attribute. As more information about the XML document is gathered, these constraints are loosened by inferring less restrictive types. The least restrictive type that can be inferred is `xs:string`. + + Take, for example, the following piece of an XML document. + +```xml + + One + Two + -``` - - In the example above, when the `attribute1` attribute is encountered with a value of `6` by the process, it is assumed to be of type `xs:unsignedByte`. When the second `parent` element is encountered by the process, the constraint is loosened by modifying the type to `xs:string` because the value of the `attribute1` attribute is now `A`. Similarly, the `minOccurs` attribute for all the `child` elements inferred in the schema are loosened to `minOccurs="0"` because the second parent element has no child elements. - -## Inferring Schemas from XML Documents - - The class uses two overloaded methods to infer a schema from an XML document. - - The first method is used to create a schema based on an XML document. The second method is used to infer a schema that describes multiple XML documents. For example, you can feed multiple XML documents to the method one at a time to produce a schema that describes the entire set of XML documents. - - The first method infers a schema from an XML document contained in an object, and returns an object containing the inferred schema. The second method searches an object for a schema with the same target namespace as the XML document contained in the object, refines the existing schema, and returns an object containing the inferred schema. - - The changes made to the refined schema are based on new structure found in the XML document. For example, as an XML document is traversed, assumptions are made about the data types found, and the schema is created based on those assumptions. However, if data is encountered on a second inference pass that differs from the original assumption, the schema is refined. The following example illustrates the refinement process. - - [!code-cpp[XmlSchemaInferenceExamples#4](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaInferenceExamples/CPP/XmlSchemaInferenceExamples.cpp#4)] +``` + + In the example above, when the `attribute1` attribute is encountered with a value of `6` by the process, it is assumed to be of type `xs:unsignedByte`. When the second `parent` element is encountered by the process, the constraint is loosened by modifying the type to `xs:string` because the value of the `attribute1` attribute is now `A`. Similarly, the `minOccurs` attribute for all the `child` elements inferred in the schema are loosened to `minOccurs="0"` because the second parent element has no child elements. + +## Inferring Schemas from XML Documents + + The class uses two overloaded methods to infer a schema from an XML document. + + The first method is used to create a schema based on an XML document. The second method is used to infer a schema that describes multiple XML documents. For example, you can feed multiple XML documents to the method one at a time to produce a schema that describes the entire set of XML documents. + + The first method infers a schema from an XML document contained in an object, and returns an object containing the inferred schema. The second method searches an object for a schema with the same target namespace as the XML document contained in the object, refines the existing schema, and returns an object containing the inferred schema. + + The changes made to the refined schema are based on new structure found in the XML document. For example, as an XML document is traversed, assumptions are made about the data types found, and the schema is created based on those assumptions. However, if data is encountered on a second inference pass that differs from the original assumption, the schema is refined. The following example illustrates the refinement process. [!code-csharp[XmlSchemaInferenceExamples#4](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaInferenceExamples/CS/XmlSchemaInferenceExamples.cs#4)] - [!code-vb[XmlSchemaInferenceExamples#4](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaInferenceExamples/VB/XmlSchemaInferenceExamples.vb#4)] - - The example takes the following file, `item1.xml`, as its first input. - - [!code-xml[XmlSchemaInferenceExamples#13](../../../../samples/snippets/xml/VS_Snippets_Data/XmlSchemaInferenceExamples/XML/item1.xml#13)] - - The example then takes the `item2.xml` file as its second input: - - [!code-xml[XmlSchemaInferenceExamples#14](../../../../samples/snippets/xml/VS_Snippets_Data/XmlSchemaInferenceExamples/XML/item2.xml#14)] - - When the `productID` attribute is encountered in the first XML document, the value of `123456789` is assumed to be an `xs:unsignedInt` type. However, when the second XML document is read and the value of `A53-246` is found, the `xs:unsignedInt` type can no longer be assumed. The schema is refined and the type of `productID` is changed to `xs:string`. In addition, the `minOccurs` attribute for the `supplierID` element is set to `0`, because the second XML document contains no `supplierID` element. - - The following is the schema inferred from the first XML document. - - [!code-xml[XmlSchemaInferenceExamples#15](../../../../samples/snippets/xml/VS_Snippets_Data/XmlSchemaInferenceExamples/XML/InferSchema1.xml#15)] - - The following is the schema inferred from the first XML document, refined by the second XML document. - - [!code-xml[XmlSchemaInferenceExamples#16](../../../../samples/snippets/xml/VS_Snippets_Data/XmlSchemaInferenceExamples/XML/InferSchema2.xml#16)] - -## Inline Schemas - - If an inline XML Schema definition language (XSD) schema is encountered during the process, an is thrown. For example, the following inline schema throws an . - -```xml - - - - - Test - -``` - -## Schemas that Cannot be Refined - - There are W3C XML Schema constructs that the XML Schema definition language (XSD) schema process cannot handle if given a type to refine and cause an exception to be thrown. Such as a complex type whose top-level compositor is anything other than a sequence. In the Schema Object Model (SOM), this corresponds to an whose property is not an instance of . - + [!code-vb[XmlSchemaInferenceExamples#4](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaInferenceExamples/VB/XmlSchemaInferenceExamples.vb#4)] + + The example takes the following file, `item1.xml`, as its first input. + + [!code-xml[XmlSchemaInferenceExamples#13](../../../../samples/snippets/xml/VS_Snippets_Data/XmlSchemaInferenceExamples/XML/item1.xml#13)] + + The example then takes the `item2.xml` file as its second input: + + [!code-xml[XmlSchemaInferenceExamples#14](../../../../samples/snippets/xml/VS_Snippets_Data/XmlSchemaInferenceExamples/XML/item2.xml#14)] + + When the `productID` attribute is encountered in the first XML document, the value of `123456789` is assumed to be an `xs:unsignedInt` type. However, when the second XML document is read and the value of `A53-246` is found, the `xs:unsignedInt` type can no longer be assumed. The schema is refined and the type of `productID` is changed to `xs:string`. In addition, the `minOccurs` attribute for the `supplierID` element is set to `0`, because the second XML document contains no `supplierID` element. + + The following is the schema inferred from the first XML document. + + [!code-xml[XmlSchemaInferenceExamples#15](../../../../samples/snippets/xml/VS_Snippets_Data/XmlSchemaInferenceExamples/XML/InferSchema1.xml#15)] + + The following is the schema inferred from the first XML document, refined by the second XML document. + + [!code-xml[XmlSchemaInferenceExamples#16](../../../../samples/snippets/xml/VS_Snippets_Data/XmlSchemaInferenceExamples/XML/InferSchema2.xml#16)] + +## Inline Schemas + + If an inline XML Schema definition language (XSD) schema is encountered during the process, an is thrown. For example, the following inline schema throws an . + +```xml + + + + + Test + +``` + +## Schemas that Cannot be Refined + + There are W3C XML Schema constructs that the XML Schema definition language (XSD) schema process cannot handle if given a type to refine and cause an exception to be thrown. Such as a complex type whose top-level compositor is anything other than a sequence. In the Schema Object Model (SOM), this corresponds to an whose property is not an instance of . + ## See also - diff --git a/docs/standard/data/xml/insert-xml-data-using-xpathnavigator.md b/docs/standard/data/xml/insert-xml-data-using-xpathnavigator.md index 6d19ef35e6f8f..650007d1f4e1a 100644 --- a/docs/standard/data/xml/insert-xml-data-using-xpathnavigator.md +++ b/docs/standard/data/xml/insert-xml-data-using-xpathnavigator.md @@ -2,341 +2,331 @@ description: "Learn more about: Insert XML Data using XPathNavigator" title: "Insert XML Data using XPathNavigator" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: 2ed8c28b-b88d-4be7-9c87-92df01f0821f --- -# Insert XML Data using XPathNavigator - -The class provides a set of methods used to insert sibling, child, and attribute nodes in an XML document. In order to use these methods, the object must be editable, that is, its property must be `true`. - - objects that can edit an XML document are created by the method of the class. objects created by the class are read-only and any attempt to use the editing methods of an object created by an object results in a . - - For more information about creating editable objects, see [Reading XML Data using XPathDocument and XmlDocument](reading-xml-data-using-xpathdocument-and-xmldocument.md). - -## Inserting Nodes - - The class provides methods to insert sibling, child, and attribute nodes in an XML document. These methods allow you to insert nodes and attributes in different locations in relation to the current position of an object and are described in the following sections. - -### Inserting Sibling Nodes - - The class provides the following methods to insert sibling nodes. - -- - -- - -- - -- - - These methods insert sibling nodes before and after the node an object is currently positioned on. - - The and methods are overloaded and accept a `string`, object, or object containing the sibling node to add as parameters. Both methods also return an object used to insert sibling nodes. - - The and methods insert a single sibling node before and after the node an object is currently positioned on using the namespace prefix, local name, namespace URI, and value specified as parameters. - - In the following example a new `pages` element is inserted before the `price` child element of the first `book` element in the `contosoBooks.xml` file. - - [!code-cpp[XPathNavigatorMethods#19](../../../../samples/snippets/cpp/VS_Snippets_Data/XPathNavigatorMethods/CPP/xpathnavigatormethods.cpp#19)] +# Insert XML data using XPathNavigator + +The class provides a set of methods used to insert sibling, child, and attribute nodes in an XML document. In order to use these methods, the object must be editable, that is, its property must be `true`. + + objects that can edit an XML document are created by the method of the class. objects created by the class are read-only and any attempt to use the editing methods of an object created by an object results in a . + + For more information about creating editable objects, see [Reading XML Data using XPathDocument and XmlDocument](reading-xml-data-using-xpathdocument-and-xmldocument.md). + +## Inserting Nodes + + The class provides methods to insert sibling, child, and attribute nodes in an XML document. These methods allow you to insert nodes and attributes in different locations in relation to the current position of an object and are described in the following sections. + +### Inserting Sibling Nodes + + The class provides the following methods to insert sibling nodes. + +- + +- + +- + +- + + These methods insert sibling nodes before and after the node an object is currently positioned on. + + The and methods are overloaded and accept a `string`, object, or object containing the sibling node to add as parameters. Both methods also return an object used to insert sibling nodes. + + The and methods insert a single sibling node before and after the node an object is currently positioned on using the namespace prefix, local name, namespace URI, and value specified as parameters. + + In the following example a new `pages` element is inserted before the `price` child element of the first `book` element in the `contosoBooks.xml` file. [!code-csharp[XPathNavigatorMethods#19](../../../../samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs#19)] - [!code-vb[XPathNavigatorMethods#19](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XPathNavigatorMethods/VB/xpathnavigatormethods.vb#19)] - - The example takes the `contosoBooks.xml` file as an input. - - [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] - - For more information about the , , and methods, see the class reference documentation. - -### Inserting Child Nodes - - The class provides the following methods to insert child nodes. - -- - -- - -- - -- - - These methods append and prepend child nodes to the end of and the beginning of the list of child nodes of the node an object is currently positioned on. - - Like the methods in the "Inserting Sibling Nodes" section, the and methods accept a `string`, object, or object containing the child node to add as parameters. Both methods also return an object used to insert child nodes. - - Also like the methods in the "Inserting Sibling Nodes" section, the and methods insert a single child node to the end of and the beginning of the list of child nodes of the node an object is currently positioned on using the namespace prefix, local name, namespace URI, and value specified as parameters. - - In the following example, a new `pages` child element is appended to the list of child elements of the first `book` element in the `contosoBooks.xml` file. - - [!code-cpp[XPathNavigatorMethods#2](../../../../samples/snippets/cpp/VS_Snippets_Data/XPathNavigatorMethods/CPP/xpathnavigatormethods.cpp#2)] + [!code-vb[XPathNavigatorMethods#19](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XPathNavigatorMethods/VB/xpathnavigatormethods.vb#19)] + + The example takes the `contosoBooks.xml` file as an input. + + [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] + + For more information about the , , and methods, see the class reference documentation. + +### Inserting Child Nodes + + The class provides the following methods to insert child nodes. + +- + +- + +- + +- + + These methods append and prepend child nodes to the end of and the beginning of the list of child nodes of the node an object is currently positioned on. + + Like the methods in the "Inserting Sibling Nodes" section, the and methods accept a `string`, object, or object containing the child node to add as parameters. Both methods also return an object used to insert child nodes. + + Also like the methods in the "Inserting Sibling Nodes" section, the and methods insert a single child node to the end of and the beginning of the list of child nodes of the node an object is currently positioned on using the namespace prefix, local name, namespace URI, and value specified as parameters. + + In the following example, a new `pages` child element is appended to the list of child elements of the first `book` element in the `contosoBooks.xml` file. [!code-csharp[XPathNavigatorMethods#2](../../../../samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs#2)] - [!code-vb[XPathNavigatorMethods#2](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XPathNavigatorMethods/VB/xpathnavigatormethods.vb#2)] - - The example takes the `contosoBooks.xml` file as an input. - - [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] - - For more information about the , , and methods, see the class reference documentation. - -### Inserting Attribute Nodes - - The class provides the following methods to insert attribute nodes. - -- - -- - - These methods insert attribute nodes on the element node an object is currently positioned on. The method creates an attribute node on the element node an object is currently positioned on using the namespace prefix, local name, namespace URI, and value specified as parameters. The method returns an object used to insert attribute nodes. - - In the following example, new `discount` and `currency` attributes are created on the `price` child element of the first `book` element in the `contosoBooks.xml` file using the object returned from the method. - - [!code-cpp[XPathNavigatorMethods#8](../../../../samples/snippets/cpp/VS_Snippets_Data/XPathNavigatorMethods/CPP/xpathnavigatormethods.cpp#8)] + [!code-vb[XPathNavigatorMethods#2](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XPathNavigatorMethods/VB/xpathnavigatormethods.vb#2)] + + The example takes the `contosoBooks.xml` file as an input. + + [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] + + For more information about the , , and methods, see the class reference documentation. + +### Inserting Attribute Nodes + + The class provides the following methods to insert attribute nodes. + +- + +- + + These methods insert attribute nodes on the element node an object is currently positioned on. The method creates an attribute node on the element node an object is currently positioned on using the namespace prefix, local name, namespace URI, and value specified as parameters. The method returns an object used to insert attribute nodes. + + In the following example, new `discount` and `currency` attributes are created on the `price` child element of the first `book` element in the `contosoBooks.xml` file using the object returned from the method. [!code-csharp[XPathNavigatorMethods#8](../../../../samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs#8)] - [!code-vb[XPathNavigatorMethods#8](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XPathNavigatorMethods/VB/xpathnavigatormethods.vb#8)] - - The example takes the `contosoBooks.xml` file as an input. - - [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] - - For more information about the and methods, see the class reference documentation. - -## Copying Nodes - - In certain cases you may want to populate an XML document with the contents from another XML document. Both the class and the class can copy nodes to an object from an existing object or object. - - The , , and methods of the class all have overloads that can accept an object or an object as a parameter. - - The method of the class has overloads that can accept an , , or object. - - The following example copies all the `book` elements from one document to another. - -```vb -Dim document As XmlDocument = New XmlDocument() -document.Load("books.xml") -Dim navigator As XPathNavigator = document.CreateNavigator() - -navigator.MoveToChild("bookstore", String.Empty) - -Dim newBooks As XPathDocument = New XPathDocument("newBooks.xml") -Dim newBooksNavigator As XPathNavigator = newBooks.CreateNavigator() - -Dim nav As XPathNavigator -For Each nav in newBooksNavigator.SelectDescendants("book", "", false) - navigator.AppendChild(nav) -Next - -document.Save("newBooks.xml"); -``` - -```csharp -XmlDocument document = new XmlDocument(); -document.Load("books.xml"); -XPathNavigator navigator = document.CreateNavigator(); - -navigator.MoveToChild("bookstore", String.Empty); - -XPathDocument newBooks = new XPathDocument("newBooks.xml"); -XPathNavigator newBooksNavigator = newBooks.CreateNavigator(); - -foreach (XPathNavigator nav in newBooksNavigator.SelectDescendants("book", "", false)) -{ - navigator.AppendChild(nav); -} - -document.Save("newBooks.xml"); -``` - -## Inserting Values - - The class provides the and methods to insert values for a node into an object. - -### Inserting Untyped Values - - The method simply inserts the untyped `string` value passed as a parameter as the value of the node the object is currently positioned on. The value is inserted without any type or without verifying that the new value is valid according to the type of the node if schema information is available. - - In the following example, the method is used to update all `price` elements in the `contosoBooks.xml` file. - - [!code-cpp[XPathNavigatorMethods#47](../../../../samples/snippets/cpp/VS_Snippets_Data/XPathNavigatorMethods/CPP/xpathnavigatormethods.cpp#47)] + [!code-vb[XPathNavigatorMethods#8](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XPathNavigatorMethods/VB/xpathnavigatormethods.vb#8)] + + The example takes the `contosoBooks.xml` file as an input. + + [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] + + For more information about the and methods, see the class reference documentation. + +## Copying Nodes + + In certain cases you may want to populate an XML document with the contents from another XML document. Both the class and the class can copy nodes to an object from an existing object or object. + + The , , and methods of the class all have overloads that can accept an object or an object as a parameter. + + The method of the class has overloads that can accept an , , or object. + + The following example copies all the `book` elements from one document to another. + +```vb +Dim document As XmlDocument = New XmlDocument() +document.Load("books.xml") +Dim navigator As XPathNavigator = document.CreateNavigator() + +navigator.MoveToChild("bookstore", String.Empty) + +Dim newBooks As XPathDocument = New XPathDocument("newBooks.xml") +Dim newBooksNavigator As XPathNavigator = newBooks.CreateNavigator() + +Dim nav As XPathNavigator +For Each nav in newBooksNavigator.SelectDescendants("book", "", false) + navigator.AppendChild(nav) +Next + +document.Save("newBooks.xml"); +``` + +```csharp +XmlDocument document = new XmlDocument(); +document.Load("books.xml"); +XPathNavigator navigator = document.CreateNavigator(); + +navigator.MoveToChild("bookstore", String.Empty); + +XPathDocument newBooks = new XPathDocument("newBooks.xml"); +XPathNavigator newBooksNavigator = newBooks.CreateNavigator(); + +foreach (XPathNavigator nav in newBooksNavigator.SelectDescendants("book", "", false)) +{ + navigator.AppendChild(nav); +} + +document.Save("newBooks.xml"); +``` + +## Inserting Values + + The class provides the and methods to insert values for a node into an object. + +### Inserting Untyped Values + + The method simply inserts the untyped `string` value passed as a parameter as the value of the node the object is currently positioned on. The value is inserted without any type or without verifying that the new value is valid according to the type of the node if schema information is available. + + In the following example, the method is used to update all `price` elements in the `contosoBooks.xml` file. [!code-csharp[XPathNavigatorMethods#47](../../../../samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs#47)] - [!code-vb[XPathNavigatorMethods#47](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XPathNavigatorMethods/VB/xpathnavigatormethods.vb#47)] - - The example takes the `contosoBooks.xml` file as an input. - - [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] - -### Inserting Typed Values - - When the type of a node is a W3C XML Schema simple type, the new value inserted by the method is checked against the facets of the simple type before the value is set. If the new value is not valid according to the type of the node (for example, setting a value of `-1` on an element whose type is `xs:positiveInteger`), it results in an exception. - - The following example attempts to change the value of the `price` element of the first `book` element in the `contosoBooks.xml` file to a value. Because the XML Schema type of the `price` element is defined as `xs:decimal` in the `contosoBooks.xsd` files, this results in an exception. - -```vb -Dim settings As XmlReaderSettings = New XmlReaderSettings() -settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd") -settings.ValidationType = ValidationType.Schema - -Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings) - -Dim document As XmlDocument = New XmlDocument() -document.Load(reader) -Dim navigator As XPathNavigator = document.CreateNavigator() - -navigator.MoveToChild("bookstore", "http://www.contoso.com/books") -navigator.MoveToChild("book", "http://www.contoso.com/books") -navigator.MoveToChild("price", "http://www.contoso.com/books") - -navigator.SetTypedValue(DateTime.Now) -``` - -```csharp -XmlReaderSettings settings = new XmlReaderSettings(); -settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd"); -settings.ValidationType = ValidationType.Schema; - -XmlReader reader = XmlReader.Create("contosoBooks.xml", settings); - -XmlDocument document = new XmlDocument(); -document.Load(reader); -XPathNavigator navigator = document.CreateNavigator(); - -navigator.MoveToChild("bookstore", "http://www.contoso.com/books"); -navigator.MoveToChild("book", "http://www.contoso.com/books"); -navigator.MoveToChild("price", "http://www.contoso.com/books"); - -navigator.SetTypedValue(DateTime.Now); -``` - - The example takes the `contosoBooks.xml` file as an input. - - [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] - - The example also takes the `contosoBooks.xsd` as an input. - - [!code-xml[XPathXMLExamples#3](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xsd#3)] - -## The InnerXml and OuterXml Properties - - The and properties of the class change the XML markup of the nodes an object is currently positioned on. - - The property changes the XML markup of the child nodes an object is currently positioned on with the parsed contents of the given XML `string`. Similarly, the property changes the XML markup of the child nodes an object is currently positioned on as well as the current node itself. - - In addition to the methods described in this topic, the and properties can be used to insert nodes and values in an XML document. For more information about using the and properties to insert nodes and values, see the [Modify XML Data using XPathNavigator](modify-xml-data-using-xpathnavigator.md) topic. - -## Namespace and xml:lang Conflicts - - Certain conflicts related to the scope of namespace and `xml:lang` declarations can occur when inserting XML data using the , , and methods of the class that take objects as parameters. - - The following are the possible namespace conflicts. - -- If there is a namespace in-scope within the object's context, where the prefix to namespace URI mapping is not in the object's context, a new namespace declaration is added to the newly inserted node. - -- If the same namespace URI is in-scope within both the object's context and the object's context, but has a different prefix mapped to it in both contexts, a new namespace declaration is added to the newly inserted node, with the prefix and namespace URI taken from the object. - -- If the same namespace prefix is in-scope within both the object's context and the object's context, but has a different namespace URI mapped to it in both contexts, a new namespace declaration is added to the newly inserted node which re-declares that prefix with the namespace URI taken from object. - -- If the prefix as well as the namespace URI in both the object's context and the object's context is the same, no new namespace declaration is added to the newly inserted node. - + [!code-vb[XPathNavigatorMethods#47](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XPathNavigatorMethods/VB/xpathnavigatormethods.vb#47)] + + The example takes the `contosoBooks.xml` file as an input. + + [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] + +### Inserting Typed Values + + When the type of a node is a W3C XML Schema simple type, the new value inserted by the method is checked against the facets of the simple type before the value is set. If the new value is not valid according to the type of the node (for example, setting a value of `-1` on an element whose type is `xs:positiveInteger`), it results in an exception. + + The following example attempts to change the value of the `price` element of the first `book` element in the `contosoBooks.xml` file to a value. Because the XML Schema type of the `price` element is defined as `xs:decimal` in the `contosoBooks.xsd` files, this results in an exception. + +```vb +Dim settings As XmlReaderSettings = New XmlReaderSettings() +settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd") +settings.ValidationType = ValidationType.Schema + +Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings) + +Dim document As XmlDocument = New XmlDocument() +document.Load(reader) +Dim navigator As XPathNavigator = document.CreateNavigator() + +navigator.MoveToChild("bookstore", "http://www.contoso.com/books") +navigator.MoveToChild("book", "http://www.contoso.com/books") +navigator.MoveToChild("price", "http://www.contoso.com/books") + +navigator.SetTypedValue(DateTime.Now) +``` + +```csharp +XmlReaderSettings settings = new XmlReaderSettings(); +settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd"); +settings.ValidationType = ValidationType.Schema; + +XmlReader reader = XmlReader.Create("contosoBooks.xml", settings); + +XmlDocument document = new XmlDocument(); +document.Load(reader); +XPathNavigator navigator = document.CreateNavigator(); + +navigator.MoveToChild("bookstore", "http://www.contoso.com/books"); +navigator.MoveToChild("book", "http://www.contoso.com/books"); +navigator.MoveToChild("price", "http://www.contoso.com/books"); + +navigator.SetTypedValue(DateTime.Now); +``` + + The example takes the `contosoBooks.xml` file as an input. + + [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] + + The example also takes the `contosoBooks.xsd` as an input. + + [!code-xml[XPathXMLExamples#3](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xsd#3)] + +## The InnerXml and OuterXml Properties + + The and properties of the class change the XML markup of the nodes an object is currently positioned on. + + The property changes the XML markup of the child nodes an object is currently positioned on with the parsed contents of the given XML `string`. Similarly, the property changes the XML markup of the child nodes an object is currently positioned on as well as the current node itself. + + In addition to the methods described in this topic, the and properties can be used to insert nodes and values in an XML document. For more information about using the and properties to insert nodes and values, see the [Modify XML Data using XPathNavigator](modify-xml-data-using-xpathnavigator.md) topic. + +## Namespace and xml:lang Conflicts + + Certain conflicts related to the scope of namespace and `xml:lang` declarations can occur when inserting XML data using the , , and methods of the class that take objects as parameters. + + The following are the possible namespace conflicts. + +- If there is a namespace in-scope within the object's context, where the prefix to namespace URI mapping is not in the object's context, a new namespace declaration is added to the newly inserted node. + +- If the same namespace URI is in-scope within both the object's context and the object's context, but has a different prefix mapped to it in both contexts, a new namespace declaration is added to the newly inserted node, with the prefix and namespace URI taken from the object. + +- If the same namespace prefix is in-scope within both the object's context and the object's context, but has a different namespace URI mapped to it in both contexts, a new namespace declaration is added to the newly inserted node which re-declares that prefix with the namespace URI taken from object. + +- If the prefix as well as the namespace URI in both the object's context and the object's context is the same, no new namespace declaration is added to the newly inserted node. + > [!NOTE] -> The description above also applies to namespace declarations with the empty `string` as a prefix (for example, the default namespace declaration). - - The following are the possible `xml:lang` conflicts. - -- If there is an `xml:lang` attribute in-scope within the object's context but not in the object's context, an `xml:lang` attribute whose value is taken from the object is added to the newly inserted node. - -- If there is an `xml:lang` attribute in-scope within both the object's context and the object's context, but each has a different value, an `xml:lang` attribute whose value is taken from the object is added to the newly inserted node. - -- If there is an `xml:lang` attribute in-scope within both the object's context and the object's context, but each with the same value, no new `xml:lang` attribute is added on the newly inserted node. - -- If there is an `xml:lang` attribute in-scope within the object's context, but none existing in the object's context, no `xml:lang` attribute is added to the newly inserted node. - -## Inserting Nodes with XmlWriter - - The methods used to insert sibling, child and attribute nodes described in the "Inserting Nodes and Values" section are overloaded. The , , , and methods of the class return an object used to insert nodes. - -### Unsupported XmlWriter Methods - - Not all of the methods used for writing information to an XML document using the class are supported by the class due to difference between the XPath data model and the Document Object Model (DOM). - - The following table describes the class methods not supported by the class. - -|Method|Description| -|------------|-----------------| -||Throws a exception.| -||Ignored at the root level and throws a exception if called at any other level in the XML document.| -||Treated as a call to the method for the equivalent character or characters.| -||Treated as a call to the method for the equivalent character or characters.| -||Treated as a call to the method for the equivalent character or characters.| - - For more information about the class, see the class reference documentation. - -### Multiple XmlWriter Objects - - It is possible to have multiple objects pointing to different parts of an XML document with one or more open objects. Multiple objects are allowed and supported in single-threaded scenarios. - - The following are important notes to consider when using multiple objects. - -- XML fragments written by objects are added to the XML document when the method of each object is called. Until that point, the object is writing a disconnected fragment. If an operation is performed on the XML document, any fragments being written by an object, before the has been called, are not affected. - -- If there is an open object on a particular XML subtree and that subtree is deleted, the object may still add to the sub-tree. The subtree simply becomes a deleted fragment. - -- If multiple objects are opened at the same point in the XML document, they are added to the XML document in the order in which the objects are closed, not in the order in which they were opened. - - The following example creates an object, creates an object, and then uses the object returned by the method to create the structure of the first book in the `books.xml` file. The example then saves it as the `book.xml` file. - -```vb -Dim document As XmlDocument = New XmlDocument() -Dim navigator As XPathNavigator = document.CreateNavigator() - -Using writer As XmlWriter = navigator.PrependChild() - - writer.WriteStartElement("bookstore") - writer.WriteStartElement("book") - writer.WriteAttributeString("genre", "autobiography") - writer.WriteAttributeString("publicationdate", "1981-03-22") - writer.WriteAttributeString("ISBN", "1-861003-11-0") - writer.WriteElementString("title", "The Autobiography of Benjamin Franklin") - writer.WriteStartElement("author") - writer.WriteElementString("first-name", "Benjamin") - writer.WriteElementString("last-name", "Franklin") - writer.WriteElementString("price", "8.99") - writer.WriteEndElement() - writer.WriteEndElement() - writer.WriteEndElement() - -End Using - -document.Save("book.xml") -``` - -```csharp -XmlDocument document = new XmlDocument(); -XPathNavigator navigator = document.CreateNavigator(); - -using (XmlWriter writer = navigator.PrependChild()) -{ - writer.WriteStartElement("bookstore"); - writer.WriteStartElement("book"); - writer.WriteAttributeString("genre", "autobiography"); - writer.WriteAttributeString("publicationdate", "1981-03-22"); - writer.WriteAttributeString("ISBN", "1-861003-11-0"); - writer.WriteElementString("title", "The Autobiography of Benjamin Franklin"); - writer.WriteStartElement("author"); - writer.WriteElementString("first-name", "Benjamin"); - writer.WriteElementString("last-name", "Franklin"); - writer.WriteElementString("price", "8.99"); - writer.WriteEndElement(); - writer.WriteEndElement(); - writer.WriteEndElement(); -} -document.Save("book.xml"); -``` - -## Saving an XML Document - - Saving changes made to an object as the result of the methods described in this topic is performed using the methods of the class. For more information about saving changes made to an object, see [Saving and Writing a Document](saving-and-writing-a-document.md). - +> The description above also applies to namespace declarations with the empty `string` as a prefix (for example, the default namespace declaration). + + The following are the possible `xml:lang` conflicts. + +- If there is an `xml:lang` attribute in-scope within the object's context but not in the object's context, an `xml:lang` attribute whose value is taken from the object is added to the newly inserted node. + +- If there is an `xml:lang` attribute in-scope within both the object's context and the object's context, but each has a different value, an `xml:lang` attribute whose value is taken from the object is added to the newly inserted node. + +- If there is an `xml:lang` attribute in-scope within both the object's context and the object's context, but each with the same value, no new `xml:lang` attribute is added on the newly inserted node. + +- If there is an `xml:lang` attribute in-scope within the object's context, but none existing in the object's context, no `xml:lang` attribute is added to the newly inserted node. + +## Inserting Nodes with XmlWriter + + The methods used to insert sibling, child and attribute nodes described in the "Inserting Nodes and Values" section are overloaded. The , , , and methods of the class return an object used to insert nodes. + +### Unsupported XmlWriter Methods + + Not all of the methods used for writing information to an XML document using the class are supported by the class due to difference between the XPath data model and the Document Object Model (DOM). + + The following table describes the class methods not supported by the class. + +|Method|Description| +|------------|-----------------| +||Throws a exception.| +||Ignored at the root level and throws a exception if called at any other level in the XML document.| +||Treated as a call to the method for the equivalent character or characters.| +||Treated as a call to the method for the equivalent character or characters.| +||Treated as a call to the method for the equivalent character or characters.| + + For more information about the class, see the class reference documentation. + +### Multiple XmlWriter Objects + + It is possible to have multiple objects pointing to different parts of an XML document with one or more open objects. Multiple objects are allowed and supported in single-threaded scenarios. + + The following are important notes to consider when using multiple objects. + +- XML fragments written by objects are added to the XML document when the method of each object is called. Until that point, the object is writing a disconnected fragment. If an operation is performed on the XML document, any fragments being written by an object, before the has been called, are not affected. + +- If there is an open object on a particular XML subtree and that subtree is deleted, the object may still add to the sub-tree. The subtree simply becomes a deleted fragment. + +- If multiple objects are opened at the same point in the XML document, they are added to the XML document in the order in which the objects are closed, not in the order in which they were opened. + + The following example creates an object, creates an object, and then uses the object returned by the method to create the structure of the first book in the `books.xml` file. The example then saves it as the `book.xml` file. + +```vb +Dim document As XmlDocument = New XmlDocument() +Dim navigator As XPathNavigator = document.CreateNavigator() + +Using writer As XmlWriter = navigator.PrependChild() + + writer.WriteStartElement("bookstore") + writer.WriteStartElement("book") + writer.WriteAttributeString("genre", "autobiography") + writer.WriteAttributeString("publicationdate", "1981-03-22") + writer.WriteAttributeString("ISBN", "1-861003-11-0") + writer.WriteElementString("title", "The Autobiography of Benjamin Franklin") + writer.WriteStartElement("author") + writer.WriteElementString("first-name", "Benjamin") + writer.WriteElementString("last-name", "Franklin") + writer.WriteElementString("price", "8.99") + writer.WriteEndElement() + writer.WriteEndElement() + writer.WriteEndElement() + +End Using + +document.Save("book.xml") +``` + +```csharp +XmlDocument document = new XmlDocument(); +XPathNavigator navigator = document.CreateNavigator(); + +using (XmlWriter writer = navigator.PrependChild()) +{ + writer.WriteStartElement("bookstore"); + writer.WriteStartElement("book"); + writer.WriteAttributeString("genre", "autobiography"); + writer.WriteAttributeString("publicationdate", "1981-03-22"); + writer.WriteAttributeString("ISBN", "1-861003-11-0"); + writer.WriteElementString("title", "The Autobiography of Benjamin Franklin"); + writer.WriteStartElement("author"); + writer.WriteElementString("first-name", "Benjamin"); + writer.WriteElementString("last-name", "Franklin"); + writer.WriteElementString("price", "8.99"); + writer.WriteEndElement(); + writer.WriteEndElement(); + writer.WriteEndElement(); +} +document.Save("book.xml"); +``` + +## Saving an XML Document + + Saving changes made to an object as the result of the methods described in this topic is performed using the methods of the class. For more information about saving changes made to an object, see [Saving and Writing a Document](saving-and-writing-a-document.md). + ## See also - diff --git a/docs/standard/data/xml/modify-xml-data-using-xpathnavigator.md b/docs/standard/data/xml/modify-xml-data-using-xpathnavigator.md index abf23abbc05d4..337d82cd6a438 100644 --- a/docs/standard/data/xml/modify-xml-data-using-xpathnavigator.md +++ b/docs/standard/data/xml/modify-xml-data-using-xpathnavigator.md @@ -2,255 +2,251 @@ description: "Learn more about: Modify XML Data using XPathNavigator" title: "Modify XML Data using XPathNavigator" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: 03a7c5a1-b296-4af4-b209-043c958dc0a5 --- -# Modify XML Data using XPathNavigator - -The class provides a set of methods used to modify nodes and values in an XML document. In order to use these methods, the object must be editable, that is, its property must be `true`. - - objects that can edit an XML document are created by the method of the class. objects created by the class are read-only and any attempt to use the editing methods of an object created by an object result in a . - - For more information about creating editable objects, see [Reading XML Data using XPathDocument and XmlDocument](reading-xml-data-using-xpathdocument-and-xmldocument.md). - -## Modifying Nodes - - A simple technique for changing the value of a node is to use the and methods of the class. - - The following table lists the effects of these methods on different node types. - -||Data Changed| -|---------------------------------------------------------------------------------------------------------------------------------------------|------------------| -||Not supported.| -||The content of the element.| -||The value of the attribute.| -||The text content.| -||The content, excluding the target.| -||The content of the comment.| -||Not Supported.| - +# Modify XML data using XPathNavigator + +The class provides a set of methods used to modify nodes and values in an XML document. In order to use these methods, the object must be editable, that is, its property must be `true`. + + objects that can edit an XML document are created by the method of the class. objects created by the class are read-only and any attempt to use the editing methods of an object created by an object result in a . + + For more information about creating editable objects, see [Reading XML Data using XPathDocument and XmlDocument](reading-xml-data-using-xpathdocument-and-xmldocument.md). + +## Modifying Nodes + + A simple technique for changing the value of a node is to use the and methods of the class. + + The following table lists the effects of these methods on different node types. + +||Data Changed| +|---------------------------------------------------------------------------------------------------------------------------------------------|------------------| +||Not supported.| +||The content of the element.| +||The value of the attribute.| +||The text content.| +||The content, excluding the target.| +||The content of the comment.| +||Not Supported.| + > [!NOTE] -> Editing nodes or the node is not supported. - - The class also provides a set of methods used to insert and remove nodes. For more information about inserting and removing nodes from an XML document, see the [Insert XML Data using XPathNavigator](insert-xml-data-using-xpathnavigator.md) and [Remove XML Data using XPathNavigator](remove-xml-data-using-xpathnavigator.md) topics. - -### Modifying Untyped Values - - The method simply inserts the untyped `string` value passed as a parameter as the value of the node the object is currently positioned on. The value is inserted without any type or without verifying that the new value is valid according to the type of the node if schema information is available. - - In the following example, the method is used to update all `price` elements in the `contosoBooks.xml` file. - - [!code-cpp[XPathNavigatorMethods#47](../../../../samples/snippets/cpp/VS_Snippets_Data/XPathNavigatorMethods/CPP/xpathnavigatormethods.cpp#47)] +> Editing nodes or the node is not supported. + + The class also provides a set of methods used to insert and remove nodes. For more information about inserting and removing nodes from an XML document, see the [Insert XML Data using XPathNavigator](insert-xml-data-using-xpathnavigator.md) and [Remove XML Data using XPathNavigator](remove-xml-data-using-xpathnavigator.md) topics. + +### Modifying Untyped Values + + The method simply inserts the untyped `string` value passed as a parameter as the value of the node the object is currently positioned on. The value is inserted without any type or without verifying that the new value is valid according to the type of the node if schema information is available. + + In the following example, the method is used to update all `price` elements in the `contosoBooks.xml` file. [!code-csharp[XPathNavigatorMethods#47](../../../../samples/snippets/csharp/VS_Snippets_Data/XPathNavigatorMethods/CS/xpathnavigatormethods.cs#47)] - [!code-vb[XPathNavigatorMethods#47](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XPathNavigatorMethods/VB/xpathnavigatormethods.vb#47)] - - The example takes the `contosoBooks.xml` file as an input. - - [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] - -### Modifying Typed Values - - When the type of a node is a W3C XML Schema simple type, the new value inserted by the method is checked against the facets of the simple type before the value is set. If the new value is not valid according to the type of the node (for example, setting a value of `-1` on an element whose type is `xs:positiveInteger`), it results in an exception. - - The following example attempts to change the value of the `price` element of the first `book` element in the `contosoBooks.xml` file to a value. Because the XML Schema type of the `price` element is defined as `xs:decimal` in the `contosoBooks.xsd` files, this results in an exception. - -```vb -Dim settings As XmlReaderSettings = New XmlReaderSettings() -settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd") -settings.ValidationType = ValidationType.Schema - -Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings) - -Dim document As XmlDocument = New XmlDocument() -document.Load(reader) -Dim navigator As XPathNavigator = document.CreateNavigator() - -navigator.MoveToChild("bookstore", "http://www.contoso.com/books") -navigator.MoveToChild("book", "http://www.contoso.com/books") -navigator.MoveToChild("price", "http://www.contoso.com/books") - -navigator.SetTypedValue(DateTime.Now) -``` - -```csharp -XmlReaderSettings settings = new XmlReaderSettings(); -settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd"); -settings.ValidationType = ValidationType.Schema; - -XmlReader reader = XmlReader.Create("contosoBooks.xml", settings); - -XmlDocument document = new XmlDocument(); -document.Load(reader); -XPathNavigator navigator = document.CreateNavigator(); - -navigator.MoveToChild("bookstore", "http://www.contoso.com/books"); -navigator.MoveToChild("book", "http://www.contoso.com/books"); -navigator.MoveToChild("price", "http://www.contoso.com/books"); - -navigator.SetTypedValue(DateTime.Now); -``` - - The example takes the `contosoBooks.xml` file as an input. - - [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] - - The example also takes the `contosoBooks.xsd` as an input. - - [!code-xml[XPathXMLExamples#3](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xsd#3)] - -#### The Effects of Editing Strongly Typed XML Data - - The class uses the W3C XML Schema as a basis for describing strongly typed XML. Elements and attributes can be annotated with type information based on validation against a W3C XML Schema document. Elements that can contain other elements or attributes are called complex types, while those that can only contain textual content are called simple types. - + [!code-vb[XPathNavigatorMethods#47](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XPathNavigatorMethods/VB/xpathnavigatormethods.vb#47)] + + The example takes the `contosoBooks.xml` file as an input. + + [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] + +### Modifying Typed Values + + When the type of a node is a W3C XML Schema simple type, the new value inserted by the method is checked against the facets of the simple type before the value is set. If the new value is not valid according to the type of the node (for example, setting a value of `-1` on an element whose type is `xs:positiveInteger`), it results in an exception. + + The following example attempts to change the value of the `price` element of the first `book` element in the `contosoBooks.xml` file to a value. Because the XML Schema type of the `price` element is defined as `xs:decimal` in the `contosoBooks.xsd` files, this results in an exception. + +```vb +Dim settings As XmlReaderSettings = New XmlReaderSettings() +settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd") +settings.ValidationType = ValidationType.Schema + +Dim reader As XmlReader = XmlReader.Create("contosoBooks.xml", settings) + +Dim document As XmlDocument = New XmlDocument() +document.Load(reader) +Dim navigator As XPathNavigator = document.CreateNavigator() + +navigator.MoveToChild("bookstore", "http://www.contoso.com/books") +navigator.MoveToChild("book", "http://www.contoso.com/books") +navigator.MoveToChild("price", "http://www.contoso.com/books") + +navigator.SetTypedValue(DateTime.Now) +``` + +```csharp +XmlReaderSettings settings = new XmlReaderSettings(); +settings.Schemas.Add("http://www.contoso.com/books", "contosoBooks.xsd"); +settings.ValidationType = ValidationType.Schema; + +XmlReader reader = XmlReader.Create("contosoBooks.xml", settings); + +XmlDocument document = new XmlDocument(); +document.Load(reader); +XPathNavigator navigator = document.CreateNavigator(); + +navigator.MoveToChild("bookstore", "http://www.contoso.com/books"); +navigator.MoveToChild("book", "http://www.contoso.com/books"); +navigator.MoveToChild("price", "http://www.contoso.com/books"); + +navigator.SetTypedValue(DateTime.Now); +``` + + The example takes the `contosoBooks.xml` file as an input. + + [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] + + The example also takes the `contosoBooks.xsd` as an input. + + [!code-xml[XPathXMLExamples#3](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xsd#3)] + +#### The Effects of Editing Strongly Typed XML Data + + The class uses the W3C XML Schema as a basis for describing strongly typed XML. Elements and attributes can be annotated with type information based on validation against a W3C XML Schema document. Elements that can contain other elements or attributes are called complex types, while those that can only contain textual content are called simple types. + > [!NOTE] -> Attributes can only have simple types. - - An element or attribute can be considered to be schema-valid if it conforms to all the rules specific to its type definition. An element that has the simple type `xs:int` has to contain a numeric value between -2147483648 and 2147483647 to be schema-valid. For complex types, the schema-validity of the element is dependent on the schema-validity of its child elements and attributes. Thus if an element is valid against its complex type definition, all its child elements and attributes are valid against their type definitions. Similarly, if even one of the child elements or attributes of an element is invalid against its type definition, or has an unknown validity, the element is also either invalid or of unknown validity. - - Given that the validity of an element is dependent on the validity of its child elements and attributes, modifications to either result in altering the validity of the element if it was previously valid. Specifically, if the child elements or attributes of an element are inserted, updated, or deleted, then the validity of the element becomes unknown. This is represented by the property of the element's property being set to . Furthermore, this effect cascades upwards recursively across the XML document, because the validity of the element's parent element (and its parent element, and so on) also becomes unknown. - - For more information about schema validation and the class, see [Schema Validation using XPathNavigator](schema-validation-using-xpathnavigator.md). - -### Modifying Attributes - - The and methods can be used to modify untyped and typed attribute nodes as well as the other node types listed in the "Modifying Nodes" section. - - The following example changes the value of the `genre` attribute of the first `book` element in the `books.xml` file. - -```vb -Dim document As XmlDocument = New XmlDocument() -document.Load("books.xml") -Dim navigator As XPathNavigator = document.CreateNavigator() - -navigator.MoveToChild("bookstore", String.Empty) -navigator.MoveToChild("book", String.Empty) -navigator.MoveToAttribute("genre", String.Empty) - -navigator.SetValue("non-fiction") - -navigator.MoveToRoot() -Console.WriteLine(navigator.OuterXml) -``` - -```csharp -XmlDocument document = new XmlDocument(); -document.Load("books.xml"); -XPathNavigator navigator = document.CreateNavigator(); - -navigator.MoveToChild("bookstore", String.Empty); -navigator.MoveToChild("book", String.Empty); -navigator.MoveToAttribute("genre", String.Empty); - -navigator.SetValue("non-fiction"); - -navigator.MoveToRoot(); -Console.WriteLine(navigator.OuterXml); -``` - - For more information about the and methods, see the "Modifying Untyped Values" and "Modifying Typed Values" sections. - -## InnerXml and OuterXml Properties - - The and properties of the class change the XML markup of the nodes an object is currently positioned on. - - The property changes the XML markup of the child nodes an object is currently positioned on with the parsed contents of the given XML `string`. Similarly, the property changes the XML markup of the child nodes an object is currently positioned on as well as the current node itself. - - The following example uses the property to modify the value of the `price` element and insert a new `discount` attribute on the first `book` element in the `contosoBooks.xml` file. - -```vb -Dim document As XmlDocument = New XmlDocument() -document.Load("contosoBooks.xml"); -Dim navigator As XPathNavigator = document.CreateNavigator() - -navigator.MoveToChild("bookstore", "http://www.contoso.com/books") -navigator.MoveToChild("book", "http://www.contoso.com/books") -navigator.MoveToChild("price", "http://www.contoso.com/books") - -navigator.OuterXml = "10.99" - -navigator.MoveToRoot() -Console.WriteLine(navigator.OuterXml) -``` - -```csharp -XmlDocument document = new XmlDocument(); -document.Load("contosoBooks.xml"); -XPathNavigator navigator = document.CreateNavigator(); - -navigator.MoveToChild("bookstore", "http://www.contoso.com/books"); -navigator.MoveToChild("book", "http://www.contoso.com/books"); -navigator.MoveToChild("price", "http://www.contoso.com/books"); - -navigator.OuterXml = "10.99"; - -navigator.MoveToRoot(); -Console.WriteLine(navigator.OuterXml); -``` - - The example takes the `contosoBooks.xml` file as an input. - - [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] - -## Modifying Namespace Nodes - - In the Document Object Model (DOM), namespace declarations are treated as if they are regular attributes that can be inserted, updated and deleted. The class does not allow such operations on namespace nodes because altering the value of a namespace node can change the identity of the elements and attributes within the scope of the namespace node as illustrated in the following example. - -```xml - - - -``` - - If the XML example above is changed in the following way, this effectively renames every element in the document because the value of each element's namespace URI is changed. - -```xml - - - -``` - - Inserting namespace nodes that do not conflict with namespace declarations at the scope that they are inserted in is allowed by the class. In this case, the namespace declarations are not declared at lower scopes in the XML document and does not result in renaming as illustrated in the following example. - -```xml - - - - - -``` - - If the XML example above is changed in the following way, the namespace declarations are correctly propagated across the XML document below the scope of the other namespace declaration. - -```xml - - - - - -``` - - In the XML example above, the attribute `a:parent-id` is inserted on the `parent` element in the `http://www.contoso.com/parent-id` namespace. The method is used to insert the attribute while positioned on the `parent` element. The `http://www.contoso.com` namespace declaration is automatically inserted by the class to preserve the consistency of the rest of the XML document. - -## Modifying Entity Reference Nodes - - Entity reference nodes in an object are read-only and cannot be edited using either the or classes. Any attempt to modify an entity reference node results in an . - -## Modifying xsi:nil Nodes - - The W3C XML Schema recommendation introduces the concept of an element being nillable. When an element is nillable, it is possible for the element to have no content and still be valid. The concept of an element being nillable is similar to the concept of an object being `null`. The main difference is that a `null` object cannot be accessed in any way, while an `xsi:nil` element still has properties such as attributes that can be accessed, but has no content (child elements or text). The existence of the `xsi:nil` attribute with a value of `true` on an element in an XML document is used to indicate that an element has no content. - - If an object is used to add content to a valid element with an `xsi:nil` attribute with a value of `true`, the value of its `xsi:nil` attribute is set to `false`. - +> Attributes can only have simple types. + + An element or attribute can be considered to be schema-valid if it conforms to all the rules specific to its type definition. An element that has the simple type `xs:int` has to contain a numeric value between -2147483648 and 2147483647 to be schema-valid. For complex types, the schema-validity of the element is dependent on the schema-validity of its child elements and attributes. Thus if an element is valid against its complex type definition, all its child elements and attributes are valid against their type definitions. Similarly, if even one of the child elements or attributes of an element is invalid against its type definition, or has an unknown validity, the element is also either invalid or of unknown validity. + + Given that the validity of an element is dependent on the validity of its child elements and attributes, modifications to either result in altering the validity of the element if it was previously valid. Specifically, if the child elements or attributes of an element are inserted, updated, or deleted, then the validity of the element becomes unknown. This is represented by the property of the element's property being set to . Furthermore, this effect cascades upwards recursively across the XML document, because the validity of the element's parent element (and its parent element, and so on) also becomes unknown. + + For more information about schema validation and the class, see [Schema Validation using XPathNavigator](schema-validation-using-xpathnavigator.md). + +### Modifying Attributes + + The and methods can be used to modify untyped and typed attribute nodes as well as the other node types listed in the "Modifying Nodes" section. + + The following example changes the value of the `genre` attribute of the first `book` element in the `books.xml` file. + +```vb +Dim document As XmlDocument = New XmlDocument() +document.Load("books.xml") +Dim navigator As XPathNavigator = document.CreateNavigator() + +navigator.MoveToChild("bookstore", String.Empty) +navigator.MoveToChild("book", String.Empty) +navigator.MoveToAttribute("genre", String.Empty) + +navigator.SetValue("non-fiction") + +navigator.MoveToRoot() +Console.WriteLine(navigator.OuterXml) +``` + +```csharp +XmlDocument document = new XmlDocument(); +document.Load("books.xml"); +XPathNavigator navigator = document.CreateNavigator(); + +navigator.MoveToChild("bookstore", String.Empty); +navigator.MoveToChild("book", String.Empty); +navigator.MoveToAttribute("genre", String.Empty); + +navigator.SetValue("non-fiction"); + +navigator.MoveToRoot(); +Console.WriteLine(navigator.OuterXml); +``` + + For more information about the and methods, see the "Modifying Untyped Values" and "Modifying Typed Values" sections. + +## InnerXml and OuterXml Properties + + The and properties of the class change the XML markup of the nodes an object is currently positioned on. + + The property changes the XML markup of the child nodes an object is currently positioned on with the parsed contents of the given XML `string`. Similarly, the property changes the XML markup of the child nodes an object is currently positioned on as well as the current node itself. + + The following example uses the property to modify the value of the `price` element and insert a new `discount` attribute on the first `book` element in the `contosoBooks.xml` file. + +```vb +Dim document As XmlDocument = New XmlDocument() +document.Load("contosoBooks.xml"); +Dim navigator As XPathNavigator = document.CreateNavigator() + +navigator.MoveToChild("bookstore", "http://www.contoso.com/books") +navigator.MoveToChild("book", "http://www.contoso.com/books") +navigator.MoveToChild("price", "http://www.contoso.com/books") + +navigator.OuterXml = "10.99" + +navigator.MoveToRoot() +Console.WriteLine(navigator.OuterXml) +``` + +```csharp +XmlDocument document = new XmlDocument(); +document.Load("contosoBooks.xml"); +XPathNavigator navigator = document.CreateNavigator(); + +navigator.MoveToChild("bookstore", "http://www.contoso.com/books"); +navigator.MoveToChild("book", "http://www.contoso.com/books"); +navigator.MoveToChild("price", "http://www.contoso.com/books"); + +navigator.OuterXml = "10.99"; + +navigator.MoveToRoot(); +Console.WriteLine(navigator.OuterXml); +``` + + The example takes the `contosoBooks.xml` file as an input. + + [!code-xml[XPathXMLExamples#2](../../../../samples/snippets/xml/VS_Snippets_Data/XPathXMLExamples/XML/contosoBooks.xml#2)] + +## Modifying Namespace Nodes + + In the Document Object Model (DOM), namespace declarations are treated as if they are regular attributes that can be inserted, updated and deleted. The class does not allow such operations on namespace nodes because altering the value of a namespace node can change the identity of the elements and attributes within the scope of the namespace node as illustrated in the following example. + +```xml + + + +``` + + If the XML example above is changed in the following way, this effectively renames every element in the document because the value of each element's namespace URI is changed. + +```xml + + + +``` + + Inserting namespace nodes that do not conflict with namespace declarations at the scope that they are inserted in is allowed by the class. In this case, the namespace declarations are not declared at lower scopes in the XML document and does not result in renaming as illustrated in the following example. + +```xml + + + + + +``` + + If the XML example above is changed in the following way, the namespace declarations are correctly propagated across the XML document below the scope of the other namespace declaration. + +```xml + + + + + +``` + + In the XML example above, the attribute `a:parent-id` is inserted on the `parent` element in the `http://www.contoso.com/parent-id` namespace. The method is used to insert the attribute while positioned on the `parent` element. The `http://www.contoso.com` namespace declaration is automatically inserted by the class to preserve the consistency of the rest of the XML document. + +## Modifying Entity Reference Nodes + + Entity reference nodes in an object are read-only and cannot be edited using either the or classes. Any attempt to modify an entity reference node results in an . + +## Modifying xsi:nil Nodes + + The W3C XML Schema recommendation introduces the concept of an element being nillable. When an element is nillable, it is possible for the element to have no content and still be valid. The concept of an element being nillable is similar to the concept of an object being `null`. The main difference is that a `null` object cannot be accessed in any way, while an `xsi:nil` element still has properties such as attributes that can be accessed, but has no content (child elements or text). The existence of the `xsi:nil` attribute with a value of `true` on an element in an XML document is used to indicate that an element has no content. + + If an object is used to add content to a valid element with an `xsi:nil` attribute with a value of `true`, the value of its `xsi:nil` attribute is set to `false`. + > [!NOTE] -> If the content of an element with an `xsi:nil` attribute set to `false` is deleted, the value of the attribute is not changed to `true`. - -## Saving an XML Document +> If the content of an element with an `xsi:nil` attribute set to `false` is deleted, the value of the attribute is not changed to `true`. + +## Saving an XML Document + + Saving changes made to an object as the result of the editing methods described in this topic is performed using the methods of the class. For more information about saving changes made to an object, see [Saving and Writing a Document](saving-and-writing-a-document.md). - Saving changes made to an object as the result of the editing methods described in this topic is performed using the methods of the class. For more information about saving changes made to an object, see [Saving and Writing a Document](saving-and-writing-a-document.md). - ## See also - diff --git a/docs/standard/data/xml/post-schema-compilation-infoset.md b/docs/standard/data/xml/post-schema-compilation-infoset.md index e4faf6ba9b799..6db91c4340919 100644 --- a/docs/standard/data/xml/post-schema-compilation-infoset.md +++ b/docs/standard/data/xml/post-schema-compilation-infoset.md @@ -2,37 +2,33 @@ description: "Learn more about: Post-Schema Compilation Infoset" title: "Post-Schema Compilation Infoset" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: 7f1bc7f4-401b-459f-9078-f099cc711fde --- -# Post-Schema Compilation Infoset - -The [World Wide Web Consortium (W3C) XML Schema Recommendation](https://www.w3.org/XML/Schema) discusses the information set (infoset) that must be exposed for pre-schema validation and post-schema compilation. The XML Schema Object Model (SOM) views this exposure before and after the method of the is called. - - The pre-schema validation infoset is built during the editing of the schema. The post-schema compilation infoset is generated after the method of the is called, during compilation of the schema, and is exposed as properties. - - The SOM is the object model that represents the pre-schema validation and post-schema compilation infosets; it consists of the classes in the namespace. All read and write properties of classes in the namespace belong to the pre-schema validation infoset, while all read-only properties of classes in the namespace belong to the post-schema compilation infoset. The exception to this rule are the following properties, which are both pre-schema validation infoset and post-schema compilation infoset properties. - -|Class|Property| -|-----------|--------------| -||| -||, , , , | -||| -||| -||, | -||| - - For example, the and classes both have `BlockResolved` and `FinalResolved` properties. These properties are used to hold the values for the `Block` and `Final` properties after the schema has been compiled and validated. `BlockResolved` and `FinalResolved` are read-only properties that are part of the post-schema compilation infoset. - - The following example shows the property of the class set after validating the schema. Before validation, the property contains a `null` reference, and the is set to the name of the type in question. After validation, the is resolved to a valid type, and the type object is available through the property. - - [!code-cpp[PsciSample#1](../../../../samples/snippets/cpp/VS_Snippets_Data/PsciSample/CPP/PsciSample.cpp#1)] +# Post-schema compilation infoset + +The [World Wide Web Consortium (W3C) XML Schema Recommendation](https://www.w3.org/XML/Schema) discusses the information set (infoset) that must be exposed for pre-schema validation and post-schema compilation. The XML Schema Object Model (SOM) views this exposure before and after the method of the is called. + + The pre-schema validation infoset is built during the editing of the schema. The post-schema compilation infoset is generated after the method of the is called, during compilation of the schema, and is exposed as properties. + + The SOM is the object model that represents the pre-schema validation and post-schema compilation infosets; it consists of the classes in the namespace. All read and write properties of classes in the namespace belong to the pre-schema validation infoset, while all read-only properties of classes in the namespace belong to the post-schema compilation infoset. The exception to this rule are the following properties, which are both pre-schema validation infoset and post-schema compilation infoset properties. + +|Class|Property| +|-----------|--------------| +||| +||, , , , | +||| +||| +||, | +||| + + For example, the and classes both have `BlockResolved` and `FinalResolved` properties. These properties are used to hold the values for the `Block` and `Final` properties after the schema has been compiled and validated. `BlockResolved` and `FinalResolved` are read-only properties that are part of the post-schema compilation infoset. + + The following example shows the property of the class set after validating the schema. Before validation, the property contains a `null` reference, and the is set to the name of the type in question. After validation, the is resolved to a valid type, and the type object is available through the property. [!code-csharp[PsciSample#1](../../../../samples/snippets/csharp/VS_Snippets_Data/PsciSample/CS/PsciSample.cs#1)] - [!code-vb[PsciSample#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/PsciSample/VB/PsciSample.vb#1)] - + [!code-vb[PsciSample#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/PsciSample/VB/PsciSample.vb#1)] + ## See also - [XML Schema Object Model (SOM)](xml-schema-object-model-som.md) diff --git a/docs/standard/data/xml/reading-and-writing-xml-schemas.md b/docs/standard/data/xml/reading-and-writing-xml-schemas.md index 6d5b78d4dd3a8..7f0920f6a72f2 100644 --- a/docs/standard/data/xml/reading-and-writing-xml-schemas.md +++ b/docs/standard/data/xml/reading-and-writing-xml-schemas.md @@ -2,45 +2,41 @@ title: "Reading and Writing XML Schemas" description: Read and write XML Schema definition language (XSD) schemas from files or other sources in .NET, using the Schema Object Model (SOM) API. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: b5757c4a-ea59-467e-ac62-be2bfe24eb77 --- -# Reading and Writing XML Schemas - -The Schema Object Model (SOM) API can be used to read and write XML Schema definition language (XSD) schemas from files or other sources and build XML schemas in-memory using the classes in the namespace that map to the structures defined in the World Wide Web Consortium (W3C) XML Schema Recommendation. - -## Reading and Writing XML Schemas - - The class provides the and methods to read and write XML schemas. The method returns an object representing the XML schema and takes an optional as a parameter to handle schema validation warnings and errors encountered while reading an XML schema. - - The method writes XML schemas to , and objects and can take an optional object as a parameter. An is used to handle namespaces encountered in an XML schema. For more information about the class, see [Managing Namespaces in an XML Document](managing-namespaces-in-an-xml-document.md). - - The following code example illustrates reading and writing XML schemas from and to a file. The code example takes the `example.xsd` file, reads it into an object using the `static` method, and then writes the file to the console and a new `new.xsd` file. The code example also provides a as a parameter to the `static` method to handle any schema validation warnings or errors encountered while reading the XML schema. If the is not specified (`null`), no warnings or errors are reported. - - [!code-cpp[XmlSchemaReadWriteExample#1](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaReadWriteExample/CPP/XmlSchemaReadWriteExample.cpp#1)] +# Read and write XML schemas + +The Schema Object Model (SOM) API can be used to read and write XML Schema definition language (XSD) schemas from files or other sources and build XML schemas in-memory using the classes in the namespace that map to the structures defined in the World Wide Web Consortium (W3C) XML Schema Recommendation. + +## Reading and Writing XML Schemas + + The class provides the and methods to read and write XML schemas. The method returns an object representing the XML schema and takes an optional as a parameter to handle schema validation warnings and errors encountered while reading an XML schema. + + The method writes XML schemas to , and objects and can take an optional object as a parameter. An is used to handle namespaces encountered in an XML schema. For more information about the class, see [Managing Namespaces in an XML Document](managing-namespaces-in-an-xml-document.md). + + The following code example illustrates reading and writing XML schemas from and to a file. The code example takes the `example.xsd` file, reads it into an object using the `static` method, and then writes the file to the console and a new `new.xsd` file. The code example also provides a as a parameter to the `static` method to handle any schema validation warnings or errors encountered while reading the XML schema. If the is not specified (`null`), no warnings or errors are reported. [!code-csharp[XmlSchemaReadWriteExample#1](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaReadWriteExample/CS/XmlSchemaReadWriteExample.cs#1)] - [!code-vb[XmlSchemaReadWriteExample#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaReadWriteExample/VB/XmlSchemaReadWriteExample.vb#1)] - - The example takes the `example.xsd` as input. - -```xml - - - - - - - - - - - - -``` - + [!code-vb[XmlSchemaReadWriteExample#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaReadWriteExample/VB/XmlSchemaReadWriteExample.vb#1)] + + The example takes the `example.xsd` as input. + +```xml + + + + + + + + + + + + +``` + ## See also - [XML Schema Object Model Overview](xml-schema-object-model-overview.md) diff --git a/docs/standard/data/xml/traversing-xml-schemas.md b/docs/standard/data/xml/traversing-xml-schemas.md index aa27ea6b6c967..da3850550dd08 100644 --- a/docs/standard/data/xml/traversing-xml-schemas.md +++ b/docs/standard/data/xml/traversing-xml-schemas.md @@ -5,10 +5,8 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: cce69574-5861-4a30-b730-2e18d915d8ee --- -# Traversing XML Schemas +# Traverse XML schemas Traversing an XML schema using the Schema Object Model (SOM) API provides access to the elements, attributes, and types stored in the SOM. Traversing an XML schema loaded into the SOM is also the first step in editing an XML schema using the SOM API. @@ -52,8 +50,6 @@ The sample traverses the customer schema in the following steps. 7. Iterates over each in the collection writing the name of each child element to the console. The following is the complete code example. - -[!code-cpp[XmlSchemaTraverseExample#1](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaTraverseExample/CPP/XmlSchemaTraverseExample.cpp#1)] [!code-csharp[XmlSchemaTraverseExample#1](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaTraverseExample/CS/XmlSchemaTraverseExample.cs#1)] [!code-vb[XmlSchemaTraverseExample#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaTraverseExample/VB/XmlSchemaTraverseExample.vb#1)] diff --git a/docs/standard/data/xml/validating-an-xml-document-in-the-dom.md b/docs/standard/data/xml/validating-an-xml-document-in-the-dom.md index 51ce2e35537b6..60d9cf1090325 100644 --- a/docs/standard/data/xml/validating-an-xml-document-in-the-dom.md +++ b/docs/standard/data/xml/validating-an-xml-document-in-the-dom.md @@ -5,10 +5,8 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: 2c61c920-d0f8-4c72-bfcc-6524570f3060 --- -# Validating an XML Document in the DOM +# Validate an XML document in the DOM The class does not validate the XML in the Document Object Model (DOM) against an XML Schema definition language (XSD) schema or document type definition (DTD) by default; the XML is only verified to be well-formed. @@ -37,8 +35,6 @@ To create an XML schema-validating , follow these ste ### Example In the code example that follows, a schema-validating validates the XML data loaded into the DOM. Invalid modifications are made to the XML document and the document is then revalidated, causing schema validation errors. Finally, one of the errors is corrected, and then part of the XML document is partially validated. - -[!code-cpp[XmlDocumentValidation.Load#1](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlDocumentValidation.Load/CPP/XmlDocumentValidationExample.cpp#1)] [!code-csharp[XmlDocumentValidation.Load#1](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlDocumentValidation.Load/CS/XmlDocumentValidationExample.cs#1)] [!code-vb[XmlDocumentValidation.Load#1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlDocumentValidation.Load/VB/XmlDocumentValidationExample.vb#1)] diff --git a/docs/standard/data/xml/xml-schema-xsd-validation-with-xmlschemaset.md b/docs/standard/data/xml/xml-schema-xsd-validation-with-xmlschemaset.md index 8c1ddec62b720..79a803b78bdb4 100644 --- a/docs/standard/data/xml/xml-schema-xsd-validation-with-xmlschemaset.md +++ b/docs/standard/data/xml/xml-schema-xsd-validation-with-xmlschemaset.md @@ -2,41 +2,37 @@ title: "XML Schema (XSD) Validation with XmlSchemaSet" description: Learn how to validate XML documents against an XML schema definition language (XSD) schema, using an XmlSchemaSet class in .NET. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -ms.assetid: 359b10eb-ec05-4cc6-ac96-c2b060afc4de --- # XML schema (XSD) validation with XmlSchemaSet -XML documents can be validated against an XML schema definition language (XSD) schema in an . - -## Validate XML documents +XML documents can be validated against an XML schema definition language (XSD) schema in an . + +## Validate XML documents + + XML documents are validated by the method of the class. To validate an XML document, construct an object that contains an XML schema definition language (XSD) schema with which to validate the XML document. - XML documents are validated by the method of the class. To validate an XML document, construct an object that contains an XML schema definition language (XSD) schema with which to validate the XML document. - > [!NOTE] > The namespace contains extension methods that make it easy to validate an XML tree against an XSD file when using [LINQ to XML (C#)](../../linq/linq-xml-overview.md) and [LINQ to XML (Visual Basic)](../../linq/linq-xml-overview.md). For more information on validating XML documents with LINQ to XML, see [How to validate using XSD (LINQ to XML) (C#)](../../linq/validate-xsd.md) and [How to: Validate Using XSD (LINQ to XML) (Visual Basic)](../../linq/validate-xsd.md). - - An individual schema or a set of schemas (as an ) can be added to an by passing either one as a parameter to the method of . When validating a document the target namespace of the document must match the target namespace of the schema in the schema set. - - The following is an example XML document. - - [!code-xml[XSDInference Examples #5](../../../../samples/snippets/xml/VS_Snippets_Data/XSDInference Examples/XML/contosoBooks.xml#5)] - - The following is the schema that validates the example XML document. - - [!code-xml[XSDInference Examples #6](../../../../samples/snippets/xml/VS_Snippets_Data/XSDInference Examples/XML/contosoBooks.xsd#6)] - - In the code example that follows, the schema above is added to the property of the object. The object is passed as a parameter to the method of the object, which validates the XML document above. - - The property of the object is set to `Schema` to enforce validation of the XML document by the method of the object. A is added to the object to handle any or events raised by errors found during the validation process of both the XML document and the schema. - - [!code-cpp[XmlSchemaSetOverall Example #1](../../../../samples/snippets/cpp/VS_Snippets_Data/XmlSchemaSetOverall Example/CPP/xmlschemasetexample.cpp#1)] + + An individual schema or a set of schemas (as an ) can be added to an by passing either one as a parameter to the method of . When validating a document the target namespace of the document must match the target namespace of the schema in the schema set. + + The following is an example XML document. + + [!code-xml[XSDInference Examples #5](../../../../samples/snippets/xml/VS_Snippets_Data/XSDInference Examples/XML/contosoBooks.xml#5)] + + The following is the schema that validates the example XML document. + + [!code-xml[XSDInference Examples #6](../../../../samples/snippets/xml/VS_Snippets_Data/XSDInference Examples/XML/contosoBooks.xsd#6)] + + In the code example that follows, the schema above is added to the property of the object. The object is passed as a parameter to the method of the object, which validates the XML document above. + + The property of the object is set to `Schema` to enforce validation of the XML document by the method of the object. A is added to the object to handle any or events raised by errors found during the validation process of both the XML document and the schema. [!code-csharp[XmlSchemaSetOverall Example #1](../../../../samples/snippets/csharp/VS_Snippets_Data/XmlSchemaSetOverall Example/CS/xmlschemasetexample.cs#1)] - [!code-vb[XmlSchemaSetOverall Example #1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaSetOverall Example/VB/xmlschemasetexample.vb#1)] - + [!code-vb[XmlSchemaSetOverall Example #1](../../../../samples/snippets/visualbasic/VS_Snippets_Data/XmlSchemaSetOverall Example/VB/xmlschemasetexample.vb#1)] + ## See also - [XmlSchemaSet for Schema Compilation](xmlschemaset-for-schema-compilation.md) diff --git a/docs/standard/events/how-to-handle-multiple-events-using-event-properties.md b/docs/standard/events/how-to-handle-multiple-events-using-event-properties.md index b717a0b39750f..81bb2f6d95f0f 100644 --- a/docs/standard/events/how-to-handle-multiple-events-using-event-properties.md +++ b/docs/standard/events/how-to-handle-multiple-events-using-event-properties.md @@ -2,45 +2,41 @@ title: "How to: Handle Multiple Events Using Event Properties" description: Learn how to handle many events by using event properties. Define delegate collections, event keys, & event properties. Implement add & remove accessor methods. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "event properties [.NET]" - "multiple events [.NET]" - "event handling [.NET], with multiple events" - "events [.NET], multiple" -ms.assetid: 30047cba-e2fd-41c6-b9ca-2ad7a49003db --- # How to: Handle Multiple Events Using Event Properties To use event properties, you define the event properties in the class that raises the events, and then set the delegates for the event properties in classes that handle the events. To implement multiple event properties in a class, the class should internally store and maintain the delegate defined for each event. For each field-like-event, a corresponding backing-field reference type is generated. This can lead to unnecessary allocations when the number of events increases. As an alternative, a common approach is to maintain an which stores events by key. - - To store the delegates for each event, you can use the class, or implement your own collection. The collection class must provide methods for setting, accessing, and retrieving the event handler delegate based on the event key. For example, you could use a class, or derive a custom class from the class. The implementation details of the delegate collection do not need to be exposed outside your class. - - Each event property within the class defines an add accessor method and a remove accessor method. The add accessor for an event property adds the input delegate instance to the delegate collection. The remove accessor for an event property removes the input delegate instance from the delegate collection. The event property accessors use the predefined key for the event property to add and remove instances from the delegate collection. - -### To handle multiple events using event properties - -1. Define a delegate collection within the class that raises the events. - -2. Define a key for each event. - -3. Define the event properties in the class that raises the events. - -4. Use the delegate collection to implement the add and remove accessor methods for the event properties. - -5. Use the public event properties to add and remove event handler delegates in the classes that handle the events. - -## Example - - The following C# example implements the event properties `MouseDown` and `MouseUp`, using an to store each event's delegate. The keywords of the event property constructs are in bold type. - - [!code-cpp[Conceptual.Events.Other#31](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.events.other/cpp/example3.cpp#31)] + + To store the delegates for each event, you can use the class, or implement your own collection. The collection class must provide methods for setting, accessing, and retrieving the event handler delegate based on the event key. For example, you could use a class, or derive a custom class from the class. The implementation details of the delegate collection do not need to be exposed outside your class. + + Each event property within the class defines an add accessor method and a remove accessor method. The add accessor for an event property adds the input delegate instance to the delegate collection. The remove accessor for an event property removes the input delegate instance from the delegate collection. The event property accessors use the predefined key for the event property to add and remove instances from the delegate collection. + +### To handle multiple events using event properties + +1. Define a delegate collection within the class that raises the events. + +2. Define a key for each event. + +3. Define the event properties in the class that raises the events. + +4. Use the delegate collection to implement the add and remove accessor methods for the event properties. + +5. Use the public event properties to add and remove event handler delegates in the classes that handle the events. + +## Example + + The following C# example implements the event properties `MouseDown` and `MouseUp`, using an to store each event's delegate. The keywords of the event property constructs are in bold type. [!code-csharp[Conceptual.Events.Other#31](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.events.other/cs/example3.cs#31)] - [!code-vb[Conceptual.Events.Other#31](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.events.other/vb/example3.vb#31)] - + [!code-vb[Conceptual.Events.Other#31](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.events.other/vb/example3.vb#31)] + ## See also - diff --git a/docs/standard/events/how-to-raise-and-consume-events.md b/docs/standard/events/how-to-raise-and-consume-events.md index b97451417efab..42cb414907e82 100644 --- a/docs/standard/events/how-to-raise-and-consume-events.md +++ b/docs/standard/events/how-to-raise-and-consume-events.md @@ -6,12 +6,10 @@ ms.custom: devdivchpfy22 dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "events [.NET], raising" - "raising events" - "events [.NET], samples" -ms.assetid: 42afade7-3a02-4f2e-868b-95845f302f8f --- # How to: Raise and Consume Events @@ -29,8 +27,6 @@ The examples use concepts described in the [Events](index.md) article. ## Example 2 The second example shows how to raise and consume an event that provides data. The delegate is associated with the event, and an instance of a custom event data object is provided. - - [!code-cpp[EventsOverview#6](../../../samples/snippets/cpp/VS_Snippets_CLR/eventsoverview/cpp/programwithdata.cpp#6)] [!code-csharp[EventsOverview#6](../../../samples/snippets/csharp/VS_Snippets_CLR/eventsoverview/cs/programwithdata.cs#6)] [!code-vb[EventsOverview#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/eventsoverview/vb/module1withdata.vb#6)] diff --git a/docs/standard/exceptions/how-to-create-user-defined-exceptions.md b/docs/standard/exceptions/how-to-create-user-defined-exceptions.md index 086df23a1c6ab..855e94ddcace3 100644 --- a/docs/standard/exceptions/how-to-create-user-defined-exceptions.md +++ b/docs/standard/exceptions/how-to-create-user-defined-exceptions.md @@ -6,20 +6,16 @@ ms.custom: devdivchpfy22 dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "user-defined exceptions" - "exceptions, examples" - "exceptions, user-defined" -ms.assetid: 25819a5a-f915-4fc8-b924-a76915674e04 --- # How to create user-defined exceptions .NET provides a hierarchy of exception classes ultimately derived from the base class. However, if none of the predefined exceptions meet your needs, you can create your own exception class by deriving from the class. When creating your own exceptions, end the class name of the user-defined exception with the word "Exception", and implement the three common constructors, as shown in the following example. The example defines a new exception class named `EmployeeListNotFoundException`. The class is derived from the base class and includes three constructors. - -[!code-cpp[dg_exceptionDesign#14](../../../samples/snippets/cpp/VS_Snippets_CLR/dg_exceptionDesign/cpp/example2.cpp#14)] [!code-csharp[dg_exceptionDesign#14](../../../samples/snippets/csharp/VS_Snippets_CLR/dg_exceptionDesign/cs/example2.cs#14)] [!code-vb[dg_exceptionDesign#14](../../../samples/snippets/visualbasic/VS_Snippets_CLR/dg_exceptionDesign/vb/example2.vb#14)] diff --git a/docs/standard/exceptions/how-to-use-finally-blocks.md b/docs/standard/exceptions/how-to-use-finally-blocks.md index 977d287bf2af5..c70b9ac5e4656 100644 --- a/docs/standard/exceptions/how-to-use-finally-blocks.md +++ b/docs/standard/exceptions/how-to-use-finally-blocks.md @@ -2,27 +2,23 @@ description: "Learn more about: How to use finally blocks" title: "How to: Use Finally Blocks" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "exceptions, try/catch blocks" - "exceptions, finally blocks" - "try/catch blocks" - "finally blocks" - "ArgumentOutOfRangeException class" -ms.assetid: 4b9c0137-04af-4468-91d1-b9014df8ddd2 --- # How to use finally blocks When an exception occurs, execution stops and control is given to the appropriate exception handler. This often means that lines of code you expect to be executed are bypassed. Some resource cleanup, such as closing a file, needs to be done even if an exception is thrown. To do this, you can use a `finally` block. A `finally` block always executes, regardless of whether an exception is thrown. The following code example uses a `try`/`catch` block to catch an . The `Main` method creates two arrays and attempts to copy one to the other. The action generates an because `length` is specified as -1, and the error is written to the console. The `finally` block executes regardless of the outcome of the copy action. - -[!code-cpp[CodeTryCatchFinallyExample#3](../../../samples/snippets/cpp/VS_Snippets_CLR/CodeTryCatchFinallyExample/CPP/source2.cpp#3)] [!code-csharp[CodeTryCatchFinallyExample#3](./snippets/how-to-use-finally-blocks/csharp/source2.cs#3)] -[!code-vb[CodeTryCatchFinallyExample#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/CodeTryCatchFinallyExample/VB/source2.vb#3)] +[!code-vb[CodeTryCatchFinallyExample#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/CodeTryCatchFinallyExample/VB/source2.vb#3)] ## See also diff --git a/docs/standard/exceptions/how-to-use-specific-exceptions-in-a-catch-block.md b/docs/standard/exceptions/how-to-use-specific-exceptions-in-a-catch-block.md index dbfbae4872868..b606c9a4c4d9b 100644 --- a/docs/standard/exceptions/how-to-use-specific-exceptions-in-a-catch-block.md +++ b/docs/standard/exceptions/how-to-use-specific-exceptions-in-a-catch-block.md @@ -2,15 +2,13 @@ description: "Learn more about: How to use specific exceptions in a catch block" title: "How to: Use Specific Exceptions in a Catch Block" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "exceptions, try/catch blocks" - "try/catch blocks" - "catch blocks" -ms.assetid: 12af9ff3-8587-4f31-90cf-6c2244e0fdae --- # How to use specific exceptions in a catch block @@ -20,7 +18,6 @@ When an exception occurs, it is passed up the stack and each catch block is give The following code example uses a `try`/`catch` block to catch an . The sample creates a class called `Employee` with a single property, employee level (`Emlevel`). A method, `PromoteEmployee`, takes an object and increments the employee level. An occurs when a instance is passed to the `PromoteEmployee` method. -:::code language="cpp" source="./snippets/how-to-use-specific-exceptions-in-a-catch-block/cpp/catchexception.cpp" id="Snippet2"::: :::code language="csharp" source="./snippets/how-to-use-specific-exceptions-in-a-catch-block/csharp/catchexception.cs" id="Snippet2"::: :::code language="vb" source="./snippets/how-to-use-specific-exceptions-in-a-catch-block/vb/catchexception.vb" id="Snippet2"::: diff --git a/docs/standard/exceptions/how-to-use-the-try-catch-block-to-catch-exceptions.md b/docs/standard/exceptions/how-to-use-the-try-catch-block-to-catch-exceptions.md index 928e5427a4bab..67a9757575cf7 100644 --- a/docs/standard/exceptions/how-to-use-the-try-catch-block-to-catch-exceptions.md +++ b/docs/standard/exceptions/how-to-use-the-try-catch-block-to-catch-exceptions.md @@ -2,16 +2,14 @@ title: "How to: Use the Try-Catch Block to Catch Exceptions" description: Use the try block to contain statements that might raise or throw an exception. Place statements to handle exceptions in one or more catch blocks. ms.date: "02/06/2019" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "exceptions, try/catch blocks" - "try blocks" - "try/catch blocks" - "catch blocks" -ms.assetid: a3ce6dfd-1f64-471b-8ad8-8cfaf406275d --- # How to use the try/catch block to catch exceptions @@ -19,7 +17,6 @@ Place any code statements that might raise or throw an exception in a `try` bloc In the following example, a opens a file called *data.txt* and retrieves a line from the file. Since the code might throw any of three exceptions, it's placed in a `try` block. Three `catch` blocks catch the exceptions and handle them by displaying the results to the console. -:::code language="cpp" source="./snippets/how-to-use-the-try-catch-block-to-catch-exceptions/cpp/catchexception.cpp" id="Snippet3"::: :::code language="csharp" source="./snippets/how-to-use-the-try-catch-block-to-catch-exceptions/csharp/catchexception.cs" id="Snippet3"::: :::code language="vb" source="./snippets/how-to-use-the-try-catch-block-to-catch-exceptions/vb/catchexception.vb" id="Snippet3"::: diff --git a/docs/standard/garbage-collection/notifications.md b/docs/standard/garbage-collection/notifications.md index 995346b3ca433..acc46095c52a2 100644 --- a/docs/standard/garbage-collection/notifications.md +++ b/docs/standard/garbage-collection/notifications.md @@ -2,122 +2,108 @@ description: "Learn more about: Garbage Collection Notifications" title: "Garbage Collection Notifications" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "garbage collection, notifications" -ms.assetid: e12d8e74-31e3-4035-a87d-f3e66f0a9b89 --- -# Garbage Collection Notifications +# Garbage collection notifications + +There are situations in which a full garbage collection (that is, a generation 2 collection) by the common language runtime may adversely affect performance. This can be an issue particularly with servers that process large volumes of requests; in this case, a long garbage collection can cause a request time-out. To prevent a full collection from occurring during a critical period, you can be notified that a full garbage collection is approaching and then take action to redirect the workload to another server instance. You can also induce a collection yourself, provided that the current server instance does not need to process requests. + + The 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. -There are situations in which a full garbage collection (that is, a generation 2 collection) by the common language runtime may adversely affect performance. This can be an issue particularly with servers that process large volumes of requests; in this case, a long garbage collection can cause a request time-out. To prevent a full collection from occurring during a critical period, you can be notified that a full garbage collection is approaching and then take action to redirect the workload to another server instance. You can also induce a collection yourself, provided that the current server instance does not need to process requests. - - The 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 [\](../../framework/configure-apps/file-schema/runtime/gcconcurrent-element.md) configuration element is enabled, may return `NotApplicable` if the full GC was done as a background GC. - - To determine when a notification has been raised, use the and methods. Typically, you use these methods in a `while` loop to continually obtain a enumeration that shows the status of the notification. If that value is , you can do the following: - -- In response to a notification obtained with the method, you can redirect the workload and possibly induce a collection yourself. - -- In response to a notification obtained with the method, you can make the current server instance available to process requests again. You can also gather information. For example, you can use the method to record the number of collections. - - The and the methods are designed to work together. Using one without the other can produce indeterminate results. - -## Full Garbage Collection - - The runtime causes a full garbage collection when any of the following scenarios are true: - -- Enough memory has been promoted into generation 2 to cause the next generation 2 collection. - -- Enough memory has been promoted into the large object heap to cause the next generation 2 collection. - -- A collection of generation 1 is escalated to a collection of generation 2 due to other factors. - - The thresholds you specify in the method apply to the first two scenarios. However, in the first scenario you will not always receive the notification at the time proportional to the threshold values you specify for two reasons: - -- The runtime does not check each small object allocation (for performance reasons). - -- Only generation 1 collections promote memory into generation 2. - - The third scenario also contributes to the uncertainty of when you will receive the notification. Although this is not a guarantee, it does prove to be a useful way to mitigate the effects of an inopportune full garbage collection by redirecting the requests during this time or inducing the collection yourself when it can be better accommodated. - -## Notification Threshold Parameters - - The method has two parameters to specify the threshold values of the generation 2 objects and the large object heap. When those values are met, a garbage collection notification should be raised. The following table describes these parameters. - -|Parameter|Description| -|---------------|-----------------| -|`maxGenerationThreshold`|A number between 1 and 99 that specifies when the notification should be raised based on the objects promoted in generation 2.| -|`largeObjectHeapThreshold`|A number between 1 and 99 that specifies when the notification should be raised based on the objects that are allocated in the large object heap.| - - If you specify a value that is too high, there is a high probability that you will receive a notification, but it could be too long a period to wait before the runtime causes a collection. If you induce a collection yourself, you may reclaim more objects than would be reclaimed if the runtime causes the collection. - - If you specify a value that is too low, the runtime may cause the collection before you have had sufficient time to be notified. - -## Example - -### Description - - In the following example, a group of servers service incoming Web requests. To simulate the workload of processing requests, byte arrays are added to a collection. Each server registers for a garbage collection notification and then starts a thread on the `WaitForFullGCProc` user method to continuously monitor the enumeration that is returned by the and the methods. - - The and the methods call their respective event-handling user methods when a notification is raised: - -- `OnFullGCApproachNotify` - - This method calls the `RedirectRequests` user method, which instructs the request queuing server to suspend sending requests to the server. This is simulated by setting the class-level variable `bAllocate` to `false` so that no more objects are allocated. - - Next, the `FinishExistingRequests` user method is called to finish processing the pending server requests. This is simulated by clearing the collection. - - Finally, a garbage collection is induced because the workload is light. - -- `OnFullGCCompleteNotify` - - This method calls the user method `AcceptRequests` to resume accepting requests because the server is no longer susceptible to a full garbage collection. This action is simulated by setting the `bAllocate` variable to `true` so that objects can resume being added to the collection. - - The following code contains the `Main` method of the example. - - [!code-cpp[GCNotification#2](../../../samples/snippets/cpp/VS_Snippets_CLR/GCNotification/cpp/program.cpp#2)] +> When the [\](../../framework/configure-apps/file-schema/runtime/gcconcurrent-element.md) configuration element is enabled, may return `NotApplicable` if the full GC was done as a background GC. + + To determine when a notification has been raised, use the and methods. Typically, you use these methods in a `while` loop to continually obtain a enumeration that shows the status of the notification. If that value is , you can do the following: + +- In response to a notification obtained with the method, you can redirect the workload and possibly induce a collection yourself. + +- In response to a notification obtained with the method, you can make the current server instance available to process requests again. You can also gather information. For example, you can use the method to record the number of collections. + + The and the methods are designed to work together. Using one without the other can produce indeterminate results. + +## Full Garbage Collection + + The runtime causes a full garbage collection when any of the following scenarios are true: + +- Enough memory has been promoted into generation 2 to cause the next generation 2 collection. + +- Enough memory has been promoted into the large object heap to cause the next generation 2 collection. + +- A collection of generation 1 is escalated to a collection of generation 2 due to other factors. + + The thresholds you specify in the method apply to the first two scenarios. However, in the first scenario you will not always receive the notification at the time proportional to the threshold values you specify for two reasons: + +- The runtime does not check each small object allocation (for performance reasons). + +- Only generation 1 collections promote memory into generation 2. + + The third scenario also contributes to the uncertainty of when you will receive the notification. Although this is not a guarantee, it does prove to be a useful way to mitigate the effects of an inopportune full garbage collection by redirecting the requests during this time or inducing the collection yourself when it can be better accommodated. + +## Notification Threshold Parameters + + The method has two parameters to specify the threshold values of the generation 2 objects and the large object heap. When those values are met, a garbage collection notification should be raised. The following table describes these parameters. + +|Parameter|Description| +|---------------|-----------------| +|`maxGenerationThreshold`|A number between 1 and 99 that specifies when the notification should be raised based on the objects promoted in generation 2.| +|`largeObjectHeapThreshold`|A number between 1 and 99 that specifies when the notification should be raised based on the objects that are allocated in the large object heap.| + + If you specify a value that is too high, there is a high probability that you will receive a notification, but it could be too long a period to wait before the runtime causes a collection. If you induce a collection yourself, you may reclaim more objects than would be reclaimed if the runtime causes the collection. + + If you specify a value that is too low, the runtime may cause the collection before you have had sufficient time to be notified. + +## Example + +### Description + + In the following example, a group of servers service incoming Web requests. To simulate the workload of processing requests, byte arrays are added to a collection. Each server registers for a garbage collection notification and then starts a thread on the `WaitForFullGCProc` user method to continuously monitor the enumeration that is returned by the and the methods. + + The and the methods call their respective event-handling user methods when a notification is raised: + +- `OnFullGCApproachNotify` + + This method calls the `RedirectRequests` user method, which instructs the request queuing server to suspend sending requests to the server. This is simulated by setting the class-level variable `bAllocate` to `false` so that no more objects are allocated. + + Next, the `FinishExistingRequests` user method is called to finish processing the pending server requests. This is simulated by clearing the collection. + + Finally, a garbage collection is induced because the workload is light. + +- `OnFullGCCompleteNotify` + + This method calls the user method `AcceptRequests` to resume accepting requests because the server is no longer susceptible to a full garbage collection. This action is simulated by setting the `bAllocate` variable to `true` so that objects can resume being added to the collection. + + The following code contains the `Main` method of the example. [!code-csharp[GCNotification#2](../../../samples/snippets/csharp/VS_Snippets_CLR/GCNotification/cs/Program.cs#2)] - [!code-vb[GCNotification#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#2)] - - The following code contains the `WaitForFullGCProc` user method, that contains a continuous while loop to check for garbage collection notifications. - - [!code-cpp[GCNotification#8](../../../samples/snippets/cpp/VS_Snippets_CLR/GCNotification/cpp/program.cpp#8)] + [!code-vb[GCNotification#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#2)] + + The following code contains the `WaitForFullGCProc` user method, that contains a continuous while loop to check for garbage collection notifications. [!code-csharp[GCNotification#8](../../../samples/snippets/csharp/VS_Snippets_CLR/GCNotification/cs/Program.cs#8)] - [!code-vb[GCNotification#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#8)] - - The following code contains the `OnFullGCApproachNotify` method as called from the - - `WaitForFullGCProc` method. - - [!code-cpp[GCNotification#5](../../../samples/snippets/cpp/VS_Snippets_CLR/GCNotification/cpp/program.cpp#5)] + [!code-vb[GCNotification#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#8)] + + The following code contains the `OnFullGCApproachNotify` method as called from the + + `WaitForFullGCProc` method. [!code-csharp[GCNotification#5](../../../samples/snippets/csharp/VS_Snippets_CLR/GCNotification/cs/Program.cs#5)] - [!code-vb[GCNotification#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#5)] - - The following code contains the `OnFullGCApproachComplete` method as called from the - - `WaitForFullGCProc` method. - - [!code-cpp[GCNotification#6](../../../samples/snippets/cpp/VS_Snippets_CLR/GCNotification/cpp/program.cpp#6)] + [!code-vb[GCNotification#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#5)] + + The following code contains the `OnFullGCApproachComplete` method as called from the + + `WaitForFullGCProc` method. [!code-csharp[GCNotification#6](../../../samples/snippets/csharp/VS_Snippets_CLR/GCNotification/cs/Program.cs#6)] - [!code-vb[GCNotification#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#6)] - - The following code contains the user methods that are called from the `OnFullGCApproachNotify` and `OnFullGCCompleteNotify` methods. The user methods redirect requests, finish existing requests, and then resume requests after a full garbage collection has occurred. - - [!code-cpp[GCNotification#9](../../../samples/snippets/cpp/VS_Snippets_CLR/GCNotification/cpp/program.cpp#9)] + [!code-vb[GCNotification#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#6)] + + The following code contains the user methods that are called from the `OnFullGCApproachNotify` and `OnFullGCCompleteNotify` methods. The user methods redirect requests, finish existing requests, and then resume requests after a full garbage collection has occurred. [!code-csharp[GCNotification#9](../../../samples/snippets/csharp/VS_Snippets_CLR/GCNotification/cs/Program.cs#9)] - [!code-vb[GCNotification#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#9)] - - The entire code sample is as follows: - - [!code-cpp[GCNotification#1](../../../samples/snippets/cpp/VS_Snippets_CLR/GCNotification/cpp/program.cpp#1)] + [!code-vb[GCNotification#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#9)] + + The entire code sample is as follows: [!code-csharp[GCNotification#1](../../../samples/snippets/csharp/VS_Snippets_CLR/GCNotification/cs/Program.cs#1)] - [!code-vb[GCNotification#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#1)] - + [!code-vb[GCNotification#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/GCNotification/vb/program.vb#1)] + ## See also - [Garbage Collection](index.md) diff --git a/docs/standard/generics/collections.md b/docs/standard/generics/collections.md index 403b38aae4a8c..317df78e32fa7 100644 --- a/docs/standard/generics/collections.md +++ b/docs/standard/generics/collections.md @@ -5,7 +5,6 @@ ms.date: "02/15/2018" dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "generics [.NET], collections" - "generic collections [.NET]" @@ -39,8 +38,6 @@ helpviewer_keywords: The generic structure provides a way to delimit a range of elements within a one-dimensional, zero-based array of any type. The generic type parameter is the type of the array's elements. The generic delegate eliminates the need to declare a delegate type to handle events, if your event follows the event-handling pattern used by .NET. For example, suppose you have created a `MyEventArgs` class, derived from , to hold the data for your event. You can then declare the event as follows: - - [!code-cpp[Conceptual.Generics.Overview#7](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source2.cpp#7)] [!code-csharp[Conceptual.Generics.Overview#7](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.generics.overview/cs/source2.cs#7)] [!code-vb[Conceptual.Generics.Overview#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.generics.overview/vb/source2.vb#7)] diff --git a/docs/standard/generics/index.md b/docs/standard/generics/index.md index d2b9f72c077d4..d341bc8491dc2 100644 --- a/docs/standard/generics/index.md +++ b/docs/standard/generics/index.md @@ -5,7 +5,6 @@ ms.date: 07/26/2022 dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "generic methods, type inference" - "generics [.NET], collections" @@ -36,14 +35,10 @@ Generics let you tailor a method, class, structure, or interface to the precise Generics are classes, structures, interfaces, and methods that have placeholders (type parameters) for one or more of the types that they store or use. A generic collection class might use a type parameter as a placeholder for the type of objects that it stores. The type parameters appear as the types of its fields and the parameter types of its methods. A generic method might use its type parameter as the type of its return value or as the type of one of its formal parameters. The following code illustrates a simple generic class definition. - - [!code-cpp[Conceptual.Generics.Overview#2](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source.cpp#2)] [!code-csharp[Conceptual.Generics.Overview#2](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.generics.overview/cs/source.cs#2)] [!code-vb[Conceptual.Generics.Overview#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.generics.overview/vb/source.vb#2)] When you create an instance of a generic class, you specify the actual types to substitute for the type parameters. This establishes a new generic class, referred to as a constructed generic class, with your chosen types substituted everywhere that the type parameters appear. The result is a type-safe class that is tailored to your choice of types, as the following code illustrates. - - [!code-cpp[Conceptual.Generics.Overview#3](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source.cpp#3)] [!code-csharp[Conceptual.Generics.Overview#3](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.generics.overview/cs/source.cs#3)] [!code-vb[Conceptual.Generics.Overview#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.generics.overview/vb/source.vb#3)] @@ -67,13 +62,11 @@ The following terms are used to discuss generics in .NET: - A *generic method definition* is a method with two parameter lists: a list of generic type parameters and a list of formal parameters. Type parameters can appear as the return type or as the types of the formal parameters, as the following code shows. - [!code-cpp[Conceptual.Generics.Overview#4](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source.cpp#4)] [!code-csharp[Conceptual.Generics.Overview#4](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.generics.overview/cs/source.cs#4)] [!code-vb[Conceptual.Generics.Overview#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.generics.overview/vb/source.vb#4)] Generic methods can appear on generic or nongeneric types. It's important to note that a method is not generic just because it belongs to a generic type, or even because it has formal parameters whose types are the generic parameters of the enclosing type. A method is generic only if it has its own list of type parameters. In the following code, only method `G` is generic. - [!code-cpp[Conceptual.Generics.Overview#5](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source.cpp#5)] [!code-csharp[Conceptual.Generics.Overview#5](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.generics.overview/cs/source.cs#5)] [!code-vb[Conceptual.Generics.Overview#5](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.generics.overview/vb/source.vb#5)] @@ -85,9 +78,8 @@ There are many advantages to using generic collections and delegates: - Less code and code is more easily reused. There is no need to inherit from a base type and override members. For example, the is ready for immediate use. For example, you can create a linked list of strings with the following variable declaration: - [!code-cpp[HowToGeneric#24](../../../samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/source2.cpp#24)] - [!code-csharp[HowToGeneric#24](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/source2.cs#24)] - [!code-vb[HowToGeneric#24](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/source2.vb#24)] + [!code-csharp[HowToGeneric#24](../../../samples/snippets/csharp/VS_Snippets_CLR/HowToGeneric/CS/source2.cs#24)] + [!code-vb[HowToGeneric#24](../../../samples/snippets/visualbasic/VS_Snippets_CLR/HowToGeneric/VB/source2.vb#24)] - Better performance. Generic collection types generally perform better for storing and manipulating value types because there is no need to box the value types. diff --git a/docs/standard/io/how-to-anticipate-out-of-space-conditions-with-isolated-storage.md b/docs/standard/io/how-to-anticipate-out-of-space-conditions-with-isolated-storage.md index ef5b4f8c97d1b..c767117296b72 100644 --- a/docs/standard/io/how-to-anticipate-out-of-space-conditions-with-isolated-storage.md +++ b/docs/standard/io/how-to-anticipate-out-of-space-conditions-with-isolated-storage.md @@ -5,7 +5,6 @@ ms.date: "03/30/2017" dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "data stores, quotas" - "isolated storage, quotas" @@ -21,7 +20,6 @@ helpviewer_keywords: - "quotas for isolated storage" - "isolated storage, out of space conditions" - "data storage using isolated storage, out of space conditions" -ms.assetid: e35d4535-3732-421e-b1a3-37412e036145 --- # How to: Anticipate Out-of-Space Conditions with Isolated Storage @@ -35,8 +33,6 @@ The property depends o ## Example The following code example obtains an isolated store, creates a few files, and retrieves the property. The remaining space is reported in bytes. - -[!code-cpp[Conceptual.IsolatedStorage#8](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source7.cpp#8)] [!code-csharp[Conceptual.IsolatedStorage#8](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source7.cs#8)] [!code-vb[Conceptual.IsolatedStorage#8](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source7.vb#8)] diff --git a/docs/standard/io/how-to-delete-files-and-directories-in-isolated-storage.md b/docs/standard/io/how-to-delete-files-and-directories-in-isolated-storage.md index 3541bf34df88e..9adc6d2e4452c 100644 --- a/docs/standard/io/how-to-delete-files-and-directories-in-isolated-storage.md +++ b/docs/standard/io/how-to-delete-files-and-directories-in-isolated-storage.md @@ -2,11 +2,10 @@ description: "Learn more about: How to: Delete Files and Directories in Isolated Storage" title: "How to: Delete Files and Directories in Isolated Storage" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "data storage using isolated storage, deleting files and directories" - "directories [.NET], isolated storage" - "files [.NET], isolated storage" @@ -16,24 +15,21 @@ helpviewer_keywords: - "deleting files within isolated stage file" - "storing data using isolated storage, deleting files and directories" - "deleting directories within isolated stage file" -ms.assetid: 8fcc0dea-435b-4d40-ba4d-ba056265c202 --- # How to: Delete Files and Directories in Isolated Storage -You can delete directories and files within an isolated storage file. Within a store, file and directory names are operating-system dependent and are specified as relative to the root of the virtual file system. They are not case-sensitive on Windows operating systems. - - The class supplies two methods for deleting directories and files: and . An exception is thrown if you try to delete a file or directory that does not exist. If you include a wildcard character in the name, throws an exception, and throws an exception. - - The method fails if the directory contains any files or subdirectories. You can use the and methods to retrieve the existing files and directories. For more information about searching the virtual file system of a store, see [How to: Find Existing Files and Directories in Isolated Storage](how-to-find-existing-files-and-directories-in-isolated-storage.md). - -## Example +You can delete directories and files within an isolated storage file. Within a store, file and directory names are operating-system dependent and are specified as relative to the root of the virtual file system. They are not case-sensitive on Windows operating systems. - The following code example creates and then deletes several directories and files. - - [!code-cpp[Conceptual.IsolatedStorage#4](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source4.cpp#4)] + The class supplies two methods for deleting directories and files: and . An exception is thrown if you try to delete a file or directory that does not exist. If you include a wildcard character in the name, throws an exception, and throws an exception. + + The method fails if the directory contains any files or subdirectories. You can use the and methods to retrieve the existing files and directories. For more information about searching the virtual file system of a store, see [How to: Find Existing Files and Directories in Isolated Storage](how-to-find-existing-files-and-directories-in-isolated-storage.md). + +## Example + + The following code example creates and then deletes several directories and files. [!code-csharp[Conceptual.IsolatedStorage#4](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source4.cs#4)] - [!code-vb[Conceptual.IsolatedStorage#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source4.vb#4)] - + [!code-vb[Conceptual.IsolatedStorage#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source4.vb#4)] + ## See also - diff --git a/docs/standard/io/how-to-delete-stores-in-isolated-storage.md b/docs/standard/io/how-to-delete-stores-in-isolated-storage.md index 93ccef5b15e72..1a9266ed8f169 100644 --- a/docs/standard/io/how-to-delete-stores-in-isolated-storage.md +++ b/docs/standard/io/how-to-delete-stores-in-isolated-storage.md @@ -2,11 +2,10 @@ description: "Learn more about: How to: Delete Stores in Isolated Storage" title: "How to: Delete Stores in Isolated Storage" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "stores, deleting" - "data stores, deleting" - "deleting stores" @@ -14,24 +13,21 @@ helpviewer_keywords: - "isolated storage, deleting stores" - "storing data using isolated storage, deleting stores" - "data storage using isolated storage, deleting stores" -ms.assetid: 3947e333-5af6-4601-b2f1-24d4d6129cf3 --- -# How to: Delete Stores in Isolated Storage +# How to: Delete stores in isolated storage -The class supplies two methods for deleting isolated storage files: - -- The instance method does not take any arguments and deletes the store that calls it. No permissions are required for this operation. Any code that can access the store can delete any or all the data inside it. - -- The static method takes the enumeration value, and deletes all the stores for the user who is running the code. This operation requires permission for the value. - -## Example +The class supplies two methods for deleting isolated storage files: - The following code example demonstrates the use of the static and instance methods. The class obtains two stores; one is isolated for user and assembly and the other is isolated for user, domain, and assembly. The user, domain, and assembly store is then deleted by calling the method of the isolated storage file `isoStore1`. Then, all remaining stores for the user are deleted by calling the static method . - - [!code-cpp[Conceptual.IsolatedStorage#3](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source3.cpp#3)] +- The instance method does not take any arguments and deletes the store that calls it. No permissions are required for this operation. Any code that can access the store can delete any or all the data inside it. + +- The static method takes the enumeration value, and deletes all the stores for the user who is running the code. This operation requires permission for the value. + +## Example + + The following code example demonstrates the use of the static and instance methods. The class obtains two stores; one is isolated for user and assembly and the other is isolated for user, domain, and assembly. The user, domain, and assembly store is then deleted by calling the method of the isolated storage file `isoStore1`. Then, all remaining stores for the user are deleted by calling the static method . [!code-csharp[Conceptual.IsolatedStorage#3](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source3.cs#3)] - [!code-vb[Conceptual.IsolatedStorage#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source3.vb#3)] - + [!code-vb[Conceptual.IsolatedStorage#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source3.vb#3)] + ## See also - diff --git a/docs/standard/io/how-to-find-existing-files-and-directories-in-isolated-storage.md b/docs/standard/io/how-to-find-existing-files-and-directories-in-isolated-storage.md index 70dad9945ff09..9391af35c9a75 100644 --- a/docs/standard/io/how-to-find-existing-files-and-directories-in-isolated-storage.md +++ b/docs/standard/io/how-to-find-existing-files-and-directories-in-isolated-storage.md @@ -2,11 +2,10 @@ description: "Learn more about: How to: Find Existing Files and Directories in Isolated Storage" title: "How to: Find Existing Files and Directories in Isolated Storage" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "stores, finding files and directories" - "locating files in isolated storage file" - "directories [.NET], isolated storage" @@ -16,24 +15,21 @@ helpviewer_keywords: - "data stores, finding files and directories" - "locating directories in isolated storage file" - "storing data using isolated storage, finding files and directories" -ms.assetid: eb28458a-6161-4e7a-9ada-30ef93761b5c --- -# How to: Find Existing Files and Directories in Isolated Storage +# How to: Find existing files and directories in isolated storage -To search for a directory in isolated storage, use the method. This method takes a string that represents a search pattern. You can use both single-character (?) and multi-character (\*) wildcard characters in the search pattern, but the wildcard characters must appear in the final portion of the name. For example, `directory1/*ect*` is a valid search string, but `*ect*/directory2` is not. - - To search for a file, use the method. The restriction for wildcard characters in search strings that applies to also applies to . - - Neither of these methods is recursive; the class does not supply any methods for listing all directories or files in your store. However, recursive methods are shown in the following code example. - -## Example +To search for a directory in isolated storage, use the method. This method takes a string that represents a search pattern. You can use both single-character (?) and multi-character (\*) wildcard characters in the search pattern, but the wildcard characters must appear in the final portion of the name. For example, `directory1/*ect*` is a valid search string, but `*ect*/directory2` is not. - The following code example illustrates how to create files and directories in an isolated store. First, a store that is isolated for user, domain, and assembly is retrieved and placed in the `isoStore` variable. The method is used to set up a few different directories, and the constructor creates some files in these directories. The code then loops through the results of the `GetAllDirectories` method. This method uses to find all the directory names in the current directory. These names are stored in an array, and then `GetAllDirectories` calls itself, passing in each directory it has found. As a result, all the directory names are returned in an array. Next, the code calls the `GetAllFiles` method. This method calls `GetAllDirectories` to find out the names of all the directories, and then it checks each directory for files by using the method. The result is returned in an array for display. - - [!code-cpp[Conceptual.IsolatedStorage#9](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source8.cpp#9)] + To search for a file, use the method. The restriction for wildcard characters in search strings that applies to also applies to . + + Neither of these methods is recursive; the class does not supply any methods for listing all directories or files in your store. However, recursive methods are shown in the following code example. + +## Example + + The following code example illustrates how to create files and directories in an isolated store. First, a store that is isolated for user, domain, and assembly is retrieved and placed in the `isoStore` variable. The method is used to set up a few different directories, and the constructor creates some files in these directories. The code then loops through the results of the `GetAllDirectories` method. This method uses to find all the directory names in the current directory. These names are stored in an array, and then `GetAllDirectories` calls itself, passing in each directory it has found. As a result, all the directory names are returned in an array. Next, the code calls the `GetAllFiles` method. This method calls `GetAllDirectories` to find out the names of all the directories, and then it checks each directory for files by using the method. The result is returned in an array for display. [!code-csharp[Conceptual.IsolatedStorage#9](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source8.cs#9)] - [!code-vb[Conceptual.IsolatedStorage#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source8.vb#9)] - + [!code-vb[Conceptual.IsolatedStorage#9](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source8.vb#9)] + ## See also - diff --git a/docs/standard/io/how-to-obtain-stores-for-isolated-storage.md b/docs/standard/io/how-to-obtain-stores-for-isolated-storage.md index e22f38743206b..993f53029197a 100644 --- a/docs/standard/io/how-to-obtain-stores-for-isolated-storage.md +++ b/docs/standard/io/how-to-obtain-stores-for-isolated-storage.md @@ -2,54 +2,48 @@ description: "Learn more about: How to: Obtain Stores for Isolated Storage" title: "How to: Obtain Stores for Isolated Storage" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "stores, obtaining" - "storing data using isolated storage, obtaining stores" - "isolated storage, obtaining stores" - "data stores, obtaining" - "data storage using isolated storage, obtaining stores" -ms.assetid: fcb6b178-d526-47c4-b029-e946f880f9db --- -# How to: Obtain Stores for Isolated Storage - -An isolated store exposes a virtual file system within a data compartment. The class supplies a number of methods for interacting with an isolated store. To create and retrieve stores, provides three static methods: - -- returns storage that is isolated by user and assembly. - -- returns storage that is isolated by domain and assembly. - - Both methods retrieve a store that belongs to the code from which they are called. - -- The static method returns an isolated store that is specified by passing in a combination of scope parameters. - - The following code returns a store that is isolated by user, assembly, and domain. - - [!code-cpp[Conceptual.IsolatedStorage#6](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source6.cpp#6)] +# How to: Obtain stores for isolated storage + +An isolated store exposes a virtual file system within a data compartment. The class supplies a number of methods for interacting with an isolated store. To create and retrieve stores, provides three static methods: + +- returns storage that is isolated by user and assembly. + +- returns storage that is isolated by domain and assembly. + + Both methods retrieve a store that belongs to the code from which they are called. + +- The static method returns an isolated store that is specified by passing in a combination of scope parameters. + + The following code returns a store that is isolated by user, assembly, and domain. [!code-csharp[Conceptual.IsolatedStorage#6](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source6.cs#6)] - [!code-vb[Conceptual.IsolatedStorage#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source6.vb#6)] - - You can use the method to specify that a store should roam with a roaming user profile. For details on how to set this up, see [Types of Isolation](types-of-isolation.md). - - Isolated stores obtained from within different assemblies are, by default, different stores. You can access the store of a different assembly or domain by passing in the assembly or domain evidence in the parameters of the method. This requires permission to access isolated storage by application domain identity. For more information, see the method overloads. - - The , , and methods return an object. To help you decide which isolation type is most appropriate for your situation, see [Types of Isolation](types-of-isolation.md). When you have an isolated storage file object, you can use the isolated storage methods to read, write, create, and delete files and directories. - - There is no mechanism that prevents code from passing an object to code that does not have sufficient access to get the store itself. Domain and assembly identities and isolated storage permissions are checked only when a reference to an object is obtained, typically in the , , or method. Protecting references to objects is, therefore, the responsibility of the code that uses these references. - -## Example - - The following code provides a simple example of a class obtaining a store that is isolated by user and assembly. The code can be changed to retrieve a store that is isolated by user, domain, and assembly by adding to the arguments that the method passes. - - After you run the code, you can confirm that a store was created by typing **StoreAdm /LIST** at the command line. This runs the [Isolated Storage tool (Storeadm.exe)](../../framework/tools/storeadm-exe-isolated-storage-tool.md) and lists all the current isolated stores for the user. - - [!code-cpp[Conceptual.IsolatedStorage#7](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source6.cpp#7)] + [!code-vb[Conceptual.IsolatedStorage#6](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source6.vb#6)] + + You can use the method to specify that a store should roam with a roaming user profile. For details on how to set this up, see [Types of Isolation](types-of-isolation.md). + + Isolated stores obtained from within different assemblies are, by default, different stores. You can access the store of a different assembly or domain by passing in the assembly or domain evidence in the parameters of the method. This requires permission to access isolated storage by application domain identity. For more information, see the method overloads. + + The , , and methods return an object. To help you decide which isolation type is most appropriate for your situation, see [Types of Isolation](types-of-isolation.md). When you have an isolated storage file object, you can use the isolated storage methods to read, write, create, and delete files and directories. + + There is no mechanism that prevents code from passing an object to code that does not have sufficient access to get the store itself. Domain and assembly identities and isolated storage permissions are checked only when a reference to an object is obtained, typically in the , , or method. Protecting references to objects is, therefore, the responsibility of the code that uses these references. + +## Example + + The following code provides a simple example of a class obtaining a store that is isolated by user and assembly. The code can be changed to retrieve a store that is isolated by user, domain, and assembly by adding to the arguments that the method passes. + + After you run the code, you can confirm that a store was created by typing **StoreAdm /LIST** at the command line. This runs the [Isolated Storage tool (Storeadm.exe)](../../framework/tools/storeadm-exe-isolated-storage-tool.md) and lists all the current isolated stores for the user. [!code-csharp[Conceptual.IsolatedStorage#7](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source6.cs#7)] - [!code-vb[Conceptual.IsolatedStorage#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source6.vb#7)] - + [!code-vb[Conceptual.IsolatedStorage#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source6.vb#7)] + ## See also - diff --git a/docs/standard/io/how-to-read-and-write-to-a-newly-created-data-file.md b/docs/standard/io/how-to-read-and-write-to-a-newly-created-data-file.md index 48c2b6cfb1813..6798f8e2faccb 100644 --- a/docs/standard/io/how-to-read-and-write-to-a-newly-created-data-file.md +++ b/docs/standard/io/how-to-read-and-write-to-a-newly-created-data-file.md @@ -2,43 +2,41 @@ title: "How to: Read and write to a newly created data file" description: Learn how to read and write to a newly created data file in .NET using the System.IO.BinaryReader and System.IO.BinaryWriter classes. ms.date: "01/21/2019" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "streams, reading and writing data" - "BinaryReader class, examples" - "I/O [.NET], reading data" - "I/O [.NET], writing data" - "BinaryWriter class, examples" -ms.assetid: e209d949-31e8-44ea-8e38-87f9093f3093 --- # How to: Read and write to a newly created data file The and classes are used for writing and reading data other than character strings. The following example shows how to create an empty file stream, write data to it, and read data from it. -The example creates a data file called *Test.data* in the current directory, creates the associated and objects, and uses the object to write the integers 0 through 10 to *Test.data*, which leaves the file pointer at the end of the file. The object then sets the file pointer back to the origin and reads out the specified content. - +The example creates a data file called *Test.data* in the current directory, creates the associated and objects, and uses the object to write the integers 0 through 10 to *Test.data*, which leaves the file pointer at the end of the file. The object then sets the file pointer back to the origin and reads out the specified content. + > [!NOTE] -> If *Test.data* already exists in the current directory, an exception is thrown. Use the file mode option rather than to always create a new file without throwing an exception. - -## Example +> If *Test.data* already exists in the current directory, an exception is thrown. Use the file mode option rather than to always create a new file without throwing an exception. + +## Example [!code-csharp[System.IO.BinaryReaderWriter#7](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.BinaryReaderWriter/CS/source6.cs#7)] - [!code-vb[System.IO.BinaryReaderWriter#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BinaryReaderWriter/VB/source6.vb#7)] - + [!code-vb[System.IO.BinaryReaderWriter#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.BinaryReaderWriter/VB/source6.vb#7)] + ## See also -- -- -- -- -- -- [How to: Enumerate directories and files](how-to-enumerate-directories-and-files.md) -- [How to: Open and append to a log file](how-to-open-and-append-to-a-log-file.md) -- [How to: Read text from a file](how-to-read-text-from-a-file.md) -- [How to: Write text to a file](how-to-write-text-to-a-file.md) -- [How to: Read characters from a string](how-to-read-characters-from-a-string.md) -- [How to: Write characters to a string](how-to-write-characters-to-a-string.md) +- +- +- +- +- +- [How to: Enumerate directories and files](how-to-enumerate-directories-and-files.md) +- [How to: Open and append to a log file](how-to-open-and-append-to-a-log-file.md) +- [How to: Read text from a file](how-to-read-text-from-a-file.md) +- [How to: Write text to a file](how-to-write-text-to-a-file.md) +- [How to: Read characters from a string](how-to-read-characters-from-a-string.md) +- [How to: Write characters to a string](how-to-write-characters-to-a-string.md) - [File and stream I/O](index.md) diff --git a/docs/standard/io/how-to-read-characters-from-a-string.md b/docs/standard/io/how-to-read-characters-from-a-string.md index 7a5656e5969f6..f13805d7e3708 100644 --- a/docs/standard/io/how-to-read-characters-from-a-string.md +++ b/docs/standard/io/how-to-read-characters-from-a-string.md @@ -2,11 +2,10 @@ title: "How to: Read characters from a string" description: Learn how to read characters from a string in .NET. See examples of character reading synchronously and asynchronously. ms.date: "01/21/2019" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "reading characters from strings" - "data streams, reading characters from string" - "I/O [.NET], reading characters from strings" @@ -16,31 +15,31 @@ ms.assetid: 27ea5e52-6db8-42d8-980a-50bcfc7fd270 --- # How to: Read characters from a string -The following code examples show how to read characters synchronously or asynchronously from a string. - +The following code examples show how to read characters synchronously or asynchronously from a string. + ## Example: Read characters synchronously - This example reads 13 characters synchronously from a string, stores them in an array, and displays them. The example then reads the rest of the characters in the string, stores them in the array starting at the sixth element, and displays the contents of the array. - + This example reads 13 characters synchronously from a string, stores them in an array, and displays them. The example then reads the rest of the characters in the string, stores them in the array starting at the sixth element, and displays the contents of the array. + [!code-csharp[Conceptual.StringReader#1](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.stringreader/cs/source.cs#1)] - [!code-vb[Conceptual.StringReader#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.stringreader/vb/source.vb#1)] - -## Example: Read characters asynchronously + [!code-vb[Conceptual.StringReader#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.stringreader/vb/source.vb#1)] + +## Example: Read characters asynchronously + + The next example is the code behind a WPF app. On window load, the example asynchronously reads all characters from a control and stores them in an array. It then asynchronously writes each letter or white-space character to a separate line of a control. - The next example is the code behind a WPF app. On window load, the example asynchronously reads all characters from a control and stores them in an array. It then asynchronously writes each letter or white-space character to a separate line of a control. - [!code-csharp[Conceptual.StringReader#2](../../../samples/snippets/csharp/VS_Snippets_Wpf/StringReaderWriter/MainWindow.xaml.cs)] - [!code-vb[Conceptual.StringReader#2](../../../samples/snippets/visualbasic/VS_Snippets_Wpf/StringReaderWriter/MainWindow.xaml.vb)] - + [!code-vb[Conceptual.StringReader#2](../../../samples/snippets/visualbasic/VS_Snippets_Wpf/StringReaderWriter/MainWindow.xaml.vb)] + ## See also -- -- -- [Asynchronous file I/O](asynchronous-file-i-o.md) -- [How to: Create a directory listing](/previous-versions/dotnet/netframework-4.0/5cf8zcfh(v=vs.100)) -- [How to: Read and write to a newly created data file](how-to-read-and-write-to-a-newly-created-data-file.md) -- [How to: Open and append to a log file](how-to-open-and-append-to-a-log-file.md) -- [How to: Read text from a file](how-to-read-text-from-a-file.md) -- [How to: Write text to a file](how-to-write-text-to-a-file.md) -- [How to: Write characters to a string](how-to-write-characters-to-a-string.md) +- +- +- [Asynchronous file I/O](asynchronous-file-i-o.md) +- [How to: Create a directory listing](/previous-versions/dotnet/netframework-4.0/5cf8zcfh(v=vs.100)) +- [How to: Read and write to a newly created data file](how-to-read-and-write-to-a-newly-created-data-file.md) +- [How to: Open and append to a log file](how-to-open-and-append-to-a-log-file.md) +- [How to: Read text from a file](how-to-read-text-from-a-file.md) +- [How to: Write text to a file](how-to-write-text-to-a-file.md) +- [How to: Write characters to a string](how-to-write-characters-to-a-string.md) - [File and stream I/O](index.md) diff --git a/docs/standard/io/how-to-use-anonymous-pipes-for-local-interprocess-communication.md b/docs/standard/io/how-to-use-anonymous-pipes-for-local-interprocess-communication.md index f1c2c833fc0a5..19e26cfc9896c 100644 --- a/docs/standard/io/how-to-use-anonymous-pipes-for-local-interprocess-communication.md +++ b/docs/standard/io/how-to-use-anonymous-pipes-for-local-interprocess-communication.md @@ -2,44 +2,38 @@ title: "How to: Use Anonymous Pipes for Local Interprocess Communication" description: Learn how to use anonymous pipes for local interprocess communication on a local computer in .NET. Anonymous pipes require less overhead than named pipes. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "anonymous pipes [.NET]" - "parent-child communication [.NET]" - "pipes [.NET]" - "one-way communication [.NET]" - "local computer communication [.NET], pipes" -ms.assetid: e7773c77-c646-4a01-8a96-a003d59fc4c9 --- -# How to: Use Anonymous Pipes for Local Interprocess Communication +# How to: Use anonymous pipes for local interprocess communication + +Anonymous pipes provide interprocess communication on a local computer. They offer less functionality than named pipes, but also require less overhead. You can use anonymous pipes to make interprocess communication on a local computer easier. You cannot use anonymous pipes for communication over a network. + + To implement anonymous pipes, use the and classes. -Anonymous pipes provide interprocess communication on a local computer. They offer less functionality than named pipes, but also require less overhead. You can use anonymous pipes to make interprocess communication on a local computer easier. You cannot use anonymous pipes for communication over a network. - - To implement anonymous pipes, use the and classes. - ## Example 1 - The following example demonstrates a way to send a string from a parent process to a child process using anonymous pipes. This example creates an object in a parent process with a value of . The parent process then creates a child process by using a client handle to create an object. The child process has a value of . - - The parent process then sends a user-supplied string to the child process. The string is displayed to the console in the child process. - - The following example shows the server process. - - [!code-cpp[System.IO.Pipes.AnonymousPipeServerStream_Sample#01](../../../samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cpp/program.cpp#01)] + The following example demonstrates a way to send a string from a parent process to a child process using anonymous pipes. This example creates an object in a parent process with a value of . The parent process then creates a child process by using a client handle to create an object. The child process has a value of . + + The parent process then sends a user-supplied string to the child process. The string is displayed to the console in the child process. + + The following example shows the server process. [!code-csharp[System.IO.Pipes.AnonymousPipeServerStream_Sample#01](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cs/Program.cs#01)] - [!code-vb[System.IO.Pipes.AnonymousPipeServerStream_Sample#01](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/vb/program.vb#01)] - -## Example 2 + [!code-vb[System.IO.Pipes.AnonymousPipeServerStream_Sample#01](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/vb/program.vb#01)] + +## Example 2 - The following example shows the client process. The server process starts the client process and gives that process a client handle. The resulting executable from the client code should be named `pipeClient.exe` and be copied to the same directory as the server executable before running the server process. - - [!code-cpp[System.IO.Pipes.AnonymousPipeClientStream_Sample#01](../../../samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cpp/program.cpp#01)] + The following example shows the client process. The server process starts the client process and gives that process a client handle. The resulting executable from the client code should be named `pipeClient.exe` and be copied to the same directory as the server executable before running the server process. [!code-csharp[System.IO.Pipes.AnonymousPipeClientStream_Sample#01](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cs/Program.cs#01)] - [!code-vb[System.IO.Pipes.AnonymousPipeClientStream_Sample#01](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/vb/program.vb#01)] - + [!code-vb[System.IO.Pipes.AnonymousPipeClientStream_Sample#01](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/vb/program.vb#01)] + ## See also - [Pipes](pipe-operations.md) diff --git a/docs/standard/io/how-to-use-named-pipes-for-network-interprocess-communication.md b/docs/standard/io/how-to-use-named-pipes-for-network-interprocess-communication.md index 061b5cb917247..88e318d7508ed 100644 --- a/docs/standard/io/how-to-use-named-pipes-for-network-interprocess-communication.md +++ b/docs/standard/io/how-to-use-named-pipes-for-network-interprocess-communication.md @@ -2,11 +2,10 @@ title: "How to: Use Named Pipes for Network Interprocess Communication" description: See two examples of using named pipes for interprocess communication between a pipe server and one or more pipe clients in a network. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "message-based communication [.NET], named pipes" - "named pipes [.NET]" - "pipes [.NET]" @@ -14,36 +13,33 @@ helpviewer_keywords: - "network communications [.NET], named pipes" - "impersonation [.NET], named pipes" - "full duplex communication [.NET], named pipes" -ms.assetid: 4e4d7e64-9f1b-4026-98f7-20488ac7b42b --- -# How to: Use Named Pipes for Network Interprocess Communication +# How to: Use named pipes for network interprocess communication -Named pipes provide interprocess communication between a pipe server and one or more pipe clients. They offer more functionality than anonymous pipes, which provide interprocess communication on a local computer. Named pipes support full duplex communication over a network and multiple server instances, message-based communication, and client impersonation, which enables connecting processes to use their own set of permissions on remote servers. +Named pipes provide interprocess communication between a pipe server and one or more pipe clients. They offer more functionality than anonymous pipes, which provide interprocess communication on a local computer. Named pipes support full duplex communication over a network and multiple server instances, message-based communication, and client impersonation, which enables connecting processes to use their own set of permissions on remote servers. > [!IMPORTANT] > .NET on Linux uses Unix Domain Sockets (UDS) for the implementation of these APIs. - To implement name pipes, use the and classes. - + To implement name pipes, use the and classes. + ## Example 1 - The following example demonstrates how to create a named pipe by using the class. In this example, the server process creates four threads. Each thread can accept a client connection. The connected client process then supplies the server with a file name. If the client has sufficient permissions, the server process opens the file and sends its contents back to the client. - - [!code-cpp[System.IO.Pipes.NamedPipeServerStream_ImpersonationSample1#01](../../../samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_ImpersonationSample1/cpp/program.cpp#01)] + The following example demonstrates how to create a named pipe by using the class. In this example, the server process creates four threads. Each thread can accept a client connection. The connected client process then supplies the server with a file name. If the client has sufficient permissions, the server process opens the file and sends its contents back to the client. [!code-csharp[System.IO.Pipes.NamedPipeServerStream_ImpersonationSample1#01](./snippets/how-to-use-named-pipes-for-network-interprocess-communication/csharp/NamedPipeServerStream_ImpersonationSample/Program.cs#01)] - [!code-vb[System.IO.Pipes.NamedPipeServerStream_ImpersonationSample1#01](./snippets/how-to-use-named-pipes-for-network-interprocess-communication/vb/NamedPipeServerStream_ImpersonationSample/program.vb#01)] - -## Example 2 + [!code-vb[System.IO.Pipes.NamedPipeServerStream_ImpersonationSample1#01](./snippets/how-to-use-named-pipes-for-network-interprocess-communication/vb/NamedPipeServerStream_ImpersonationSample/program.vb#01)] + +## Example 2 + + The following example shows the client process, which uses the class. The client connects to the server process and sends a file name to the server. The example uses impersonation, so the identity that is running the client application must have permission to access the file. The server then sends the contents of the file back to the client. The file contents are then displayed to the console. - The following example shows the client process, which uses the class. The client connects to the server process and sends a file name to the server. The example uses impersonation, so the identity that is running the client application must have permission to access the file. The server then sends the contents of the file back to the client. The file contents are then displayed to the console. - [!code-csharp[System.IO.Pipes.NamedPipeClientStream_ImpersonationSample1#01](./snippets/how-to-use-named-pipes-for-network-interprocess-communication/csharp/NamedPipeClientStream_ImpersonationSample/Program.cs#01)] - [!code-vb[System.IO.Pipes.NamedPipeClientStream_ImpersonationSample1#01](./snippets/how-to-use-named-pipes-for-network-interprocess-communication/vb//NamedPipeClientStream_ImpersonationSample/program.vb#01)] - -## Robust Programming + [!code-vb[System.IO.Pipes.NamedPipeClientStream_ImpersonationSample1#01](./snippets/how-to-use-named-pipes-for-network-interprocess-communication/vb//NamedPipeClientStream_ImpersonationSample/program.vb#01)] + +## Robust Programming + + The client and server processes in this example are intended to run on the same computer, so the server name provided to the object is `"."`. If the client and server processes were on separate computers, `"."` would be replaced with the network name of the computer that runs the server process. - The client and server processes in this example are intended to run on the same computer, so the server name provided to the object is `"."`. If the client and server processes were on separate computers, `"."` would be replaced with the network name of the computer that runs the server process. - ## See also - diff --git a/docs/standard/io/types-of-isolation.md b/docs/standard/io/types-of-isolation.md index 5712671c7bb7c..639f01b668515 100644 --- a/docs/standard/io/types-of-isolation.md +++ b/docs/standard/io/types-of-isolation.md @@ -2,11 +2,10 @@ description: "Learn more about: Types of isolation" title: "Types of Isolation" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "storing data using isolated storage, accessing isolated storage" - "storing data using isolated storage, isolation types" - "authentication [.NET], isolated storage" @@ -17,93 +16,80 @@ helpviewer_keywords: - "domain identity" - "isolated storage, types" - "user authentication, isolated storage" -ms.assetid: 14812988-473f-44ae-b75f-fd5c2f21fb7b --- # Types of isolation -Access to isolated storage is always restricted to the user who created it. To implement this type of isolation, the common language runtime uses the same notion of user identity that the operating system recognizes, which is the identity associated with the process in which the code is running when the store is opened. This identity is an authenticated user identity, but impersonation can cause the identity of the current user to change dynamically. - - Access to isolated storage is also restricted according to the identity associated with the application's domain and assembly, or with the assembly alone. The runtime obtains these identities in the following ways: - -- Domain identity represents the evidence of the application, which in the case of a web application might be the full URL. For shell-hosted code, the domain identity might be based on the application directory path. For example, if the executable runs from the path C:\Office\MyApp.exe, the domain identity would be C:\Office\MyApp.exe. - -- Assembly identity is the evidence of the assembly. This might come from a cryptographic digital signature, which can be the assembly's [strong name](../assembly/strong-named.md), the software publisher of the assembly, or its URL identity. If an assembly has both a strong name and a software publisher identity, then the software publisher identity is used. If the assembly comes from the Internet and is unsigned, the URL identity is used. For more information about assemblies and strong names, see [Programming with Assemblies](../assembly/index.md). - -- Roaming stores move with a user that has a roaming user profile. Files are written to a network directory and are downloaded to any computer the user logs into. For more information about roaming user profiles, see . - - By combining the concepts of user, domain, and assembly identity, isolated storage can isolate data in the following ways, each of which has its own usage scenarios: - -- [Isolation by user and assembly](#UserAssembly) - -- [Isolation by user, domain, and assembly](#UserDomainAssembly) - - Either of these isolations can be combined with a roaming user profile. For more information, see the section [Isolated Storage and Roaming](#Roaming). - - The following illustration demonstrates how stores are isolated in different scopes: - - ![Diagram that shows isolation by user and assembly.](./media/types-of-isolation/isolated-storage-types.gif) - - Except for roaming stores, isolated storage is always implicitly isolated by computer because it uses the storage facilities that are local to a given computer. - +Access to isolated storage is always restricted to the user who created it. To implement this type of isolation, the common language runtime uses the same notion of user identity that the operating system recognizes, which is the identity associated with the process in which the code is running when the store is opened. This identity is an authenticated user identity, but impersonation can cause the identity of the current user to change dynamically. + + Access to isolated storage is also restricted according to the identity associated with the application's domain and assembly, or with the assembly alone. The runtime obtains these identities in the following ways: + +- Domain identity represents the evidence of the application, which in the case of a web application might be the full URL. For shell-hosted code, the domain identity might be based on the application directory path. For example, if the executable runs from the path C:\Office\MyApp.exe, the domain identity would be C:\Office\MyApp.exe. + +- Assembly identity is the evidence of the assembly. This might come from a cryptographic digital signature, which can be the assembly's [strong name](../assembly/strong-named.md), the software publisher of the assembly, or its URL identity. If an assembly has both a strong name and a software publisher identity, then the software publisher identity is used. If the assembly comes from the Internet and is unsigned, the URL identity is used. For more information about assemblies and strong names, see [Programming with Assemblies](../assembly/index.md). + +- Roaming stores move with a user that has a roaming user profile. Files are written to a network directory and are downloaded to any computer the user logs into. For more information about roaming user profiles, see . + + By combining the concepts of user, domain, and assembly identity, isolated storage can isolate data in the following ways, each of which has its own usage scenarios: + +- [Isolation by user and assembly](#UserAssembly) + +- [Isolation by user, domain, and assembly](#UserDomainAssembly) + + Either of these isolations can be combined with a roaming user profile. For more information, see the section [Isolated Storage and Roaming](#Roaming). + + The following illustration demonstrates how stores are isolated in different scopes: + + ![Diagram that shows isolation by user and assembly.](./media/types-of-isolation/isolated-storage-types.gif) + + Except for roaming stores, isolated storage is always implicitly isolated by computer because it uses the storage facilities that are local to a given computer. + > [!IMPORTANT] -> Isolated storage is not available for Windows 8.x Store apps. Instead, use the application data classes in the `Windows.Storage` namespaces included in the Windows Runtime API to store local data and files. For more information, see [Application data](/previous-versions/windows/apps/hh464917(v=win.10)) in the Windows Dev Center. - +> Isolated storage is not available for Windows 8.x Store apps. Instead, use the application data classes in the `Windows.Storage` namespaces included in the Windows Runtime API to store local data and files. For more information, see [Application data](/previous-versions/windows/apps/hh464917(v=win.10)) in the Windows Dev Center. + -## Isolation by User and Assembly +## Isolation by User and Assembly + + When the assembly that uses the data store needs to be accessible from any application's domain, isolation by user and assembly is appropriate. Typically, in this situation, isolated storage is used to store data that applies across multiple applications and is not tied to any particular application, such as the user's name or license information. To access storage isolated by user and assembly, code must be trusted to transfer information between applications. Typically, isolation by user and assembly is allowed on intranets but not on the Internet. Calling the static method and passing in a user and an assembly returns storage with this kind of isolation. - When the assembly that uses the data store needs to be accessible from any application's domain, isolation by user and assembly is appropriate. Typically, in this situation, isolated storage is used to store data that applies across multiple applications and is not tied to any particular application, such as the user's name or license information. To access storage isolated by user and assembly, code must be trusted to transfer information between applications. Typically, isolation by user and assembly is allowed on intranets but not on the Internet. Calling the static method and passing in a user and an assembly returns storage with this kind of isolation. - - The following code example retrieves a store that is isolated by user and assembly. The store can be accessed through the `isoFile` object. - - [!code-cpp[Conceptual.IsolatedStorage#17](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source11.cpp#17)] + The following code example retrieves a store that is isolated by user and assembly. The store can be accessed through the `isoFile` object. [!code-csharp[Conceptual.IsolatedStorage#17](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source11.cs#17)] - [!code-vb[Conceptual.IsolatedStorage#17](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source11.vb#17)] - - For an example that uses the evidence parameters, see . - - The method is available as a shortcut, as shown in the following code example. This shortcut cannot be used to open stores that are capable of roaming; use in such cases. - - [!code-cpp[Conceptual.IsolatedStorage#18](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source11.cpp#18)] + [!code-vb[Conceptual.IsolatedStorage#17](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source11.vb#17)] + + For an example that uses the evidence parameters, see . + + The method is available as a shortcut, as shown in the following code example. This shortcut cannot be used to open stores that are capable of roaming; use in such cases. [!code-csharp[Conceptual.IsolatedStorage#18](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source11.cs#18)] - [!code-vb[Conceptual.IsolatedStorage#18](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source11.vb#18)] - + [!code-vb[Conceptual.IsolatedStorage#18](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source11.vb#18)] + -## Isolation by User, Domain, and Assembly +## Isolation by User, Domain, and Assembly + + If your application uses a third-party assembly that requires a private data store, you can use isolated storage to store the private data. Isolation by user, domain, and assembly ensures that only code in a given assembly can access the data, and only when the assembly is used by the application that was running when the assembly created the store, and only when the user for whom the store was created runs the application. Isolation by user, domain, and assembly keeps the third-party assembly from leaking data to other applications. This isolation type should be your default choice if you know that you want to use isolated storage but are not sure which type of isolation to use. Calling the static method of and passing in a user, domain, and assembly returns storage with this kind of isolation. - If your application uses a third-party assembly that requires a private data store, you can use isolated storage to store the private data. Isolation by user, domain, and assembly ensures that only code in a given assembly can access the data, and only when the assembly is used by the application that was running when the assembly created the store, and only when the user for whom the store was created runs the application. Isolation by user, domain, and assembly keeps the third-party assembly from leaking data to other applications. This isolation type should be your default choice if you know that you want to use isolated storage but are not sure which type of isolation to use. Calling the static method of and passing in a user, domain, and assembly returns storage with this kind of isolation. - - The following code example retrieves a store isolated by user, domain, and assembly. The store can be accessed through the `isoFile` object. - - [!code-cpp[Conceptual.IsolatedStorage#14](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source10.cpp#14)] + The following code example retrieves a store isolated by user, domain, and assembly. The store can be accessed through the `isoFile` object. [!code-csharp[Conceptual.IsolatedStorage#14](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source10.cs#14)] - [!code-vb[Conceptual.IsolatedStorage#14](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source10.vb#14)] - - Another method is available as a shortcut, as shown in the following code example. This shortcut cannot be used to open stores that are capable of roaming; use in such cases. - - [!code-cpp[Conceptual.IsolatedStorage#15](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source10.cpp#15)] + [!code-vb[Conceptual.IsolatedStorage#14](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source10.vb#14)] + + Another method is available as a shortcut, as shown in the following code example. This shortcut cannot be used to open stores that are capable of roaming; use in such cases. [!code-csharp[Conceptual.IsolatedStorage#15](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source10.cs#15)] - [!code-vb[Conceptual.IsolatedStorage#15](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source10.vb#15)] - + [!code-vb[Conceptual.IsolatedStorage#15](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source10.vb#15)] + -## Isolated Storage and Roaming +## Isolated Storage and Roaming + + Roaming user profiles are a Windows feature that enables a user to set up an identity on a network and use that identity to log into any network computer, carrying over all personalized settings. An assembly that uses isolated storage can specify that the user's isolated storage should move with the roaming user profile. Roaming can be used in conjunction with isolation by user and assembly or with isolation by user, domain, and assembly. If a roaming scope is not used, stores will not roam even if a roaming user profile is used. - Roaming user profiles are a Windows feature that enables a user to set up an identity on a network and use that identity to log into any network computer, carrying over all personalized settings. An assembly that uses isolated storage can specify that the user's isolated storage should move with the roaming user profile. Roaming can be used in conjunction with isolation by user and assembly or with isolation by user, domain, and assembly. If a roaming scope is not used, stores will not roam even if a roaming user profile is used. - - The following code example retrieves a roaming store isolated by user and assembly. The store can be accessed through the `isoFile` object. - - [!code-cpp[Conceptual.IsolatedStorage#11](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source9.cpp#11)] + The following code example retrieves a roaming store isolated by user and assembly. The store can be accessed through the `isoFile` object. [!code-csharp[Conceptual.IsolatedStorage#11](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source9.cs#11)] - [!code-vb[Conceptual.IsolatedStorage#11](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source9.vb#11)] - - A domain scope can be added to create a roaming store isolated by user, domain, and application. The following code example demonstrates this. - - [!code-cpp[Conceptual.IsolatedStorage#12](../../../samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source9.cpp#12)] + [!code-vb[Conceptual.IsolatedStorage#11](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source9.vb#11)] + + A domain scope can be added to create a roaming store isolated by user, domain, and application. The following code example demonstrates this. [!code-csharp[Conceptual.IsolatedStorage#12](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.isolatedstorage/cs/source9.cs#12)] - [!code-vb[Conceptual.IsolatedStorage#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source9.vb#12)] - + [!code-vb[Conceptual.IsolatedStorage#12](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.isolatedstorage/vb/source9.vb#12)] + ## See also - diff --git a/docs/standard/native-interop/qualify-net-types-for-interoperation.md b/docs/standard/native-interop/qualify-net-types-for-interoperation.md index 1c943927d6acd..bb134ed242dcb 100644 --- a/docs/standard/native-interop/qualify-net-types-for-interoperation.md +++ b/docs/standard/native-interop/qualify-net-types-for-interoperation.md @@ -61,7 +61,7 @@ When .NET code tries to call a method on a COM object through an interface with Consider a COM interface with a few methods: -```c++ +```cpp struct IComInterface : public IUnknown { STDMETHOD(Method)() = 0; @@ -71,13 +71,13 @@ struct IComInterface : public IUnknown For this interface, the following table describes its virtual function table layout: -| `IComInterface` virtual function table slot | Method name | -|-----------------------------|-------------| -| 0 | `IUnknown::QueryInterface` | -| 1 | `IUnknown::AddRef` | -| 2 | `IUnknown::Release` | -| 3 | `IComInterface::Method` | -| 4 | `IComInterface::Method2` | +| `IComInterface` virtual function table slot | Method name | +|---------------------------------------------|----------------------------| +| 0 | `IUnknown::QueryInterface` | +| 1 | `IUnknown::AddRef` | +| 2 | `IUnknown::Release` | +| 3 | `IComInterface::Method` | +| 4 | `IComInterface::Method2` | Each method is added to the virtual function table in the order it was declared. The particular order is defined by the C++ compiler, but for simple cases without overloads, declaration order defines the order in the table. @@ -128,22 +128,22 @@ struct IComInterface2 : public IComInterface This declaration style is regularly used as a mechanism to add methods to COM objects without changing existing interfaces, which would be a breaking change. This inheritance mechanism results in the following virtual function table layouts: -| `IComInterface` virtual function table slot | Method name | -|-----------------------------|-------------| -| 0 | `IUnknown::QueryInterface` | -| 1 | `IUnknown::AddRef` | -| 2 | `IUnknown::Release` | -| 3 | `IComInterface::Method` | -| 4 | `IComInterface::Method2` | - -| `IComInterface2` virtual function table slot | Method name | -|-----------------------------|-------------| -| 0 | `IUnknown::QueryInterface` | -| 1 | `IUnknown::AddRef` | -| 2 | `IUnknown::Release` | -| 3 | `IComInterface::Method` | -| 4 | `IComInterface::Method2` | -| 5 | `IComInterface2::Method3` | +| `IComInterface` virtual function table slot | Method name | +|---------------------------------------------|----------------------------| +| 0 | `IUnknown::QueryInterface` | +| 1 | `IUnknown::AddRef` | +| 2 | `IUnknown::Release` | +| 3 | `IComInterface::Method` | +| 4 | `IComInterface::Method2` | + +| `IComInterface2` virtual function table slot | Method name | +|----------------------------------------------|----------------------------| +| 0 | `IUnknown::QueryInterface` | +| 1 | `IUnknown::AddRef` | +| 2 | `IUnknown::Release` | +| 3 | `IComInterface::Method` | +| 4 | `IComInterface::Method2` | +| 5 | `IComInterface2::Method3` | As a result, it's easy to call a method defined on `IComInterface` from an `IComInterface2*`. Specifically, calling a method on a base interface does not require a call to `QueryInterface` to get a pointer to the base interface. Additionally, C++ allows an implicit conversion from `IComInterface2*` to `IComInterface*`, which is well defined and lets you avoid calling a `QueryInterface` again. As a result, in C or C++, you never have to call `QueryInterface` to get to the base type if you don't want to, which can allow some performance improvements. @@ -190,20 +190,20 @@ interface IComInterface2 : IComInterface Virtual function table layouts: -| `IComInterface` virtual function table slot | Method name | -|-----------------------------|-------------| -| 0 | `IUnknown::QueryInterface` | -| 1 | `IUnknown::AddRef` | -| 2 | `IUnknown::Release` | -| 3 | `IComInterface::Method` | -| 4 | `IComInterface::Method2` | - -| `IComInterface2` virtual function table slot | Method name | -|-----------------------------|-------------| -| 0 | `IUnknown::QueryInterface` | -| 1 | `IUnknown::AddRef` | -| 2 | `IUnknown::Release` | -| 3 | `IComInterface2::Method3` | +| `IComInterface` virtual function table slot | Method name | +|---------------------------------------------|----------------------------| +| 0 | `IUnknown::QueryInterface` | +| 1 | `IUnknown::AddRef` | +| 2 | `IUnknown::Release` | +| 3 | `IComInterface::Method` | +| 4 | `IComInterface::Method2` | + +| `IComInterface2` virtual function table slot | Method name | +|----------------------------------------------|----------------------------| +| 0 | `IUnknown::QueryInterface` | +| 1 | `IUnknown::AddRef` | +| 2 | `IUnknown::Release` | +| 3 | `IComInterface2::Method3` | As these virtual function tables differ from the C++ example, this will lead to serious problems at run time. The correct definition of these interfaces in .NET with is as follows: @@ -251,22 +251,22 @@ interface IComInterface2 : IComInterface The methods of the base interfaces do not need to be redeclared and should not be redeclared. The following table describes the resulting virtual function tables: -| `IComInterface` virtual function table slot | Method name | -|-----------------------------|-------------| -| 0 | `IUnknown::QueryInterface` | -| 1 | `IUnknown::AddRef` | -| 2 | `IUnknown::Release` | -| 3 | `IComInterface::Method` | -| 4 | `IComInterface::Method2` | - -| `IComInterface2` virtual function table slot | Method name | -|-----------------------------|-------------| -| 0 | `IUnknown::QueryInterface` | -| 1 | `IUnknown::AddRef` | -| 2 | `IUnknown::Release` | -| 3 | `IComInterface::Method` | -| 4 | `IComInterface::Method2` | -| 5 | `IComInterface2::Method3` | +| `IComInterface` virtual function table slot | Method name | +|---------------------------------------------|----------------------------| +| 0 | `IUnknown::QueryInterface` | +| 1 | `IUnknown::AddRef` | +| 2 | `IUnknown::Release` | +| 3 | `IComInterface::Method` | +| 4 | `IComInterface::Method2` | + +| `IComInterface2` virtual function table slot | Method name | +|----------------------------------------------|----------------------------| +| 0 | `IUnknown::QueryInterface` | +| 1 | `IUnknown::AddRef` | +| 2 | `IUnknown::Release` | +| 3 | `IComInterface::Method` | +| 4 | `IComInterface::Method2` | +| 5 | `IComInterface2::Method3` | As you can see, these tables match the C++ example, so these interfaces will function correctly. @@ -274,7 +274,7 @@ As you can see, these tables match the C++ example, so these interfaces will fun - - -- [Exposing .NET Framework Components to COM](../../framework/interop/exposing-dotnet-components-to-com.md) +- [Expose .NET Framework components to COM](../../framework/interop/exposing-dotnet-components-to-com.md) - [Introducing the class interface](com-callable-wrapper.md#introducing-the-class-interface) -- [Applying Interop Attributes](apply-interop-attributes.md) -- [Packaging a .NET Framework Assembly for COM](../../framework/interop/packaging-an-assembly-for-com.md) +- [Apply interop attributes](apply-interop-attributes.md) +- [Package a .NET Framework assembly for COM](../../framework/interop/packaging-an-assembly-for-com.md) diff --git a/docs/standard/security/how-to-access-hardware-encryption-devices.md b/docs/standard/security/how-to-access-hardware-encryption-devices.md index 27a3cc361b2e8..aa8b6bab1d837 100644 --- a/docs/standard/security/how-to-access-hardware-encryption-devices.md +++ b/docs/standard/security/how-to-access-hardware-encryption-devices.md @@ -2,61 +2,57 @@ description: "Learn more about: How to: Access Hardware Encryption Devices" title: "How to: Access Hardware Encryption Devices" ms.date: 07/14/2020 -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "encryption" - "key card" - "cryptography" - "hardware encryption" - "CspParameters" -ms.assetid: b0e734df-6eb4-4b16-b48c-6f0fe82d5f17 --- -# How to: Access Hardware Encryption Devices +# How to: Access hardware encryption devices > [!NOTE] > This article applies to Windows. -You can use the class to access hardware encryption devices. For example, you can use this class to integrate your application with a smart card, a hardware random number generator, or a hardware implementation of a particular cryptographic algorithm. - -The class creates a cryptographic service provider (CSP) that accesses a properly installed hardware encryption device. You can verify the availability of a CSP by inspecting the following registry key using the Registry Editor (Regedit.exe): HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider. - -### To sign data using a key card - -1. Create a new instance of the class, passing the integer provider type and the provider name to the constructor. - -2. Pass the appropriate flags to the property of the newly created object. For example, pass the flag. - -3. Create a new instance of an class (for example, the class), passing the object to the constructor. - -4. Sign your data using one of the `Sign` methods and verify your data using one of the `Verify` methods. - -### To generate a random number using a hardware random number generator - -1. Create a new instance of the class, passing the integer provider type and the provider name to the constructor. - -2. Create a new instance of the , passing the object to the constructor. - -3. Create a random value using the or method. - +You can use the class to access hardware encryption devices. For example, you can use this class to integrate your application with a smart card, a hardware random number generator, or a hardware implementation of a particular cryptographic algorithm. + +The class creates a cryptographic service provider (CSP) that accesses a properly installed hardware encryption device. You can verify the availability of a CSP by inspecting the following registry key using the Registry Editor (Regedit.exe): HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider. + +### To sign data using a key card + +1. Create a new instance of the class, passing the integer provider type and the provider name to the constructor. + +2. Pass the appropriate flags to the property of the newly created object. For example, pass the flag. + +3. Create a new instance of an class (for example, the class), passing the object to the constructor. + +4. Sign your data using one of the `Sign` methods and verify your data using one of the `Verify` methods. + +### To generate a random number using a hardware random number generator + +1. Create a new instance of the class, passing the integer provider type and the provider name to the constructor. + +2. Create a new instance of the , passing the object to the constructor. + +3. Create a random value using the or method. + ## Example -The following code example demonstrates how to sign data using a smart card. The code example creates a object that exposes a smart card, and then initializes an object using the CSP. The code example then signs and verifies some data. +The following code example demonstrates how to sign data using a smart card. The code example creates a object that exposes a smart card, and then initializes an object using the CSP. The code example then signs and verifies some data. Due to collision problems with SHA1, we recommend SHA256 or better. - -[!code-cpp[Cryptography.SmartCardCSP#1](../../../samples/snippets/cpp/VS_Snippets_CLR/Cryptography.SmartCardCSP/CPP/Cryptography.SmartCardCSP.cpp#1)] [!code-csharp[Cryptography.SmartCardCSP#1](../../../samples/snippets/csharp/VS_Snippets_CLR/Cryptography.SmartCardCSP/CS/example.cs#1)] -[!code-vb[Cryptography.SmartCardCSP#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Cryptography.SmartCardCSP/VB/example.vb#1)] - -## Compiling the Code - -- Include the and namespaces. - -- You must have a smart card reader and drivers installed on your computer. - +[!code-vb[Cryptography.SmartCardCSP#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR/Cryptography.SmartCardCSP/VB/example.vb#1)] + +## Compiling the Code + +- Include the and namespaces. + +- You must have a smart card reader and drivers installed on your computer. + - You must initialize the object using information specific to your card reader. For more information, see the documentation of your card reader. ## See also diff --git a/docs/standard/security/key-security-concepts.md b/docs/standard/security/key-security-concepts.md index bef72483aa4b4..f0ea2e7660378 100644 --- a/docs/standard/security/key-security-concepts.md +++ b/docs/standard/security/key-security-concepts.md @@ -5,14 +5,12 @@ ms.date: 07/15/2020 dev_langs: - "csharp" - "vb" - - "cpp" helpviewer_keywords: - "unauthorized access" - "permissions [.NET]" - "security [.NET], about security" -ms.assetid: 3cfced4f-ea02-4e66-ae98-d69286363e98 --- -# Key Security Concepts +# Key security concepts > [!NOTE] > This article applies to Windows. @@ -55,14 +53,10 @@ The following example requires that the active principal be an administrator. Th > [!NOTE] > In Windows Vista, User Account Control (UAC) determines the privileges of a user. If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. By default, you are in the standard user role. To execute the code that requires you to be an administrator, you must first elevate your privileges from standard user to administrator. You can do this when you start an application by right-clicking the application icon and indicating that you want to run as an administrator. - - [!code-cpp[Classic PrincipalPermission Example#1](../../../samples/snippets/cpp/VS_Snippets_CLR_Classic/classic PrincipalPermission Example/CPP/source.cpp#1)] [!code-csharp[Classic PrincipalPermission Example#1](../../../samples/snippets/csharp/VS_Snippets_CLR_Classic/classic PrincipalPermission Example/CS/source.cs#1)] [!code-vb[Classic PrincipalPermission Example#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR_Classic/classic PrincipalPermission Example/VB/source.vb#1)] The following example demonstrates how to determine the identity of the principal and the roles available to the principal. An application of this example might be to confirm that the current user is in a role you allow for using your application. - - [!code-cpp[System.Security.Principal.WindowsBuiltInRole Example#1](../../../samples/snippets/cpp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CPP/source.cpp#1)] [!code-csharp[System.Security.Principal.WindowsBuiltInRole Example#1](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CS/source.cs#1)] [!code-vb[System.Security.Principal.WindowsBuiltInRole Example#1](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/VB/source.vb#1)] diff --git a/docs/standard/threading/creating-threads-and-passing-data-at-start-time.md b/docs/standard/threading/creating-threads-and-passing-data-at-start-time.md index fe182c7b0b6ad..658f73d0068c5 100644 --- a/docs/standard/threading/creating-threads-and-passing-data-at-start-time.md +++ b/docs/standard/threading/creating-threads-and-passing-data-at-start-time.md @@ -2,55 +2,48 @@ title: "Creating threads and passing data at start time" description: Understand how to create threads and pass data at the start time of an operating system process in .NET. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "threading [.NET], creating" - "threading [.NET], passing data to threads" - "threading [.NET], retrieving data from threads" ms.topic: how-to --- -# Creating threads and passing data at start time +# Create threads and pass data at start time + +When an operating-system process is created, the operating system injects a thread to execute code in that process, including any original application domain. From that point on, application domains can be created and destroyed without any operating system threads necessarily being created or destroyed. If the code being executed is managed code, then a object for the thread executing in the current application domain can be obtained by retrieving the static property of type . This topic describes thread creation and discusses alternatives for passing data to the thread procedure. -When an operating-system process is created, the operating system injects a thread to execute code in that process, including any original application domain. From that point on, application domains can be created and destroyed without any operating system threads necessarily being created or destroyed. If the code being executed is managed code, then a object for the thread executing in the current application domain can be obtained by retrieving the static property of type . This topic describes thread creation and discusses alternatives for passing data to the thread procedure. - ## Creating a thread - Creating a new object creates a new managed thread. The class has constructors that take a delegate or a delegate; the delegate wraps the method that is invoked by the new thread when you call the method. Calling more than once causes a to be thrown. - - The method returns immediately, often before the new thread has actually started. You can use the and properties to determine the state of the thread at any one moment, but these properties should never be used for synchronizing the activities of threads. - + Creating a new object creates a new managed thread. The class has constructors that take a delegate or a delegate; the delegate wraps the method that is invoked by the new thread when you call the method. Calling more than once causes a to be thrown. + + The method returns immediately, often before the new thread has actually started. You can use the and properties to determine the state of the thread at any one moment, but these properties should never be used for synchronizing the activities of threads. + > [!NOTE] -> Once a thread is started, it is not necessary to retain a reference to the object. The thread continues to execute until the thread procedure ends. - - The following code example creates two new threads to call instance and static methods on another object. - - [!code-cpp[System.Threading.ThreadStart2#2](../../../samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source2.cpp#2)] +> Once a thread is started, it is not necessary to retain a reference to the object. The thread continues to execute until the thread procedure ends. + + The following code example creates two new threads to call instance and static methods on another object. [!code-csharp[System.Threading.ThreadStart2#2](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source2.cs#2)] - [!code-vb[System.Threading.ThreadStart2#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Threading.ThreadStart2/VB/source2.vb#2)] - + [!code-vb[System.Threading.ThreadStart2#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Threading.ThreadStart2/VB/source2.vb#2)] + ## Passing data to threads The delegate provides an easy way to pass an object containing data to a thread when you call . See for a code example. - - Using the delegate is not a type-safe way to pass data, because the method accepts any object. An alternative is to encapsulate the thread procedure and the data in a helper class and use the delegate to execute the thread procedure. The following example demonstrates this technique: - [!code-cpp[System.Threading.ThreadStart2#3](../../../samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source3.cpp#3)] + Using the delegate is not a type-safe way to pass data, because the method accepts any object. An alternative is to encapsulate the thread procedure and the data in a helper class and use the delegate to execute the thread procedure. The following example demonstrates this technique: [!code-csharp[System.Threading.ThreadStart2#3](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source3.cs#3)] - [!code-vb[System.Threading.ThreadStart2#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Threading.ThreadStart2/VB/source3.vb#3)] + [!code-vb[System.Threading.ThreadStart2#3](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Threading.ThreadStart2/VB/source3.vb#3)] Neither nor delegate has a return value, because there is no place to return the data from an asynchronous call. To retrieve the results of a thread method, you can use a callback method, as shown in the next section. - + ## Retrieving data from threads with callback methods - The following example demonstrates a callback method that retrieves data from a thread. The constructor for the class that contains the data and the thread method also accepts a delegate representing the callback method; before the thread method ends, it invokes the callback delegate. - - [!code-cpp[System.Threading.ThreadStart2#4](../../../samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source4.cpp#4)] + The following example demonstrates a callback method that retrieves data from a thread. The constructor for the class that contains the data and the thread method also accepts a delegate representing the callback method; before the thread method ends, it invokes the callback delegate. [!code-csharp[System.Threading.ThreadStart2#4](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CS/source4.cs#4)] - [!code-vb[System.Threading.ThreadStart2#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Threading.ThreadStart2/VB/source4.vb#4)] - + [!code-vb[System.Threading.ThreadStart2#4](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Threading.ThreadStart2/VB/source4.vb#4)] + ## See also - diff --git a/docs/standard/threading/timers.md b/docs/standard/threading/timers.md index 54e7beb7614a7..2ddcb500d5e7c 100644 --- a/docs/standard/threading/timers.md +++ b/docs/standard/threading/timers.md @@ -2,14 +2,12 @@ title: "Timers" description: Learn what .NET timers to use in a multithreaded environment. ms.date: "07/03/2018" -dev_langs: +dev_langs: - "csharp" - "vb" - - "cpp" -helpviewer_keywords: +helpviewer_keywords: - "threading [.NET], timers" - "timers, about timers" -ms.assetid: 7091500d-be18-499b-a942-95366ce185e5 author: "pkulikov" --- # Timers @@ -23,7 +21,7 @@ author: "pkulikov" > [!NOTE] > Some .NET implementations may include additional timers: > -> - : a Windows Forms component that fires an event at regular intervals. The component has no user interface and is designed for use in a single-threaded environment. +> - : a Windows Forms component that fires an event at regular intervals. The component has no user interface and is designed for use in a single-threaded environment. > - : an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval. > - : a timer that is integrated into the queue which is processed at a specified interval of time and at a specified priority. @@ -34,8 +32,6 @@ The class enables you When you create a object, you specify a delegate that defines the callback method, an optional state object that is passed to the callback, the amount of time to delay before the first invocation of the callback, and the time interval between callback invocations. To cancel a pending timer, call the method. The following example creates a timer that calls the provided delegate for the first time after one second (1000 milliseconds) and then calls it every two seconds. The state object in the example is used to count how many times the delegate is called. The timer is stopped when the delegate has been called at least 10 times. - -[!code-cpp[System.Threading.Timer#2](../../../samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.Timer/CPP/source2.cpp#2)] [!code-csharp[System.Threading.Timer#2](../../../samples/snippets/csharp/VS_Snippets_CLR_System/system.Threading.Timer/CS/source2.cs#2)] [!code-vb[System.Threading.Timer#2](../../../samples/snippets/visualbasic/VS_Snippets_CLR_System/system.Threading.Timer/VB/source2.vb#2)] @@ -58,7 +54,7 @@ When you create a method returns a [`ValueTask`](xref:System.Threading.Tasks.ValueTask%601); `true` upon successful firing of the timer, and `false` when the timer has been canceled by calling . optionally accepts a , which results in a when a cancellation has been requested. For more information, see . - + ## See also - diff --git a/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/EndInvoke.cpp b/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/EndInvoke.cpp deleted file mode 100644 index 93f282505574a..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/EndInvoke.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Threading; -using namespace Examples::AdvancedProgramming::AsynchronousOperations; - -void main() -{ - // The asynchronous method puts the thread id here. - int threadId = 2546; - - // Create an instance of the test class. - AsyncDemo^ ad = gcnew AsyncDemo(); - - // Create the delegate. - AsyncMethodCaller^ caller = gcnew AsyncMethodCaller(ad, &AsyncDemo::TestMethod); - - // Initiate the asynchronous call. - IAsyncResult^ result = caller->BeginInvoke(3000, - threadId, nullptr, nullptr); - - Thread::Sleep(1); - Console::WriteLine("Main thread {0} does some work.", - Thread::CurrentThread->ManagedThreadId); - - // Call EndInvoke to wait for the asynchronous call to complete, - // and to retrieve the results. - String^ returnValue = caller->EndInvoke(threadId, result); - - Console::WriteLine("The call executed on thread {0}, with return value \"{1}\".", - threadId, returnValue); -} - -/* This example produces output similar to the following: - -Main thread 1 does some work. -Test method begins. -The call executed on thread 3, with return value "My call time was 3000.". - */ -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/TestMethod.cpp b/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/TestMethod.cpp deleted file mode 100644 index 91ec8999683a7..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/TestMethod.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// -using namespace System; -using namespace System::Threading; -using namespace System::Runtime::InteropServices; - -namespace Examples { -namespace AdvancedProgramming { -namespace AsynchronousOperations -{ - public ref class AsyncDemo - { - public: - // The method to be executed asynchronously. - String^ TestMethod(int callDuration, [OutAttribute] int% threadId) - { - Console::WriteLine("Test method begins."); - Thread::Sleep(callDuration); - threadId = Thread::CurrentThread->ManagedThreadId; - return String::Format("My call time was {0}.", callDuration); - } - }; - - // The delegate must have the same signature as the method - // it will call asynchronously. - public delegate String^ AsyncMethodCaller(int callDuration, [OutAttribute] int% threadId); -}}} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/callback.cpp b/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/callback.cpp deleted file mode 100644 index 4f99e90248e64..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/callback.cpp +++ /dev/null @@ -1,79 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Threading; -using namespace System::Runtime::Remoting::Messaging; -using namespace Examples::AdvancedProgramming::AsynchronousOperations; - -// The callback method must have the same signature as the -// AsyncCallback delegate. -void CallbackMethod(IAsyncResult^ ar) -{ - // Retrieve the delegate. - AsyncResult^ result = (AsyncResult^) ar; - AsyncMethodCaller^ caller = (AsyncMethodCaller^) result->AsyncDelegate; - - // Retrieve the format string that was passed as state - // information. - String^ formatString = (String^) ar->AsyncState; - - // Define a variable to receive the value of the out parameter. - // If the parameter were ref rather than out then it would have to - // be a class-level field so it could also be passed to BeginInvoke. - int threadId = 0; - - // Call EndInvoke to retrieve the results. - String^ returnValue = caller->EndInvoke(threadId, ar); - - // Use the format string to format the output message. - Console::WriteLine(formatString, threadId, returnValue); -}; - -void main() -{ - // Create an instance of the test class. - AsyncDemo^ ad = gcnew AsyncDemo(); - - // Create the delegate. - AsyncMethodCaller^ caller = gcnew AsyncMethodCaller(ad, &AsyncDemo::TestMethod); - - // The threadId parameter of TestMethod is an out parameter, so - // its input value is never used by TestMethod. Therefore, a dummy - // variable can be passed to the BeginInvoke call. If the threadId - // parameter were a ref parameter, it would have to be a class- - // level field so that it could be passed to both BeginInvoke and - // EndInvoke. - int dummy = 0; - - // Initiate the asynchronous call, passing three seconds (3000 ms) - // for the callDuration parameter of TestMethod; a dummy variable - // for the out parameter (threadId); the callback delegate; and - // state information that can be retrieved by the callback method. - // In this case, the state information is a string that can be used - // to format a console message. - IAsyncResult^ result = caller->BeginInvoke(3000, - dummy, - gcnew AsyncCallback(&CallbackMethod), - "The call executed on thread {0}, with return value \"{1}\"."); - - Console::WriteLine("The main thread {0} continues to execute...", - Thread::CurrentThread->ManagedThreadId); - - // The callback is made on a ThreadPool thread. ThreadPool threads - // are background threads, which do not keep the application running - // if the main thread ends. Comment out the next line to demonstrate - // this. - Thread::Sleep(4000); - Console::WriteLine("The main thread ends."); -} - -/* This example produces output similar to the following: - -The main thread 1 continues to execute... -Test method begins. -The call executed on thread 3, with return value "My call time was 3000.". -The main thread ends. - */ -// - diff --git a/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/polling.cpp b/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/polling.cpp deleted file mode 100644 index c06b2317b8d1f..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/polling.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Threading; -using namespace Examples::AdvancedProgramming::AsynchronousOperations; - -void main() -{ - // The asynchronous method puts the thread id here. - int threadId; - - // Create an instance of the test class. - AsyncDemo^ ad = gcnew AsyncDemo(); - - // Create the delegate. - AsyncMethodCaller^ caller = gcnew AsyncMethodCaller(ad, &AsyncDemo::TestMethod); - - // Initiate the asynchronous call. - IAsyncResult^ result = caller->BeginInvoke(3000, - threadId, nullptr, nullptr); - - // Poll while simulating work. - while(result->IsCompleted == false) - { - Thread::Sleep(250); - Console::Write("."); - } - - // Call EndInvoke to retrieve the results. - String^ returnValue = caller->EndInvoke(threadId, result); - - Console::WriteLine("\nThe call executed on thread {0}, with return value \"{1}\".", - threadId, returnValue); -} - -/* This example produces output similar to the following: - -Test method begins. -............. -The call executed on thread 3, with return value "My call time was 3000.". - */ -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/waithandle.cpp b/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/waithandle.cpp deleted file mode 100644 index 74aafedbaa14e..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/AsyncDelegateExamples/cpp/waithandle.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Threading; -using namespace Examples::AdvancedProgramming::AsynchronousOperations; - -void main() -{ - // The asynchronous method puts the thread id here. - int threadId; - - // Create an instance of the test class. - AsyncDemo^ ad = gcnew AsyncDemo(); - - // Create the delegate. - AsyncMethodCaller^ caller = gcnew AsyncMethodCaller(ad, &AsyncDemo::TestMethod); - - // Initiate the asynchronous call. - IAsyncResult^ result = caller->BeginInvoke(3000, - threadId, nullptr, nullptr); - - Thread::Sleep(0); - Console::WriteLine("Main thread {0} does some work.", - Thread::CurrentThread->ManagedThreadId); - - // Wait for the WaitHandle to become signaled. - result->AsyncWaitHandle->WaitOne(); - - // Perform additional processing here. - // Call EndInvoke to retrieve the results. - String^ returnValue = caller->EndInvoke(threadId, result); - - // Close the wait handle. - result->AsyncWaitHandle->Close(); - - Console::WriteLine("The call executed on thread {0}, with return value \"{1}\".", - threadId, returnValue); -} - -/* This example produces output similar to the following: - -Main thread 1 does some work. -Test method begins. -The call executed on thread 3, with return value "My call time was 3000.". - */ -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/CodeTryCatchFinallyExample/CPP/source2.cpp b/samples/snippets/cpp/VS_Snippets_CLR/CodeTryCatchFinallyExample/CPP/source2.cpp deleted file mode 100644 index d3970fe76ced4..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/CodeTryCatchFinallyExample/CPP/source2.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// -using namespace System; - -ref class ArgumentOutOfRangeExample -{ -public: - static void Main() - { - array^ array1 = {0, 0}; - array^ array2 = {0, 0}; - - try - { - Array::Copy(array1, array2, -1); - } - catch (ArgumentOutOfRangeException^ e) - { - Console::WriteLine("Error: {0}", e); - throw; - } - finally - { - Console::WriteLine("This statement is always executed."); - } - } -}; - -int main() -{ - ArgumentOutOfRangeExample::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp b/samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp deleted file mode 100644 index 21dbe9651cac4..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/Conceptual.StringBuilder/cpp/example.cpp +++ /dev/null @@ -1,99 +0,0 @@ -// -using namespace System; -using namespace System::Text; -// - -[assembly:CLSCompliant(true)]; -public ref class Example -{ -public: - static void Main() - { - InstantiateStringBuilder(); - InstantiateWithCapacity(); - Appending(); - AppendingFormat(); - Inserting(); - Removing(); - Replacing(); - } - -private: - static void InstantiateStringBuilder() - { - // - StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!"); - // - } - - static void InstantiateWithCapacity() - { - // - StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!", 25); - // - // - myStringBuilder->Capacity = 25; - // - } - - static void Appending() - { - // - StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!"); - myStringBuilder->Append(" What a beautiful day."); - Console::WriteLine(myStringBuilder); - // The example displays the following output: - // Hello World! What a beautiful day. - // - } - - static void AppendingFormat() - { - // - int MyInt = 25; - StringBuilder^ myStringBuilder = gcnew StringBuilder("Your total is "); - myStringBuilder->AppendFormat("{0:C} ", MyInt); - Console::WriteLine(myStringBuilder); - // The example displays the following output: - // Your total is $25.00 - // - } - - static void Inserting() - { - // - StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!"); - myStringBuilder->Insert(6,"Beautiful "); - Console::WriteLine(myStringBuilder); - // The example displays the following output: - // Hello Beautiful World! - // - } - - static void Removing() - { - // - StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!"); - myStringBuilder->Remove(5,7); - Console::WriteLine(myStringBuilder); - // The example displays the following output: - // Hello - // - } - - static void Replacing() - { - // - StringBuilder^ myStringBuilder = gcnew StringBuilder("Hello World!"); - myStringBuilder->Replace('!', '?'); - Console::WriteLine(myStringBuilder); - // The example displays the following output: - // Hello World? - // - } -}; - -int main() -{ - Example::Main(); -} diff --git a/samples/snippets/cpp/VS_Snippets_CLR/Cryptography.SmartCardCSP/CPP/Cryptography.SmartCardCSP.cpp b/samples/snippets/cpp/VS_Snippets_CLR/Cryptography.SmartCardCSP/CPP/Cryptography.SmartCardCSP.cpp deleted file mode 100644 index 6695d91dcde59..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/Cryptography.SmartCardCSP/CPP/Cryptography.SmartCardCSP.cpp +++ /dev/null @@ -1,38 +0,0 @@ - -// -using namespace System; -using namespace System::Security::Cryptography; -int main() -{ - - // To identify the Smart Card CryptoGraphic Providers on your - // computer, use the Microsoft Registry Editor (Regedit.exe). - // The available Smart Card CryptoGraphic Providers are listed - // in HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider. - // Create a new CspParameters object that identifies a - // Smart Card CryptoGraphic Provider. - // The 1st parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider Types. - // The 2nd parameter comes from HKEY_LOCAL_MACHINE\Software\Microsoft\Cryptography\Defaults\Provider. - CspParameters^ csp = gcnew CspParameters( 1,L"Schlumberger Cryptographic Service Provider" ); - csp->Flags = CspProviderFlags::UseDefaultKeyContainer; - - // Initialize an RSACryptoServiceProvider object using - // the CspParameters object. - RSACryptoServiceProvider^ rsa = gcnew RSACryptoServiceProvider( csp ); - - // Create some data to sign. - array^data = gcnew array{ - 0,1,2,3,4,5,6,7 - }; - Console::WriteLine( L"Data : {0}", BitConverter::ToString( data ) ); - - // Sign the data using the Smart Card CryptoGraphic Provider. - array^sig = rsa->SignData( data, L"SHA1" ); - Console::WriteLine( L"Signature : {0}", BitConverter::ToString( sig ) ); - - // Verify the data using the Smart Card CryptoGraphic Provider. - bool verified = rsa->VerifyData( data, L"SHA1", sig ); - Console::WriteLine( L"Verified : {0}", verified ); -} - -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/CustomAttributeData/CPP/source2.cpp b/samples/snippets/cpp/VS_Snippets_CLR/CustomAttributeData/CPP/source2.cpp deleted file mode 100644 index 7963bbd36ae3d..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/CustomAttributeData/CPP/source2.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// -using namespace System; - -public ref class ExampleAttribute : Attribute -{ -private: - String^ stringVal; - -public: - ExampleAttribute() - { - stringVal = "This is the default string."; - } - - - property String^ StringValue - { - String^ get() { return stringVal; } - void set(String^ value) { stringVal = value; } - } -}; - -[Example(StringValue="This is a string.")] -public ref class Class1 -{ -public: - static void Main() - { - System::Reflection::MemberInfo^ info = Type::GetType("Class1"); - for each (Object^ attrib in info->GetCustomAttributes(true)) - { - Console::WriteLine(attrib); - } - } -}; - -int main() -{ - Class1::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp b/samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp deleted file mode 100644 index 9ccf0fa3384b5..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/DynamicMethodHowTo/cpp/source.cpp +++ /dev/null @@ -1,189 +0,0 @@ -// -using namespace System; -using namespace System::Reflection; -using namespace System::Reflection::Emit; - -public ref class Example -{ - // The following constructor and private field are used to - // demonstrate a method bound to an object. -private: - int test; - -public: - Example(int test) { this->test = test; } - - // Declare delegates that can be used to execute the completed - // SquareIt dynamic method. The OneParameter delegate can be - // used to execute any method with one parameter and a return - // value, or a method with two parameters and a return value - // if the delegate is bound to an object. - // - // -private: - delegate long long SquareItInvoker(int input); - - // - generic - delegate TReturn OneParameter(TParameter0 p0); - // - // - -public: - static void Main() - { - // Example 1: A simple dynamic method. - // - // Create an array that specifies the parameter types for the - // dynamic method. In this example the only parameter is an - // int, so the array has only one element. - // - // - array^ methodArgs = { int::typeid }; - // - - // Create a DynamicMethod. In this example the method is - // named SquareIt. It is not necessary to give dynamic - // methods names. They cannot be invoked by name, and two - // dynamic methods can have the same name. However, the - // name appears in calls stacks and can be useful for - // debugging. - // - // In this example the return type of the dynamic method is - // long long. The method is associated with the module that - // contains the Example class. Any loaded module could be - // specified. The dynamic method is like a module-level - // static method. - // - // - DynamicMethod^ squareIt = gcnew DynamicMethod( - "SquareIt", - long long::typeid, - methodArgs, - Example::typeid->Module); - // - - // Emit the method body. In this example ILGenerator is used - // to emit the MSIL. DynamicMethod has an associated type - // DynamicILInfo that can be used in conjunction with - // unmanaged code generators. - // - // The MSIL loads the argument, which is an int, onto the - // stack, converts the int to a long long, duplicates the top - // item on the stack, and multiplies the top two items on the - // stack. This leaves the squared number on the stack, and - // all the method has to do is return. - // - // - ILGenerator^ il = squareIt->GetILGenerator(); - il->Emit(OpCodes::Ldarg_0); - il->Emit(OpCodes::Conv_I8); - il->Emit(OpCodes::Dup); - il->Emit(OpCodes::Mul); - il->Emit(OpCodes::Ret); - // - - // Create a delegate that represents the dynamic method. - // Creating the delegate completes the method, and any further - // attempts to change the method (for example, by adding more - // MSIL) are ignored. The following code uses a generic - // delegate that can produce delegate types matching any - // single-parameter method that has a return type. - // - // - OneParameter^ invokeSquareIt = - (OneParameter^) - squareIt->CreateDelegate(OneParameter::typeid); - - Console::WriteLine("123456789 squared = {0}", - invokeSquareIt(123456789)); - // - - // Example 2: A dynamic method bound to an instance. - // - // Create an array that specifies the parameter types for a - // dynamic method. If the delegate representing the method - // is to be bound to an object, the first parameter must - // match the type the delegate is bound to. In the following - // code the bound instance is of the Example class. - // - // - array^ methodArgs2 = { Example::typeid, int::typeid }; - // - - // Create a DynamicMethod. In this example the method has no - // name. The return type of the method is int. The method - // has access to the protected and private data of the - // Example class. - // - // - DynamicMethod^ multiplyHidden = gcnew DynamicMethod( - "", - int::typeid, - methodArgs2, - Example::typeid); - // - - // Emit the method body. In this example ILGenerator is used - // to emit the MSIL. DynamicMethod has an associated type - // DynamicILInfo that can be used in conjunction with - // unmanaged code generators. - // - // The MSIL loads the first argument, which is an instance of - // the Example class, and uses it to load the value of a - // private instance field of type int. The second argument is - // loaded, and the two numbers are multiplied. If the result - // is larger than int, the value is truncated and the most - // significant bits are discarded. The method returns, with - // the return value on the stack. - // - // - ILGenerator^ ilMH = multiplyHidden->GetILGenerator(); - ilMH->Emit(OpCodes::Ldarg_0); - - FieldInfo^ testInfo = Example::typeid->GetField("test", - BindingFlags::NonPublic | BindingFlags::Instance); - - ilMH->Emit(OpCodes::Ldfld, testInfo); - ilMH->Emit(OpCodes::Ldarg_1); - ilMH->Emit(OpCodes::Mul); - ilMH->Emit(OpCodes::Ret); - // - - // Create a delegate that represents the dynamic method. - // Creating the delegate completes the method, and any further - // attempts to change the method � for example, by adding more - // MSIL � are ignored. - // - // The following code binds the method to a new instance - // of the Example class whose private test field is set to 42. - // That is, each time the delegate is invoked the instance of - // Example is passed to the first parameter of the method. - // - // The delegate OneParameter is used, because the first - // parameter of the method receives the instance of Example. - // When the delegate is invoked, only the second parameter is - // required. - // - // - OneParameter^ invoke = (OneParameter^) - multiplyHidden->CreateDelegate( - OneParameter::typeid, - gcnew Example(42) - ); - - Console::WriteLine("3 * test = {0}", invoke(3)); - // - } -}; - -void main() -{ - Example::Main(); -} -/* This code example produces the following output: - -123456789 squared = 15241578750190521 -3 * test = 126 - */ -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp b/samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp deleted file mode 100644 index e069546862226..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/EmitGenericType/CPP/source.cpp +++ /dev/null @@ -1,300 +0,0 @@ -// -using namespace System; -using namespace System::Reflection; -using namespace System::Reflection::Emit; -using namespace System::Collections::Generic; - -// Dummy class to satisfy TFirst constraints. -// -public ref class Example {}; - -// Define a trivial base class and two trivial interfaces -// to use when demonstrating constraints. -// -public ref class ExampleBase {}; -public interface class IExampleA {}; -public interface class IExampleB {}; - -// Define a trivial type that can substitute for type parameter -// TSecond. -// -public ref class ExampleDerived : ExampleBase, IExampleA, IExampleB {}; - -// List the constraint flags. The GenericParameterAttributes -// enumeration contains two sets of attributes, variance and -// constraints. For this example, only constraints are used. -// -static void ListConstraintAttributes( Type^ t ) -{ - // Mask off the constraint flags. - GenericParameterAttributes constraints = - t->GenericParameterAttributes & - GenericParameterAttributes::SpecialConstraintMask; - - if ((constraints & GenericParameterAttributes::ReferenceTypeConstraint) - != GenericParameterAttributes::None) - Console::WriteLine( L" ReferenceTypeConstraint"); - - if ((constraints & GenericParameterAttributes::NotNullableValueTypeConstraint) - != GenericParameterAttributes::None) - Console::WriteLine( L" NotNullableValueTypeConstraint"); - - if ((constraints & GenericParameterAttributes::DefaultConstructorConstraint) - != GenericParameterAttributes::None) - Console::WriteLine( L" DefaultConstructorConstraint"); -} - -static void DisplayGenericParameters( Type^ t ) -{ - if (!t->IsGenericType) - { - Console::WriteLine( L"Type '{0}' is not generic." ); - return; - } - if (!t->IsGenericTypeDefinition) - t = t->GetGenericTypeDefinition(); - - array^ typeParameters = t->GetGenericArguments(); - Console::WriteLine( L"\r\nListing {0} type parameters for type '{1}'.", - typeParameters->Length, t ); - - for each ( Type^ tParam in typeParameters ) - { - Console::WriteLine( L"\r\nType parameter {0}:", - tParam->ToString() ); - - for each (Type^ c in tParam->GetGenericParameterConstraints()) - { - if (c->IsInterface) - Console::WriteLine( L" Interface constraint: {0}", c); - else - Console::WriteLine( L" Base type constraint: {0}", c); - } - ListConstraintAttributes(tParam); - } -} - -void main() -{ - // Define a dynamic assembly to contain the sample type. The - // assembly will be run and also saved to disk, so - // AssemblyBuilderAccess.RunAndSave is specified. - // - // - AppDomain^ myDomain = AppDomain::CurrentDomain; - AssemblyName^ myAsmName = gcnew AssemblyName( L"GenericEmitExample1" ); - AssemblyBuilder^ myAssembly = myDomain->DefineDynamicAssembly( - myAsmName, AssemblyBuilderAccess::RunAndSave ); - // - - // An assembly is made up of executable modules. For a single- - // module assembly, the module name and file name are the same - // as the assembly name. - // - // - ModuleBuilder^ myModule = myAssembly->DefineDynamicModule( - myAsmName->Name, String::Concat( myAsmName->Name, L".dll" ) ); - // - - // Get type objects for the base class trivial interfaces to - // be used as constraints. - // - Type^ baseType = ExampleBase::typeid; - Type^ interfaceA = IExampleA::typeid; - Type^ interfaceB = IExampleB::typeid; - - // Define the sample type. - // - // - TypeBuilder^ myType = myModule->DefineType( L"Sample", - TypeAttributes::Public ); - // - - Console::WriteLine( L"Type 'Sample' is generic: {0}", - myType->IsGenericType ); - - // Define type parameters for the type. Until you do this, - // the type is not generic, as the preceding and following - // WriteLine statements show. The type parameter names are - // specified as an array of strings. To make the code - // easier to read, each GenericTypeParameterBuilder is placed - // in a variable with the same name as the type parameter. - // - // - array^typeParamNames = {L"TFirst",L"TSecond"}; - array^typeParams = - myType->DefineGenericParameters( typeParamNames ); - - GenericTypeParameterBuilder^ TFirst = typeParams[0]; - GenericTypeParameterBuilder^ TSecond = typeParams[1]; - // - - Console::WriteLine( L"Type 'Sample' is generic: {0}", - myType->IsGenericType ); - - // Apply constraints to the type parameters. - // - // A type that is substituted for the first parameter, TFirst, - // must be a reference type and must have a parameterless - // constructor. - // - TFirst->SetGenericParameterAttributes( - GenericParameterAttributes::DefaultConstructorConstraint | - GenericParameterAttributes::ReferenceTypeConstraint - ); - // - - // A type that is substituted for the second type - // parameter must implement IExampleA and IExampleB, and - // inherit from the trivial test class ExampleBase. The - // interface constraints are specified as an array - // containing the interface types. - // - array^interfaceTypes = { interfaceA, interfaceB }; - TSecond->SetInterfaceConstraints( interfaceTypes ); - TSecond->SetBaseTypeConstraint( baseType ); - // - - // The following code adds a private field named ExampleField, - // of type TFirst. - // - FieldBuilder^ exField = - myType->DefineField("ExampleField", TFirst, - FieldAttributes::Private); - // - - // Define a static method that takes an array of TFirst and - // returns a List containing all the elements of - // the array. To define this method it is necessary to create - // the type List by calling MakeGenericType on the - // generic type definition, generic List. - // The parameter type is created by using the - // MakeArrayType method. - // - // - Type^ listOf = List::typeid; - Type^ listOfTFirst = listOf->MakeGenericType(TFirst); - array^ mParamTypes = { TFirst->MakeArrayType() }; - - MethodBuilder^ exMethod = - myType->DefineMethod("ExampleMethod", - MethodAttributes::Public | MethodAttributes::Static, - listOfTFirst, - mParamTypes); - // - - // Emit the method body. - // The method body consists of just three opcodes, to load - // the input array onto the execution stack, to call the - // List constructor that takes IEnumerable, - // which does all the work of putting the input elements into - // the list, and to return, leaving the list on the stack. The - // hard work is getting the constructor. - // - // The GetConstructor method is not supported on a - // GenericTypeParameterBuilder, so it is not possible to get - // the constructor of List directly. There are two - // steps, first getting the constructor of generic List and then - // calling a method that converts it to the corresponding - // constructor of List. - // - // The constructor needed here is the one that takes an - // IEnumerable. Note, however, that this is not the - // generic type definition of generic IEnumerable; instead, the - // T from generic List must be substituted for the T of - // generic IEnumerable. (This seems confusing only because both - // types have type parameters named T. That is why this example - // uses the somewhat silly names TFirst and TSecond.) To get - // the type of the constructor argument, take the generic - // type definition generic IEnumerable and - // call MakeGenericType with the first generic type parameter - // of generic List. The constructor argument list must be passed - // as an array, with just one argument in this case. - // - // Now it is possible to get the constructor of generic List, - // using GetConstructor on the generic type definition. To get - // the constructor of List, pass List and - // the constructor from generic List to the static - // TypeBuilder.GetConstructor method. - // - // - ILGenerator^ ilgen = exMethod->GetILGenerator(); - - Type^ ienumOf = IEnumerable::typeid; - Type^ TfromListOf = listOf->GetGenericArguments()[0]; - Type^ ienumOfT = ienumOf->MakeGenericType(TfromListOf); - array^ ctorArgs = {ienumOfT}; - - ConstructorInfo^ ctorPrep = listOf->GetConstructor(ctorArgs); - ConstructorInfo^ ctor = - TypeBuilder::GetConstructor(listOfTFirst, ctorPrep); - - ilgen->Emit(OpCodes::Ldarg_0); - ilgen->Emit(OpCodes::Newobj, ctor); - ilgen->Emit(OpCodes::Ret); - // - - // Create the type and save the assembly. - // - Type^ finished = myType->CreateType(); - myAssembly->Save( String::Concat( myAsmName->Name, L".dll" ) ); - // - - // Invoke the method. - // ExampleMethod is not generic, but the type it belongs to is - // generic, so in order to get a MethodInfo that can be invoked - // it is necessary to create a constructed type. The Example - // class satisfies the constraints on TFirst, because it is a - // reference type and has a default constructor. In order to - // have a class that satisfies the constraints on TSecond, - // this code example defines the ExampleDerived type. These - // two types are passed to MakeGenericMethod to create the - // constructed type. - // - // - array^ typeArgs = - { Example::typeid, ExampleDerived::typeid }; - Type^ constructed = finished->MakeGenericType(typeArgs); - MethodInfo^ mi = constructed->GetMethod("ExampleMethod"); - // - - // Create an array of Example objects, as input to the generic - // method. This array must be passed as the only element of an - // array of arguments. The first argument of Invoke is - // null, because ExampleMethod is static. Display the count - // on the resulting List. - // - // - array^ input = { gcnew Example(), gcnew Example() }; - array^ arguments = { input }; - - List^ listX = - (List^) mi->Invoke(nullptr, arguments); - - Console::WriteLine( - "\nThere are {0} elements in the List.", - listX->Count); - // - - DisplayGenericParameters(finished); -} - -/* This code example produces the following output: - -Type 'Sample' is generic: False -Type 'Sample' is generic: True - -There are 2 elements in the List. - -Listing 2 type parameters for type 'Sample[TFirst,TSecond]'. - -Type parameter TFirst: - ReferenceTypeConstraint - DefaultConstructorConstraint - -Type parameter TSecond: - Interface constraint: IExampleA - Interface constraint: IExampleB - Base type constraint: ExampleBase - */ -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp b/samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp deleted file mode 100644 index 505abfa8d291c..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/Standard.cpp +++ /dev/null @@ -1,228 +0,0 @@ -using namespace System; -using namespace System::Globalization; - -void ShowCurrency() -{ - // - double value = 12345.6789; - Console::WriteLine(value.ToString("C", CultureInfo::CurrentCulture)); - - Console::WriteLine(value.ToString("C3", CultureInfo::CurrentCulture)); - - Console::WriteLine(value.ToString("C3", - CultureInfo::CreateSpecificCulture("da-DK"))); - // The example displays the following output on a system whose - // current culture is English (United States): - // $12,345.68 - // $12,345.679 - // kr 12.345,679 - // -} - -void ShowDecimal() -{ - // - int value; - - value = 12345; - Console::WriteLine(value.ToString("D")); - // Displays 12345 - Console::WriteLine(value.ToString("D8")); - // Displays 00012345 - - value = -12345; - Console::WriteLine(value.ToString("D")); - // Displays -12345 - Console::WriteLine(value.ToString("D8")); - // Displays -00012345 - // -} - -void ShowExponentiation() -{ - // - double value = 12345.6789; - Console::WriteLine(value.ToString("E", CultureInfo::InvariantCulture)); - // Displays 1.234568E+004 - - Console::WriteLine(value.ToString("E10", CultureInfo::InvariantCulture)); - // Displays 1.2345678900E+004 - - Console::WriteLine(value.ToString("e4", CultureInfo::InvariantCulture)); - // Displays 1.2346e+004 - - Console::WriteLine(value.ToString("E", - CultureInfo::CreateSpecificCulture("fr-FR"))); - // Displays 1,234568E+004 - // -} - -void ShowFixedPoint() -{ - // - int integerNumber; - integerNumber = 17843; - Console::WriteLine(integerNumber.ToString("F", - CultureInfo::InvariantCulture)); - // Displays 17843.00 - - integerNumber = -29541; - Console::WriteLine(integerNumber.ToString("F3", - CultureInfo::InvariantCulture)); - // Displays -29541.000 - - double doubleNumber; - doubleNumber = 18934.1879; - Console::WriteLine(doubleNumber.ToString("F", CultureInfo::InvariantCulture)); - // Displays 18934.19 - - Console::WriteLine(doubleNumber.ToString("F0", CultureInfo::InvariantCulture)); - // Displays 18934 - - doubleNumber = -1898300.1987; - Console::WriteLine(doubleNumber.ToString("F1", CultureInfo::InvariantCulture)); - // Displays -1898300.2 - - Console::WriteLine(doubleNumber.ToString("F3", - CultureInfo::CreateSpecificCulture("es-ES"))); - // Displays -1898300,199 - // -} - -void ShowGeneral() -{ - // - double number; - - number = 12345.6789; - Console::WriteLine(number.ToString("G", CultureInfo::InvariantCulture)); - // Displays 12345.6789 - Console::WriteLine(number.ToString("G", - CultureInfo::CreateSpecificCulture("fr-FR"))); - // Displays 12345,6789 - - Console::WriteLine(number.ToString("G7", CultureInfo::InvariantCulture)); - // Displays 12345.68 - - number = .0000023; - Console::WriteLine(number.ToString("G", CultureInfo::InvariantCulture)); - // Displays 2.3E-06 - Console::WriteLine(number.ToString("G", - CultureInfo::CreateSpecificCulture("fr-FR"))); - // Displays 2,3E-06 - - number = .0023; - Console::WriteLine(number.ToString("G", CultureInfo::InvariantCulture)); - // Displays 0.0023 - - number = 1234; - Console::WriteLine(number.ToString("G2", CultureInfo::InvariantCulture)); - // Displays 1.2E+03 - - number = Math::PI; - Console::WriteLine(number.ToString("G5", CultureInfo::InvariantCulture)); - // Displays 3.1416 - // -} - -void ShowNumeric() -{ - // - double dblValue = -12445.6789; - Console::WriteLine(dblValue.ToString("N", CultureInfo::InvariantCulture)); - // Displays -12,445.68 - Console::WriteLine(dblValue.ToString("N1", - CultureInfo::CreateSpecificCulture("sv-SE"))); - // Displays -12 445,7 - - int intValue = 123456789; - Console::WriteLine(intValue.ToString("N1", CultureInfo::InvariantCulture)); - // Displays 123,456,789.0 - // -} - -void ShowPercent() -{ - // - double number = .2468013; - Console::WriteLine(number.ToString("P", CultureInfo::InvariantCulture)); - // Displays 24.68 % - Console::WriteLine(number.ToString("P", - CultureInfo::CreateSpecificCulture("hr-HR"))); - // Displays 24,68% - Console::WriteLine(number.ToString("P1", CultureInfo::InvariantCulture)); - // Displays 24.7 % - // -} - -void ShowRoundTrip() -{ - // - double value; - - value = Math::PI; - Console::WriteLine(value.ToString("r")); - // Displays 3.1415926535897931 - Console::WriteLine(value.ToString("r", - CultureInfo::CreateSpecificCulture("fr-FR"))); - // Displays 3,1415926535897931 - value = 1.623e-21; - Console::WriteLine(value.ToString("r")); - // Displays 1.623E-21 - // -} - -void ShowHex() -{ - // - int value; - - value = 0x2045e; - Console::WriteLine(value.ToString("x")); - // Displays 2045e - Console::WriteLine(value.ToString("X")); - // Displays 2045E - Console::WriteLine(value.ToString("X8")); - // Displays 0002045E - - value = 123456789; - Console::WriteLine(value.ToString("X")); - // Displays 75BCD15 - Console::WriteLine(value.ToString("X2")); - // Displays 75BCD15 - // -} - -void main() -{ - Console::Clear(); - Console::WriteLine(CultureInfo::CurrentUICulture->Name); - Console::WriteLine(CultureInfo::CurrentCulture->Name); - Console::WriteLine(); - Console::WriteLine("Currency Format Specifier:"); - ShowCurrency(); - Console::WriteLine(); - Console::WriteLine("Decimal Format Specifier:"); - ShowDecimal(); - Console::WriteLine(); - Console::WriteLine("Exponentiation Format Specifier:"); - ShowExponentiation(); - Console::WriteLine(); - Console::WriteLine("Fixed Point Format Specifier:"); - ShowFixedPoint(); - Console::WriteLine(); - Console::WriteLine("'G' Format Specifier:"); - ShowGeneral(); - Console::WriteLine(); - Console::WriteLine("'N' Format Specifier:"); - ShowNumeric(); - Console::WriteLine(); - Console::WriteLine("Percent Format Specifier:"); - ShowPercent(); - Console::WriteLine(); - Console::WriteLine("Round-trip Format Specifier:"); - ShowRoundTrip(); - Console::WriteLine(); - Console::WriteLine("Hexadecimal Format Specifier:"); - ShowHex(); - } \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/standardusage1.cpp b/samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/standardusage1.cpp deleted file mode 100644 index 9cabf92e11835..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/Formatting.Numeric.Standard/cpp/standardusage1.cpp +++ /dev/null @@ -1,39 +0,0 @@ -using namespace System; - -void ShowToString() -{ - // - Decimal value = static_cast(123.456); - Console::WriteLine(value.ToString("C2")); - // Displays $123.46 - // -} - -void ShowComposite() -{ - // - Decimal value = static_cast(123.456); - Console::WriteLine("Your account balance is {0:C2}.", value); - // Displays "Your account balance is $123.46." - // -} - -void ShowCompositeWithAlignment() -{ - // - array^ amounts = { static_cast(16305.32), - static_cast(18794.16) }; - Console::WriteLine(" Beginning Balance Ending Balance"); - Console::WriteLine(" {0,-28:C2}{1,14:C2}", amounts[0], amounts[1]); - // Displays: - // Beginning Balance Ending Balance - // $16,305.32 $18,794.16 - // -} - -void main() -{ - ShowToString(); - ShowComposite(); - ShowCompositeWithAlignment(); -} diff --git a/samples/snippets/cpp/VS_Snippets_CLR/GCNotification/cpp/program.cpp b/samples/snippets/cpp/VS_Snippets_CLR/GCNotification/cpp/program.cpp deleted file mode 100644 index e69abbd4e0739..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/GCNotification/cpp/program.cpp +++ /dev/null @@ -1,242 +0,0 @@ -// -// -using namespace System; -using namespace System::Collections::Generic; -using namespace System::Threading; - -namespace GCNotify -{ - ref class Program - { - private: - // Variable for continual checking in the - // While loop in the WaitForFullGCProc method. - static bool checkForNotify = false; - - // Variable for suspending work - // (such servicing allocated server requests) - // after a notification is received and then - // resuming allocation after inducing a garbage collection. - static bool bAllocate = false; - - // Variable for ending the example. - static bool finalExit = false; - - // Collection for objects that - // simulate the server request workload. - static List^>^ load = gcnew List^>(); - - - public: - static void Main() - { - try - { - // Register for a notification. - GC::RegisterForFullGCNotification(10, 10); - Console::WriteLine("Registered for GC notification."); - - checkForNotify = true; - bAllocate = true; - - // Start a thread using WaitForFullGCProc. - Thread^ thWaitForFullGC = gcnew Thread(gcnew ThreadStart(&WaitForFullGCProc)); - thWaitForFullGC->Start(); - - // While the thread is checking for notifications in - // WaitForFullGCProc, create objects to simulate a server workload. - try - { - int lastCollCount = 0; - int newCollCount = 0; - - - while (true) - { - if (bAllocate) - { - load->Add(gcnew array(1000)); - newCollCount = GC::CollectionCount(2); - if (newCollCount != lastCollCount) - { - // Show collection count when it increases: - Console::WriteLine("Gen 2 collection count: {0}", GC::CollectionCount(2).ToString()); - lastCollCount = newCollCount; - } - - // For ending the example (arbitrary). - if (newCollCount == 500) - { - finalExit = true; - checkForNotify = false; - break; - } - } - } - - } - catch (OutOfMemoryException^) - { - Console::WriteLine("Out of memory."); - } - - - // - finalExit = true; - checkForNotify = false; - GC::CancelFullGCNotification(); - // - - } - catch (InvalidOperationException^ invalidOp) - { - - Console::WriteLine("GC Notifications are not supported while concurrent GC is enabled.\n" - + invalidOp->Message); - } - } - - // - public: - static void OnFullGCApproachNotify() - { - Console::WriteLine("Redirecting requests."); - - // Method that tells the request queuing - // server to not direct requests to this server. - RedirectRequests(); - - // Method that provides time to - // finish processing pending requests. - FinishExistingRequests(); - - // This is a good time to induce a GC collection - // because the runtime will induce a full GC soon. - // To be very careful, you can check precede with a - // check of the GC.GCCollectionCount to make sure - // a full GC did not already occur since last notified. - GC::Collect(); - Console::WriteLine("Induced a collection."); - - } - // - - - // - public: - static void OnFullGCCompleteEndNotify() - { - // Method that informs the request queuing server - // that this server is ready to accept requests again. - AcceptRequests(); - Console::WriteLine("Accepting requests again."); - } - // - - // - public: - static void WaitForFullGCProc() - { - while (true) - { - // CheckForNotify is set to true and false in Main. - while (checkForNotify) - { - // - // Check for a notification of an approaching collection. - GCNotificationStatus s = GC::WaitForFullGCApproach(); - if (s == GCNotificationStatus::Succeeded) - { - Console::WriteLine("GC Notification raised."); - OnFullGCApproachNotify(); - } - else if (s == GCNotificationStatus::Canceled) - { - Console::WriteLine("GC Notification cancelled."); - break; - } - else - { - // This can occur if a timeout period - // is specified for WaitForFullGCApproach(Timeout) - // or WaitForFullGCComplete(Timeout) - // and the time out period has elapsed. - Console::WriteLine("GC Notification not applicable."); - break; - } - // - - // - // Check for a notification of a completed collection. - s = GC::WaitForFullGCComplete(); - if (s == GCNotificationStatus::Succeeded) - { - Console::WriteLine("GC Notification raised."); - OnFullGCCompleteEndNotify(); - } - else if (s == GCNotificationStatus::Canceled) - { - Console::WriteLine("GC Notification cancelled."); - break; - } - else - { - // Could be a time out. - Console::WriteLine("GC Notification not applicable."); - break; - } - // - } - - - Thread::Sleep(500); - // FinalExit is set to true right before - // the main thread cancelled notification. - if (finalExit) - { - break; - } - } - } - // - - // - private: - static void RedirectRequests() - { - // Code that sends requests - // to other servers. - - // Suspend work. - bAllocate = false; - - } - - static void FinishExistingRequests() - { - // Code that waits a period of time - // for pending requests to finish. - - // Clear the simulated workload. - load->Clear(); - - } - - static void AcceptRequests() - { - // Code that resumes processing - // requests on this server. - - // Resume work. - bAllocate = true; - } - // - }; -} - -int main() -{ - GCNotify::Program::Main(); -} -// -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp b/samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp deleted file mode 100644 index 82beff87e33bd..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/HookUpDelegate/cpp/source.cpp +++ /dev/null @@ -1,190 +0,0 @@ -// -#using -#using - -using namespace System; -using namespace System::Reflection; -using namespace System::Reflection::Emit; -using namespace System::Windows::Forms; - -// -public ref class ExampleForm : public Form -{ -public: - ExampleForm() : Form() - { - this->Text = "Click me"; - } -}; -// - -public ref class Example -{ -public: - static void Main() - { - Example^ ex = gcnew Example(); - ex->HookUpDelegate(); - } - -private: - void HookUpDelegate() - { - // Load an assembly, for example using the Assembly.Load - // method. In this case, the executing assembly is loaded, to - // keep the demonstration simple. - // - // - Assembly^ assem = Example::typeid->Assembly; - // - - // Get the type that is to be loaded, and create an instance - // of it. Activator::CreateInstance has other overloads, if - // the type lacks a default constructor. The new instance - // is stored as type Object, to maintain the fiction that - // nothing is known about the assembly. (Note that you can - // get the types in an assembly without knowing their names - // in advance.) - // - // - Type^ tExForm = assem->GetType("ExampleForm"); - Object^ exFormAsObj = Activator::CreateInstance(tExForm); - // - - // Get an EventInfo representing the Click event, and get the - // type of delegate that handles the event. - // - // - EventInfo^ evClick = tExForm->GetEvent("Click"); - Type^ tDelegate = evClick->EventHandlerType; - // - - // If you already have a method with the correct signature, - // you can simply get a MethodInfo for it. - // - // - MethodInfo^ miHandler = - Type::GetType("Example")->GetMethod("LuckyHandler", - BindingFlags::NonPublic | BindingFlags::Instance); - // - - // Create an instance of the delegate. Using the overloads - // of CreateDelegate that take MethodInfo is recommended. - // - // - Delegate^ d = Delegate::CreateDelegate(tDelegate, this, miHandler); - // - - // Get the "add" accessor of the event and invoke it late- - // bound, passing in the delegate instance. This is equivalent - // to using the += operator in C#, or AddHandler in Visual - // Basic. The instance on which the "add" accessor is invoked - // is the form; the arguments must be passed as an array. - // - // - MethodInfo^ addHandler = evClick->GetAddMethod(); - array^ addHandlerArgs = { d }; - addHandler->Invoke(exFormAsObj, addHandlerArgs); - // - - // Event handler methods can also be generated at run time, - // using lightweight dynamic methods and Reflection.Emit. - // To construct an event handler, you need the return type - // and parameter types of the delegate. These can be obtained - // by examining the delegate's Invoke method. - // - // It is not necessary to name dynamic methods, so the empty - // string can be used. The last argument associates the - // dynamic method with the current type, giving the delegate - // access to all the public and private members of Example, - // as if it were an instance method. - // - // - Type^ returnType = GetDelegateReturnType(tDelegate); - if (returnType != void::typeid) - throw gcnew ApplicationException("Delegate has a return type."); - - DynamicMethod^ handler = - gcnew DynamicMethod("", - nullptr, - GetDelegateParameterTypes(tDelegate), - Example::typeid); - // - - // Generate a method body. This method loads a string, calls - // the Show method overload that takes a string, pops the - // return value off the stack (because the handler has no - // return type), and returns. - // - // - ILGenerator^ ilgen = handler->GetILGenerator(); - - array^ showParameters = { String::typeid }; - MethodInfo^ simpleShow = - MessageBox::typeid->GetMethod("Show", showParameters); - - ilgen->Emit(OpCodes::Ldstr, - "This event handler was constructed at run time."); - ilgen->Emit(OpCodes::Call, simpleShow); - ilgen->Emit(OpCodes::Pop); - ilgen->Emit(OpCodes::Ret); - // - - // Complete the dynamic method by calling its CreateDelegate - // method. Use the "add" accessor to add the delegate to - // the invocation list for the event. - // - // - Delegate^ dEmitted = handler->CreateDelegate(tDelegate); - addHandler->Invoke(exFormAsObj, gcnew array { dEmitted }); - // - - // Show the form. Clicking on the form causes the two - // delegates to be invoked. - // - // - Application::Run((Form^) exFormAsObj); - // - } - - void LuckyHandler(Object^ sender, EventArgs^ e) - { - MessageBox::Show("This event handler just happened to be lying around."); - } - - array^ GetDelegateParameterTypes(Type^ d) - { - if (d->BaseType != MulticastDelegate::typeid) - throw gcnew ApplicationException("Not a delegate."); - - MethodInfo^ invoke = d->GetMethod("Invoke"); - if (invoke == nullptr) - throw gcnew ApplicationException("Not a delegate."); - - array^ parameters = invoke->GetParameters(); - array^ typeParameters = gcnew array(parameters->Length); - for (int i = 0; i < parameters->Length; i++) - { - typeParameters[i] = parameters[i]->ParameterType; - } - return typeParameters; - } - - Type^ GetDelegateReturnType(Type^ d) - { - if (d->BaseType != MulticastDelegate::typeid) - throw gcnew ApplicationException("Not a delegate."); - - MethodInfo^ invoke = d->GetMethod("Invoke"); - if (invoke == nullptr) - throw gcnew ApplicationException("Not a delegate."); - - return invoke->ReturnType; - } -}; - -int main() -{ - Example::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/source2.cpp b/samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/source2.cpp deleted file mode 100644 index 62aba6460169a..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/source2.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Collections::Generic; - -ref class AdvantageGenerics -{ -public: - static void Main() - { - array^ myArray = - {"First String", "test string", "Last String"}; - - // - LinkedList^ llist = gcnew LinkedList(); - // - - for each (String^ item in myArray) - { - llist->AddLast(item); - } - LinkedListNode^ found = llist->Find("test string"); - if (found != nullptr) - { - Console::WriteLine("Item found: {0}", found->Value); - } - // - int index0 = Array::BinarySearch(myArray, "test string"); - int index1 = Array::BinarySearch(myArray, "test string"); - // - - Console::WriteLine("Indexes for binary searches: {0}, {1}", index0, index1); - } -}; - -int main() -{ - AdvantageGenerics::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp b/samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp deleted file mode 100644 index d37bfd6556290..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/HowToGeneric/cpp/ur.cpp +++ /dev/null @@ -1,204 +0,0 @@ -// Example code for How to: Discover and Manipulate Generic Types -// -using namespace System; -using namespace System::Reflection; -using namespace System::Collections::Generic; -using namespace System::Security::Permissions; - -// Define an example interface. -public interface class ITestArgument {}; - -// Define an example base class. -public ref class TestBase {}; - -// Define a generic class with one parameter. The parameter -// has three constraints: It must inherit TestBase, it must -// implement ITestArgument, and it must have a parameterless -// constructor. - -generic - where T : TestBase, ITestArgument, gcnew() -public ref class Test {}; - -// Define a class that meets the constraints on the type -// parameter of class Test. -public ref class TestArgument : TestBase, ITestArgument -{ -public: - TestArgument() {} -}; - -public ref class Example -{ - // The following method displays information about a generic - // type. -private: - static void DisplayGenericType(Type^ t) - { - Console::WriteLine("\r\n {0}", t); - // - Console::WriteLine(" Is this a generic type? {0}", - t->IsGenericType); - Console::WriteLine(" Is this a generic type definition? {0}", - t->IsGenericTypeDefinition); - // - - // Get the generic type parameters or type arguments. - // - array^ typeParameters = t->GetGenericArguments(); - // - - // - Console::WriteLine(" List {0} type arguments:", - typeParameters->Length); - for each( Type^ tParam in typeParameters ) - { - if (tParam->IsGenericParameter) - { - DisplayGenericParameter(tParam); - } - else - { - Console::WriteLine(" Type argument: {0}", - tParam); - } - } - // - } - - // The following method displays information about a generic - // type parameter. Generic type parameters are represented by - // instances of System.Type, just like ordinary types. - // - static void DisplayGenericParameter(Type^ tp) - { - Console::WriteLine(" Type parameter: {0} position {1}", - tp->Name, tp->GenericParameterPosition); - // - - // - Type^ classConstraint = nullptr; - - for each(Type^ iConstraint in tp->GetGenericParameterConstraints()) - { - if (iConstraint->IsInterface) - { - Console::WriteLine(" Interface constraint: {0}", - iConstraint); - } - } - - if (classConstraint != nullptr) - { - Console::WriteLine(" Base type constraint: {0}", - tp->BaseType); - } - else - Console::WriteLine(" Base type constraint: None"); - // - - // - GenericParameterAttributes sConstraints = - tp->GenericParameterAttributes & - GenericParameterAttributes::SpecialConstraintMask; - // - - // - if (sConstraints == GenericParameterAttributes::None) - { - Console::WriteLine(" No special constraints."); - } - else - { - if (GenericParameterAttributes::None != (sConstraints & - GenericParameterAttributes::DefaultConstructorConstraint)) - { - Console::WriteLine(" Must have a parameterless constructor."); - } - if (GenericParameterAttributes::None != (sConstraints & - GenericParameterAttributes::ReferenceTypeConstraint)) - { - Console::WriteLine(" Must be a reference type."); - } - if (GenericParameterAttributes::None != (sConstraints & - GenericParameterAttributes::NotNullableValueTypeConstraint)) - { - Console::WriteLine(" Must be a non-nullable value type."); - } - } - // - } - -public: - [PermissionSetAttribute(SecurityAction::Demand, Name="FullTrust")] - static void Main() - { - // Two ways to get a Type object that represents the generic - // type definition of the Dictionary class. - // - // - // Use the typeid keyword to create the generic type - // definition directly. - // - Type^ d1 = Dictionary::typeid; - // - - // You can also obtain the generic type definition from a - // constructed class. In this case, the constructed class - // is a dictionary of Example objects, with String keys. - Dictionary^ d2 = gcnew Dictionary(); - // Get a Type object that represents the constructed type, - // and from that get the generic type definition. The - // variables d1 and d4 contain the same type. - Type^ d3 = d2->GetType(); - Type^ d4 = d3->GetGenericTypeDefinition(); - // - - // Display information for the generic type definition, and - // for the constructed type Dictionary. - DisplayGenericType(d1); - DisplayGenericType(d2->GetType()); - - // Construct an array of type arguments to substitute for - // the type parameters of the generic Dictionary class. - // The array must contain the correct number of types, in - // the same order that they appear in the type parameter - // list of Dictionary. The key (first type parameter) - // is of type string, and the type to be contained in the - // dictionary is Example. - // - array^ typeArgs = {String::typeid, Example::typeid}; - // - - // Construct the type Dictionary. - // - Type^ constructed = d1->MakeGenericType(typeArgs); - // - - DisplayGenericType(constructed); - - // - Object^ o = Activator::CreateInstance(constructed); - // - - Console::WriteLine("\r\nCompare types obtained by different methods:"); - Console::WriteLine(" Are the constructed types equal? {0}", - (d2->GetType()==constructed)); - Console::WriteLine(" Are the generic definitions equal? {0}", - (d1==constructed->GetGenericTypeDefinition())); - - // Demonstrate the DisplayGenericType and - // DisplayGenericParameter methods with the Test class - // defined above. This shows base, interface, and special - // constraints. - DisplayGenericType(Test::typeid); - } -}; - -int main() -{ - Example::Main(); -} -// - - diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source1.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source1.cpp deleted file mode 100644 index 770aa27da9b13..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source1.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// -using namespace System; -// -using namespace System::Reflection; -[assembly:AssemblyTitle("My Assembly")]; -// - -// -public ref class Example -{ - // Specify attributes between square brackets in C#. - // This attribute is applied only to the Add method. -public: - [Obsolete("Will be removed in next version.")] - static int Add(int a, int b) - { - return (a + b); - } -}; - -ref class Test -{ -public: - static void Main() - { - // This generates a compile-time warning. - int i = Example::Add(2, 2); - } -}; - -int main() -{ - Test::Main(); -} -// -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp deleted file mode 100644 index 2cb353a3e406b..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source2.cpp +++ /dev/null @@ -1,216 +0,0 @@ -using namespace System; - -namespace CustomCodeAttributes -{ - // - [AttributeUsage(AttributeTargets::All)] - public ref class DeveloperAttribute : Attribute - { - // Private fields. - private: - String^ name; - String^ level; - bool reviewed; - - public: - // This constructor defines two required parameters: name and level. - - DeveloperAttribute(String^ name, String^ level) - { - this->name = name; - this->level = level; - this->reviewed = false; - } - - // Define Name property. - // This is a read-only attribute. - - virtual property String^ Name - { - String^ get() {return name;} - } - - // Define Level property. - // This is a read-only attribute. - - virtual property String^ Level - { - String^ get() {return level;} - } - - // Define Reviewed property. - // This is a read/write attribute. - - virtual property bool Reviewed - { - bool get() {return reviewed;} - void set(bool value) {reviewed = value;} - } - }; - // -} - -namespace CustomCodeAttributes_Examples1 -{ - // - [AttributeUsage(AttributeTargets::All, Inherited = false, AllowMultiple = true)] - // - public ref class DummyAttribute1 : Attribute - { - }; - - // - [AttributeUsage(AttributeTargets::Class | AttributeTargets::Method)] - // - public ref class DummyAttribute2 : Attribute - { - }; - - // - // This defaults to Inherited = true. - public ref class MyAttribute : Attribute - { - //... - }; - - [AttributeUsage(AttributeTargets::Method, Inherited = false)] - public ref class YourAttribute : Attribute - { - //... - }; - // - - // - public ref class MyClass - { - public: - [MyAttribute] - [YourAttribute] - virtual void MyMethod() - { - //... - } - }; - // - - // - public ref class YourClass : MyClass - { - public: - // MyMethod will have MyAttribute but not YourAttribute. - virtual void MyMethod() override - { - //... - } - - }; - // -} - -namespace CustomCodeAttributes_Examples2 -{ - // - //This defaults to AllowMultiple = false. - public ref class MyAttribute : Attribute - { - }; - - [AttributeUsage(AttributeTargets::Method, AllowMultiple = true)] - public ref class YourAttribute : Attribute - { - }; - // - -// #if'd out since MyClass will intentionally not compile -#if 0 - // - [Developer("Joan Smith", "1")] - - -or- - - [Developer("Joan Smith", "1", Reviewed = true)] - // - - // - public ref class MyClass - { - public: - // This produces an error. - // Duplicates are not allowed. - [MyAttribute] - [MyAttribute] - void MyMethod() - { - //... - } - - // This is valid. - [YourAttribute] - [YourAttribute] - void YourMethod() - { - //... - } - }; - // -#endif -} - -namespace CustomCodeAttributes_Examples3 -{ - // - [AttributeUsage(AttributeTargets::Method)] - public ref class MyAttribute : Attribute - { - // . . . - }; - // -} - -namespace CustomCodeAttributes_Examples4 -{ - public ref class MyAttribute : Attribute - { - private: - bool myvalue; - String^ myoptional; - - public: - // - MyAttribute(bool myvalue) - { - this->myvalue = myvalue; - } - // - - // - property bool MyProperty - { - bool get() {return this->myvalue;} - void set(bool value) {this->myvalue = value;} - } - // - - property String^ OptionalParameter - { - String^ get() {return this->myoptional;} - void set(String^ value) {this->myoptional = value;} - } - }; - - // - // One required (positional) and one optional (named) parameter are applied. - [MyAttribute(false, OptionalParameter = "optional data")] - public ref class SomeClass - { - //... - }; - // One required (positional) parameter is applied. - [MyAttribute(false)] - public ref class SomeOtherClass - { - //... - }; - // -} - diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source3.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source3.cpp deleted file mode 100644 index 3837ecce1972b..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.attributes.usage/cpp/source3.cpp +++ /dev/null @@ -1,124 +0,0 @@ -// -using namespace System; -using namespace System::Reflection; -using namespace CustomCodeAttributes; - -[Developer("Joan Smith", "42", Reviewed = true)] -ref class MainApp -{ -public: - static void Main() - { - // Call function to get and display the attribute. - GetAttribute(MainApp::typeid); - } - - static void GetAttribute(Type^ t) - { - // Get instance of the attribute. - DeveloperAttribute^ MyAttribute = - (DeveloperAttribute^) Attribute::GetCustomAttribute(t, DeveloperAttribute::typeid); - - if (MyAttribute == nullptr) - { - Console::WriteLine("The attribute was not found."); - } - else - { - // Get the Name value. - Console::WriteLine("The Name Attribute is: {0}." , MyAttribute->Name); - // Get the Level value. - Console::WriteLine("The Level Attribute is: {0}." , MyAttribute->Level); - // Get the Reviewed value. - Console::WriteLine("The Reviewed Attribute is: {0}." , MyAttribute->Reviewed); - } - } -}; -// - -ref class GetAttribTest1 -{ - // -public: - static void GetAttribute(Type^ t) - { - array^ MyAttributes = - (array^) Attribute::GetCustomAttributes(t, DeveloperAttribute::typeid); - - if (MyAttributes->Length == 0) - { - Console::WriteLine("The attribute was not found."); - } - else - { - for (int i = 0 ; i < MyAttributes->Length; i++) - { - // Get the Name value. - Console::WriteLine("The Name Attribute is: {0}." , MyAttributes[i]->Name); - // Get the Level value. - Console::WriteLine("The Level Attribute is: {0}." , MyAttributes[i]->Level); - // Get the Reviewed value. - Console::WriteLine("The Reviewed Attribute is: {0}.", MyAttributes[i]->Reviewed); - } - } - } - // -}; - -ref class GetAttribTest2 -{ - // -public: - static void GetAttribute(Type^ t) - { - DeveloperAttribute^ att; - - // Get the class-level attributes. - - // Put the instance of the attribute on the class level in the att object. - att = (DeveloperAttribute^) Attribute::GetCustomAttribute (t, DeveloperAttribute::typeid); - - if (att == nullptr) - { - Console::WriteLine("No attribute in class {0}.\n", t->ToString()); - } - else - { - Console::WriteLine("The Name Attribute on the class level is: {0}.", att->Name); - Console::WriteLine("The Level Attribute on the class level is: {0}.", att->Level); - Console::WriteLine("The Reviewed Attribute on the class level is: {0}.\n", att->Reviewed); - } - - // Get the method-level attributes. - - // Get all methods in this class, and put them - // in an array of System.Reflection.MemberInfo objects. - array^ MyMemberInfo = t->GetMethods(); - - // Loop through all methods in this class that are in the - // MyMemberInfo array. - for (int i = 0; i < MyMemberInfo->Length; i++) - { - att = (DeveloperAttribute^) Attribute::GetCustomAttribute(MyMemberInfo[i], DeveloperAttribute::typeid); - if (att == nullptr) - { - Console::WriteLine("No attribute in member function {0}.\n" , MyMemberInfo[i]->ToString()); - } - else - { - Console::WriteLine("The Name Attribute for the {0} member is: {1}.", - MyMemberInfo[i]->ToString(), att->Name); - Console::WriteLine("The Level Attribute for the {0} member is: {1}.", - MyMemberInfo[i]->ToString(), att->Level); - Console::WriteLine("The Reviewed Attribute for the {0} member is: {1}.\n", - MyMemberInfo[i]->ToString(), att->Reviewed); - } - } - } - // -}; - -int main() -{ - MainApp::Main(); -} diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.events.other/cpp/example3.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.events.other/cpp/example3.cpp deleted file mode 100644 index 9aa573b40705b..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.events.other/cpp/example3.cpp +++ /dev/null @@ -1,82 +0,0 @@ -// -#using -#using - -using namespace System; -using namespace System::ComponentModel; -using namespace System::Windows::Forms; - -// -// The class SampleControl defines two event properties, MouseUp and MouseDown. -ref class SampleControl : Component -{ - // : - // Define other control methods and properties. - // : - - // Define the delegate collection. -protected: - EventHandlerList^ listEventDelegates; - -private: - // Define a unique key for each event. - static Object^ mouseDownEventKey = gcnew Object(); - static Object^ mouseUpEventKey = gcnew Object(); - - // Define the MouseDown event property. -public: - SampleControl() - { - listEventDelegates = gcnew EventHandlerList(); - } - - event MouseEventHandler^ MouseDown - { - // Add the input delegate to the collection. - void add(MouseEventHandler^ value) - { - listEventDelegates->AddHandler(mouseDownEventKey, value); - } - // Remove the input delegate from the collection. - void remove(MouseEventHandler^ value) - { - listEventDelegates->RemoveHandler(mouseDownEventKey, value); - } - // Raise the event with the delegate specified by mouseDownEventKey - void raise(Object^ sender, MouseEventArgs^ e) - { - MouseEventHandler^ mouseEventDelegate = - (MouseEventHandler^)listEventDelegates[mouseDownEventKey]; - mouseEventDelegate(sender, e); - } - } - - // Define the MouseUp event property. - event MouseEventHandler^ MouseUp - { - // Add the input delegate to the collection. - void add(MouseEventHandler^ value) - { - listEventDelegates->AddHandler(mouseUpEventKey, value); - } - // Remove the input delegate from the collection. - void remove(MouseEventHandler^ value) - { - listEventDelegates->RemoveHandler(mouseUpEventKey, value); - } - // Raise the event with the delegate specified by mouseUpEventKey - void raise(Object^ sender, MouseEventArgs^ e) - { - MouseEventHandler^ mouseEventDelegate = - (MouseEventHandler^)listEventDelegates[mouseUpEventKey]; - mouseEventDelegate(sender, e); - } - } -}; -// - -int main() -{ - return 0; -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source.cpp deleted file mode 100644 index 1a5ada217ce31..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// -using namespace System; - -namespace GenericsExample1 -{ - // - generic - public ref class SimpleGenericClass - { - public: - T Field; - }; - // - - public ref class GenericsTest - { - public: - // - static void Main() - { - SimpleGenericClass^ g = gcnew SimpleGenericClass(); - g->Field = "A string"; - //... - Console::WriteLine("SimpleGenericClass.Field = \"{0}\"", g->Field); - Console::WriteLine("SimpleGenericClass.Field.GetType() = {0}", g->Field->GetType()->FullName); - } - // - - // - generic - T MyGenericMethod(T arg) - { - T temp = arg; - //... - return temp; - } - // - - }; -} // GenericsExample1 - -namespace GenericsExample2 -{ - // - ref class A - { - generic - T G(T arg) - { - T temp = arg; - //... - return temp; - } - }; - generic - ref class MyGenericClass - { - T M(T arg) - { - T temp = arg; - //... - return temp; - } - }; - // -} // GenericsExample2 - -int main() -{ - GenericsExample1::GenericsTest::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source2.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source2.cpp deleted file mode 100644 index e7aeb263c0dcd..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.generics.overview/cpp/source2.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// -using namespace System; - -public ref class MyEventArgs : EventArgs -{ -private: - String^ msg; - -public: - MyEventArgs(String^ messageArg) - { - msg = messageArg; - } - - property String^ Message - { - String^ get() {return msg;} - } -}; - -ref class Dummy -{ -// -public: - event EventHandler^ MyEvent; -// - - static void Main() - { - Dummy^ dummo = gcnew Dummy(); - - dummo->DoEvent(); - } - - void DoEvent() - { - MyEventArgs^ eArgs = gcnew MyEventArgs("My Event Message"); - - MyEvent += gcnew EventHandler(this, &Dummy::MyEventHandler); - MyEvent(this, eArgs); - } - -private: - void MyEventHandler(Object^ sender, MyEventArgs^ eArgs) - { - Console::WriteLine(eArgs->Message); - } -}; - -int main() -{ - Dummy::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source10.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source10.cpp deleted file mode 100644 index da7c3e6bc61a0..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source10.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// -using namespace System; -using namespace System::IO::IsolatedStorage; - -ref class UserDomainAssembly_IsoStorage -{ -public: - static void Main() - { - SnippetA(); - SnippetB(); - } - - static void SnippetA() - { - // - IsolatedStorageFile^ isoFile = - IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Domain | - IsolatedStorageScope::Assembly, (Type^)nullptr, (Type^)nullptr); - // - } - - static void SnippetB() - { - // - IsolatedStorageFile^ isoFile = IsolatedStorageFile::GetUserStoreForDomain(); - // - } -}; - -int main() -{ - UserDomainAssembly_IsoStorage::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source11.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source11.cpp deleted file mode 100644 index f1903ecea2042..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source11.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// -using namespace System; -using namespace System::IO::IsolatedStorage; - -ref class UserDomainAssembly_IsoStorage -{ -public: - static void Main() - { - SnippetA(); - SnippetB(); - } - - static void SnippetA() - { - // - IsolatedStorageFile^ isoFile = - IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Assembly, (Type^)nullptr, (Type^)nullptr); - // - } - - static void SnippetB() - { - // - IsolatedStorageFile^ isoFile = IsolatedStorageFile::GetUserStoreForAssembly(); - // - } -}; - -int main() -{ - UserDomainAssembly_IsoStorage::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source3.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source3.cpp deleted file mode 100644 index 5ca7a24d44ca2..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source3.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// -using namespace System; -using namespace System::IO::IsolatedStorage; - -public ref class DeletingStores -{ -public: - static void Main() - { - // Get a new isolated store for this user, domain, and assembly. - // Put the store into an IsolatedStorageFile object. - - IsolatedStorageFile^ isoStore1 = IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Domain | IsolatedStorageScope::Assembly, (Type ^)nullptr, (Type ^)nullptr); - Console::WriteLine("A store isolated by user, assembly, and domain has been obtained."); - - // Get a new isolated store for user and assembly. - // Put that store into a different IsolatedStorageFile object. - - IsolatedStorageFile^ isoStore2 = IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Assembly, (Type ^)nullptr, (Type ^)nullptr); - Console::WriteLine("A store isolated by user and assembly has been obtained."); - - // The Remove method deletes a specific store, in this case the - // isoStore1 file. - - isoStore1->Remove(); - Console::WriteLine("The user, domain, and assembly isolated store has been deleted."); - - // This static method deletes all the isolated stores for this user. - - IsolatedStorageFile::Remove(IsolatedStorageScope::User); - Console::WriteLine("All isolated stores for this user have been deleted."); - } // End of Main. -}; - -int main() -{ - DeletingStores::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source4.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source4.cpp deleted file mode 100644 index 18724a3231b02..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source4.cpp +++ /dev/null @@ -1,75 +0,0 @@ -// -using namespace System; -using namespace System::IO::IsolatedStorage; -using namespace System::IO; - -public ref class DeletingFilesDirectories -{ -public: - static void Main() - { - // Get a new isolated store for this user domain and assembly. - // Put the store into an isolatedStorageFile object. - - IsolatedStorageFile^ isoStore = IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Domain | IsolatedStorageScope::Assembly, (Type ^)nullptr, (Type ^)nullptr); - - Console::WriteLine("Creating Directories:"); - - // This code creates several different directories. - - isoStore->CreateDirectory("TopLevelDirectory"); - Console::WriteLine("TopLevelDirectory"); - isoStore->CreateDirectory("TopLevelDirectory/SecondLevel"); - Console::WriteLine("TopLevelDirectory/SecondLevel"); - - // This code creates two new directories, one inside the other. - - isoStore->CreateDirectory("AnotherTopLevelDirectory/InsideDirectory"); - Console::WriteLine("AnotherTopLevelDirectory/InsideDirectory"); - Console::WriteLine(); - - // This code creates a few files and places them in the directories. - - Console::WriteLine("Creating Files:"); - - // This file is placed in the root. - - IsolatedStorageFileStream^ isoStream1 = gcnew IsolatedStorageFileStream("InTheRoot.txt", - FileMode::Create, isoStore); - Console::WriteLine("InTheRoot.txt"); - - isoStream1->Close(); - - // This file is placed in the InsideDirectory. - - IsolatedStorageFileStream^ isoStream2 = gcnew IsolatedStorageFileStream( - "AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt", FileMode::Create, isoStore); - Console::WriteLine("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt"); - Console::WriteLine(); - - isoStream2->Close(); - - Console::WriteLine("Deleting File:"); - - // This code deletes the HereIAm.txt file. - isoStore->DeleteFile("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt"); - Console::WriteLine("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt"); - Console::WriteLine(); - - Console::WriteLine("Deleting Directory:"); - - // This code deletes the InsideDirectory. - - isoStore->DeleteDirectory("AnotherTopLevelDirectory/InsideDirectory/"); - Console::WriteLine("AnotherTopLevelDirectory/InsideDirectory/"); - Console::WriteLine(); - - } // End of main. -}; - -int main() -{ - DeletingFilesDirectories::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source6.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source6.cpp deleted file mode 100644 index 1d914bb5a244a..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source6.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// -using namespace System; -using namespace System::IO::IsolatedStorage; - -public ref class ObtainingAStore -{ -public: - static void Main() - { - // Get a new isolated store for this assembly and put it into an - // isolated store object. - - IsolatedStorageFile^ isoStore = IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Assembly, (Type ^)nullptr, (Type ^)nullptr); - } -}; -// - -public ref class ObtainingAStoreWithDomain -{ -public: - static void Dummy() - { - // - IsolatedStorageFile^ isoStore = IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Assembly | IsolatedStorageScope::Domain, (Type ^)nullptr, (Type ^)nullptr); - // - } -}; - -int main() -{ - ObtainingAStore::Main(); -} \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source7.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source7.cpp deleted file mode 100644 index 1ce29517ff6ad..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source7.cpp +++ /dev/null @@ -1,31 +0,0 @@ -// -using namespace System; -using namespace System::IO; -using namespace System::IO::IsolatedStorage; - -public ref class CheckingSpace -{ -public: - static void Main() - { - // Get an isolated store for this assembly and put it into an - // IsolatedStoreFile object. - IsolatedStorageFile^ isoStore = IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Assembly, (Type ^)nullptr, (Type ^)nullptr); - - // Create a few placeholder files in the isolated store. - gcnew IsolatedStorageFileStream("InTheRoot.txt", FileMode::Create, isoStore); - gcnew IsolatedStorageFileStream("Another.txt", FileMode::Create, isoStore); - gcnew IsolatedStorageFileStream("AThird.txt", FileMode::Create, isoStore); - gcnew IsolatedStorageFileStream("AFourth.txt", FileMode::Create, isoStore); - gcnew IsolatedStorageFileStream("AFifth.txt", FileMode::Create, isoStore); - - Console::WriteLine(isoStore->AvailableFreeSpace + " bytes of space remain in this isolated store."); - } // End of Main. -}; - -int main() -{ - CheckingSpace::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source8.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source8.cpp deleted file mode 100644 index 123277a3d2d66..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source8.cpp +++ /dev/null @@ -1,111 +0,0 @@ -// -using namespace System; -using namespace System::IO; -using namespace System::IO::IsolatedStorage; -using namespace System::Collections; -using namespace System::Collections::Generic; - -public class FindingExistingFilesAndDirectories -{ -public: - // Retrieves an array of all directories in the store, and - // displays the results. - static void Main() - { - // This part of the code sets up a few directories and files in the - // store. - IsolatedStorageFile^ isoStore = IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Assembly, (Type ^)nullptr, (Type ^)nullptr); - isoStore->CreateDirectory("TopLevelDirectory"); - isoStore->CreateDirectory("TopLevelDirectory/SecondLevel"); - isoStore->CreateDirectory("AnotherTopLevelDirectory/InsideDirectory"); - gcnew IsolatedStorageFileStream("InTheRoot.txt", FileMode::Create, isoStore); - gcnew IsolatedStorageFileStream("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt", - FileMode::Create, isoStore); - // End of setup. - - Console::WriteLine('\r'); - Console::WriteLine("Here is a list of all directories in this isolated store:"); - - for each (String^ directory in GetAllDirectories("*", isoStore)) - { - Console::WriteLine(directory); - } - Console::WriteLine('\r'); - - // Retrieve all the files in the directory by calling the GetFiles - // method. - - Console::WriteLine("Here is a list of all the files in this isolated store:"); - for each (String^ file in GetAllFiles("*", isoStore)) - { - Console::WriteLine(file); - } - - } // End of Main. - - // Method to retrieve all directories, recursively, within a store. - static List^ GetAllDirectories(String^ pattern, IsolatedStorageFile^ storeFile) - { - // Get the root of the search string. - String^ root = Path::GetDirectoryName(pattern); - - if (root != "") - { - root += "/"; - } - - // Retrieve directories. - array^ directories = storeFile->GetDirectoryNames(pattern); - - List^ directoryList = gcnew List(directories); - - // Retrieve subdirectories of matches. - for (int i = 0, max = directories->Length; i < max; i++) - { - String^ directory = directoryList[i] + "/"; - List^ more = GetAllDirectories (root + directory + "*", storeFile); - - // For each subdirectory found, add in the base path. - for (int j = 0; j < more->Count; j++) - { - more[j] = directory + more[j]; - } - - // Insert the subdirectories into the list and - // update the counter and upper bound. - directoryList->InsertRange(i + 1, more); - i += more->Count; - max += more->Count; - } - - return directoryList; - } - - static List^ GetAllFiles(String^ pattern, IsolatedStorageFile^ storeFile) - { - // Get the root and file portions of the search string. - String^ fileString = Path::GetFileName(pattern); - array^ files = storeFile->GetFileNames(pattern); - - List^ fileList = gcnew List(files); - - // Loop through the subdirectories, collect matches, - // and make separators consistent. - for each (String^ directory in GetAllDirectories( "*", storeFile)) - { - for each (String^ file in storeFile->GetFileNames(directory + "/" + fileString)) - { - fileList->Add((directory + "/" + file)); - } - } - - return fileList; - } // End of GetFiles. -}; - -int main() -{ - FindingExistingFilesAndDirectories::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source9.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source9.cpp deleted file mode 100644 index 724509c93da07..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.isolatedstorage/cpp/source9.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// -using namespace System; -using namespace System::IO::IsolatedStorage; - -ref class RoamingIsoStorage -{ -public: - static void Main() - { - SnippetA(); - SnippetB(); - } - - static void SnippetA() - { - // - IsolatedStorageFile^ isoFile = - IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Assembly | - IsolatedStorageScope::Roaming, (Type^)nullptr, (Type^)nullptr); - // - } - - static void SnippetB() - { - // - IsolatedStorageFile^ isoFile = - IsolatedStorageFile::GetStore(IsolatedStorageScope::User | - IsolatedStorageScope::Assembly | IsolatedStorageScope::Domain | - IsolatedStorageScope::Roaming, (Type^)nullptr, (Type^)nullptr); - // - } -}; - -int main() -{ - RoamingIsoStorage::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp deleted file mode 100644 index 2980113db8397..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/compare.cpp +++ /dev/null @@ -1,100 +0,0 @@ -// -using namespace System; - -ref class Example -{ -public: - static void Main() - { - Compare(); - CompareOrdinal(); - CompareTo(); - Equals1(); - Equals2(); - StartsWith(); - EndsWith(); - IndexOf(); - LastIndexOf(); - } - - static void Compare() - { - // - String^ string1 = "Hello World!"; - Console::WriteLine(String::Compare(string1, "Hello World?")); - // - } - - static void CompareOrdinal() - { - // - String^ string1 = "Hello World!"; - Console::WriteLine(String::CompareOrdinal(string1, "hello world!")); - // - } - - static void CompareTo() - { - // - String^ string1 = "Hello World"; - String^ string2 = "Hello World!"; - int MyInt = string1->CompareTo(string2); - Console::WriteLine( MyInt ); - // - } - - static void Equals1() - { - // - String^ string1 = "Hello World"; - Console::WriteLine(string1->Equals("Hello World")); - // - } - - static void Equals2() - { - // - String^ string1 = "Hello World"; - String^ string2 = "Hello World"; - Console::WriteLine(String::Equals(string1, string2)); - // - } - - static void StartsWith() - { - // - String^ string1 = "Hello World"; - Console::WriteLine(string1->StartsWith("Hello")); - // - } - - static void EndsWith() - { - // - String^ string1 = "Hello World"; - Console::WriteLine(string1->EndsWith("Hello")); - // - } - - static void IndexOf() - { - // - String^ string1 = "Hello World"; - Console::WriteLine(string1->IndexOf('l')); - // - } - - static void LastIndexOf() - { - // - String^ string1 = "Hello World"; - Console::WriteLine(string1->LastIndexOf('l')); - // - } -}; - -int main() -{ - Example::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/padding.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/padding.cpp deleted file mode 100644 index f20861cfc52aa..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/padding.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// -using namespace System; - -ref class Example -{ -public: - static void Main() - { - PadLeft(); - PadRight(); - } - - static void PadLeft() - { - // - String^ MyString = "Hello World!"; - Console::WriteLine(MyString->PadLeft(20, '-')); - // - } - - static void PadRight() - { - // - String^ MyString = "Hello World!"; - Console::WriteLine(MyString->PadRight(20, '-')); - // - } -}; - -int main() -{ - Example::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/trimming.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/trimming.cpp deleted file mode 100644 index 8321ee1bbc166..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.basicops/cpp/trimming.cpp +++ /dev/null @@ -1,75 +0,0 @@ -// -using namespace System; - -ref class Example -{ -public: - static void Main() - { - Trim(); - TrimEnd1(); - TrimEnd2(); - TrimStart(); - Remove(); - } - - static void Trim() - { - // - String^ MyString = " Big "; - Console::WriteLine("Hello{0}World!", MyString); - String^ TrimString = MyString->Trim(); - Console::WriteLine("Hello{0}World!", TrimString); - // The example displays the following output: - // Hello Big World! - // HelloBigWorld! - // - } - - - static void TrimEnd1() - { - // - String^ MyString = "Hello World!"; - array^ MyChar = {'r','o','W','l','d','!',' '}; - String^ NewString = MyString->TrimEnd(MyChar); - Console::WriteLine(NewString); - // - } - - static void TrimEnd2() - { - // - String^ MyString = "Hello, World!"; - array^ MyChar = {'r','o','W','l','d','!',' '}; - String^ NewString = MyString->TrimEnd(MyChar); - Console::WriteLine(NewString); - // - } - - static void TrimStart() - { - // - String^ MyString = "Hello World!"; - array^ MyChar = {'e', 'H','l','o',' ' }; - String^ NewString = MyString->TrimStart(MyChar); - Console::WriteLine(NewString); - // - } - - static void Remove() - { - // - String^ MyString = "Hello Beautiful World!"; - Console::WriteLine(MyString->Remove(5,10)); - // The example displays the following output: - // Hello World! - // - } -}; - -int main() -{ - Example::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.parse/cpp/parse.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.parse/cpp/parse.cpp deleted file mode 100644 index 2504423a4ffa6..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.string.parse/cpp/parse.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// -using namespace System; - -ref class StringParseMethod -{ -public: - static void Main() - { - // - String^ MyString1 = "A"; - char MyChar = Char::Parse(MyString1); - // MyChar now contains a Unicode "A" character. - // - - // - String^ MyString2 = "True"; - bool MyBool = bool::Parse(MyString2); - // MyBool now contains a True Boolean value. - // - - // - String^ MyString3 = "Thursday"; - DayOfWeek MyDays = (DayOfWeek)Enum::Parse(DayOfWeek::typeid, MyString3); - Console::WriteLine(MyDays); - // The result is Thursday. - // - } -}; - -int main() -{ - StringParseMethod::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.dynamic/cpp/source1.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.dynamic/cpp/source1.cpp deleted file mode 100644 index c034cd8b06bce..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.dynamic/cpp/source1.cpp +++ /dev/null @@ -1,228 +0,0 @@ -// -// Code for building SimpleType.dll. -using namespace System; -using namespace System::Reflection; -using namespace System::Globalization; - -namespace Simple_Type -{ - public ref class MySimpleClass - { - public: - void MyMethod(String^ str, int i) - { - Console::WriteLine("MyMethod parameters: {0}, {1}", str, i); - } - - void MyMethod(String^ str, int i, int j) - { - Console::WriteLine("MyMethod parameters: {0}, {1}, {2}", - str, i, j); - } - }; -} - -using namespace Simple_Type; - -namespace Custom_Binder -{ - // **************************************************** - // A simple custom binder that provides no - // argument type conversion. - // **************************************************** - public ref class MyCustomBinder : Binder - { - public: - virtual MethodBase^ BindToMethod( - BindingFlags bindingAttr, - array^ match, - array^% args, - array^ modifiers, - CultureInfo^ culture, - array^ names, - Object^% state) override - { - if (match == nullptr) - { - throw gcnew ArgumentNullException("match"); - } - // Arguments are not being reordered. - state = nullptr; - // Find a parameter match and return the first method with - // parameters that match the request. - for each (MethodBase^ mb in match) - { - array^ parameters = mb->GetParameters(); - - if (ParametersMatch(parameters, args)) - { - return mb; - } - } - return nullptr; - } - - virtual FieldInfo^ BindToField(BindingFlags bindingAttr, - array^ match, Object^ value, CultureInfo^ culture) override - { - if (match == nullptr) - { - throw gcnew ArgumentNullException("match"); - } - for each (FieldInfo^ fi in match) - { - if (fi->GetType() == value->GetType()) - { - return fi; - } - } - return nullptr; - } - - virtual MethodBase^ SelectMethod( - BindingFlags bindingAttr, - array^ match, - array^ types, - array^ modifiers) override - { - if (match == nullptr) - { - throw gcnew ArgumentNullException("match"); - } - - // Find a parameter match and return the first method with - // parameters that match the request. - for each (MethodBase^ mb in match) - { - array^ parameters = mb->GetParameters(); - if (ParametersMatch(parameters, types)) - { - return mb; - } - } - - return nullptr; - } - - virtual PropertyInfo^ SelectProperty( - BindingFlags bindingAttr, - array^ match, - Type^ returnType, - array^ indexes, - array^ modifiers) override - { - if (match == nullptr) - { - throw gcnew ArgumentNullException("match"); - } - for each (PropertyInfo^ pi in match) - { - if (pi->GetType() == returnType && - ParametersMatch(pi->GetIndexParameters(), indexes)) - { - return pi; - } - } - return nullptr; - } - - virtual Object^ ChangeType( - Object^ value, - Type^ myChangeType, - CultureInfo^ culture) override - { - try - { - Object^ newType; - newType = Convert::ChangeType(value, myChangeType); - return newType; - } - // Throw an InvalidCastException if the conversion cannot - // be done by the Convert.ChangeType method. - catch (InvalidCastException^) - { - return nullptr; - } - } - - virtual void ReorderArgumentArray(array^% args, - Object^ state) override - { - // No operation is needed here because BindToMethod does not - // reorder the args array. The most common implementation - // of this method is shown below. - - // ((BinderState^)state).args.CopyTo(args, 0); - } - - // Returns true only if the type of each object in a matches - // the type of each corresponding object in b. - private: - bool ParametersMatch(array^ a, array^ b) - { - if (a->Length != b->Length) - { - return false; - } - for (int i = 0; i < a->Length; i++) - { - if (a[i]->ParameterType != b[i]->GetType()) - { - return false; - } - } - return true; - } - - // Returns true only if the type of each object in a matches - // the type of each corresponding entry in b. - bool ParametersMatch(array^ a, array^ b) - { - if (a->Length != b->Length) - { - return false; - } - for (int i = 0; i < a->Length; i++) - { - if (a[i]->ParameterType != b[i]) - { - return false; - } - } - return true; - } - }; - - public ref class MyMainClass - { - public: - static void Main() - { - // Get the type of MySimpleClass. - Type^ myType = MySimpleClass::typeid; - - // Get an instance of MySimpleClass. - MySimpleClass^ myInstance = gcnew MySimpleClass(); - MyCustomBinder^ myCustomBinder = gcnew MyCustomBinder(); - - // Get the method information for the particular overload - // being sought. - MethodInfo^ myMethod = myType->GetMethod("MyMethod", - BindingFlags::Public | BindingFlags::Instance, - myCustomBinder, gcnew array {String::typeid, - int::typeid}, nullptr); - Console::WriteLine(myMethod->ToString()); - - // Invoke the overload. - myType->InvokeMember("MyMethod", BindingFlags::InvokeMethod, - myCustomBinder, myInstance, - gcnew array {"Testing...", (int)32}); - } - }; -} - -int main() -{ - Custom_Binder::MyMainClass::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.dynamic/cpp/source2.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.dynamic/cpp/source2.cpp deleted file mode 100644 index 68984ed972afc..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.dynamic/cpp/source2.cpp +++ /dev/null @@ -1,218 +0,0 @@ -using namespace System; -using namespace System::Reflection; -using namespace System::Globalization; - -public ref class CustomBinder : Binder -{ -public: - virtual MethodBase^ BindToMethod( - BindingFlags bindingAttr, - array^ match, - array^% args, - array^ modifiers, - CultureInfo^ culture, - array^ names, - Object^% state) override - { - if (match == nullptr) - { - throw gcnew ArgumentNullException("match"); - } - // Arguments are not being reordered. - state = nullptr; - // Find a parameter match and return the first method with - // parameters that match the request. - for each (MethodBase^ mb in match) - { - array^ parameters = mb->GetParameters(); - - if (ParametersMatch(parameters, args)) - { - return mb; - } - } - return nullptr; - } - - virtual FieldInfo^ BindToField(BindingFlags bindingAttr, - array^ match, Object^ value, CultureInfo^ culture) override - { - if (match == nullptr) - { - throw gcnew ArgumentNullException("match"); - } - for each (FieldInfo^ fi in match) - { - if (fi->GetType() == value->GetType()) - { - return fi; - } - } - return nullptr; - } - - virtual MethodBase^ SelectMethod( - BindingFlags bindingAttr, - array^ match, - array^ types, - array^ modifiers) override - { - if (match == nullptr) - { - throw gcnew ArgumentNullException("match"); - } - - // Find a parameter match and return the first method with - // parameters that match the request. - for each (MethodBase^ mb in match) - { - array^ parameters = mb->GetParameters(); - if (ParametersMatch(parameters, types)) - { - return mb; - } - } - - return nullptr; - } - - virtual PropertyInfo^ SelectProperty( - BindingFlags bindingAttr, - array^ match, - Type^ returnType, - array^ indexes, - array^ modifiers) override - { - if (match == nullptr) - { - throw gcnew ArgumentNullException("match"); - } - for each (PropertyInfo^ pi in match) - { - if (pi->GetType() == returnType && - ParametersMatch(pi->GetIndexParameters(), indexes)) - { - return pi; - } - } - return nullptr; - } - - virtual Object^ ChangeType( - Object^ value, - Type^ myChangeType, - CultureInfo^ culture) override - { - try - { - Object^ newType; - newType = Convert::ChangeType(value, myChangeType); - return newType; - } - // Throw an InvalidCastException if the conversion cannot - // be done by the Convert.ChangeType method. - catch (InvalidCastException^) - { - return nullptr; - } - } - - virtual void ReorderArgumentArray(array^% args, - Object^ state) override - { - // No operation is needed here because BindToMethod does not - // reorder the args array. The most common implementation - // of this method is shown below. - - // ((BinderState^)state).args.CopyTo(args, 0); - } - - // Returns true only if the type of each object in a matches - // the type of each corresponding object in b. -private: - bool ParametersMatch(array^ a, array^ b) - { - if (a->Length != b->Length) - { - return false; - } - for (int i = 0; i < a->Length; i++) - { - if (a[i]->ParameterType != b[i]->GetType()) - { - return false; - } - } - return true; - } - - // Returns true only if the type of each object in a matches - // the type of each corresponding entry in b. - bool ParametersMatch(array^ a, array^ b) - { - if (a->Length != b->Length) - { - return false; - } - for (int i = 0; i < a->Length; i++) - { - if (a[i]->ParameterType != b[i]) - { - return false; - } - } - return true; - } -}; - -// -public ref class CustomBinderDriver -{ -public: - static void Main() - { - Type^ t = CustomBinderDriver::typeid; - CustomBinder^ binder = gcnew CustomBinder(); - BindingFlags flags = BindingFlags::InvokeMethod | BindingFlags::Instance | - BindingFlags::Public | BindingFlags::Static; - array^ args; - - // Case 1. Neither argument coercion nor member selection is needed. - args = gcnew array {}; - t->InvokeMember("PrintBob", flags, binder, nullptr, args); - - // Case 2. Only member selection is needed. - args = gcnew array {42}; - t->InvokeMember("PrintValue", flags, binder, nullptr, args); - - // Case 3. Only argument coercion is needed. - args = gcnew array {"5.5"}; - t->InvokeMember("PrintNumber", flags, binder, nullptr, args); - } - - static void PrintBob() - { - Console::WriteLine("PrintBob"); - } - - static void PrintValue(long value) - { - Console::WriteLine("PrintValue({0})", value); - } - - static void PrintValue(String^ value) - { - Console::WriteLine("PrintValue\"{0}\")", value); - } - - static void PrintNumber(double value) - { - Console::WriteLine("PrintNumber ({0})", value); - } -}; - -int main() -{ - CustomBinderDriver::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source1.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source1.cpp deleted file mode 100644 index af03cf9750c8a..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source1.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// -// This program lists all the public constructors -// of the System.String class. -using namespace System; -using namespace System::Reflection; - -class ListMembers -{ -public: - static void Main() - { - Type^ t = System::String::typeid; - Console::WriteLine ("Listing all the public constructors of the {0} type", t); - // Constructors. - array^ ci = t->GetConstructors(BindingFlags::Public | BindingFlags::Instance); - Console::WriteLine ("//Constructors"); - PrintMembers(ci); - } - - static void PrintMembers(array^ ms) - { - for each (MemberInfo^ m in ms) - { - Console::WriteLine ("{0}{1}", " ", m); - } - Console::WriteLine(); - } -}; - -int main() -{ - ListMembers::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source2.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source2.cpp deleted file mode 100644 index a8d5ca8bf3a5d..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source2.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// -using namespace System; -using namespace System::IO; -using namespace System::Reflection; - -public ref class MyMemberInfo -{ -public: - static void Main() - { - Console::WriteLine ("\nReflection.MemberInfo"); - // Gets the Type and MemberInfo. - Type^ myType = Type::GetType("System.IO.File"); - array^ myMemberInfoArray = myType->GetMembers(); - // Gets and displays the DeclaringType method. - Console::WriteLine("\nThere are {0} members in {1}.", - myMemberInfoArray->Length, myType->FullName); - Console::WriteLine("{0}.", myType->FullName); - if (myType->IsPublic) - { - Console::WriteLine("{0} is public.", myType->FullName); - } - } -}; - -int main() -{ - MyMemberInfo::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source3.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source3.cpp deleted file mode 100644 index d1fbf3af7362d..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source3.cpp +++ /dev/null @@ -1,55 +0,0 @@ -// -// This code displays information about the GetValue method of FieldInfo. -using namespace System; -using namespace System::Reflection; - -public ref class MyMethodInfo -{ -public: - static int Main() - { - Console::WriteLine("Reflection.MethodInfo"); - // Gets and displays the Type. - Type^ myType = Type::GetType("System.Reflection.FieldInfo"); - // Specifies the member for which you want type information. - MethodInfo^ myMethodInfo = myType->GetMethod("GetValue"); - Console::WriteLine(myType->FullName + "." + myMethodInfo->Name); - // Gets and displays the MemberType property. - MemberTypes myMemberTypes = myMethodInfo->MemberType; - if (MemberTypes::Constructor == myMemberTypes) - { - Console::WriteLine("MemberType is of type All"); - } - else if (MemberTypes::Custom == myMemberTypes) - { - Console::WriteLine("MemberType is of type Custom"); - } - else if (MemberTypes::Event == myMemberTypes) - { - Console::WriteLine("MemberType is of type Event"); - } - else if (MemberTypes::Field == myMemberTypes) - { - Console::WriteLine("MemberType is of type Field"); - } - else if (MemberTypes::Method == myMemberTypes) - { - Console::WriteLine("MemberType is of type Method"); - } - else if (MemberTypes::Property == myMemberTypes) - { - Console::WriteLine("MemberType is of type Property"); - } - else if (MemberTypes::TypeInfo == myMemberTypes) - { - Console::WriteLine("MemberType is of type TypeInfo"); - } - return 0; - } -}; - -int main() -{ - MyMethodInfo::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source4.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source4.cpp deleted file mode 100644 index 06fffd85fe7fb..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source4.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// -// This program lists all the members of the -// System.IO.BufferedStream class. -using namespace System; -using namespace System::IO; -using namespace System::Reflection; - -public ref class ListMembers -{ -public: - static void Main() - { - // Specifies the class. - Type^ t = System::IO::BufferedStream::typeid; - Console::WriteLine("Listing all the members (public and non public) of the {0} type", t); - - // Lists static fields first. - array^ fi = t->GetFields(BindingFlags::Static | - BindingFlags::NonPublic | BindingFlags::Public); - Console::WriteLine("// Static Fields"); - PrintMembers(fi); - - // Static properties. - array^ pi = t->GetProperties(BindingFlags::Static | - BindingFlags::NonPublic | BindingFlags::Public); - Console::WriteLine("// Static Properties"); - PrintMembers(pi); - - // Static events. - array^ ei = t->GetEvents(BindingFlags::Static | - BindingFlags::NonPublic | BindingFlags::Public); - Console::WriteLine("// Static Events"); - PrintMembers(ei); - - // Static methods. - array^ mi = t->GetMethods (BindingFlags::Static | - BindingFlags::NonPublic | BindingFlags::Public); - Console::WriteLine("// Static Methods"); - PrintMembers(mi); - - // Constructors. - array^ ci = t->GetConstructors(BindingFlags::Instance | - BindingFlags::NonPublic | BindingFlags::Public); - Console::WriteLine("// Constructors"); - PrintMembers(ci); - - // Instance fields. - fi = t->GetFields(BindingFlags::Instance | BindingFlags::NonPublic | - BindingFlags::Public); - Console::WriteLine("// Instance Fields"); - PrintMembers(fi); - - // Instance properties. - pi = t->GetProperties(BindingFlags::Instance | BindingFlags::NonPublic | - BindingFlags::Public); - Console::WriteLine ("// Instance Properties"); - PrintMembers(pi); - - // Instance events. - ei = t->GetEvents(BindingFlags::Instance | BindingFlags::NonPublic | - BindingFlags::Public); - Console::WriteLine("// Instance Events"); - PrintMembers(ei); - - // Instance methods. - mi = t->GetMethods(BindingFlags::Instance | BindingFlags::NonPublic - | BindingFlags::Public); - Console::WriteLine("// Instance Methods"); - PrintMembers(mi); - - Console::WriteLine("\r\nPress ENTER to exit."); - Console::Read(); - } - - static void PrintMembers(array^ ms) - { - for each (MemberInfo^ m in ms) - { - Console::WriteLine ("{0}{1}", " ", m); - } - Console::WriteLine(); - } -}; - -int main() -{ - ListMembers::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source5.cpp b/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source5.cpp deleted file mode 100644 index b25f455197fe9..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/conceptual.types.viewinfo/cpp/source5.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// -// This program lists all the public constructors -// of the System.String class. -using namespace System; -using namespace System::Reflection; - -public ref class OtherSnippets -{ -public: - static void Main() - { - SnippetA(); - SnippetB(); - } - - static void SnippetA() - { - // - // Gets the mscorlib assembly in which the object is defined. - Assembly^ a = Object::typeid->Module->Assembly; - // - } - - static void SnippetB() - { - // - // Loads an assembly using its file name. - Assembly^ a = Assembly::LoadFrom("MyExe.exe"); - // Gets the type names from the assembly. - array^ types2 = a->GetTypes(); - for each (Type^ t in types2) - { - Console::WriteLine(t->FullName); - } - // - } -}; - -int main() -{ - OtherSnippets::Main(); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/dg_exceptionDesign/cpp/example2.cpp b/samples/snippets/cpp/VS_Snippets_CLR/dg_exceptionDesign/cpp/example2.cpp deleted file mode 100644 index 40c6a94186621..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/dg_exceptionDesign/cpp/example2.cpp +++ /dev/null @@ -1,40 +0,0 @@ -// -using namespace System; - -public ref class EmployeeListNotFoundException : Exception -{ -public: - EmployeeListNotFoundException() - { - } - - EmployeeListNotFoundException(String^ message) - : Exception(message) - { - } - - EmployeeListNotFoundException(String^ message, Exception^ inner) - : Exception(message, inner) - { - } -}; -// - -public ref class TestExample -{ -public: - static void Main() - { - EmployeeListNotFoundException ^e1, ^e2, ^e3; - Exception^ ex = gcnew Exception(); - - e1 = gcnew EmployeeListNotFoundException(); - e2 = gcnew EmployeeListNotFoundException("Hi!"); - e3 = gcnew EmployeeListNotFoundException("Hi!", ex); - } -}; - -int main() -{ - TestExample::Main(); -} \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_CLR/eventsoverview/cpp/programwithdata.cpp b/samples/snippets/cpp/VS_Snippets_CLR/eventsoverview/cpp/programwithdata.cpp deleted file mode 100644 index d1bc63b6472ec..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/eventsoverview/cpp/programwithdata.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// -using namespace System; - -public ref class ThresholdReachedEventArgs : public EventArgs -{ - public: - property int Threshold; - property DateTime TimeReached; -}; - -public ref class Counter -{ - private: - int threshold; - int total; - - public: - Counter() {}; - - Counter(int passedThreshold) - { - threshold = passedThreshold; - } - - void Add(int x) - { - total += x; - if (total >= threshold) { - ThresholdReachedEventArgs^ args = gcnew ThresholdReachedEventArgs(); - args->Threshold = threshold; - args->TimeReached = DateTime::Now; - OnThresholdReached(args); - } - } - - event EventHandler^ ThresholdReached; - - protected: - virtual void OnThresholdReached(ThresholdReachedEventArgs^ e) - { - ThresholdReached(this, e); - } -}; - -public ref class SampleHandler -{ - public: - static void c_ThresholdReached(Object^ sender, ThresholdReachedEventArgs^ e) - { - Console::WriteLine("The threshold of {0} was reached at {1}.", - e->Threshold, e->TimeReached); - Environment::Exit(0); - } -}; - -void main() -{ - Counter^ c = gcnew Counter((gcnew Random())->Next(10)); - c->ThresholdReached += gcnew EventHandler(SampleHandler::c_ThresholdReached); - - Console::WriteLine("press 'a' key to increase total"); - while (Console::ReadKey(true).KeyChar == 'a') { - Console::WriteLine("adding one"); - c->Add(1); - } -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/SpaceOrDigit1.cpp b/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/SpaceOrDigit1.cpp deleted file mode 100644 index 7376b4309d183..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/SpaceOrDigit1.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// -using namespace System; - -void main() -{ - Double value = .324; - Console::WriteLine("The value is: '{0,5:#.###}'", value); -} -// The example displays the following output if the current culture -// is en-US: -// The value is: ' .324' -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp b/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp deleted file mode 100644 index cb8f1953a8814..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp +++ /dev/null @@ -1,263 +0,0 @@ -using namespace System; -using namespace System::Globalization; - -void ShowZeroPlaceholder() -{ - // - double value; - - value = 123; - Console::WriteLine(value.ToString("00000")); - Console::WriteLine(String::Format("{0:00000}", value)); - // Displays 00123 - - value = 1.2; - Console::WriteLine(value.ToString("0.00", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:0.00}", value)); - // Displays 1.20 - - Console::WriteLine(value.ToString("00.00", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:00.00}", value)); - // Displays 01.20 - - CultureInfo^ daDK = CultureInfo::CreateSpecificCulture("da-DK"); - Console::WriteLine(value.ToString("00.00", daDK)); - Console::WriteLine(String::Format(daDK, "{0:00.00}", value)); - // Displays 01,20 - - value = .56; - Console::WriteLine(value.ToString("0.0", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:0.0}", value)); - // Displays 0.6 - - value = 1234567890; - Console::WriteLine(value.ToString("0,0", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:0,0}", value)); - // Displays 1,234,567,890 - - CultureInfo^ elGR = CultureInfo::CreateSpecificCulture("el-GR"); - Console::WriteLine(value.ToString("0,0", elGR)); - Console::WriteLine(String::Format(elGR, "{0:0,0}", value)); - // Displays 1.234.567.890 - - value = 1234567890.123456; - Console::WriteLine(value.ToString("0,0.0", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:0,0.0}", value)); - // Displays 1,234,567,890.1 - - value = 1234.567890; - Console::WriteLine(value.ToString("0,0.00", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:0,0.00}", value)); - // Displays 1,234.57 - // -} - -void ShowDigitPlaceholder() -{ - // - double value; - - value = 1.2; - Console::WriteLine(value.ToString("#.##", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:#.##}", value)); - // Displays 1.2 - - value = 123; - Console::WriteLine(value.ToString("#####")); - Console::WriteLine(String::Format("{0:#####}", value)); - // Displays 123 - - value = 123456; - Console::WriteLine(value.ToString("[##-##-##]")); - Console::WriteLine(String::Format("{0:[##-##-##]}", value)); - // Displays [12-34-56] - - value = 1234567890; - Console::WriteLine(value.ToString("#")); - Console::WriteLine(String::Format("{0:#}", value)); - // Displays 1234567890 - - Console::WriteLine(value.ToString("(###) ###-####")); - Console::WriteLine(String::Format("{0:(###) ###-####}", value)); - // Displays (123) 456-7890 - // -} - -void ShowDecimalPoint() -{ - // - double value; - - value = 1.2; - Console::WriteLine(value.ToString("0.00", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:0.00}", value)); - // Displays 1.20 - - Console::WriteLine(value.ToString("00.00", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:00.00}", value)); - // Displays 01.20 - - Console::WriteLine(value.ToString("00.00", - CultureInfo::CreateSpecificCulture("da-DK"))); - Console::WriteLine(String::Format(CultureInfo::CreateSpecificCulture("da-DK"), - "{0:00.00}", value)); - // Displays 01,20 - - value = .086; - Console::WriteLine(value.ToString("#0.##%", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:#0.##%}", value)); - // Displays 8.6% - - value = 86000; - Console::WriteLine(value.ToString("0.###E+0", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:0.###E+0}", value)); - // Displays 8.6E+4 - // -} - -void ShowThousandSpecifier() -{ - // - double value = 1234567890; - Console::WriteLine(value.ToString("#,#", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:#,#}", value)); - // Displays 1,234,567,890 - - Console::WriteLine(value.ToString("#,##0,,", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:#,##0,,}", value)); - // Displays 1,235 - // -} - -void ShowScalingSpecifier() -{ - // - double value = 1234567890; - Console::WriteLine(value.ToString("#,,", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:#,,}", value)); - // Displays 1235 - - Console::WriteLine(value.ToString("#,,,", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:#,,,}", value)); - // Displays 1 - - Console::WriteLine(value.ToString("#,##0,,", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:#,##0,,}", value)); - // Displays 1,235 - // -} - -void ShowPercentagePlaceholder() -{ - // - double value = .086; - Console::WriteLine(value.ToString("#0.##%", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:#0.##%}", value)); - // Displays 8.6% - // -} - -void ShowScientificNotation() -{ - // - double value = 86000; - Console::WriteLine(value.ToString("0.###E+0", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:0.###E+0}", value)); - // Displays 8.6E+4 - - Console::WriteLine(value.ToString("0.###E+000", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:0.###E+000}", value)); - // Displays 8.6E+004 - - Console::WriteLine(value.ToString("0.###E-000", CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:0.###E-000}", value)); - // Displays 8.6E004 - // -} - -void ShowSectionSpecifier() -{ - // - double posValue = 1234; - double negValue = -1234; - double zeroValue = 0; - - String^ fmt2 = "##;(##)"; - String^ fmt3 = "##;(##);**Zero**"; - - Console::WriteLine(posValue.ToString(fmt2)); - Console::WriteLine(String::Format("{0:" + fmt2 + "}", posValue)); - // Displays 1234 - - Console::WriteLine(negValue.ToString(fmt2)); - Console::WriteLine(String::Format("{0:" + fmt2 + "}", negValue)); - // Displays (1234) - - Console::WriteLine(zeroValue.ToString(fmt3)); - Console::WriteLine(String::Format("{0:" + fmt3 + "}", zeroValue)); - // Displays **Zero** - // -} - -void ShowPerMillePlaceholder() -{ - // - double value = .00354; - String^ perMilleFmt = "#0.## " + '\u2030'; - Console::WriteLine(value.ToString(perMilleFmt, CultureInfo::InvariantCulture)); - Console::WriteLine(String::Format(CultureInfo::InvariantCulture, - "{0:" + perMilleFmt + "}", value)); - // Displays 3.54‰ - // -} - -void main() -{ - Console::WriteLine("Zero Placeholder:"); - ShowZeroPlaceholder(); - Console::WriteLine(); - Console::WriteLine("Digit Placeholder:"); - ShowDigitPlaceholder(); - Console::WriteLine(); - Console::WriteLine("Decimal Point:"); - ShowDecimalPoint(); - Console::WriteLine(); - Console::WriteLine("Thousand Specifier:"); - ShowThousandSpecifier(); - Console::WriteLine(); - Console::WriteLine("Scaling Specifier:"); - ShowScalingSpecifier(); - Console::WriteLine(); - Console::WriteLine("Percentage Placeholder:"); - ShowPercentagePlaceholder(); - Console::WriteLine(); - Console::WriteLine("Scientific Notation:"); - ShowScientificNotation(); - Console::WriteLine(); - Console::WriteLine("Section Specifier:"); - ShowSectionSpecifier(); - Console::WriteLine(); - Console::WriteLine("Per Mille Placeholder:"); - ShowPerMillePlaceholder(); -} - diff --git a/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/escape1.cpp b/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/escape1.cpp deleted file mode 100644 index d8550cc863ea4..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/escape1.cpp +++ /dev/null @@ -1,27 +0,0 @@ -using namespace System; - -void main() -{ - // - int value = 123; - Console::WriteLine(value.ToString("\\#\\#\\# ##0 dollars and \\0\\0 cents \\#\\#\\#")); - Console::WriteLine(String::Format("{0:\\#\\#\\# ##0 dollars and \\0\\0 cents \\#\\#\\#}", - value)); - // Displays ### 123 dollars and 00 cents ### - - Console::WriteLine(value.ToString("\\#\\#\\# ##0 dollars and \0\0 cents \\#\\#\\#")); - Console::WriteLine(String::Format("{0:\\#\\#\\# ##0 dollars and \0\0 cents \\#\\#\\#}", - value)); - // Displays ### 123 dollars and 00 cents ### - - Console::WriteLine(value.ToString("\\\\\\\\\\\\ ##0 dollars and \\0\\0 cents \\\\\\\\\\\\")); - Console::WriteLine(String::Format("{0:\\\\\\\\\\\\ ##0 dollars and \\0\\0 cents \\\\\\\\\\\\}", - value)); - // Displays \\\ 123 dollars and 00 cents \\\ - - Console::WriteLine(value.ToString("\\\\\\ ##0 dollars and \0\0 cents \\\\\\")); - Console::WriteLine(String::Format("{0:\\\\\\ ##0 dollars and \0\0 cents \\\\\\}", - value)); - // Displays \\\ 123 dollars and 00 cents \\\ - // -} diff --git a/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/example1.cpp b/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/example1.cpp deleted file mode 100644 index bec4a5b670036..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/example1.cpp +++ /dev/null @@ -1,17 +0,0 @@ -using namespace System; - -void main() -{ - // - double number1 = 1234567890; - String^ value1 = number1.ToString("(###) ###-####"); - Console::WriteLine(value1); - - int number2 = 42; - String^ value2 = number2.ToString("My Number = #"); - Console::WriteLine(value2); - // The example displays the following output: - // (123) 456-7890 - // My Number = 42 - // -} diff --git a/samples/snippets/cpp/VS_Snippets_CLR_Classic/classic PrincipalPermission Example/CPP/source.cpp b/samples/snippets/cpp/VS_Snippets_CLR_Classic/classic PrincipalPermission Example/CPP/source.cpp deleted file mode 100644 index da729d96fce37..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR_Classic/classic PrincipalPermission Example/CPP/source.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// -using namespace System; -using namespace System::Security; -using namespace System::Security::Permissions; -using namespace System::Security::Policy; -using namespace System::Security::Principal; - -int main(array ^args) -{ - System::String^ null; - AppDomain::CurrentDomain->SetPrincipalPolicy(PrincipalPolicy::WindowsPrincipal); - PrincipalPermission^ principalPerm = gcnew PrincipalPermission(null, "Administrators" ); - principalPerm->Demand(); - Console::WriteLine("Demand succeeded"); - return 0; -} -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cpp/program.cpp b/samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cpp/program.cpp deleted file mode 100644 index 2aed9679b078a..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeClientStream_Sample/cpp/program.cpp +++ /dev/null @@ -1,51 +0,0 @@ -// -#using - -using namespace System; -using namespace System::IO; -using namespace System::IO::Pipes; - -ref class PipeClient -{ -public: - static void Main(array^ args) - { - if (args->Length > 1) - { - PipeStream^ pipeClient = gcnew AnonymousPipeClientStream(PipeDirection::In, args[1]); - - Console::WriteLine("[CLIENT] Current TransmissionMode: {0}.", - pipeClient->TransmissionMode); - - StreamReader^ sr = gcnew StreamReader(pipeClient); - - // Display the read text to the console - String^ temp; - - // Wait for 'sync message' from the server. - do - { - Console::WriteLine("[CLIENT] Wait for sync..."); - temp = sr->ReadLine(); - } - while (!temp->StartsWith("SYNC")); - - // Read the server data and echo to the console. - while ((temp = sr->ReadLine()) != nullptr) - { - Console::WriteLine("[CLIENT] Echo: " + temp); - } - sr->Close(); - pipeClient->Close(); - } - Console::Write("[CLIENT] Press Enter to continue..."); - Console::ReadLine(); - } -}; - -int main() -{ - array^ args = Environment::GetCommandLineArgs(); - PipeClient::Main(args); -} -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cpp/program.cpp b/samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cpp/program.cpp deleted file mode 100644 index 26174ff6fe949..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.AnonymousPipeServerStream_Sample/cpp/program.cpp +++ /dev/null @@ -1,65 +0,0 @@ -// -#using -#using - -using namespace System; -using namespace System::IO; -using namespace System::IO::Pipes; -using namespace System::Diagnostics; - -ref class PipeServer -{ -public: - static void Main() - { - Process^ pipeClient = gcnew Process(); - - pipeClient->StartInfo->FileName = "pipeClient.exe"; - - AnonymousPipeServerStream^ pipeServer = - gcnew AnonymousPipeServerStream(PipeDirection::Out, - HandleInheritability::Inheritable); - - Console::WriteLine("[SERVER] Current TransmissionMode: {0}.", - pipeServer->TransmissionMode); - - // Pass the client process a handle to the server. - pipeClient->StartInfo->Arguments = - pipeServer->GetClientHandleAsString(); - pipeClient->StartInfo->UseShellExecute = false; - pipeClient->Start(); - - pipeServer->DisposeLocalCopyOfClientHandle(); - - try - { - // Read user input and send that to the client process. - StreamWriter^ sw = gcnew StreamWriter(pipeServer); - - sw->AutoFlush = true; - // Send a 'sync message' and wait for client to receive it. - sw->WriteLine("SYNC"); - pipeServer->WaitForPipeDrain(); - // Send the console input to the client process. - Console::Write("[SERVER] Enter text: "); - sw->WriteLine(Console::ReadLine()); - sw->Close(); - } - // Catch the IOException that is raised if the pipe is broken - // or disconnected. - catch (IOException^ e) - { - Console::WriteLine("[SERVER] Error: {0}", e->Message); - } - pipeServer->Close(); - pipeClient->WaitForExit(); - pipeClient->Close(); - Console::WriteLine("[SERVER] Client quit. Server terminating."); - } -}; - -int main() -{ - PipeServer::Main(); -} -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_ImpersonationSample1/cpp/program.cpp b/samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_ImpersonationSample1/cpp/program.cpp deleted file mode 100644 index 8908a78121836..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR_System/system.IO.Pipes.NamedPipeServerStream_ImpersonationSample1/cpp/program.cpp +++ /dev/null @@ -1,160 +0,0 @@ -// -#using - -using namespace System; -using namespace System::IO; -using namespace System::IO::Pipes; -using namespace System::Text; -using namespace System::Threading; - -// Defines the data protocol for reading and writing strings on our stream -public ref class StreamString -{ -private: - Stream^ ioStream; - UnicodeEncoding^ streamEncoding; - -public: - StreamString(Stream^ ioStream) - { - this->ioStream = ioStream; - streamEncoding = gcnew UnicodeEncoding(); - } - - String^ ReadString() - { - int len; - - len = ioStream->ReadByte() * 256; - len += ioStream->ReadByte(); - array^ inBuffer = gcnew array(len); - ioStream->Read(inBuffer, 0, len); - - return streamEncoding->GetString(inBuffer); - } - - int WriteString(String^ outString) - { - array^ outBuffer = streamEncoding->GetBytes(outString); - int len = outBuffer->Length; - if (len > UInt16::MaxValue) - { - len = (int)UInt16::MaxValue; - } - ioStream->WriteByte((Byte)(len / 256)); - ioStream->WriteByte((Byte)(len & 255)); - ioStream->Write(outBuffer, 0, len); - ioStream->Flush(); - - return outBuffer->Length + 2; - } -}; - -// Contains the method executed in the context of the impersonated user -public ref class ReadFileToStream -{ -private: - String^ fn; - StreamString ^ss; - -public: - ReadFileToStream(StreamString^ str, String^ filename) - { - fn = filename; - ss = str; - } - - void Start() - { - String^ contents = File::ReadAllText(fn); - ss->WriteString(contents); - } -}; - -public ref class PipeServer -{ -private: - static int numThreads = 4; - -public: - static void Main() - { - int i; - array^ servers = gcnew array(numThreads); - - Console::WriteLine("\n*** Named pipe server stream with impersonation example ***\n"); - Console::WriteLine("Waiting for client connect...\n"); - for (i = 0; i < numThreads; i++) - { - servers[i] = gcnew Thread(gcnew ThreadStart(&ServerThread)); - servers[i]->Start(); - } - Thread::Sleep(250); - while (i > 0) - { - for (int j = 0; j < numThreads; j++) - { - if (servers[j] != nullptr) - { - if (servers[j]->Join(250)) - { - Console::WriteLine("Server thread[{0}] finished.", servers[j]->ManagedThreadId); - servers[j] = nullptr; - i--; // decrement the thread watch count - } - } - } - } - Console::WriteLine("\nServer threads exhausted, exiting."); - } - -private: - static void ServerThread() - { - NamedPipeServerStream^ pipeServer = - gcnew NamedPipeServerStream("testpipe", PipeDirection::InOut, numThreads); - - int threadId = Thread::CurrentThread->ManagedThreadId; - - // Wait for a client to connect - pipeServer->WaitForConnection(); - - Console::WriteLine("Client connected on thread[{0}].", threadId); - try - { - // - // Read the request from the client. Once the client has - // written to the pipe its security token will be available. - - StreamString^ ss = gcnew StreamString(pipeServer); - - // Verify our identity to the connected client using a - // string that the client anticipates. - - ss->WriteString("I am the one true server!"); - String^ filename = ss->ReadString(); - - // Read in the contents of the file while impersonating the client. - ReadFileToStream^ fileReader = gcnew ReadFileToStream(ss, filename); - - // Display the name of the user we are impersonating. - Console::WriteLine("Reading file: {0} on thread[{1}] as user: {2}.", - filename, threadId, pipeServer->GetImpersonationUserName()); - pipeServer->RunAsClient(gcnew PipeStreamImpersonationWorker(fileReader, &ReadFileToStream::Start)); - // - } - // Catch the IOException that is raised if the pipe is broken - // or disconnected. - catch (IOException^ e) - { - Console::WriteLine("ERROR: {0}", e->Message); - } - pipeServer->Close(); - } -}; - -int main() -{ - PipeServer::Main(); -} -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CPP/source.cpp b/samples/snippets/cpp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CPP/source.cpp deleted file mode 100644 index 3ded7b386b68d..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR_System/system.Security.Principal.WindowsBuiltInRole Example/CPP/source.cpp +++ /dev/null @@ -1,41 +0,0 @@ -using namespace System; -using namespace System::Threading; -using namespace System::Security::Permissions; -using namespace System::Security::Principal; - -class SecurityPrincipalDemo -{ - // -public: - static void DemonstrateWindowsBuiltInRoleEnum() - { - AppDomain^ myDomain = Thread::GetDomain(); - - myDomain->SetPrincipalPolicy( PrincipalPolicy::WindowsPrincipal ); - WindowsPrincipal^ myPrincipal = dynamic_cast(Thread::CurrentPrincipal); - - Console::WriteLine( "{0} belongs to: ", myPrincipal->Identity->Name ); - - Array^ wbirFields = Enum::GetValues( WindowsBuiltInRole::typeid ); - - for each ( Object^ roleName in wbirFields ) - { - try - { - Console::WriteLine( "{0}? {1}.", roleName, - myPrincipal->IsInRole( *dynamic_cast(roleName) ) ); - } - catch ( Exception^ ) - { - Console::WriteLine( "{0}: Could not obtain role for this RID.", - roleName ); - } - } - } - // -}; - -int main() -{ - SecurityPrincipalDemo::DemonstrateWindowsBuiltInRoleEnum(); -} diff --git a/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source2.cpp b/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source2.cpp deleted file mode 100644 index 15c4c583e888f..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source2.cpp +++ /dev/null @@ -1,78 +0,0 @@ -// -using namespace System; -using namespace System::Threading; - -public ref class ServerClass -{ -public: - // The method that will be called when the thread is started. - void InstanceMethod() - { - Console::WriteLine( - "ServerClass.InstanceMethod is running on another thread."); - - // Pause for a moment to provide a delay to make - // threads more apparent. - Thread::Sleep(3000); - Console::WriteLine( - "The instance method called by the worker thread has ended."); - } - - static void StaticMethod() - { - Console::WriteLine( - "ServerClass.StaticMethod is running on another thread."); - - // Pause for a moment to provide a delay to make - // threads more apparent. - Thread::Sleep(5000); - Console::WriteLine( - "The static method called by the worker thread has ended."); - } -}; - -public ref class Simple -{ -public: - static void Main() - { - ServerClass^ serverObject = gcnew ServerClass(); - - // Create the thread object, passing in the - // serverObject.InstanceMethod method using a - // ThreadStart delegate. - Thread^ InstanceCaller = gcnew Thread( - gcnew ThreadStart(serverObject, &ServerClass::InstanceMethod)); - - // Start the thread. - InstanceCaller->Start(); - - Console::WriteLine("The Main() thread calls this after " - + "starting the new InstanceCaller thread."); - - // Create the thread object, passing in the - // serverObject.StaticMethod method using a - // ThreadStart delegate. - Thread^ StaticCaller = gcnew Thread( - gcnew ThreadStart(&ServerClass::StaticMethod)); - - // Start the thread. - StaticCaller->Start(); - - Console::WriteLine("The Main() thread calls this after " - + "starting the new StaticCaller thread."); - } -}; - -int main() -{ - Simple::Main(); -} -// The example displays output like the following: -// The Main() thread calls this after starting the new InstanceCaller thread. -// The Main() thread calls this after starting the new StaticCaller thread. -// ServerClass.StaticMethod is running on another thread. -// ServerClass.InstanceMethod is running on another thread. -// The instance method called by the worker thread has ended. -// The static method called by the worker thread has ended. -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source3.cpp b/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source3.cpp deleted file mode 100644 index d9273607c7655..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source3.cpp +++ /dev/null @@ -1,61 +0,0 @@ -// -using namespace System; -using namespace System::Threading; - -// The ThreadWithState class contains the information needed for -// a task, and the method that executes the task. -// -public ref class ThreadWithState -{ -private: - // State information used in the task. - String^ boilerplate; - int numberValue; - - // The constructor obtains the state information. -public: - ThreadWithState(String^ text, int number) - { - boilerplate = text; - numberValue = number; - } - - // The thread procedure performs the task, such as formatting - // and printing a document. - void ThreadProc() - { - Console::WriteLine(boilerplate, numberValue); - } -}; - -// Entry point for the example. -// -public ref class Example -{ -public: - static void Main() - { - // Supply the state information required by the task. - ThreadWithState^ tws = gcnew ThreadWithState( - "This report displays the number {0}.", 42); - - // Create a thread to execute the task, and then - // start the thread. - Thread^ t = gcnew Thread(gcnew ThreadStart(tws, &ThreadWithState::ThreadProc)); - t->Start(); - Console::WriteLine("Main thread does some work, then waits."); - t->Join(); - Console::WriteLine( - "Independent task has completed; main thread ends."); - } -}; - -int main() -{ - Example::Main(); -} -// This example displays the following output: -// Main thread does some work, then waits. -// This report displays the number 42. -// Independent task has completed; main thread ends. -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source4.cpp b/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source4.cpp deleted file mode 100644 index 369a7b645889a..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.ThreadStart2/CPP/source4.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// -using namespace System; -using namespace System::Threading; - -// Delegate that defines the signature for the callback method. -// -public delegate void ExampleCallback(int lineCount); - -// The ThreadWithState class contains the information needed for -// a task, the method that executes the task, and a delegate -// to call when the task is complete. -// -public ref class ThreadWithState -{ -private: - // State information used in the task. - String^ boilerplate; - int numberValue; - - // Delegate used to execute the callback method when the - // task is complete. - ExampleCallback^ callback; - -public: - // The constructor obtains the state information and the - // callback delegate. - ThreadWithState(String^ text, int number, - ExampleCallback^ callbackDelegate) - { - boilerplate = text; - numberValue = number; - callback = callbackDelegate; - } - - // The thread procedure performs the task, such as - // formatting and printing a document, and then invokes - // the callback delegate with the number of lines printed. - void ThreadProc() - { - Console::WriteLine(boilerplate, numberValue); - if (callback != nullptr) - { - callback(1); - } - } -}; - -// Entry point for the example. -// -public ref class Example -{ -public: - static void Main() - { - // Supply the state information required by the task. - ThreadWithState^ tws = gcnew ThreadWithState( - "This report displays the number {0}.", - 42, - gcnew ExampleCallback(&Example::ResultCallback) - ); - - Thread^ t = gcnew Thread(gcnew ThreadStart(tws, &ThreadWithState::ThreadProc)); - t->Start(); - Console::WriteLine("Main thread does some work, then waits."); - t->Join(); - Console::WriteLine( - "Independent task has completed; main thread ends."); - } - - // The callback method must match the signature of the - // callback delegate. - // - static void ResultCallback(int lineCount) - { - Console::WriteLine( - "Independent task printed {0} lines.", lineCount); - } -}; - -int main() -{ - Example::Main(); -} -// The example displays the following output: -// Main thread does some work, then waits. -// This report displays the number 42. -// Independent task printed 1 lines. -// Independent task has completed; main thread ends. -// diff --git a/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.Timer/CPP/source2.cpp b/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.Timer/CPP/source2.cpp deleted file mode 100644 index 02f7a2b04a357..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_CLR_System/system.Threading.Timer/CPP/source2.cpp +++ /dev/null @@ -1,46 +0,0 @@ -// -using namespace System; -using namespace System::Threading; - -ref class TimerState -{ -public: - int counter; -}; - -ref class Example -{ -private: - static Timer^ timer; - -public: - static void TimerTask(Object^ state) - { - Console::WriteLine("{0:HH:mm:ss.fff}: starting a new callback.", DateTime::Now); - - TimerState^ timerState = dynamic_cast(state); - Interlocked::Increment(timerState->counter); - } - - static void Main() - { - TimerCallback^ tcb = gcnew TimerCallback(&TimerTask); - TimerState^ state = gcnew TimerState(); - state->counter = 0; - timer = gcnew Timer(tcb, state, 1000, 2000); - - while (state->counter <= 10) - { - Thread::Sleep(1000); - } - - timer->~Timer(); - Console::WriteLine("{0:HH:mm:ss.fff}: done.", DateTime::Now); - } -}; - -int main() -{ - Example::Main(); -} -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_Data/PsciSample/CPP/PsciSample.cpp b/samples/snippets/cpp/VS_Snippets_Data/PsciSample/CPP/PsciSample.cpp deleted file mode 100644 index 4cce2e29e1ff4..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/PsciSample/CPP/PsciSample.cpp +++ /dev/null @@ -1,58 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Xml; -using namespace System::Xml::Schema; - -ref class PsciSample -{ -private: - static void ValidationCallbackOne(Object^ sender, ValidationEventArgs^ args) - { - Console::WriteLine(args->Message); - } - -public: - static void Main() - { - XmlSchema^ schema = gcnew XmlSchema(); - - // Create an element of type integer and add it to the schema. - XmlSchemaElement^ priceElem = gcnew XmlSchemaElement(); - priceElem->Name = "Price"; - priceElem->SchemaTypeName = gcnew XmlQualifiedName("integer", "http://www.w3.org/2001/XMLSchema"); - schema->Items->Add(priceElem); - - // Print the pre-compilation value of the ElementSchemaType property - // of the XmlSchemaElement which is a PSCI property. - Console::WriteLine("Before compilation the ElementSchemaType of Price is " + priceElem->ElementSchemaType); - - //Compile the schema which validates the schema and - // if valid will place the PSCI values in certain properties. - XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet(); - ValidationEventHandler^ eventHandler = gcnew ValidationEventHandler(ValidationCallbackOne); - schemaSet->ValidationEventHandler += eventHandler; - schemaSet->Add(schema); - schemaSet->Compile(); - - for each (XmlSchema^ compiledSchema in schemaSet->Schemas()) - { - schema = compiledSchema; - } - - // After compilation of the schema, the ElementSchemaType property of the - // XmlSchemaElement will contain a reference to a valid object because the - // SchemaTypeName referred to a valid type. - Console::WriteLine("After compilation the ElementSchemaType of Price is " - + priceElem->ElementSchemaType); - - } -}; - -int main() -{ - PsciSample::Main(); - return 0; -} -// diff --git a/samples/snippets/cpp/VS_Snippets_Data/XPathNavigatorMethods/CPP/xpathnavigatormethods.cpp b/samples/snippets/cpp/VS_Snippets_Data/XPathNavigatorMethods/CPP/xpathnavigatormethods.cpp deleted file mode 100644 index beabf44763baa..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/XPathNavigatorMethods/CPP/xpathnavigatormethods.cpp +++ /dev/null @@ -1,1166 +0,0 @@ -#using -#using - -using namespace System; -using namespace System::IO; -using namespace System::Xml; -using namespace System::Xml::Schema; -using namespace System::Xml::XPath; -using namespace System::Collections; - -ref class XPathNavigatorMethods -{ -public: - - static String^ contosobooks = "C:\\Documents and Settings\\dylanm\\My Documents\\contosoBooks.xml"; - - static void XPathNavigatorMethods_AppendChild1() - { - // XPathNavigator->AppendChild() - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - XmlWriter^ pages = navigator->AppendChild(); - pages->WriteElementString("pages", "100"); - pages->Close(); - - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_AppendChild2() - { - // XPathNavigator->AppendChild(string) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - navigator->AppendChild("100"); - - Console::WriteLine(navigator->OuterXml); - // - } - - - static void XPathNavigatorMethods_AppendChild3() - { - // XPathNavigator->AppendChile(XmlReader^) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - XmlReader^ pages = XmlReader::Create(gcnew StringReader("100")); - - navigator->AppendChild(pages); - - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_AppendChild4() - { - // XPathNavigator->AppendChild(XPathNavigator^) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - XmlDocument^ childNodes = gcnew XmlDocument(); - childNodes->Load(gcnew StringReader("100")); - XPathNavigator^ childNodesNavigator = childNodes->CreateNavigator(); - - - if (childNodesNavigator->MoveToChild("pages", "http://www.contoso.com/books")) - { - navigator->AppendChild(childNodesNavigator); - } - - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_AppendChildElement() - { - // XPathNavigator->AppendChildElement(string, string, string, string) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - navigator->AppendChildElement(navigator->Prefix, "pages", navigator->LookupNamespace(navigator->Prefix), "100"); - - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_Clone() - { - // XPathNavigator->Clone() - - // - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - // Select all books authored by Melville. - XPathNodeIterator^ nodes = navigator->Select("descendant::book[author/last-name='Melville']"); - - while (nodes->MoveNext()) - { - // Clone the navigator returned by the Current property. - // Use the cloned navigator to get the title element. - XPathNavigator^ clone = nodes->Current->Clone(); - clone->MoveToFirstChild(); - Console::WriteLine("Book title: {0}", clone->Value); - } - // - } - - static void XPathNavigatorMethods_CreateAttribute() - { - // XPathNavigator->CreateAttribute(string, string, string, string) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - navigator->CreateAttribute("", "discount", "", "1.00"); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_CreateAttributes() - { - // XPathNavigator->CreateAttributes() - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - XmlWriter^ attributes = navigator->CreateAttributes(); - - attributes->WriteAttributeString("discount", "1.00"); - attributes->WriteAttributeString("currency", "USD"); - attributes->Close(); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_DeleteSelf() - { - // XPathNavigator->DeleteSelf() - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - navigator->DeleteSelf(); - - Console::WriteLine("Position after delete: {0}", navigator->Name); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_DeleteRange() - { - // XPathNavigator->DeleteRange() - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XmlNamespaceManager^ manager = gcnew XmlNamespaceManager(document->NameTable); - manager->AddNamespace("bk", "http://www.contoso.com/books"); - - XPathNavigator^ first = navigator->SelectSingleNode("/bk:bookstore/bk:book[1]", manager); - XPathNavigator^ last = navigator->SelectSingleNode("/bk:bookstore/bk:book[2]", manager); - - navigator->MoveTo(first); - navigator->DeleteRange(last); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_Evaluate1() - { - // XPathNavigator->Evaluate(string) - - // - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - Double total = (double)navigator->Evaluate("sum(descendant::book/price)"); - Console::WriteLine("Total price for all books: {0}", total.ToString()); - // - } - - static void XPathNavigatorMethods_Evaluate2() - { - // XPathNavigator->Evaluate(XPathExpression) - - // - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XPathExpression^ query = navigator->Compile("sum(descendant::book/price)"); - - Double total = (double)navigator->Evaluate(query); - Console::WriteLine("Total price for all books: {0}", total.ToString()); - // - } - - static void XPathNavigatorMethods_Evaluate3() - { - // XPathNavigator->Evaluate(string, IXmlNamespaceResolver) - - // - XPathDocument^ document = gcnew XPathDocument("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XmlNamespaceManager^ manager = gcnew XmlNamespaceManager(navigator->NameTable); - manager->AddNamespace("bk", "http://www.contoso.com/books"); - - Double total = (double)navigator->Evaluate("sum(descendant::bk:book/bk:price)", manager); - Console::WriteLine("Total price for all books: {0}", total.ToString()); - // - } - - static void XPathNavigatorMethods_Evaluate4() - { - // XPathNavigator->Evaluate(XPathExpression, XPathNodeIterator^) - - // - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XPathNodeIterator^ nodes = navigator->Select("//book"); - XPathExpression^ query = nodes->Current->Compile("sum(descendant::price)"); - - Double total = (double)navigator->Evaluate(query, nodes); - Console::WriteLine("Total price for all books: {0}", total.ToString()); - // - } - - static void XPathNavigatorMethods_InsertAfter1() - { - // XPathNavigator->InsertAfter() - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - XmlWriter^ pages = navigator->InsertAfter(); - pages->WriteElementString("pages", "100"); - pages->Close(); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_InsertAfter2() - { - // XPathNavigator->InsertAfter(string) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - navigator->InsertAfter("100"); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_InsertAfter3() - { - // XPathNavigator->InsertAfter(XmlReader^) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - XmlReader^ pages = XmlReader::Create(gcnew StringReader("100")); - - navigator->InsertAfter(pages); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_InsertAfter4() - { - // XPathNavigator->InsertAfter(XPathNavigator^) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - XmlDocument^ childNodes = gcnew XmlDocument(); - childNodes->Load(gcnew StringReader("100")); - XPathNavigator^ childNodesNavigator = childNodes->CreateNavigator(); - - navigator->InsertAfter(childNodesNavigator); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_InsertBefore1() - { - // XPathNavigator->InsertBefore() - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - XmlWriter^ pages = navigator->InsertBefore(); - pages->WriteElementString("pages", "100"); - pages->Close(); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_InsertBefore2() - { - // XPathNavigator->InsertBefore(string) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - navigator->InsertBefore("100"); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_InsertBefore3() - { - // XPathNavigator->InsertBefore(XmlReader^) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - XmlReader^ pages = XmlReader::Create(gcnew StringReader("100")); - - navigator->InsertBefore(pages); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_InsertBefore4() - { - // XPathNavigator->InsertBefore(XPathNavigator^) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - XmlDocument^ childNodes = gcnew XmlDocument(); - childNodes->Load(gcnew StringReader("100")); - XPathNavigator^ childNodesNavigator = childNodes->CreateNavigator(); - - navigator->InsertBefore(childNodesNavigator); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_InsertElementAfter() - { - // XPathNavigator->InsertElementAfter(string, string, string, string) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - navigator->InsertElementAfter(navigator->Prefix, "pages", navigator->LookupNamespace(navigator->Prefix), "100"); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_InsertElementBefore() - { - // XPathNavigator->InsertElementBefore(string, string, string, string) - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - navigator->InsertElementBefore(navigator->Prefix, "pages", navigator->LookupNamespace(navigator->Prefix), "100"); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_Matches() - { - // - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - // Select all book nodes. - XPathNodeIterator^ nodes = navigator->SelectDescendants("book", "", false); - - // Select all book nodes that have the matching attribute value. - XPathExpression^ expr = navigator->Compile("book[@genre='novel']"); - while (nodes->MoveNext()) - { - XPathNavigator^ navigator2 = nodes->Current->Clone(); - if (navigator2->Matches(expr)) - { - navigator2->MoveToFirstChild(); - Console::WriteLine("Book title: {0}", navigator2->Value); - } - } - // - } - - static void XPathNavigatorMethods_MoveToFollowing1() - { - // - XPathDocument^ document = gcnew XPathDocument("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToFollowing(XPathNodeType::Element); - - Console::WriteLine("Position: {0}", navigator->Name); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_MoveToFollowing2() - { - // - XPathDocument^ document = gcnew XPathDocument("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToFollowing("price", "http://www.contoso.com/books"); - - Console::WriteLine("Position: {0}", navigator->Name); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_MoveToFollowing3() - { - // - XPathDocument^ document = gcnew XPathDocument("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToFollowing("price", "http://www.contoso.com/books"); - XPathNavigator^ boundary = navigator->Clone(); - - navigator->MoveToRoot(); - - while (navigator->MoveToFollowing(XPathNodeType::Text, boundary)) - { - Console::WriteLine(navigator->OuterXml); - } - // - } - - static void XPathNavigatorMethods_MoveToFollowing4() - { - // - XPathDocument^ document = gcnew XPathDocument("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToFollowing("book", "http://www.contoso.com/books"); - XPathNavigator^ boundary = navigator->Clone(); - boundary->MoveToFollowing("first-name", "http://www.contoso.com/books"); - - navigator->MoveToFollowing("price", "http://www.contoso.com/books", boundary); - - Console::WriteLine("Position (after boundary): {0}", navigator->Name); - Console::WriteLine(navigator->OuterXml); - - navigator->MoveToFollowing("title", "http://www.contoso.com/books", boundary); - - Console::WriteLine("Position (before boundary): {0}", navigator->Name); - Console::WriteLine(navigator->OuterXml); - // - } - - // - static void XPathNavigatorMethods_MoveToNext() - { - - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - XPathNodeIterator^ nodeset = navigator->Select("descendant::book[author/last-name='Melville']"); - - while (nodeset->MoveNext()) - { - // Clone iterator here when working with it. - RecursiveWalk(nodeset->Current->Clone()); - } - } - - static void RecursiveWalk(XPathNavigator^ navigator) - { - switch (navigator->NodeType) - { - case XPathNodeType::Element: - if (navigator->Prefix == String::Empty) - Console::WriteLine("<{0}>", navigator->LocalName); - else - Console::Write("<{0}:{1}>", navigator->Prefix, navigator->LocalName); - Console::WriteLine("\t" + navigator->NamespaceURI); - break; - case XPathNodeType::Text: - Console::WriteLine("\t" + navigator->Value); - break; - } - - if (navigator->MoveToFirstChild()) - { - do - { - RecursiveWalk(navigator); - } while (navigator->MoveToNext()); - - navigator->MoveToParent(); - if (navigator->NodeType == XPathNodeType::Element) - Console::WriteLine("", navigator->Name); - } - else - { - if (navigator->NodeType == XPathNodeType::Element) - { - Console::WriteLine("", navigator->Name); - } - } - } - // - - static void XPathNavigatorMethods_PrependChild1() - { - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - XmlWriter^ pages = navigator->PrependChild(); - pages->WriteElementString("pages", "100"); - pages->Close(); - - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_PrependChild2() - { - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - navigator->PrependChild("100"); - - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_PrependChild3() - { - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - XmlReader^ pages = XmlReader::Create(gcnew StringReader("100")); - - navigator->PrependChild(pages); - - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_PrependChild4() - { - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - XmlDocument^ childNodes = gcnew XmlDocument(); - childNodes->Load(gcnew StringReader("100")); - XPathNavigator^ childNodesNavigator = childNodes->CreateNavigator(); - - navigator->PrependChild(childNodesNavigator); - - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_PrependChildElement() - { - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - navigator->PrependChildElement(navigator->Prefix, "pages", navigator->LookupNamespace(navigator->Prefix), "100"); - - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_ReadSubtree() - { - // - XPathDocument^ document = gcnew XPathDocument("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - XmlReader^ reader = navigator->ReadSubtree(); - - while (reader->Read()) - { - Console::WriteLine(reader->ReadInnerXml()); - } - - reader->Close(); - // - } - - static void XPathNavigatorMethods_ReplaceRange() - { - // XPathNavigator->ReplaceRange() - - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XmlNamespaceManager^ manager = gcnew XmlNamespaceManager(document->NameTable); - manager->AddNamespace("bk", "http://www.contoso.com/books"); - - XPathNavigator^ first = navigator->SelectSingleNode("/bk:bookstore/bk:book[1]", manager); - XPathNavigator^ last = navigator->SelectSingleNode("/bk:bookstore/bk:book[2]", manager); - - navigator->MoveTo(first); - XmlWriter^ newRange = navigator->ReplaceRange(last); - newRange->WriteStartElement("book"); - newRange->WriteAttributeString("genre", ""); - newRange->WriteAttributeString("publicationdate", "2005-04-07"); - newRange->WriteAttributeString("ISBN", "0"); - newRange->WriteStartElement("title"); - newRange->WriteString("New Book"); - newRange->WriteEndElement(); - newRange->WriteStartElement("author"); - newRange->WriteStartElement("first-name"); - newRange->WriteString("First Name"); - newRange->WriteEndElement(); - newRange->WriteStartElement("last-name"); - newRange->WriteString("Last Name"); - newRange->WriteEndElement(); - newRange->WriteEndElement(); - newRange->WriteElementString("price", "$0.00"); - newRange->WriteEndElement(); - newRange->Close(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_ReplaceSelf1() - { - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - navigator->ReplaceSelf("100"); - - Console::WriteLine("Position after delete: {0}", navigator->Name); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_ReplaceSelf2() - { - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - XmlReader^ pages = XmlReader::Create(gcnew StringReader("100")); - - navigator->ReplaceSelf(pages); - - Console::WriteLine("Position after delete: {0}", navigator->Name); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_ReplaceSelf3() - { - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - XmlDocument^ childNodes = gcnew XmlDocument(); - childNodes->Load(gcnew StringReader("100")); - XPathNavigator^ childNodesNavigator = childNodes->CreateNavigator(); - - navigator->ReplaceSelf(childNodesNavigator); - - Console::WriteLine("Position after delete: {0}", navigator->Name); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_Select1() - { - // - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XPathNodeIterator^ nodes = navigator->Select("/bookstore/book"); - nodes->MoveNext(); - XPathNavigator^ nodesNavigator = nodes->Current; - - XPathNodeIterator^ nodesText = nodesNavigator->SelectDescendants(XPathNodeType::Text, false); - - while (nodesText->MoveNext()) - Console::WriteLine(nodesText->Current->Value); - // - } - - static void XPathNavigatorMethods_Select2() - { - // - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XPathExpression^ query = navigator->Compile("/bookstore/book"); - XPathNodeIterator^ nodes = navigator->Select(query); - XPathNavigator^ nodesNavigator = nodes->Current; - - XPathNodeIterator^ nodesText = nodesNavigator->SelectDescendants(XPathNodeType::Text, false); - - while (nodesText->MoveNext()) - { - Console::WriteLine(nodesText->Current->Value); - } - // - } - - static void XPathNavigatorMethods_Select3() - { - // - XPathDocument^ document = gcnew XPathDocument("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XmlNamespaceManager^ manager = gcnew XmlNamespaceManager(navigator->NameTable); - manager->AddNamespace("bk", "http://www.contoso.com/books"); - - XPathNodeIterator^ nodes = navigator->Select("/bk:bookstore/bk:book/bk:price", manager); - // Move to the first node bk:price node. - if(nodes->MoveNext()) - { - // Now nodes.Current points to the first selected node. - XPathNavigator^ nodesNavigator = nodes->Current; - - // Select all the descendants of the current price node. - XPathNodeIterator^ nodesText = nodesNavigator->SelectDescendants(XPathNodeType::Text, false); - - while(nodesText->MoveNext()) - { - Console::WriteLine(nodesText->Current->Value); - } - } - // - } - - static void XPathNavigatorMethods_SelectAncestorsChildrenDescendants() - { - // - XPathDocument^ document = gcnew XPathDocument("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - // Select all the descendant nodes of the book node. - XPathNodeIterator^ bookDescendants = navigator->SelectDescendants("", "http://www.contoso.com/books", false); - - // Display the LocalName of each descendant node. - Console::WriteLine("Descendant nodes of the book node:"); - while (bookDescendants->MoveNext()) - { - Console::WriteLine(bookDescendants->Current->Name); - } - - // Select all the child nodes of the book node. - XPathNodeIterator^ bookChildren = navigator->SelectChildren("", "http://www.contoso.com/books"); - - // Display the LocalName of each child node. - Console::WriteLine("\nChild nodes of the book node:"); - while (bookChildren->MoveNext()) - { - Console::WriteLine(bookChildren->Current->Name); - } - - // Select all the ancestor nodes of the title node. - navigator->MoveToChild("title", "http://www.contoso.com/books"); - - XPathNodeIterator^ bookAncestors = navigator->SelectAncestors("", "http://www.contoso.com/books", false); - - // Display the LocalName of each ancestor node. - Console::WriteLine("\nAncestor nodes of the title node:"); - - while (bookAncestors->MoveNext()) - { - Console::WriteLine(bookAncestors->Current->Name); - } - // - } - - static void XPathNavigatorMethods_SelectSingleNode1() - { - // - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XPathNavigator^ node = navigator->SelectSingleNode("//title"); - Console::WriteLine(node->InnerXml); - // - } - - static void XPathNavigatorMethods_SelectSingleNode2() - { - // - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XPathExpression^ query = navigator->Compile("//title"); - - XPathNavigator^ node = navigator->SelectSingleNode(query); - Console::WriteLine(node->InnerXml); - // - } - - static void XPathNavigatorMethods_SelectSingleNode3() - { - // - XPathDocument^ document = gcnew XPathDocument("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XmlNamespaceManager^ manager = gcnew XmlNamespaceManager(navigator->NameTable); - manager->AddNamespace("bk", "http://www.contoso.com/books"); - - XPathNavigator^ node = navigator->SelectSingleNode("//bk:title", manager); - Console::WriteLine(node->InnerXml); - // - } - - static void XPathNavigatorMethods_SetTypedValue() - { - // - XmlReaderSettings^ settings = gcnew XmlReaderSettings(); - settings->Schemas->Add("http://www.contoso.com/books", "contosoBooks.xsd"); - settings->ValidationType = ValidationType::Schema; - - XmlReader^ reader = XmlReader::Create("contosoBooks.xml", settings); - XmlDocument^ document = gcnew XmlDocument(); - document->Load(reader); - - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - navigator->MoveToChild("price", "http://www.contoso.com/books"); - - Decimal^ price = gcnew Decimal(19.99); - navigator->SetTypedValue(price); - - navigator->MoveToParent(); - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_SetValue() - { - // - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - XmlNamespaceManager^ manager = gcnew XmlNamespaceManager(navigator->NameTable); - manager->AddNamespace("bk", "http://www.contoso.com/books"); - - for each (XPathNavigator^ nav in navigator->Select("//bk:price", manager)) - { - if(nav->Value == "11.99") - { - nav->SetValue("12.99"); - } - } - - Console::WriteLine(navigator->OuterXml); - // - } - - static void XPathNavigatorMethods_WriteSubtree() - { - // - XPathDocument^ document = gcnew XPathDocument("contosoBooks.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - navigator->MoveToChild("bookstore", "http://www.contoso.com/books"); - navigator->MoveToChild("book", "http://www.contoso.com/books"); - - XmlWriter^ writer = XmlWriter::Create("contosoBook.xml"); - navigator->WriteSubtree(writer); - - writer->Close(); - // - } - - static void XPathNavigatorMethods_MoveToNextAttribute() - { - // - XPathDocument^ document = gcnew XPathDocument("books.xml"); - XPathNavigator^ navigator = document->CreateNavigator(); - - // Select all book nodes and display all attributes on each book. - XPathNodeIterator^ nodes = navigator->SelectDescendants("book", "", false); - while (nodes->MoveNext()) - { - XPathNavigator^ navigator2 = nodes->Current->Clone(); - navigator2->MoveToFirstAttribute(); - Console::WriteLine("{0} = {1}", navigator2->Name, navigator2->Value); - - while (navigator2->MoveToNextAttribute()) - { - Console::WriteLine("{0} = {1}", navigator2->Name, navigator2->Value); - } - - Console::WriteLine(); - } - // - } - - static void XPathNavigatorMethods_BasicMoveTos() - { - // - // Load the XML document. - XmlDocument^ document = gcnew XmlDocument(); - document->Load("contosoBooks.xml"); - - // Create the XPathNavigator. - XPathNavigator^ navigator = document->CreateNavigator(); - - // Create an XmlNamespaceManager used to handle namespaces - // found in the XML document. - XmlNamespaceManager^ manager = gcnew XmlNamespaceManager(document->NameTable); - manager->AddNamespace("bk", "http://www.contoso.com/books"); - - // Move to the last book node using the SelectSingleNode method. - navigator = navigator->SelectSingleNode("//bk:book[last()]", manager); - Console::WriteLine("Last book node: \n===============\n{0}", navigator->OuterXml); - - // Move to the previous book node and write it to the console - // if the move was successful. - if (navigator->MoveToPrevious()) - { - Console::WriteLine("\nSecond book node: \n=================\n{0}", - navigator->OuterXml); - } - - // Move to the first book node and write it to the console - // if the move was successful. - if (navigator->MoveToFirst()) - { - Console::WriteLine("\nFirst book node: \n================\n{0}", - navigator->OuterXml); - } - - // Move to the parent bookstore node and write it to the console - // if the move was successful. - if (navigator->MoveToParent()) - { - Console::WriteLine("\nParent bookstore node: \n======================\n{0}", - navigator->OuterXml); - } - - // Move to the first child node of the bookstore node and write - // it to the console if the move was successful. - if (navigator->MoveToFirstChild()) - { - Console::WriteLine("\nFirst book node: \n================\n{0}", - navigator->OuterXml); - } - - // Move to the root node and write it to the console. - navigator->MoveToRoot(); - Console::WriteLine("\nRoot node: \n==========\n{0}", - navigator->OuterXml); - // - } - static void XPathNavigatorMethods_TwoWaysToIterateOverXPathNavigator() - { - XPathDocument^ doc = gcnew XPathDocument(gcnew StringReader("")); - XPathNavigator^ nav = doc->CreateNavigator(); - XPathNodeIterator^ nodeIterator = nav->SelectDescendants("", "", false); - - // - while (nodeIterator->MoveNext()) - { - XPathNavigator^ n = nodeIterator->Current; - Console::WriteLine(n->LocalName); - } - // - - // - for each (XPathNavigator^ n in nodeIterator) - Console::WriteLine(n->LocalName); - // - } - - -}; - -int main() -{ - return 0; -}; \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_Data/XmlDocumentValidation.Load/CPP/XmlDocumentValidationExample.cpp b/samples/snippets/cpp/VS_Snippets_Data/XmlDocumentValidation.Load/CPP/XmlDocumentValidationExample.cpp deleted file mode 100644 index 11d2d38669223..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/XmlDocumentValidation.Load/CPP/XmlDocumentValidationExample.cpp +++ /dev/null @@ -1,95 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Xml; -using namespace System::Xml::Schema; - -ref class XmlDocumentValidationExample -{ -public: - - static void Main() - { - try - { - // Create a schema validating XmlReader. - XmlReaderSettings^ settings = gcnew XmlReaderSettings(); - settings->Schemas->Add("http://www.contoso.com/books", "contosoBooks.xsd"); - ValidationEventHandler^ eventHandler = gcnew ValidationEventHandler(ValidationEventHandlerOne); - settings->ValidationEventHandler += eventHandler; - settings->ValidationFlags = settings->ValidationFlags | XmlSchemaValidationFlags::ReportValidationWarnings; - settings->ValidationType = ValidationType::Schema; - - XmlReader^ reader = XmlReader::Create("contosoBooks.xml", settings); - - // The XmlDocument validates the XML document contained - // in the XmlReader as it is loaded into the DOM. - XmlDocument^ document = gcnew XmlDocument(); - document->Load(reader); - - // Make an invalid change to the first and last - // price elements in the XML document, and write - // the XmlSchemaInfo values assigned to the price - // element during load validation to the console. - XmlNamespaceManager^ manager = gcnew XmlNamespaceManager(document->NameTable); - manager->AddNamespace("bk", "http://www.contoso.com/books"); - - XmlNode^ priceNode = document->SelectSingleNode("/bk:bookstore/bk:book/bk:price", manager); - - Console::WriteLine("SchemaInfo.IsDefault: {0}", priceNode->SchemaInfo->IsDefault); - Console::WriteLine("SchemaInfo.IsNil: {0}", priceNode->SchemaInfo->IsNil); - Console::WriteLine("SchemaInfo.SchemaElement: {0}", priceNode->SchemaInfo->SchemaElement); - Console::WriteLine("SchemaInfo.SchemaType: {0}", priceNode->SchemaInfo->SchemaType); - Console::WriteLine("SchemaInfo.Validity: {0}", priceNode->SchemaInfo->Validity); - - priceNode->InnerXml = "A"; - - XmlNodeList^ priceNodes = document->SelectNodes("/bk:bookstore/bk:book/bk:price", manager); - XmlNode^ lastprice = priceNodes[priceNodes->Count - 1]; - - lastprice->InnerXml = "B"; - - // Validate the XML document with the invalid changes. - // The invalid changes cause schema validation errors. - document->Validate(eventHandler); - - // Correct the invalid change to the first price element. - priceNode->InnerXml = "8.99"; - - // Validate only the first book element. The last book - // element is invalid, but not included in validation. - XmlNode^ bookNode = document->SelectSingleNode("/bk:bookstore/bk:book", manager); - document->Validate(eventHandler, bookNode); - } - catch (XmlException^ ex) - { - Console::WriteLine("XmlDocumentValidationExample.XmlException: {0}", ex->Message); - } - catch(XmlSchemaValidationException^ ex) - { - Console::WriteLine("XmlDocumentValidationExample.XmlSchemaValidationException: {0}", ex->Message); - } - catch (Exception^ ex) - { - Console::WriteLine("XmlDocumentValidationExample.Exception: {0}", ex->Message); - } - } - - static void ValidationEventHandlerOne(Object^ sender, ValidationEventArgs^ args) - { - if (args->Severity == XmlSeverityType::Warning) - Console::Write("\nWARNING: "); - else if (args->Severity == XmlSeverityType::Error) - Console::Write("\nERROR: "); - - Console::WriteLine(args->Message); - } -}; - -int main() -{ - XmlDocumentValidationExample::Main(); - return 0; -} -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaCreateExample/CPP/XmlSchemaCreateExample.cpp b/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaCreateExample/CPP/XmlSchemaCreateExample.cpp deleted file mode 100644 index 2e7060f1c2cda..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaCreateExample/CPP/XmlSchemaCreateExample.cpp +++ /dev/null @@ -1,111 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Xml; -using namespace System::Xml::Schema; - -ref class XmlSchemaCreateExample -{ -public: - - static void Main() - { - // - // Create the FirstName and LastName elements. - XmlSchemaElement^ firstNameElement = gcnew XmlSchemaElement(); - firstNameElement->Name = "FirstName"; - XmlSchemaElement^ lastNameElement = gcnew XmlSchemaElement(); - lastNameElement->Name = "LastName"; - - // Create CustomerId attribute. - XmlSchemaAttribute^ idAttribute = gcnew XmlSchemaAttribute(); - idAttribute->Name = "CustomerId"; - idAttribute->Use = XmlSchemaUse::Required; - // - - // - // Create the simple type for the LastName element. - XmlSchemaSimpleType^ lastNameType = gcnew XmlSchemaSimpleType(); - lastNameType->Name = "LastNameType"; - XmlSchemaSimpleTypeRestriction^ lastNameRestriction = - gcnew XmlSchemaSimpleTypeRestriction(); - lastNameRestriction->BaseTypeName = - gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); - XmlSchemaMaxLengthFacet^ maxLength = gcnew XmlSchemaMaxLengthFacet(); - maxLength->Value = "20"; - lastNameRestriction->Facets->Add(maxLength); - lastNameType->Content = lastNameRestriction; - - // Associate the elements and attributes with their types. - // Built-in type. - firstNameElement->SchemaTypeName = - gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); - // User-defined type. - lastNameElement->SchemaTypeName = - gcnew XmlQualifiedName("LastNameType", "http://www.tempuri.org"); - // Built-in type. - idAttribute->SchemaTypeName = gcnew XmlQualifiedName("positiveInteger", - "http://www.w3.org/2001/XMLSchema"); - - // Create the top-level Customer element. - XmlSchemaElement^ customerElement = gcnew XmlSchemaElement(); - customerElement->Name = "Customer"; - - // Create an anonymous complex type for the Customer element. - XmlSchemaComplexType^ customerType = gcnew XmlSchemaComplexType(); - XmlSchemaSequence^ sequence = gcnew XmlSchemaSequence(); - sequence->Items->Add(firstNameElement); - sequence->Items->Add(lastNameElement); - customerType->Particle = sequence; - - // Add the CustomerId attribute to the complex type. - customerType->Attributes->Add(idAttribute); - - // Set the SchemaType of the Customer element to - // the anonymous complex type created above. - customerElement->SchemaType = customerType; - // - - // - // Create an empty schema. - XmlSchema^ customerSchema = gcnew XmlSchema(); - customerSchema->TargetNamespace = "http://www.tempuri.org"; - - // Add all top-level element and types to the schema - customerSchema->Items->Add(customerElement); - customerSchema->Items->Add(lastNameType); - - // Create an XmlSchemaSet to compile the customer schema. - XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet(); - schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback); - schemaSet->Add(customerSchema); - schemaSet->Compile(); - - for each (XmlSchema^ schema in schemaSet->Schemas()) - { - customerSchema = schema; - } - - // Write the complete schema to the Console. - customerSchema->Write(Console::Out); - // - } - - static void ValidationCallback(Object^ sender, ValidationEventArgs^ args) - { - if (args->Severity == XmlSeverityType::Warning) - Console::Write("WARNING: "); - else if (args->Severity == XmlSeverityType::Error) - Console::Write("ERROR: "); - - Console::WriteLine(args->Message); - } -}; - -int main() -{ - XmlSchemaCreateExample::Main(); - return 0; -} -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaEditExample1/CPP/XmlSchemaEditExample1.cpp b/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaEditExample1/CPP/XmlSchemaEditExample1.cpp deleted file mode 100644 index d0104c8216a76..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaEditExample1/CPP/XmlSchemaEditExample1.cpp +++ /dev/null @@ -1,91 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Xml; -using namespace System::Xml::Schema; - -ref class XmlSchemaEditExample -{ -public: - - static void Main() - { - // Add the customer schema to a new XmlSchemaSet and compile it. - // Any schema validation warnings and errors encountered reading or - // compiling the schema are handled by the ValidationEventHandler delegate. - XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet(); - schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback); - schemaSet->Add("http://www.tempuri.org", "customer.xsd"); - schemaSet->Compile(); - - // Retrieve the compiled XmlSchema object from the XmlSchemaSet - // by iterating over the Schemas property. - XmlSchema^ customerSchema = nullptr; - for each (XmlSchema^ schema in schemaSet->Schemas()) - { - customerSchema = schema; - } - - // Create the PhoneNumber element. - XmlSchemaElement^ phoneElement = gcnew XmlSchemaElement(); - phoneElement->Name = "PhoneNumber"; - - // Create the xs:string simple type restriction. - XmlSchemaSimpleType^ phoneType = gcnew XmlSchemaSimpleType(); - XmlSchemaSimpleTypeRestriction^ restriction = - gcnew XmlSchemaSimpleTypeRestriction(); - restriction->BaseTypeName = gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); - - // Add a pattern facet to the restriction. - XmlSchemaPatternFacet^ phonePattern = gcnew XmlSchemaPatternFacet(); - phonePattern->Value = "\\d{3}-\\d{3}-\\d(4)"; - restriction->Facets->Add(phonePattern); - - // Add the restriction to the Content property of the simple type - // and the simple type to the SchemaType of the PhoneNumber element. - phoneType->Content = restriction; - phoneElement->SchemaType = phoneType; - - // Iterate over each XmlSchemaElement in the Values collection - // of the Elements property. - for each (XmlSchemaElement^ element in customerSchema->Elements->Values) - { - // If the qualified name of the element is "Customer", - // get the complex type of the Customer element - // and the sequence particle of the complex type. - if (element->QualifiedName->Name->Equals("Customer")) - { - XmlSchemaComplexType^ customerType = - dynamic_cast(element->ElementSchemaType); - XmlSchemaSequence^ sequence = - dynamic_cast(customerType->Particle); - - // Add the new PhoneNumber element to the sequence. - sequence->Items->Add(phoneElement); - } - } - - // Reprocess and compile the modified XmlSchema object and write it to the console. - schemaSet->Reprocess(customerSchema); - schemaSet->Compile(); - customerSchema->Write(Console::Out); - } - - static void ValidationCallback(Object^ sender, ValidationEventArgs^ args) - { - if (args->Severity == XmlSeverityType::Warning) - Console::Write("WARNING: "); - else if (args->Severity == XmlSeverityType::Error) - Console::Write("ERROR: "); - - Console::WriteLine(args->Message); - } -}; - -int main() -{ - XmlSchemaEditExample::Main(); - return 0; -} -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaEditExample2/CPP/XmlSchemaEditExample2.cpp b/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaEditExample2/CPP/XmlSchemaEditExample2.cpp deleted file mode 100644 index 79a6e45873d1e..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaEditExample2/CPP/XmlSchemaEditExample2.cpp +++ /dev/null @@ -1,122 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Xml; -using namespace System::Xml::Schema; - -ref class XmlSchemaEditExample -{ -public: - - static void Main() - { - // Add the customer schema to a new XmlSchemaSet and compile it. - // Any schema validation warnings and errors encountered reading or - // compiling the schema are handled by the ValidationEventHandler delegate. - XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet(); - schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback); - schemaSet->Add("http://www.tempuri.org", "customer.xsd"); - schemaSet->Compile(); - - // Retrieve the compiled XmlSchema object from the XmlSchemaSet - // by iterating over the Schemas property. - XmlSchema^ customerSchema = nullptr; - for each (XmlSchema^ schema in schemaSet->Schemas()) - { - customerSchema = schema; - } - - // Create a complex type for the FirstName element. - XmlSchemaComplexType^ complexType = gcnew XmlSchemaComplexType(); - complexType->Name = "FirstNameComplexType"; - - // Create a simple content extension with a base type of xs:string. - XmlSchemaSimpleContent^ simpleContent = gcnew XmlSchemaSimpleContent(); - XmlSchemaSimpleContentExtension^ simpleContentExtension = - gcnew XmlSchemaSimpleContentExtension(); - simpleContentExtension->BaseTypeName = - gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); - - // Create the new Title attribute with a SchemaTypeName of xs:string - // and add it to the simple content extension. - XmlSchemaAttribute^ attribute = gcnew XmlSchemaAttribute(); - attribute->Name = "Title"; - attribute->SchemaTypeName = - gcnew XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); - simpleContentExtension->Attributes->Add(attribute); - - // Set the content model of the simple content to the simple content extension - // and the content model of the complex type to the simple content. - simpleContent->Content = simpleContentExtension; - complexType->ContentModel = simpleContent; - - // Add the new complex type to the pre-schema-compilation Items collection. - customerSchema->Items->Add(complexType); - - // Iterate over each XmlSchemaObject in the pre-schema-compilation - // Items collection. - for each (XmlSchemaObject^ schemaObject in customerSchema->Items) - { - // If the XmlSchemaObject is an element, whose QualifiedName - // is "Customer", get the complex type of the Customer element - // and the sequence particle of the complex type. - if (schemaObject::typeid == XmlSchemaElement::typeid) - { - XmlSchemaElement^ element = dynamic_cast(schemaObject); - - if (element->QualifiedName->Name->Equals("Customer")) - { - XmlSchemaComplexType^ customerType = - dynamic_cast(element->ElementSchemaType); - - XmlSchemaSequence^ sequence = - dynamic_cast(customerType->Particle); - - // Iterate over each XmlSchemaParticle in the pre-schema-compilation - // Items property. - for each (XmlSchemaParticle^ particle in sequence->Items) - { - // If the XmlSchemaParticle is an element, who's QualifiedName - // is "FirstName", set the SchemaTypeName of the FirstName element - // to the new FirstName complex type. - if (particle::typeid == XmlSchemaElement::typeid) - { - XmlSchemaElement^ childElement = - dynamic_cast(particle); - - if (childElement->Name->Equals("FirstName")) - { - childElement->SchemaTypeName = - gcnew XmlQualifiedName("FirstNameComplexType", - "http://www.tempuri.org"); - } - } - } - } - } - } - - // Reprocess and compile the modified XmlSchema object and write it to the console. - schemaSet->Reprocess(customerSchema); - schemaSet->Compile(); - customerSchema->Write(Console::Out); - } - - static void ValidationCallback(Object^ sender, ValidationEventArgs^ args) - { - if (args->Severity == XmlSeverityType::Warning) - Console::Write("WARNING: "); - else if (args->Severity == XmlSeverityType::Error) - Console::Write("ERROR: "); - - Console::WriteLine(args->Message); - } -}; - -int main() -{ - XmlSchemaEditExample::Main(); - return 0; -} -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaImportExample/CPP/XmlSchemaImportExample.cpp b/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaImportExample/CPP/XmlSchemaImportExample.cpp deleted file mode 100644 index 825457af395f9..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaImportExample/CPP/XmlSchemaImportExample.cpp +++ /dev/null @@ -1,96 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Xml; -using namespace System::Xml::Schema; - -ref class XmlSchemaImportExample -{ -public: - - static void Main() - { - // Add the customer and address schemas to a new XmlSchemaSet and compile them. - // Any schema validation warnings and errors encountered reading or - // compiling the schemas are handled by the ValidationEventHandler delegate. - XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet(); - schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback); - schemaSet->Add("http://www.tempuri.org", "customer.xsd"); - schemaSet->Add("http://www.example.com/IPO", "address.xsd"); - schemaSet->Compile(); - - // Retrieve the compiled XmlSchema objects for the customer and - // address schema from the XmlSchemaSet by iterating over - // the Schemas property. - XmlSchema^ customerSchema = nullptr; - XmlSchema^ addressSchema = nullptr; - for each (XmlSchema^ schema in schemaSet->Schemas()) - { - if (schema->TargetNamespace == "http://www.tempuri.org") - customerSchema = schema; - else if (schema->TargetNamespace == "http://www.example.com/IPO") - addressSchema = schema; - } - - // Create an XmlSchemaImport object, set the Namespace property - // to the namespace of the address schema, the Schema property - // to the address schema, and add it to the Includes property - // of the customer schema. - XmlSchemaImport^ import = gcnew XmlSchemaImport(); - import->Namespace = "http://www.example.com/IPO"; - import->Schema = addressSchema; - customerSchema->Includes->Add(import); - - // Reprocess and compile the modified XmlSchema object - // of the customer schema and write it to the console. - schemaSet->Reprocess(customerSchema); - schemaSet->Compile(); - customerSchema->Write(Console::Out); - - // Recursively write all of the schemas imported into the - // customer schema to the console using the Includes - // property of the customer schema. - RecurseExternals(customerSchema); - } - - static void RecurseExternals(XmlSchema^ schema) - { - for each (XmlSchemaExternal^ external in schema->Includes) - { - if (external->SchemaLocation != nullptr) - { - Console::WriteLine("External SchemaLocation: {0}", external->SchemaLocation); - } - - if (external::typeid == XmlSchemaImport::typeid) - { - XmlSchemaImport^ import = dynamic_cast(external); - Console::WriteLine("Imported namespace: {0}", import->Namespace); - } - - if (external->Schema != nullptr) - { - external->Schema->Write(Console::Out); - RecurseExternals(external->Schema); - } - } - } - - static void ValidationCallback(Object^ sender, ValidationEventArgs^ args) - { - if (args->Severity == XmlSeverityType::Warning) - Console::Write("WARNING: "); - else if (args->Severity == XmlSeverityType::Error) - Console::Write("ERROR: "); - - Console::WriteLine(args->Message); - } -}; - -int main() -{ - XmlSchemaImportExample::Main(); - return 0; -} -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaInferenceExamples/CPP/XmlSchemaInferenceExamples.cpp b/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaInferenceExamples/CPP/XmlSchemaInferenceExamples.cpp deleted file mode 100644 index 0d338c1f4c0d3..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaInferenceExamples/CPP/XmlSchemaInferenceExamples.cpp +++ /dev/null @@ -1,101 +0,0 @@ -#using - -using namespace System; -using namespace System::Xml; -using namespace System::Xml::Schema; - -ref class XmlSchemaInferenceExamples -{ -public: - - static void Main() - { - - } - - static void XmlSchemaInference_OverallExample() - { - // - XmlReader^ reader = XmlReader::Create("contosoBooks.xml"); - XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet(); - XmlSchemaInference^ schema = gcnew XmlSchemaInference(); - - schemaSet = schema->InferSchema(reader); - - for each (XmlSchema^ s in schemaSet->Schemas()) - { - s->Write(Console::Out); - } - // - } - - static void XmlSchemaInference_Occurrence() - { - // - XmlReader^ reader = XmlReader::Create("input.xml"); - XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet(); - XmlSchemaInference^ schema = gcnew XmlSchemaInference(); - - schema->Occurrence = XmlSchemaInference::InferenceOption::Relaxed; - - schemaSet = schema->InferSchema(reader); - - for each (XmlSchema^ s in schemaSet->Schemas()) - { - s->Write(Console::Out); - } - // - } - - static void XmlSchemaInference_TypeInference() - { - // - XmlReader^ reader = XmlReader::Create("input.xml"); - XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet(); - XmlSchemaInference^ schema = gcnew XmlSchemaInference(); - - schema->TypeInference = XmlSchemaInference::InferenceOption::Relaxed; - - schemaSet = schema->InferSchema(reader); - - for each (XmlSchema^ s in schemaSet->Schemas()) - { - s->Write(Console::Out); - } - // - } - - static void XmlSchemaInference_RefinementProcess() - { - // - XmlReader^ reader = XmlReader::Create("item1.xml"); - XmlReader^ reader1 = XmlReader::Create("item2.xml"); - XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet(); - XmlSchemaInference^ inference = gcnew XmlSchemaInference(); - schemaSet = inference->InferSchema(reader); - - // Display the inferred schema. - Console::WriteLine("Original schema:\n"); - for each (XmlSchema^ schema in schemaSet->Schemas("http://www.contoso.com/items")) - { - schema->Write(Console::Out); - } - - // Use the additional data in item2.xml to refine the original schema. - schemaSet = inference->InferSchema(reader1, schemaSet); - - // Display the refined schema. - Console::WriteLine("\n\nRefined schema:\n"); - for each (XmlSchema^ schema in schemaSet->Schemas("http://www.contoso.com/items")) - { - schema->Write(Console::Out); - } - // - } -}; - -int main() -{ - XmlSchemaInferenceExamples::Main(); - return 0; -} diff --git a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaReadWriteExample/CPP/XmlSchemaReadWriteExample.cpp b/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaReadWriteExample/CPP/XmlSchemaReadWriteExample.cpp deleted file mode 100644 index 0bd5609d3fc32..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaReadWriteExample/CPP/XmlSchemaReadWriteExample.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// -#using - -using namespace System; -using namespace System::IO; -using namespace System::Text; -using namespace System::Xml; -using namespace System::Xml::Schema; - -ref class XmlSchemaReadWriteExample -{ -public: - - static void Main() - { - try - { - XmlTextReader^ reader = gcnew XmlTextReader("example.xsd"); - ValidationEventHandler^ eventHandler = gcnew ValidationEventHandler(ValidationCallback); - XmlSchema^ myschema = XmlSchema::Read(reader, eventHandler); - myschema->Write(Console::Out); - FileStream^ file = gcnew FileStream("new.xsd", FileMode::Create, FileAccess::ReadWrite); - XmlTextWriter^ xwriter = gcnew XmlTextWriter(file, gcnew UTF8Encoding()); - xwriter->Formatting = Formatting::Indented; - myschema->Write(xwriter); - } - catch(Exception^ e) - { - Console::WriteLine(e); - } - } - - static void ValidationCallback(Object^ sender, ValidationEventArgs^ args) - { - if (args->Severity == XmlSeverityType::Warning) - Console::Write("WARNING: "); - else if (args->Severity == XmlSeverityType::Error) - Console::Write("ERROR: "); - - Console::WriteLine(args->Message); - } -}; - -int main() -{ - XmlSchemaReadWriteExample::Main(); - return 0; -}; -// \ No newline at end of file diff --git a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaSetOverall Example/CPP/xmlschemasetexample.cpp b/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaSetOverall Example/CPP/xmlschemasetexample.cpp deleted file mode 100644 index 1f3adf25c445f..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaSetOverall Example/CPP/xmlschemasetexample.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Xml; -using namespace System::Xml::Schema; - -static void booksSettingsValidationEventHandler( Object^ /*sender*/, ValidationEventArgs^ e ) -{ - if ( e->Severity == XmlSeverityType::Warning ) - { - Console::Write( L"WARNING: " ); - Console::WriteLine( e->Message ); - } - else - if ( e->Severity == XmlSeverityType::Error ) - { - Console::Write( L"ERROR: " ); - Console::WriteLine( e->Message ); - } -} - -int main() -{ - XmlReaderSettings^ booksSettings = gcnew XmlReaderSettings; - booksSettings->Schemas->Add( L"http://www.contoso.com/books", L"books.xsd" ); - booksSettings->ValidationType = ValidationType::Schema; - booksSettings->ValidationEventHandler += gcnew ValidationEventHandler( booksSettingsValidationEventHandler ); - XmlReader^ books = XmlReader::Create( L"books.xml", booksSettings ); - while ( books->Read() ) - {} - - return 0; -} - -// diff --git a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaTraverseExample/CPP/XmlSchemaTraverseExample.cpp b/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaTraverseExample/CPP/XmlSchemaTraverseExample.cpp deleted file mode 100644 index 3ff2171e71917..0000000000000 --- a/samples/snippets/cpp/VS_Snippets_Data/XmlSchemaTraverseExample/CPP/XmlSchemaTraverseExample.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// -#using - -using namespace System; -using namespace System::Collections; -using namespace System::Xml; -using namespace System::Xml::Schema; - -ref class XmlSchemaTraverseExample -{ -public: - - static void Main() - { - // Add the customer schema to a new XmlSchemaSet and compile it. - // Any schema validation warnings and errors encountered reading or - // compiling the schema are handled by the ValidationEventHandler delegate. - XmlSchemaSet^ schemaSet = gcnew XmlSchemaSet(); - schemaSet->ValidationEventHandler += gcnew ValidationEventHandler(ValidationCallback); - schemaSet->Add("http://www.tempuri.org", "customer.xsd"); - schemaSet->Compile(); - - // Retrieve the compiled XmlSchema object from the XmlSchemaSet - // by iterating over the Schemas property. - XmlSchema^ customerSchema = nullptr; - for each (XmlSchema^ schema in schemaSet->Schemas()) - { - customerSchema = schema; - } - - // Iterate over each XmlSchemaElement in the Values collection - // of the Elements property. - for each (XmlSchemaElement^ element in customerSchema->Elements->Values) - { - - Console::WriteLine("Element: {0}", element->Name); - - // Get the complex type of the Customer element. - XmlSchemaComplexType^ complexType = dynamic_cast(element->ElementSchemaType); - - // If the complex type has any attributes, get an enumerator - // and write each attribute name to the console. - if (complexType->AttributeUses->Count > 0) - { - IDictionaryEnumerator^ enumerator = - complexType->AttributeUses->GetEnumerator(); - - while (enumerator->MoveNext()) - { - XmlSchemaAttribute^ attribute = - dynamic_cast(enumerator->Value); - - Console::WriteLine("Attribute: {0}", attribute->Name); - } - } - - // Get the sequence particle of the complex type. - XmlSchemaSequence^ sequence = dynamic_cast(complexType->ContentTypeParticle); - - // Iterate over each XmlSchemaElement in the Items collection. - for each (XmlSchemaElement^ childElement in sequence->Items) - { - Console::WriteLine("Element: {0}", childElement->Name); - } - } - } - - static void ValidationCallback(Object^ sender, ValidationEventArgs^ args) - { - if (args->Severity == XmlSeverityType::Warning) - Console::Write("WARNING: "); - else if (args->Severity == XmlSeverityType::Error) - Console::Write("ERROR: "); - - Console::WriteLine(args->Message); - } -}; - -int main() -{ - XmlSchemaTraverseExample::Main(); - return 0; -}; -// \ No newline at end of file