diff --git a/docs/framework/wcf/configuration-editor-tool-svcconfigeditor-exe.md b/docs/framework/wcf/configuration-editor-tool-svcconfigeditor-exe.md index 315a8511e655f..e6b34e463af49 100644 --- a/docs/framework/wcf/configuration-editor-tool-svcconfigeditor-exe.md +++ b/docs/framework/wcf/configuration-editor-tool-svcconfigeditor-exe.md @@ -69,7 +69,7 @@ The viewer automatically follows the configuration merge path and creates a view ### Services -The **Services** node displays all of the services currently assigned in the configuration file. Each sub-node in the tree corresponds to a sub-element of the <`services`> element in the configuration file. +The **Services** node displays all of the services currently assigned in the configuration file. Each sub-node in the tree corresponds to a sub-element of the `` element in the configuration file. When you click the **Services** node, you can view or perform tasks on the service Summary Page in the **Detail** Pane. @@ -116,7 +116,7 @@ You can create a new service endpoint configuration in the following ways: ### Client -The **Client** node displays all of the client endpoints in the configuration file. Every sub-node in the tree corresponds to a sub-element of the <`client`> element in the configuration file. +The **Client** node displays all of the client endpoints in the configuration file. Every sub-node in the tree corresponds to a sub-element of the `` element in the configuration file. When you click the **Client** node, you can view or perform tasks on the client **Summary Page** in the **Detail Pane**. @@ -176,7 +176,7 @@ If the standard endpoint is in used, a warning message is displayed when you att Binding configurations are used to configure bindings on endpoints. Such configuration settings are stored in the **Binding** node. Endpoints reference binding configurations by name and multiple endpoints can reference a single binding configuration. -The **Bindings** node displays all of the binding settings in the configuration file. Every sub-node in the tree corresponds to a sub-element in the <`bindings`> element in the configuration file. +The **Bindings** node displays all of the binding settings in the configuration file. Every sub-node in the tree corresponds to a sub-element in the `` element in the configuration file. When you click the **Bindings** node, you can view or perform tasks on the binding **Summary Page** in the **Detail Pane**. @@ -220,7 +220,7 @@ A custom binding is a collection of binding elements that form a stack. Each bin ### Diagnostics -The **Diagnostics** node displays all of the diagnostic settings in the configuration file. It enables you to turn performance counters on or off, enable or disable Windows Management Instrumentation (WMI), configure WCF tracing, and configure WCF message logging. The settings in the **Diagnostics** node correspond to the <`system.diagnostics`> section, and `` section in `` in the configuration file. +The **Diagnostics** node displays all of the diagnostic settings in the configuration file. It enables you to turn performance counters on or off, enable or disable Windows Management Instrumentation (WMI), configure WCF tracing, and configure WCF message logging. The settings in the **Diagnostics** node correspond to the `` section, and `` section in `` in the configuration file. When you click the **Diagnostics** node, you can view or perform tasks on the diagnostics **Summary Page** in the **Detail Pane**. @@ -384,7 +384,7 @@ One way to create a new configuration file is to use the New Service Element Wiz ## Configuring COM+ -The Service Configuration Editor enables you to create a new configuration file for an existing COM+ application, or edit an existing COM+ configuration. The **COM Contract** node is only visible when the <`comContract`> section exists in the configuration file. +The Service Configuration Editor enables you to create a new configuration file for an existing COM+ application, or edit an existing COM+ configuration. The **COM Contract** node is only visible when the `` section exists in the configuration file. ### Creating a New COM+ Configuration diff --git a/docs/framework/wcf/configuring-services-using-configuration-files.md b/docs/framework/wcf/configuring-services-using-configuration-files.md index d7cacf0b90554..515ea1a984d3f 100644 --- a/docs/framework/wcf/configuring-services-using-configuration-files.md +++ b/docs/framework/wcf/configuring-services-using-configuration-files.md @@ -2,273 +2,273 @@ title: "Configuring Services Using Configuration Files" description: Learn how a configuration file for a WCF service gives you the flexibility of providing endpoint and service behavior data during deployment. ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "configuring services [WCF]" ms.assetid: c9c8cd32-2c9d-4541-ad0d-16dff6bd2a00 --- # Configuring Services Using Configuration Files -Configuring a Windows Communication Foundation (WCF) service with a configuration file gives you the flexibility of providing endpoint and service behavior data at the point of deployment instead of at design time. This topic outlines the primary techniques available. - - A WCF service is configurable using the .NET Framework configuration technology. Most commonly, XML elements are added to the Web.config file for an Internet Information Services (IIS) site that hosts a WCF service. The elements allow you to change details such as the endpoint addresses (the actual addresses used to communicate with the service) on a machine-by-machine basis. In addition, WCF includes several system-provided elements that allow you to quickly select the most basic features for a service. Starting with .NET Framework 4, WCF comes with a new default configuration model that simplifies WCF configuration requirements. If you do not provide any WCF configuration for a particular service, the runtime automatically configures your service with some standard endpoints and default binding/behavior. In practice, writing configuration is a major part of programming WCF applications. - - For more information, see [Configuring Bindings for Services](configuring-bindings-for-wcf-services.md). For a list of the most commonly used elements, see [System-Provided Bindings](system-provided-bindings.md). For more information about default endpoints, bindings, and behaviors, see [Simplified Configuration](simplified-configuration.md) and [Simplified Configuration for WCF Services](./samples/simplified-configuration-for-wcf-services.md). - +Configuring a Windows Communication Foundation (WCF) service with a configuration file gives you the flexibility of providing endpoint and service behavior data at the point of deployment instead of at design time. This topic outlines the primary techniques available. + + A WCF service is configurable using the .NET Framework configuration technology. Most commonly, XML elements are added to the Web.config file for an Internet Information Services (IIS) site that hosts a WCF service. The elements allow you to change details such as the endpoint addresses (the actual addresses used to communicate with the service) on a machine-by-machine basis. In addition, WCF includes several system-provided elements that allow you to quickly select the most basic features for a service. Starting with .NET Framework 4, WCF comes with a new default configuration model that simplifies WCF configuration requirements. If you do not provide any WCF configuration for a particular service, the runtime automatically configures your service with some standard endpoints and default binding/behavior. In practice, writing configuration is a major part of programming WCF applications. + + For more information, see [Configuring Bindings for Services](configuring-bindings-for-wcf-services.md). For a list of the most commonly used elements, see [System-Provided Bindings](system-provided-bindings.md). For more information about default endpoints, bindings, and behaviors, see [Simplified Configuration](simplified-configuration.md) and [Simplified Configuration for WCF Services](./samples/simplified-configuration-for-wcf-services.md). + > [!IMPORTANT] -> When deploying side by side scenarios where two different versions of a service are deployed, it is necessary to specify partial names of assemblies referenced in configuration files. This is because the configuration file is shared across all versions of a service and they could be running under different versions of the .NET Framework. - -## System.Configuration: Web.config and App.config - - WCF uses the System.Configuration configuration system of the .NET Framework. - - When configuring a service in Visual Studio, use either a Web.config file or an App.config file to specify the settings. The choice of the configuration file name is determined by the hosting environment you choose for the service. If you are using IIS to host your service, use a Web.config file. If you are using any other hosting environment, use an App.config file. - - In Visual Studio, the file named App.config is used to create the final configuration file. The final name actually used for the configuration depends on the assembly name. For example, an assembly named "Cohowinery.exe" has a final configuration file name of "Cohowinery.exe.config". However, you only need to modify the App.config file. Changes made to that file are automatically made to the final application configuration file at compile time. - - In using an App.config, file the configuration system merges the App.config file with content of the Machine.config file when the application starts and the configuration is applied. This mechanism allows machine-wide settings to be defined in the Machine.config file. The App.config file can be used to override the settings of the Machine.config file; you can also lock in the settings in Machine.config file so that they get used. In the Web.config case, the configuration system merges the Web.config files in all directories leading up to the application directory into the configuration that gets applied. For more information about configuration and the setting priorities, see topics in the namespace. - -## Major Sections of the Configuration File - - The main sections in the configuration file include the following elements. - -```xml - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - - -``` - + + + + + + + + + + + + + + +``` + > [!NOTE] -> The bindings and behaviors sections are optional and are only included if required. - -### The \ Element - - The `services` element contains the specifications for all services the application hosts. Starting with the simplified configuration model in .NET Framework 4, this section is optional. - - [\](../configure-apps/file-schema/wcf/services.md) - -### The \ Element - - Each service has these attributes: - -- `name`. Specifies the type that provides an implementation of a service contract. This is a fully qualified name which consists of the namespace, a period, and then the type name. For example `"MyNameSpace.myServiceType"`. - -- `behaviorConfiguration`. Specifies the name of one of the `behavior` elements found in the `behaviors` element. The specified behavior governs actions such as whether the service allows impersonation. If its value is the empty name or no `behaviorConfiguration` is provided then the default set of service behaviors is added to the service. - -- [\](../configure-apps/file-schema/wcf/service.md) - -### The \ Element - - Each endpoint requires an address, a binding, and a contract, which are represented by the following attributes: - -- `address`. Specifies the service's Uniform Resource Identifier (URI), which can be an absolute address or one that is given relative to the base address of the service. If set to an empty string, it indicates that the endpoint is available at the base address that is specified when creating the for the service. - -- `binding`. Typically specifies a system-provided binding like , but can also specify a user-defined binding. The binding specified determines the type of transport, security and encoding used, and whether reliable sessions, transactions, or streaming is supported or enabled. - -- `bindingConfiguration`. If the default values of a binding must be modified, this can be done by configuring the appropriate `binding` element in the `bindings` element. This attribute should be given the same value as the `name` attribute of the `binding` element that is used to change the defaults. If no name is given, or no `bindingConfiguration` is specified in the binding, then the default binding of the binding type is used in the endpoint. - -- `contract`. Specifies the interface that defines the contract. This is the interface implemented in the common language runtime (CLR) type specified by the `name` attribute of the `service` element. - -- [\](../configure-apps/file-schema/wcf/endpoint-element.md) - -### The \ Element - - The `bindings` element contains the specifications for all bindings that can be used by any endpoint defined in any service. - - [\](../configure-apps/file-schema/wcf/bindings.md) - -### The \ Element - - The `binding` elements contained in the `bindings` element can be either one of the system-provided bindings (see [System-Provided Bindings](system-provided-bindings.md)) or a custom binding (see [Custom Bindings](./extending/custom-bindings.md)). The `binding` element has a `name` attribute that correlates the binding with the endpoint specified in the `bindingConfiguration` attribute of the `endpoint` element. If no name is specified then that binding corresponds to the default of that binding type. - +> The bindings and behaviors sections are optional and are only included if required. + +### The \ Element + + The `services` element contains the specifications for all services the application hosts. Starting with the simplified configuration model in .NET Framework 4, this section is optional. + + [\](../configure-apps/file-schema/wcf/services.md) + +### The \ Element + + Each service has these attributes: + +- `name`. Specifies the type that provides an implementation of a service contract. This is a fully qualified name which consists of the namespace, a period, and then the type name. For example `"MyNameSpace.myServiceType"`. + +- `behaviorConfiguration`. Specifies the name of one of the `behavior` elements found in the `behaviors` element. The specified behavior governs actions such as whether the service allows impersonation. If its value is the empty name or no `behaviorConfiguration` is provided then the default set of service behaviors is added to the service. + +- [\](../configure-apps/file-schema/wcf/service.md) + +### The \ Element + + Each endpoint requires an address, a binding, and a contract, which are represented by the following attributes: + +- `address`. Specifies the service's Uniform Resource Identifier (URI), which can be an absolute address or one that is given relative to the base address of the service. If set to an empty string, it indicates that the endpoint is available at the base address that is specified when creating the for the service. + +- `binding`. Typically specifies a system-provided binding like , but can also specify a user-defined binding. The binding specified determines the type of transport, security and encoding used, and whether reliable sessions, transactions, or streaming is supported or enabled. + +- `bindingConfiguration`. If the default values of a binding must be modified, this can be done by configuring the appropriate `binding` element in the `bindings` element. This attribute should be given the same value as the `name` attribute of the `binding` element that is used to change the defaults. If no name is given, or no `bindingConfiguration` is specified in the binding, then the default binding of the binding type is used in the endpoint. + +- `contract`. Specifies the interface that defines the contract. This is the interface implemented in the common language runtime (CLR) type specified by the `name` attribute of the `service` element. + +- [\](../configure-apps/file-schema/wcf/endpoint-element.md) + +### The \ Element + + The `bindings` element contains the specifications for all bindings that can be used by any endpoint defined in any service. + + [\](../configure-apps/file-schema/wcf/bindings.md) + +### The \ Element + + The `binding` elements contained in the `bindings` element can be either one of the system-provided bindings (see [System-Provided Bindings](system-provided-bindings.md)) or a custom binding (see [Custom Bindings](./extending/custom-bindings.md)). The `binding` element has a `name` attribute that correlates the binding with the endpoint specified in the `bindingConfiguration` attribute of the `endpoint` element. If no name is specified then that binding corresponds to the default of that binding type. + For more information about configuring services and clients, see [Configuring WCF services](configuring-services.md). - - [\](../configure-apps/file-schema/wcf/bindings.md) - -### The \ Element - - This is a container element for the `behavior` elements that define the behaviors for a service. - - [\](../configure-apps/file-schema/wcf/behaviors.md) - -### The \ Element - - Each `behavior` element is identified by a `name` attribute and provides either a system-provided behavior, such as <`throttling`>, or a custom behavior. If no name is given then that behavior element corresponds to the default service or endpoint behavior. - - [\](../configure-apps/file-schema/wcf/behavior-of-servicebehaviors.md) - -## How to Use Binding and Behavior Configurations - - WCF makes it easy to share configurations between endpoints using a reference system in configuration. Rather than directly assigning configuration values to an endpoint, binding-related configuration values are grouped in `bindingConfiguration` elements in the `` section. A binding configuration is a named group of settings on a binding. Endpoints can then reference the `bindingConfiguration` by name. - -```xml - - - - - - - - - - - - + + [\](../configure-apps/file-schema/wcf/bindings.md) + +### The \ Element + + This is a container element for the `behavior` elements that define the behaviors for a service. + + [\](../configure-apps/file-schema/wcf/behaviors.md) + +### The \ Element + + Each `behavior` element is identified by a `name` attribute and provides either a system-provided behavior, such as ``, or a custom behavior. If no name is given then that behavior element corresponds to the default service or endpoint behavior. + + [\](../configure-apps/file-schema/wcf/behavior-of-servicebehaviors.md) + +## How to Use Binding and Behavior Configurations + + WCF makes it easy to share configurations between endpoints using a reference system in configuration. Rather than directly assigning configuration values to an endpoint, binding-related configuration values are grouped in `bindingConfiguration` elements in the `` section. A binding configuration is a named group of settings on a binding. Endpoints can then reference the `bindingConfiguration` by name. + +```xml + + + + + + + + + + + + + bindingConfiguration="myBindingConfiguration1" + contract="MyContract" /> + bindingConfiguration="myBindingConfiguration2" + contract="MyContract" /> - - - - -``` - - The `name` of the `bindingConfiguration` is set in the `` element. The `name` must be a unique string within the scope of the binding type—in this case the [](../configure-apps/file-schema/wcf/basichttpbinding.md), or an empty value to refer to the default binding. The endpoint links to the configuration by setting the `bindingConfiguration` attribute to this string. - - A `behaviorConfiguration` is implemented the same way, as illustrated in the following sample. - -```xml - - - - - - - - - - - - - - - - - - + contract="MyContract" /> + + + + +``` + + The `name` of the `bindingConfiguration` is set in the `` element. The `name` must be a unique string within the scope of the binding type—in this case the [](../configure-apps/file-schema/wcf/basichttpbinding.md), or an empty value to refer to the default binding. The endpoint links to the configuration by setting the `bindingConfiguration` attribute to this string. + + A `behaviorConfiguration` is implemented the same way, as illustrated in the following sample. + +```xml + + + + + + + + + + + + + + + + + + - - - - -``` - - Note that the default set of service behaviors are added to the service. This system allows endpoints to share common configurations without redefining the settings. If machine-wide scope is required, create the binding or behavior configuration in Machine.config. The configuration settings are available in all App.config files. The [Configuration Editor Tool (SvcConfigEditor.exe)](configuration-editor-tool-svcconfigeditor-exe.md) makes it easy to create configurations. - -## Behavior Merge - - The behavior merge feature makes it easier to manage behaviors when you want a set of common behaviors to be used consistently. This feature allows you to specify behaviors at different levels of the configuration hierarchy and have services inherit behaviors from multiple levels of the configuration hierarchy. To illustrate how this works assume you have the following virtual directory layout in IIS: - + address="myAddress3" behaviorConfiguration="myBehavior" + binding="basicHttpBinding" + contract="MyContract" /> + + + + +``` + + Note that the default set of service behaviors are added to the service. This system allows endpoints to share common configurations without redefining the settings. If machine-wide scope is required, create the binding or behavior configuration in Machine.config. The configuration settings are available in all App.config files. The [Configuration Editor Tool (SvcConfigEditor.exe)](configuration-editor-tool-svcconfigeditor-exe.md) makes it easy to create configurations. + +## Behavior Merge + + The behavior merge feature makes it easier to manage behaviors when you want a set of common behaviors to be used consistently. This feature allows you to specify behaviors at different levels of the configuration hierarchy and have services inherit behaviors from multiple levels of the configuration hierarchy. To illustrate how this works assume you have the following virtual directory layout in IIS: + `~\Web.config~\Service.svc~\Child\Web.config~\Child\Service.svc` - - And your `~\Web.config` file has the following contents: - -```xml - - - - - - - - - - - -``` - - And you have a child Web.config located at ~\Child\Web.config with the following contents: - -```xml - - - - - - - - - - - -``` - - The service located at ~\Child\Service.svc will behave as though it has both the serviceDebug and serviceMetadata behaviors. The service located at ~\Service.svc will only have the serviceDebug behavior. What happens is that the two behavior collections with the same name (in this case the empty string) are merged. - - You can also clear behavior collections by using the \ tag and removed individual behaviors from the collection by using the \ tag. For example, the following two configuration results in the child service having only the serviceMetadata behavior: - -```xml - - - - - - - - - - - - -``` - -```xml - - - - - - - - - - - - -``` - - Behavior merge is done for nameless behavior collections as shown above and named behavior collections as well. - - Behavior merge works in the IIS hosting environment, in which Web.config files merge hierarchically with the root Web.config file and machine.config. But it also works in the application environment, where machine.config can merge with the App.config file. - - Behavior merge applies to both endpoint behaviors and service behaviors in configuration. - - If a child behavior collection contains a behavior that’s already present in the parent behavior collection, the child behavior overrides the parent. So if a parent behavior collection had `` and a child behavior collection had ``, the child behavior would override the parent behavior in the behavior collection and httpGetEnabled would be "true". - + + And your `~\Web.config` file has the following contents: + +```xml + + + + + + + + + + + +``` + + And you have a child Web.config located at ~\Child\Web.config with the following contents: + +```xml + + + + + + + + + + + +``` + + The service located at ~\Child\Service.svc will behave as though it has both the serviceDebug and serviceMetadata behaviors. The service located at ~\Service.svc will only have the serviceDebug behavior. What happens is that the two behavior collections with the same name (in this case the empty string) are merged. + + You can also clear behavior collections by using the \ tag and removed individual behaviors from the collection by using the \ tag. For example, the following two configuration results in the child service having only the serviceMetadata behavior: + +```xml + + + + + + + + + + + + +``` + +```xml + + + + + + + + + + + + +``` + + Behavior merge is done for nameless behavior collections as shown above and named behavior collections as well. + + Behavior merge works in the IIS hosting environment, in which Web.config files merge hierarchically with the root Web.config file and machine.config. But it also works in the application environment, where machine.config can merge with the App.config file. + + Behavior merge applies to both endpoint behaviors and service behaviors in configuration. + + If a child behavior collection contains a behavior that’s already present in the parent behavior collection, the child behavior overrides the parent. So if a parent behavior collection had `` and a child behavior collection had ``, the child behavior would override the parent behavior in the behavior collection and httpGetEnabled would be "true". + ## See also - [Simplified Configuration](simplified-configuration.md) diff --git a/docs/framework/wcf/configuring-wcf-services-in-code.md b/docs/framework/wcf/configuring-wcf-services-in-code.md index 8f40b5bdccf89..5d0214035b74e 100644 --- a/docs/framework/wcf/configuring-wcf-services-in-code.md +++ b/docs/framework/wcf/configuring-wcf-services-in-code.md @@ -74,7 +74,7 @@ public class Service1 : IService1 } ``` - The settings in the <`protocolMappings`> section are only used if no application endpoints are added to the programmatically.You can optionally load the service configuration from the default application configuration file by calling and then change the settings. The class also allows you to load configuration from a centralized configuration. The following code illustrates how to implement this: + The settings in the `` section are only used if no application endpoints are added to the programmatically.You can optionally load the service configuration from the default application configuration file by calling and then change the settings. The class also allows you to load configuration from a centralized configuration. The following code illustrates how to implement this: ```csharp public class Service1 : IService1 @@ -88,7 +88,7 @@ public class Service1 : IService1 ``` > [!IMPORTANT] -> Note that ignores <`host`> settings within the <`service`> tag of <`system.serviceModel`>. Conceptually, <`host`> is about host configuration, not service configuration, and it gets loaded before the Configure method executes. +> Note that ignores `` settings within the `` tag of ``. Conceptually, `` is about host configuration, not service configuration, and it gets loaded before the Configure method executes. ## See also diff --git a/docs/framework/wcf/extending/overriding-the-identity-of-a-service-for-authentication.md b/docs/framework/wcf/extending/overriding-the-identity-of-a-service-for-authentication.md index 8c91ebee8fa4c..0e25e2690bf02 100644 --- a/docs/framework/wcf/extending/overriding-the-identity-of-a-service-for-authentication.md +++ b/docs/framework/wcf/extending/overriding-the-identity-of-a-service-for-authentication.md @@ -48,7 +48,7 @@ Typically, you do not have to set the identity on a service because the selectio If you change the client credential type in the binding previously shown to `Certificate`, then the generated WSDL contains a Base64 serialized X.509 certificate for the identity value as shown in the following code. This is the default for all client credential types other than Windows. - You can change the value of the default service identity or change the type of the identity by using the <`identity`> element in configuration or by setting the identity in code. The following configuration code sets a domain name system (DNS) identity with the value `contoso.com`. + You can change the value of the default service identity or change the type of the identity by using the `` element in configuration or by setting the identity in code. The following configuration code sets a domain name system (DNS) identity with the value `contoso.com`. ### Set Identity Programmatically diff --git a/docs/framework/wcf/extending/specifying-a-custom-crypto-algorithm.md b/docs/framework/wcf/extending/specifying-a-custom-crypto-algorithm.md index 8a73165920409..85d97f8c71e63 100644 --- a/docs/framework/wcf/extending/specifying-a-custom-crypto-algorithm.md +++ b/docs/framework/wcf/extending/specifying-a-custom-crypto-algorithm.md @@ -6,124 +6,124 @@ ms.topic: how-to --- # Specifying a Custom Crypto Algorithm -WCF allows you to specify a custom crypto algorithm to use when encrypting data or computing digital signatures. This is done by the following steps: - -1. Derive a class from - -2. Register the algorithm - -3. Configure the binding with the -derived class. - -## Derive a class from SecurityAlgorithmSuite - - The is an abstract base class that allows you to specify the algorithm to use when performing various security related operations. For example, computing a hash for a digital signature or encrypting a message. The following code shows how to derive a class from : - -```csharp -public class MyCustomAlgorithmSuite : SecurityAlgorithmSuite - { - public override string DefaultAsymmetricKeyWrapAlgorithm - { - get { return SecurityAlgorithms.RsaOaepKeyWrap; } - } - - public override string DefaultAsymmetricSignatureAlgorithm - { - get { return SecurityAlgorithms.RsaSha1Signature; } - } - - public override string DefaultCanonicalizationAlgorithm - { - get { return SecurityAlgorithms.ExclusiveC14n; ; } - } - - public override string DefaultDigestAlgorithm - { - get { return SecurityAlgorithms.MyCustomHashAlgorithm; } - } - - public override string DefaultEncryptionAlgorithm - { - get { return SecurityAlgorithms.Aes128Encryption; } - } - - public override int DefaultEncryptionKeyDerivationLength - { - get { return 128; } - } - - public override int DefaultSignatureKeyDerivationLength - { - get { return 128; } - } - - public override int DefaultSymmetricKeyLength - { - get { return 128; } - } - - public override string DefaultSymmetricKeyWrapAlgorithm - { - get { return SecurityAlgorithms.Aes128Encryption; } - } - - public override string DefaultSymmetricSignatureAlgorithm - { - get { return SecurityAlgorithms.HmacSha1Signature; } - } - - public override bool IsAsymmetricKeyLengthSupported(int length) - { - return length >= 1024 && length <= 4096; - } - - public override bool IsSymmetricKeyLengthSupported(int length) - { - return length >= 128 && length <= 256; - } - } -``` - -## Register the Custom Algorithm - - Registration can be done in a configuration file or in imperative code. Registering a custom algorithm is done by creating a mapping between a class that implements a crypto service provider and an alias. The alias is then mapped to a URI which is used when specifying the algorithm in the WCF service's binding. The following configuration snippet illustrates how to register a custom algorithm in config: - -```xml - - - - - - - - - - - - -``` - - The section under the <`cryptoClasses`> element creates the mapping between the SHA256CryptoServiceProvider and the alias "SHA256CSP". The <`nameEntry`> element creates the mapping between the "SHA256CSP" alias and the specified URL `http://contoso.com/CustomAlgorithms/CustomHashAlgorithm`. - - To register the custom algorithm in code use the method. This method creates both mappings. The following example shows how to call this method: - +WCF allows you to specify a custom crypto algorithm to use when encrypting data or computing digital signatures. This is done by the following steps: + +1. Derive a class from + +2. Register the algorithm + +3. Configure the binding with the -derived class. + +## Derive a class from SecurityAlgorithmSuite + + The is an abstract base class that allows you to specify the algorithm to use when performing various security related operations. For example, computing a hash for a digital signature or encrypting a message. The following code shows how to derive a class from : + +```csharp +public class MyCustomAlgorithmSuite : SecurityAlgorithmSuite + { + public override string DefaultAsymmetricKeyWrapAlgorithm + { + get { return SecurityAlgorithms.RsaOaepKeyWrap; } + } + + public override string DefaultAsymmetricSignatureAlgorithm + { + get { return SecurityAlgorithms.RsaSha1Signature; } + } + + public override string DefaultCanonicalizationAlgorithm + { + get { return SecurityAlgorithms.ExclusiveC14n; ; } + } + + public override string DefaultDigestAlgorithm + { + get { return SecurityAlgorithms.MyCustomHashAlgorithm; } + } + + public override string DefaultEncryptionAlgorithm + { + get { return SecurityAlgorithms.Aes128Encryption; } + } + + public override int DefaultEncryptionKeyDerivationLength + { + get { return 128; } + } + + public override int DefaultSignatureKeyDerivationLength + { + get { return 128; } + } + + public override int DefaultSymmetricKeyLength + { + get { return 128; } + } + + public override string DefaultSymmetricKeyWrapAlgorithm + { + get { return SecurityAlgorithms.Aes128Encryption; } + } + + public override string DefaultSymmetricSignatureAlgorithm + { + get { return SecurityAlgorithms.HmacSha1Signature; } + } + + public override bool IsAsymmetricKeyLengthSupported(int length) + { + return length >= 1024 && length <= 4096; + } + + public override bool IsSymmetricKeyLengthSupported(int length) + { + return length >= 128 && length <= 256; + } + } +``` + +## Register the Custom Algorithm + + Registration can be done in a configuration file or in imperative code. Registering a custom algorithm is done by creating a mapping between a class that implements a crypto service provider and an alias. The alias is then mapped to a URI which is used when specifying the algorithm in the WCF service's binding. The following configuration snippet illustrates how to register a custom algorithm in config: + +```xml + + + + + + + + + + + + +``` + + The section under the `` element creates the mapping between the SHA256CryptoServiceProvider and the alias "SHA256CSP". The `` element creates the mapping between the "SHA256CSP" alias and the specified URL `http://contoso.com/CustomAlgorithms/CustomHashAlgorithm`. + + To register the custom algorithm in code use the method. This method creates both mappings. The following example shows how to call this method: + ```csharp // Register the custom URI string defined for the hashAlgorithm in MyCustomAlgorithmSuite class to create the -// SHA256CryptoServiceProvider hash algorithm object. -CryptoConfig.AddAlgorithm(typeof(SHA256CryptoServiceProvider), "http://contoso.com/CustomAlgorithms/CustomHashAlgorithm"); -``` - -## Configure the Binding - - You configure the binding by specifying the custom -derived class in the binding settings as shown in the following code snippet: - -```csharp -WSHttpBinding binding = new WSHttpBinding(); - binding.Security.Message.AlgorithmSuite = new MyCustomAlgorithmSuite(); -``` - - For a complete code example, see the [Cryptographic Agility in WCF Security](../samples/cryptographic-agility-in-wcf-security.md) sample. - +// SHA256CryptoServiceProvider hash algorithm object. +CryptoConfig.AddAlgorithm(typeof(SHA256CryptoServiceProvider), "http://contoso.com/CustomAlgorithms/CustomHashAlgorithm"); +``` + +## Configure the Binding + + You configure the binding by specifying the custom -derived class in the binding settings as shown in the following code snippet: + +```csharp +WSHttpBinding binding = new WSHttpBinding(); + binding.Security.Message.AlgorithmSuite = new MyCustomAlgorithmSuite(); +``` + + For a complete code example, see the [Cryptographic Agility in WCF Security](../samples/cryptographic-agility-in-wcf-security.md) sample. + ## See also - [Securing Services and Clients](../feature-details/securing-services-and-clients.md) diff --git a/docs/framework/wcf/extending/walkthrough-creating-custom-client-and-service-credentials.md b/docs/framework/wcf/extending/walkthrough-creating-custom-client-and-service-credentials.md index 50934b00997ac..892f6ff899e55 100644 --- a/docs/framework/wcf/extending/walkthrough-creating-custom-client-and-service-credentials.md +++ b/docs/framework/wcf/extending/walkthrough-creating-custom-client-and-service-credentials.md @@ -108,9 +108,9 @@ Once you have the configuration handler class, it can be integrated into the WCF #### To register and use a custom client credentials configuration handler in the application configuration -1. Add an <`extensions`> element and a <`behaviorExtensions`> element to the configuration file. +1. Add an `` element and a `` element to the configuration file. -2. Add an <`add`> element to the <`behaviorExtensions`> element and set the `name` attribute to an appropriate value. +2. Add an `` element to the `` element and set the `name` attribute to an appropriate value. 3. Set the `type` attribute to the fully-qualified type name. Also include the assembly name and other assembly attributes. @@ -124,7 +124,7 @@ Once you have the configuration handler class, it can be integrated into the WCF ``` -4. After registering your configuration handler, the custom credentials element can be used inside the same configuration file instead of the system-provided <`clientCredentials`> element. You can use both the system-provided properties and any new properties that you have added to your configuration handler implementation. The following example sets the value of a custom property using the `creditCardNumber` attribute. +4. After registering your configuration handler, the custom credentials element can be used inside the same configuration file instead of the system-provided `` element. You can use both the system-provided properties and any new properties that you have added to your configuration handler implementation. The following example sets the value of a custom property using the `creditCardNumber` attribute. ```xml diff --git a/docs/framework/wcf/feature-details/config-workflow-unhandled-exception-workflowservicehost.md b/docs/framework/wcf/feature-details/config-workflow-unhandled-exception-workflowservicehost.md index 0bddfdf3f18e1..c23ebb7534fe3 100644 --- a/docs/framework/wcf/feature-details/config-workflow-unhandled-exception-workflowservicehost.md +++ b/docs/framework/wcf/feature-details/config-workflow-unhandled-exception-workflowservicehost.md @@ -7,47 +7,47 @@ ms.assetid: 51b25c86-292c-43e4-8d13-273d2badc8ad --- # How to: Configure Workflow Unhandled Exception Behavior with WorkflowServiceHost -The is a behavior that enables you to specify the action to take if an unhandled exception occurs within a workflow hosted in . This topic shows how to configure this behavior in a configuration file. - -### To configure WorkflowUnhandledExceptionBehavior - -1. Add a <`workflowUnhandledException`> element in a <`behavior`> element within a <`serviceBehaviors`> element, using the `action` attribute to specify the action to take when an unhandled exception occurs as shown in the following example. - - ```xml - - - +The is a behavior that enables you to specify the action to take if an unhandled exception occurs within a workflow hosted in . This topic shows how to configure this behavior in a configuration file. + +### To configure WorkflowUnhandledExceptionBehavior + +1. Add a `` element in a `` element within a `` element, using the `action` attribute to specify the action to take when an unhandled exception occurs as shown in the following example. + + ```xml + + + - - - - ``` - + + + + ``` + > [!NOTE] - > The preceding configuration sample is using simplified configuration. For more information, see [Simplified Configuration](../simplified-configuration.md). - - This behavior can be configured in code as shown in the following example. - - ```csharp - host.Description.Behaviors.Add(new WorkflowUnhandledExceptionBehavior { Action = WorkflowUnhandledExceptionAction.AbandonAndSuspend }); - ``` - - The `action` attribute of the <`workflowUnhandledException`> element can be set to one of the following values: - - **abandon** - Aborts the instance in memory without touching the persisted instance state (that is, roll back to the last persist point). - - **abandonAndSuspend** - Aborts the instance in memory and updates the persisted instance to be suspended. - - **cancel** - Calls cancellation handlers for the instance and then completes the instance in memory, which may also remove it from the instance store - - **terminate** - Completes the instance in memory and removes it from the instance store. - - For more information about , see [Workflow Service Host Extensibility](workflow-service-host-extensibility.md). - + > The preceding configuration sample is using simplified configuration. For more information, see [Simplified Configuration](../simplified-configuration.md). + + This behavior can be configured in code as shown in the following example. + + ```csharp + host.Description.Behaviors.Add(new WorkflowUnhandledExceptionBehavior { Action = WorkflowUnhandledExceptionAction.AbandonAndSuspend }); + ``` + + The `action` attribute of the `` element can be set to one of the following values: + + **abandon** + Aborts the instance in memory without touching the persisted instance state (that is, roll back to the last persist point). + + **abandonAndSuspend** + Aborts the instance in memory and updates the persisted instance to be suspended. + + **cancel** + Calls cancellation handlers for the instance and then completes the instance in memory, which may also remove it from the instance store + + **terminate** + Completes the instance in memory and removes it from the instance store. + + For more information about , see [Workflow Service Host Extensibility](workflow-service-host-extensibility.md). + ## See also - [Workflow Service Host Extensibility](workflow-service-host-extensibility.md) diff --git a/docs/framework/wcf/feature-details/configuration-based-activation-in-iis-and-was.md b/docs/framework/wcf/feature-details/configuration-based-activation-in-iis-and-was.md index 83fd726e0174b..d6a7a028c03b0 100644 --- a/docs/framework/wcf/feature-details/configuration-based-activation-in-iis-and-was.md +++ b/docs/framework/wcf/feature-details/configuration-based-activation-in-iis-and-was.md @@ -10,10 +10,10 @@ Normally when hosting a Windows Communication Foundation (WCF) service under Int ## Configuration-Based Activation -Configuration-based activation takes the metadata that used to be placed in the .svc file and places it in the Web.config file. Within the<`serviceHostingEnvironment`> element there is a <`serviceActivations`> element. Within the <`serviceActivations`> element are one or more <`add`> elements, one for each hosted service. The <`add`> element contains attributes that let you set the relative address for the service and the service type or a service host factory. The following configuration example code shows how this section is used. +Configuration-based activation takes the metadata that used to be placed in the .svc file and places it in the Web.config file. Within the`` element there is a `` element. Within the `` element are one or more `` elements, one for each hosted service. The `` element contains attributes that let you set the relative address for the service and the service type or a service host factory. The following configuration example code shows how this section is used. > [!NOTE] -> Each <`add`> element must specify a service or a factory attribute. Specifying both service and factory attributes is allowed. +> Each `` element must specify a service or a factory attribute. Specifying both service and factory attributes is allowed. ```xml diff --git a/docs/framework/wcf/feature-details/configuring-discovery-in-a-configuration-file.md b/docs/framework/wcf/feature-details/configuring-discovery-in-a-configuration-file.md index b3ad61a3f70be..7f9a9e476af68 100644 --- a/docs/framework/wcf/feature-details/configuring-discovery-in-a-configuration-file.md +++ b/docs/framework/wcf/feature-details/configuring-discovery-in-a-configuration-file.md @@ -6,273 +6,273 @@ ms.topic: how-to --- # Configuring Discovery in a Configuration File -There are four major groups of configuration settings used in discovery. This topic will briefly describe each and show examples of how to configure them. Following each section will be a link to more in-depth documentation about each area. - -## Behavior Configuration - - Discovery uses service behaviors and endpoint behaviors. The behavior enables discovery for all of a service's endpoints and allows you to specify announcement endpoints. The following example shows how to add the and specify an announcement endpoint. - -```xml - - - - - - - - - - - -``` - - Once you specify the behavior, reference it from a <`service`> element as shown in the following sample. - -```xml - - - - - - - - - - -``` - - In order for a service to be discoverable, you must also add a discovery endpoint, the example above adds a standard endpoint. - - When you add announcement endpoints you must also add an announcement listener service to the <`services`> element as shown in the following example. - -```xml - - - - - - - - - - - +There are four major groups of configuration settings used in discovery. This topic will briefly describe each and show examples of how to configure them. Following each section will be a link to more in-depth documentation about each area. + +## Behavior Configuration + + Discovery uses service behaviors and endpoint behaviors. The behavior enables discovery for all of a service's endpoints and allows you to specify announcement endpoints. The following example shows how to add the and specify an announcement endpoint. + +```xml + + + + + + + + + + + +``` + + Once you specify the behavior, reference it from a `` element as shown in the following sample. + +```xml + + + + + + + + + + +``` + + In order for a service to be discoverable, you must also add a discovery endpoint, the example above adds a standard endpoint. + + When you add announcement endpoints you must also add an announcement listener service to the `` element as shown in the following example. + +```xml + + + + + + + + + + + -``` - - The behavior is used to enable or disable discovery of a specific endpoint. The following example configures a service with two application endpoints, one with discovery enabled and one with discovery disabled. For each endpoint an behavior is added. - -```xml - - - - - - behavior is used to enable or disable discovery of a specific endpoint. The following example configures a service with two application endpoints, one with discovery enabled and one with discovery disabled. For each endpoint an behavior is added. + +```xml + + + + + + - - - - - - - - - - - - - - - - - - - - - - - -``` - - The behavior can also be used to add custom metadata to the endpoint metadata returned by the service. The following example shows how to do this. - -```xml - - - - This is custom metadata. - i:PrintBasic - - This is a nested custom metadata. - - - - -``` - - The behavior can also be used to add scopes and types that clients use to search for services. The following example shows how to do this in a client side configuration file. - -```xml - - - - - - - - - - - - -``` - - For more information about and see [WCF Discovery Overview](wcf-discovery-overview.md). - -## Binding Element Configuration - - Binding element configuration is most interesting on the client side. You can use configuration to specify the find criteria used to discover services from a WCF client application. The following example creates a custom binding with the channel and specifies find criteria that includes a type and scope. In addition it specifies values for the and properties. - -```xml - - - - - - - - - - - - + behaviorConfiguration="ep0Behavior" /> + + + + + + + + + + + + + + + + + + + + + + + +``` + + The behavior can also be used to add custom metadata to the endpoint metadata returned by the service. The following example shows how to do this. + +```xml + + + + This is custom metadata. + i:PrintBasic + + This is a nested custom metadata. + + + + +``` + + The behavior can also be used to add scopes and types that clients use to search for services. The following example shows how to do this in a client side configuration file. + +```xml + + + + + + + + + + + + +``` + + For more information about and see [WCF Discovery Overview](wcf-discovery-overview.md). + +## Binding Element Configuration + + Binding element configuration is most interesting on the client side. You can use configuration to specify the find criteria used to discover services from a WCF client application. The following example creates a custom binding with the channel and specifies find criteria that includes a type and scope. In addition it specifies values for the and properties. + +```xml + + + + + + + + + + + + - - - - + + + + - -``` - - This custom binding configuration must be referenced by a client endpoint: - -```xml - - - -``` - - For more information about find criteria see [Discovery Find and FindCriteria](discovery-find-and-findcriteria.md). For more information about discovery and binding elements see, [WCF Discovery Overview](wcf-discovery-overview.md) - -## Standard Endpoint Configuration - - Standard endpoints are predefined endpoints that have default values for one or more properties (address, binding, or contract) or one or more property values that cannot change. .NET 4 ships with 3 discovery related standard endpoints: , , and . The is a standard endpoint that is pre-configured for discovery operations over a UDP multicast binding. The is a standard endpoint that is pre-configured to send announcement messages over a UDP binding. The is a standard endpoint that uses discovery to find the endpoint address of a discovered service dynamically at run time. Standard bindings are specified with an <`endpoint`> element that contains kind attribute that specified the type of standard endpoint to add. The following example shows how to add a and a . - -```xml - - + +``` + + This custom binding configuration must be referenced by a client endpoint: + +```xml + + + +``` + + For more information about find criteria see [Discovery Find and FindCriteria](discovery-find-and-findcriteria.md). For more information about discovery and binding elements see, [WCF Discovery Overview](wcf-discovery-overview.md) + +## Standard Endpoint Configuration + + Standard endpoints are predefined endpoints that have default values for one or more properties (address, binding, or contract) or one or more property values that cannot change. .NET 4 ships with 3 discovery related standard endpoints: , , and . The is a standard endpoint that is pre-configured for discovery operations over a UDP multicast binding. The is a standard endpoint that is pre-configured to send announcement messages over a UDP binding. The is a standard endpoint that uses discovery to find the endpoint address of a discovered service dynamically at run time. Standard bindings are specified with an `` element that contains kind attribute that specified the type of standard endpoint to add. The following example shows how to add a and a . + +```xml + + - - - - - - -``` - - Standard endpoints are configured in a <`standardEndpoints`> element. The following example shows how to configure the and the . - -```xml - - + + + + + + +``` + + Standard endpoints are configured in a `` element. The following example shows how to configure the and the . + +```xml + + - - - - - - - + maxAnnouncementDelay="00:00:00.800"> + + + + + + + -``` - - Once you've added the standard endpoint configuration, reference the configuration in the <`endpoint`> element for each endpoint as shown in the following sample. - -```xml - - +``` + + Once you've added the standard endpoint configuration, reference the configuration in the `` element for each endpoint as shown in the following sample. + +```xml + + - - - - - - -``` - - Unlike the other standard endpoints used in discovery, you specify a binding and contract for . The following example shows how to add and configure a . - -```xml - - - + + + + + + +``` + + Unlike the other standard endpoints used in discovery, you specify a binding and contract for . The following example shows how to add and configure a . + +```xml + + + - - - - - - - - - - - - + + + + + + + + + + + + This is custom metadata. - - - - - - - -``` - + + + + + + + +``` + For more information about standard endpoints see [Standard Endpoints](standard-endpoints.md). diff --git a/docs/framework/wcf/feature-details/hosting-workflow-services.md b/docs/framework/wcf/feature-details/hosting-workflow-services.md index 963b6c76dcbae..b39147516ad38 100644 --- a/docs/framework/wcf/feature-details/hosting-workflow-services.md +++ b/docs/framework/wcf/feature-details/hosting-workflow-services.md @@ -40,7 +40,7 @@ A workflow service must be hosted for it to respond to incoming messages. Workfl - Place an assembly in the IIS/WAS virtual directory that contains an activity that uses the WCF messaging activities. - A .xamlx file that defines a workflow service must contain a <`Service`> root element or a root element that contains any type derived from . When using the Visual Studio activity template, a .xamlx file is created. When using the WCF Workflow Service template, a .xamlx file is created. + A .xamlx file that defines a workflow service must contain a `` root element or a root element that contains any type derived from . When using the Visual Studio activity template, a .xamlx file is created. When using the WCF Workflow Service template, a .xamlx file is created. ## Hosting Workflow Services under Windows Server App Fabric @@ -48,7 +48,7 @@ A workflow service must be hosted for it to respond to incoming messages. Workfl ## Referencing Custom Activities - References to custom activities must be added to the <`Assemblies`> section under <`System.Web.Compilation`> so that they are loaded into the Application Domain and the XAML deserializer is able to locate the types. These settings can be made at the application level or in the root Web.config if the settings should be applied to all applications on the machine. + References to custom activities must be added to the `` section under `` so that they are loaded into the Application Domain and the XAML deserializer is able to locate the types. These settings can be made at the application level or in the root Web.config if the settings should be applied to all applications on the machine. ## Deployment diff --git a/docs/framework/wcf/feature-details/how-to-call-wcf-service-operations-asynchronously.md b/docs/framework/wcf/feature-details/how-to-call-wcf-service-operations-asynchronously.md index 4bc92835d30ae..e2823cf285a0b 100644 --- a/docs/framework/wcf/feature-details/how-to-call-wcf-service-operations-asynchronously.md +++ b/docs/framework/wcf/feature-details/how-to-call-wcf-service-operations-asynchronously.md @@ -2,63 +2,63 @@ title: "How to: Call WCF Service Operations Asynchronously" description: Learn how to create a WCF client that can access a service operation asynchronously by using the event-driven asynchronous calling model. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 0face17f-43ca-417b-9b33-737c0fc360df --- # How to: Call WCF Service Operations Asynchronously -This article covers how a client can access a service operation asynchronously. The service in this article implements the `ICalculator` interface. The client can call the operations on this interface asynchronously by using the event-driven asynchronous calling model. (For more information about the event-based asynchronous calling model, see [Multithreaded Programming with the Event-based Asynchronous Pattern](../../../standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-eap.md)). For an example that shows how to implement an operation asynchronously in a service, see [How to: Implement an Asynchronous Service Operation](../how-to-implement-an-asynchronous-service-operation.md). For more information about synchronous and asynchronous operations, see [Synchronous and Asynchronous Operations](../synchronous-and-asynchronous-operations.md). - +This article covers how a client can access a service operation asynchronously. The service in this article implements the `ICalculator` interface. The client can call the operations on this interface asynchronously by using the event-driven asynchronous calling model. (For more information about the event-based asynchronous calling model, see [Multithreaded Programming with the Event-based Asynchronous Pattern](../../../standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-eap.md)). For an example that shows how to implement an operation asynchronously in a service, see [How to: Implement an Asynchronous Service Operation](../how-to-implement-an-asynchronous-service-operation.md). For more information about synchronous and asynchronous operations, see [Synchronous and Asynchronous Operations](../synchronous-and-asynchronous-operations.md). + > [!NOTE] -> The event-driven asynchronous calling model is not supported when using a . For information about making asynchronous calls using the , see [How to: Call Operations Asynchronously Using a Channel Factory](how-to-call-operations-asynchronously-using-a-channel-factory.md). - -## Procedure - -#### To call WCF service operations asynchronously - -1. Run the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) tool with both the `/async` and the `/tcv:Version35` command options together as shown in the following command. - +> The event-driven asynchronous calling model is not supported when using a . For information about making asynchronous calls using the , see [How to: Call Operations Asynchronously Using a Channel Factory](how-to-call-operations-asynchronously-using-a-channel-factory.md). + +## Procedure + +#### To call WCF service operations asynchronously + +1. Run the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) tool with both the `/async` and the `/tcv:Version35` command options together as shown in the following command. + ```console - svcutil /n:http://Microsoft.ServiceModel.Samples,Microsoft.ServiceModel.Samples http://localhost:8000/servicemodelsamples/service/mex /a /tcv:Version35 - ``` - - This generates, in addition to the synchronous and standard delegate-based asynchronous operations, a WCF client class that contains: - - - Two <`operationName`>`Async` operations for use with the event-based asynchronous calling approach. For example: - + svcutil /n:http://Microsoft.ServiceModel.Samples,Microsoft.ServiceModel.Samples http://localhost:8000/servicemodelsamples/service/mex /a /tcv:Version35 + ``` + + This generates, in addition to the synchronous and standard delegate-based asynchronous operations, a WCF client class that contains: + + - Two ```Async` operations for use with the event-based asynchronous calling approach. For example: + [!code-csharp[EventAsync#1](../../../../samples/snippets/csharp/VS_Snippets_CFX/eventasync/cs/generatedclient.cs#1)] - [!code-vb[EventAsync#1](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/generatedclient.vb#1)] - - - Operation completed events of the form <`operationName`>`Completed` for use with the event-based asynchronous calling approach. For example: - + [!code-vb[EventAsync#1](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/generatedclient.vb#1)] + + - Operation completed events of the form ```Completed` for use with the event-based asynchronous calling approach. For example: + [!code-csharp[EventAsync#2](../../../../samples/snippets/csharp/VS_Snippets_CFX/eventasync/cs/generatedclient.cs#2)] - [!code-vb[EventAsync#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/generatedclient.vb#2)] - - - types for each operation (of the form <`operationName`>`CompletedEventArgs`) for use with the event-based asynchronous calling approach. For example: - + [!code-vb[EventAsync#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/generatedclient.vb#2)] + + - types for each operation (of the form ```CompletedEventArgs`) for use with the event-based asynchronous calling approach. For example: + [!code-csharp[EventAsync#3](../../../../samples/snippets/csharp/VS_Snippets_CFX/eventasync/cs/generatedclient.cs#3)] - [!code-vb[EventAsync#3](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/generatedclient.vb#3)] - -2. In the calling application, create a callback method to be called when the asynchronous operation is complete, as shown in the following sample code. - + [!code-vb[EventAsync#3](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/generatedclient.vb#3)] + +2. In the calling application, create a callback method to be called when the asynchronous operation is complete, as shown in the following sample code. + [!code-csharp[EventAsync#4](../../../../samples/snippets/csharp/VS_Snippets_CFX/eventasync/cs/client.cs#4)] - [!code-vb[EventAsync#4](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/client.vb#4)] - -3. Prior to calling the operation, use a new generic of type <`operationName`>`EventArgs` to add the handler method (created in the preceding step) to the <`operationName`>`Completed` event. Then call the <`operationName`>`Async` method. For example: - + [!code-vb[EventAsync#4](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/client.vb#4)] + +3. Prior to calling the operation, use a new generic of type ```EventArgs` to add the handler method (created in the preceding step) to the ```Completed` event. Then call the ```Async` method. For example: + [!code-csharp[EventAsync#5](../../../../samples/snippets/csharp/VS_Snippets_CFX/eventasync/cs/client.cs#5)] - [!code-vb[EventAsync#5](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/client.vb#5)] - -## Example - + [!code-vb[EventAsync#5](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/client.vb#5)] + +## Example + > [!NOTE] -> The design guidelines for the event-based asynchronous model state that if more than one value is returned, one value is returned as the `Result` property and the others are returned as properties on the object. One result of this is that if a client imports metadata using the event-based asynchronous command options and the operation returns more than one value, the default object returns one value as the `Result` property and the remainder are properties of the object.If you want to receive the message object as the `Result` property and have the returned values as properties on that object, use the `/messageContract` command option. This generates a signature that returns the response message as the `Result` property on the object. All internal return values are then properties of the response message object. - +> The design guidelines for the event-based asynchronous model state that if more than one value is returned, one value is returned as the `Result` property and the others are returned as properties on the object. One result of this is that if a client imports metadata using the event-based asynchronous command options and the operation returns more than one value, the default object returns one value as the `Result` property and the remainder are properties of the object.If you want to receive the message object as the `Result` property and have the returned values as properties on that object, use the `/messageContract` command option. This generates a signature that returns the response message as the `Result` property on the object. All internal return values are then properties of the response message object. + [!code-csharp[EventAsync#6](../../../../samples/snippets/csharp/VS_Snippets_CFX/eventasync/cs/client.cs#6)] - [!code-vb[EventAsync#6](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/client.vb#6)] - + [!code-vb[EventAsync#6](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/eventasync/vb/client.vb#6)] + ## See also - [How to: Implement an Asynchronous Service Operation](../how-to-implement-an-asynchronous-service-operation.md) diff --git a/docs/framework/wcf/feature-details/how-to-configure-a-local-issuer.md b/docs/framework/wcf/feature-details/how-to-configure-a-local-issuer.md index d566d96d05fc9..c84c412e661b7 100644 --- a/docs/framework/wcf/feature-details/how-to-configure-a-local-issuer.md +++ b/docs/framework/wcf/feature-details/how-to-configure-a-local-issuer.md @@ -63,9 +63,9 @@ Windows Communication Foundation (WCF) uses a local issuer in cases where the is 3. Set the `binding` and `bindingConfiguration` attributes to values that reference the appropriate binding to use when communicating with the local issuer endpoint. -4. Optional. Set the [\](../../configure-apps/file-schema/wcf/identity.md) element as a child of the <`localIssuer`> element and specify identity information for the local issuer. +4. Optional. Set the [\](../../configure-apps/file-schema/wcf/identity.md) element as a child of the `` element and specify identity information for the local issuer. -5. Optional. Set the [\](../../configure-apps/file-schema/wcf/headers.md) element as a child of the <`localIssuer`> element and specify additional headers that are required in order to correctly address the local issuer. +5. Optional. Set the [\](../../configure-apps/file-schema/wcf/headers.md) element as a child of the `` element and specify additional headers that are required in order to correctly address the local issuer. ## .NET Framework Security diff --git a/docs/framework/wcf/feature-details/how-to-configure-credentials-on-a-federation-service.md b/docs/framework/wcf/feature-details/how-to-configure-credentials-on-a-federation-service.md index cfb884509e51e..b526dc1523fb7 100644 --- a/docs/framework/wcf/feature-details/how-to-configure-credentials-on-a-federation-service.md +++ b/docs/framework/wcf/feature-details/how-to-configure-credentials-on-a-federation-service.md @@ -2,72 +2,72 @@ description: "Learn more about: How to: Configure Credentials on a Federation Service" title: "How to: Configure Credentials on a Federation Service" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "WCF, federation" - "federation" ms.assetid: 149ab165-0ef3-490a-83a9-4322a07bd98a --- # How to: Configure Credentials on a Federation Service -In Windows Communication Foundation (WCF), creating a federated service consists of the following main procedures: - -1. Configuring a or similar custom binding. For more information about creating an appropriate binding, see [How to: Create a WSFederationHttpBinding](how-to-create-a-wsfederationhttpbinding.md). - -2. Configuring the that controls how issued tokens presented to the service are authenticated. - - This topic provides details about the second step. For more information about how a federated service works, see [Federation](federation.md). - -### To set the properties of IssuedTokenServiceCredential in code - -1. Use the property of the class to return a reference to an instance. The property is accessed from the property of the class. - -2. Set the property to `true` if self-issued tokens such as CardSpace cards are to be authenticated. The default is `false`. - -3. Populate the collection returned by the property with instances of the class. Each instance represents an issuer from which the service will authenticate tokens. - +In Windows Communication Foundation (WCF), creating a federated service consists of the following main procedures: + +1. Configuring a or similar custom binding. For more information about creating an appropriate binding, see [How to: Create a WSFederationHttpBinding](how-to-create-a-wsfederationhttpbinding.md). + +2. Configuring the that controls how issued tokens presented to the service are authenticated. + + This topic provides details about the second step. For more information about how a federated service works, see [Federation](federation.md). + +### To set the properties of IssuedTokenServiceCredential in code + +1. Use the property of the class to return a reference to an instance. The property is accessed from the property of the class. + +2. Set the property to `true` if self-issued tokens such as CardSpace cards are to be authenticated. The default is `false`. + +3. Populate the collection returned by the property with instances of the class. Each instance represents an issuer from which the service will authenticate tokens. + > [!NOTE] - > Unlike the client-side collection returned by the property, the known certificates collection is not a keyed collection. The service accepts the tokens that the specified certificates issue regardless of the address of the client that sent the message containing the issued token (subject to the further constraints, which are described later in this topic). - -4. Set the property to one of the enumeration values. This can be done only in code. The default is . - -5. If the property is set to , then assign an instance of the custom class to the property. - -6. If the is set to `ChainTrust` or `PeerOrChainTrust`, set the property to an appropriate value from the enumeration. Note that the revocation mode is not used in `PeerTrust` or `Custom` validation modes. - -7. If needed, assign an instance of a custom class to the property. A custom Security Assertions Markup Language (SAML) serializer is needed, for example, for parsing custom SAML assertions. - -### To set the properties of IssuedTokenServiceCredential in configuration - -1. Create an `` element as a child of a <`serviceCredentials`> element. - -2. Set the `allowUntrustedRsaIssuers` attribute of the `` element to `true` if authenticating a self-issued token, such as a CardSpace card. - -3. Create a `` element as a child of the `` element. - -4. Create zero or more `` elements as children of the `` element, and specify how to locate the certificate using the `storeLocation`, `storeName`, `x509FindType`, and `findValue` attributes. - -5. If necessary, set the `samlSerializer` attribute of the <`issuedTokenAuthentication`> element to the type name of the custom class. - -## Example - - The following example sets the properties of an in code. - + > Unlike the client-side collection returned by the property, the known certificates collection is not a keyed collection. The service accepts the tokens that the specified certificates issue regardless of the address of the client that sent the message containing the issued token (subject to the further constraints, which are described later in this topic). + +4. Set the property to one of the enumeration values. This can be done only in code. The default is . + +5. If the property is set to , then assign an instance of the custom class to the property. + +6. If the is set to `ChainTrust` or `PeerOrChainTrust`, set the property to an appropriate value from the enumeration. Note that the revocation mode is not used in `PeerTrust` or `Custom` validation modes. + +7. If needed, assign an instance of a custom class to the property. A custom Security Assertions Markup Language (SAML) serializer is needed, for example, for parsing custom SAML assertions. + +### To set the properties of IssuedTokenServiceCredential in configuration + +1. Create an `` element as a child of a `` element. + +2. Set the `allowUntrustedRsaIssuers` attribute of the `` element to `true` if authenticating a self-issued token, such as a CardSpace card. + +3. Create a `` element as a child of the `` element. + +4. Create zero or more `` elements as children of the `` element, and specify how to locate the certificate using the `storeLocation`, `storeName`, `x509FindType`, and `findValue` attributes. + +5. If necessary, set the `samlSerializer` attribute of the `` element to the type name of the custom class. + +## Example + + The following example sets the properties of an in code. + [!code-csharp[C_FederatedService#2](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_federatedservice/cs/source.cs#2)] - [!code-vb[C_FederatedService#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federatedservice/vb/source.vb#2)] - - In order for a federated service to authenticate a client, the following must be true about the issued token: - -- When the issued token’s digital signature uses an RSA security key identifier, the property must be `true`. - -- When the issued token’s signature uses an X.509 issuer serial number, X.509 subject key identifier, or X.509 thumbprint security identifier, the issued token must be signed by a certificate in the collection returned by the property of the class. - -- When the issued token is signed using an X.509 certificate, the certificate must validate per the semantics specified by the value of the property, regardless of whether the certificate was sent to the relying party as a or was obtained from the property. For more information about X.509 certificate validation, see [Working with Certificates](working-with-certificates.md). - - For example, setting the to would authenticate any issued token whose signing certificate is in the `TrustedPeople` certificate store. In that case, set the property to either or . You can select other modes, including . When `Custom` is selected, you must assign an instance of the class to the property. The custom validator can validate certificates using any criteria it likes. For more information, see [How to: Create a Service that Employs a Custom Certificate Validator](../extending/how-to-create-a-service-that-employs-a-custom-certificate-validator.md). - + [!code-vb[C_FederatedService#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federatedservice/vb/source.vb#2)] + + In order for a federated service to authenticate a client, the following must be true about the issued token: + +- When the issued token’s digital signature uses an RSA security key identifier, the property must be `true`. + +- When the issued token’s signature uses an X.509 issuer serial number, X.509 subject key identifier, or X.509 thumbprint security identifier, the issued token must be signed by a certificate in the collection returned by the property of the class. + +- When the issued token is signed using an X.509 certificate, the certificate must validate per the semantics specified by the value of the property, regardless of whether the certificate was sent to the relying party as a or was obtained from the property. For more information about X.509 certificate validation, see [Working with Certificates](working-with-certificates.md). + + For example, setting the to would authenticate any issued token whose signing certificate is in the `TrustedPeople` certificate store. In that case, set the property to either or . You can select other modes, including . When `Custom` is selected, you must assign an instance of the class to the property. The custom validator can validate certificates using any criteria it likes. For more information, see [How to: Create a Service that Employs a Custom Certificate Validator](../extending/how-to-create-a-service-that-employs-a-custom-certificate-validator.md). + ## See also - [Federation](federation.md) diff --git a/docs/framework/wcf/feature-details/how-to-configure-idle-behavior-with-workflowservicehost.md b/docs/framework/wcf/feature-details/how-to-configure-idle-behavior-with-workflowservicehost.md index 8bf3d3b1ca8de..8531775a0ce0a 100644 --- a/docs/framework/wcf/feature-details/how-to-configure-idle-behavior-with-workflowservicehost.md +++ b/docs/framework/wcf/feature-details/how-to-configure-idle-behavior-with-workflowservicehost.md @@ -2,41 +2,41 @@ description: "Learn more about: How to: Configure Idle Behavior with WorkflowServiceHost" title: "How to: Configure Idle Behavior with WorkflowServiceHost" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 1bb93652-d687-46ff-bff6-69ecdcf97437 --- # How to: Configure Idle Behavior with WorkflowServiceHost -Workflows go idle when they encounter a bookmark that must be resumed by some external stimulus, for example when the workflow instance is waiting for a message to be delivered using a activity. is a behavior that allows you to specify the time between when a service instance goes idle and when the instance is persisted or unloaded. It contains two properties that enable you to set these time spans. specifies the time span between when a workflow service instance goes idle and when the workflow service instance is persisted. specifies the time span between when a workflow service instance goes idle and when the workflow service instance is unloaded, where unload means persisting the instance to the instance store and removing it from memory. This topic explains how to configure the in a configuration file. - -### To configure WorkflowIdleBehavior - -1. Add a <`workflowIdle`> element to the <`behavior`> element within the <`serviceBehaviors`> element as shown in the following example. - - ```xml - - - +Workflows go idle when they encounter a bookmark that must be resumed by some external stimulus, for example when the workflow instance is waiting for a message to be delivered using a activity. is a behavior that allows you to specify the time between when a service instance goes idle and when the instance is persisted or unloaded. It contains two properties that enable you to set these time spans. specifies the time span between when a workflow service instance goes idle and when the workflow service instance is persisted. specifies the time span between when a workflow service instance goes idle and when the workflow service instance is unloaded, where unload means persisting the instance to the instance store and removing it from memory. This topic explains how to configure the in a configuration file. + +### To configure WorkflowIdleBehavior + +1. Add a `` element to the `` element within the `` element as shown in the following example. + + ```xml + + + - - - - ``` - - The `timeToUnload` attribute specifies the time period between when a workflow service instance goes idle and when the workflow service is unloaded. The `timeToPersist` attribute specifies the time period between when a workflow service instance goes idle and when the workflow service instance is persisted. The default value for `timeToUnload` is 1 minute. The default value for `timeToPersist` is . If you want to keep idle instances in memory but persist them for robustness, set values so that `timeToPersist` < `timeToUnload`. If you want to prevent idle instances from being unloaded, set `timeToUnload` to . For more information about , see [Workflow Service Host Extensibility](workflow-service-host-extensibility.md) - + + + + ``` + + The `timeToUnload` attribute specifies the time period between when a workflow service instance goes idle and when the workflow service is unloaded. The `timeToPersist` attribute specifies the time period between when a workflow service instance goes idle and when the workflow service instance is persisted. The default value for `timeToUnload` is 1 minute. The default value for `timeToPersist` is . If you want to keep idle instances in memory but persist them for robustness, set values so that `timeToPersist` < `timeToUnload`. If you want to prevent idle instances from being unloaded, set `timeToUnload` to . For more information about , see [Workflow Service Host Extensibility](workflow-service-host-extensibility.md) + > [!NOTE] - > The preceding configuration sample is using simplified configuration. For more information, see [Simplified Configuration](../simplified-configuration.md). - -### To change idle behavior in code - -- The following example changes the time to wait before persisting and unloading programmatically. - + > The preceding configuration sample is using simplified configuration. For more information, see [Simplified Configuration](../simplified-configuration.md). + +### To change idle behavior in code + +- The following example changes the time to wait before persisting and unloading programmatically. + [!code-csharp[Wf_SvcHost_Idle_persist#1](../../../../samples/snippets/csharp/VS_Snippets_CFX/wf_svchost_idle_persist/cs/source.cs#1)] - [!code-vb[Wf_SvcHost_Idle_persist#1](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/wf_svchost_idle_persist/vb/source.vb#1)] - + [!code-vb[Wf_SvcHost_Idle_persist#1](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/wf_svchost_idle_persist/vb/source.vb#1)] + ## See also - [Workflow Service Host Extensibility](workflow-service-host-extensibility.md) diff --git a/docs/framework/wcf/feature-details/how-to-configure-persistence-with-workflowservicehost.md b/docs/framework/wcf/feature-details/how-to-configure-persistence-with-workflowservicehost.md index 8594c72478c6b..f2dfc54fa0942 100644 --- a/docs/framework/wcf/feature-details/how-to-configure-persistence-with-workflowservicehost.md +++ b/docs/framework/wcf/feature-details/how-to-configure-persistence-with-workflowservicehost.md @@ -9,7 +9,7 @@ This article describes how to configure the SQL Workflow Instance Store feature ## To Configure the SQL Workflow Instance Store in Configuration -1. The properties of the SQL workflow instance store can be configured through the , a service behavior that allows you to change the settings through XML configuration. The following configuration example shows how to configure the SQL workflow instance store by using the <`sqlWorkflowInstanceStore`> behavior element in a configuration file. +1. The properties of the SQL workflow instance store can be configured through the , a service behavior that allows you to change the settings through XML configuration. The following configuration example shows how to configure the SQL workflow instance store by using the `` behavior element in a configuration file. ```xml @@ -26,7 +26,7 @@ This article describes how to configure the SQL Workflow Instance Store feature ``` - For more information about how to configure the SQL workflow instance store, see [How to: Enable SQL Persistence for Workflows and Workflow Services](../../windows-workflow-foundation/how-to-enable-sql-persistence-for-workflows-and-workflow-services.md). For more information about the individual settings for the <`sqlWorkflowInstanceStore`> behavior element, see [SQL Workflow Instance Store](../../windows-workflow-foundation/sql-workflow-instance-store.md). + For more information about how to configure the SQL workflow instance store, see [How to: Enable SQL Persistence for Workflows and Workflow Services](../../windows-workflow-foundation/how-to-enable-sql-persistence-for-workflows-and-workflow-services.md). For more information about the individual settings for the `` behavior element, see [SQL Workflow Instance Store](../../windows-workflow-foundation/sql-workflow-instance-store.md). > [!NOTE] > The preceding configuration example uses simplified configuration. For more information, see [Simplified Configuration](../simplified-configuration.md) diff --git a/docs/framework/wcf/feature-details/how-to-configure-tracking-with-workflowservicehost.md b/docs/framework/wcf/feature-details/how-to-configure-tracking-with-workflowservicehost.md index 0e567be0983da..d6c067cbc03ab 100644 --- a/docs/framework/wcf/feature-details/how-to-configure-tracking-with-workflowservicehost.md +++ b/docs/framework/wcf/feature-details/how-to-configure-tracking-with-workflowservicehost.md @@ -6,64 +6,64 @@ ms.assetid: ed1485fe-7529-4351-bca3-8bb915260b17 --- # How to: Configure Tracking with WorkflowServiceHost -This topic explains how to configure tracking for a [!INCLUDE[netfx_current_long](../../../../includes/netfx-current-long-md.md)] workflow hosted in . It is configured through a Web.config file by specifying a service behavior. - -### Configure Tracking in Configuration - -1. Add the using the <`behavior`> element in a configuration file, as shown in the following example. - - ```xml - - - - +This topic explains how to configure tracking for a [!INCLUDE[netfx_current_long](../../../../includes/netfx-current-long-md.md)] workflow hosted in . It is configured through a Web.config file by specifying a service behavior. + +### Configure Tracking in Configuration + +1. Add the using the `` element in a configuration file, as shown in the following example. + + ```xml + + + + - - - ``` - + + + ``` + > [!NOTE] - > The preceding configuration sample is using simplified configuration. For more information, see [Simplified Configuration](../simplified-configuration.md). - - The preceding configuration sample adds a and specifies a tracking profile name. Tracking profiles are created in a <`trackingProfile`> element within a <`tracking`> element. The tracking profile contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at run time. The following example shows how to create a tracking profile. - - ```xml - + > The preceding configuration sample is using simplified configuration. For more information, see [Simplified Configuration](../simplified-configuration.md). + + The preceding configuration sample adds a and specifies a tracking profile name. Tracking profiles are created in a `` element within a `` element. The tracking profile contains tracking queries that permit a tracking participant to subscribe to workflow events that are emitted when the state of a workflow instance changes at run time. The following example shows how to create a tracking profile. + + ```xml + - - - - - - - - - - - + + + + + + + + + + + - - - ``` - - For more information about tracking profiles, see [Tracking Profiles](../../windows-workflow-foundation/tracking-profiles.md). - - For more information about tracking in general, see [Workflow Tracking and Tracing](../../windows-workflow-foundation/workflow-tracking-and-tracing.md). - -### Configure Tracking in Code - -1. Add the using the behavior in code, as shown in the following example. - - ```csharp - host.Description.Behaviors.Add(new EtwTrackingBehavior { ProfileName = "Sample Tracking Profile" }); - ``` - - The preceding code sample adds a and specifies a tracking profile name. Tracking profiles are created in a <`trackingProfile`> element within a <`tracking`> element as shown in the previous section. - - For more information about tracking profiles, see [Tracking Profiles](../../windows-workflow-foundation/tracking-profiles.md). - - For more information about tracking in general, see [Workflow Tracking and Tracing](../../windows-workflow-foundation/workflow-tracking-and-tracing.md). For an example of configuring tracking programmatically see [Configuring Tracking for a Workflow](../../windows-workflow-foundation/configuring-tracking-for-a-workflow.md). - + + + ``` + + For more information about tracking profiles, see [Tracking Profiles](../../windows-workflow-foundation/tracking-profiles.md). + + For more information about tracking in general, see [Workflow Tracking and Tracing](../../windows-workflow-foundation/workflow-tracking-and-tracing.md). + +### Configure Tracking in Code + +1. Add the using the behavior in code, as shown in the following example. + + ```csharp + host.Description.Behaviors.Add(new EtwTrackingBehavior { ProfileName = "Sample Tracking Profile" }); + ``` + + The preceding code sample adds a and specifies a tracking profile name. Tracking profiles are created in a `` element within a `` element as shown in the previous section. + + For more information about tracking profiles, see [Tracking Profiles](../../windows-workflow-foundation/tracking-profiles.md). + + For more information about tracking in general, see [Workflow Tracking and Tracing](../../windows-workflow-foundation/workflow-tracking-and-tracing.md). For an example of configuring tracking programmatically see [Configuring Tracking for a Workflow](../../windows-workflow-foundation/configuring-tracking-for-a-workflow.md). + ## See also - [Simplified Configuration for WCF Services](../samples/simplified-configuration-for-wcf-services.md) diff --git a/docs/framework/wcf/feature-details/how-to-create-a-federated-client.md b/docs/framework/wcf/feature-details/how-to-create-a-federated-client.md index 38be02de5050d..621d37cf020ce 100644 --- a/docs/framework/wcf/feature-details/how-to-create-a-federated-client.md +++ b/docs/framework/wcf/feature-details/how-to-create-a-federated-client.md @@ -2,164 +2,164 @@ description: "Learn more about: How to: Create a Federated Client" title: "How to: Create a Federated Client" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "WCF, federation" - "federation" ms.assetid: 56ece47e-98bf-4346-b92b-fda1fc3b4d9c --- # How to: Create a Federated Client -In Windows Communication Foundation (WCF), creating a client for a *federated service* consists of three main steps: - -1. Configure a [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md) or similar custom binding. For more information about creating an appropriate binding, see [How to: Create a WSFederationHttpBinding](how-to-create-a-wsfederationhttpbinding.md). Alternatively, run the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) against the metadata endpoint of the federated service to generate a configuration file for communicating with the federated service and one or more security token services. - -2. Set the properties of the that controls various aspects of a client's interaction with a security token service. - -3. Set the properties of the , which allows certificates needed to communicate securely with given endpoints, such as security token services. - +In Windows Communication Foundation (WCF), creating a client for a *federated service* consists of three main steps: + +1. Configure a [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md) or similar custom binding. For more information about creating an appropriate binding, see [How to: Create a WSFederationHttpBinding](how-to-create-a-wsfederationhttpbinding.md). Alternatively, run the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) against the metadata endpoint of the federated service to generate a configuration file for communicating with the federated service and one or more security token services. + +2. Set the properties of the that controls various aspects of a client's interaction with a security token service. + +3. Set the properties of the , which allows certificates needed to communicate securely with given endpoints, such as security token services. + > [!NOTE] -> A might be thrown when a client uses impersonated credentials, the binding or a custom-issued token, and asymmetric keys. Asymmetric keys are used with the binding and custom-issued tokens when the and properties, respectively, are set to . The is thrown when the client attempts to send a message and a user profile doesn’t exist for the identity that the client is impersonating. To mitigate this issue, log on to the client computer or call `LoadUserProfile` before sending the message. - - This topic provides detailed information about these procedures. For more information about creating an appropriate binding, see [How to: Create a WSFederationHttpBinding](how-to-create-a-wsfederationhttpbinding.md). For more information about how a federated service works, see [Federation](federation.md). - -### To generate and examine the configuration for a federated service - -1. Run the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) with the address of the metadata URL of the service as a command-line parameter. - -2. Open the generated configuration file in an appropriate editor. - -3. Examine the attributes and content of any generated [\](../../configure-apps/file-schema/wcf/issuer.md) and [\](../../configure-apps/file-schema/wcf/issuermetadata.md) elements. These are located within the [\](../../configure-apps/file-schema/wcf/security-of-wsfederationhttpbinding.md) elements for the [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md) or custom bindings elements. Ensure that the addresses contain the expected domain names or other address information. It is important to check this information because the client authenticates to these addresses and may disclose information such as user name/password pairs. If the address is not the expected address, this could result in information disclosure to an unintended recipient. - -4. Examine any additional [\](../../configure-apps/file-schema/wcf/issuedtokenparameters.md) elements inside the commented out <`alternativeIssuedTokenParameters`> element. When using the Svcutil.exe tool to generate configuration for a federated service, if the federated service or any intermediate security token services do not specify an issuer address, but rather specify a metadata address for a security token service that exposes multiple endpoints, the resulting configuration file refers to the first endpoint. Additional endpoints are in the configuration file as commented-out <`alternativeIssuedTokenParameters`> elements. - - Determine whether one of these <`issuedTokenParameters`> is preferable to the one already present in the configuration. For example, the client may prefer to authenticate to a security token service using a Windows CardSpace token rather than a user name/password pair. - +> A might be thrown when a client uses impersonated credentials, the binding or a custom-issued token, and asymmetric keys. Asymmetric keys are used with the binding and custom-issued tokens when the and properties, respectively, are set to . The is thrown when the client attempts to send a message and a user profile doesn’t exist for the identity that the client is impersonating. To mitigate this issue, log on to the client computer or call `LoadUserProfile` before sending the message. + + This topic provides detailed information about these procedures. For more information about creating an appropriate binding, see [How to: Create a WSFederationHttpBinding](how-to-create-a-wsfederationhttpbinding.md). For more information about how a federated service works, see [Federation](federation.md). + +### To generate and examine the configuration for a federated service + +1. Run the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) with the address of the metadata URL of the service as a command-line parameter. + +2. Open the generated configuration file in an appropriate editor. + +3. Examine the attributes and content of any generated [\](../../configure-apps/file-schema/wcf/issuer.md) and [\](../../configure-apps/file-schema/wcf/issuermetadata.md) elements. These are located within the [\](../../configure-apps/file-schema/wcf/security-of-wsfederationhttpbinding.md) elements for the [\](../../configure-apps/file-schema/wcf/wsfederationhttpbinding.md) or custom bindings elements. Ensure that the addresses contain the expected domain names or other address information. It is important to check this information because the client authenticates to these addresses and may disclose information such as user name/password pairs. If the address is not the expected address, this could result in information disclosure to an unintended recipient. + +4. Examine any additional [\](../../configure-apps/file-schema/wcf/issuedtokenparameters.md) elements inside the commented out `` element. When using the Svcutil.exe tool to generate configuration for a federated service, if the federated service or any intermediate security token services do not specify an issuer address, but rather specify a metadata address for a security token service that exposes multiple endpoints, the resulting configuration file refers to the first endpoint. Additional endpoints are in the configuration file as commented-out `` elements. + + Determine whether one of these `` is preferable to the one already present in the configuration. For example, the client may prefer to authenticate to a security token service using a Windows CardSpace token rather than a user name/password pair. + > [!NOTE] - > Where multiple security token services must be traversed before communicating with the service, it is possible for an intermediate security token service to direct the client to an incorrect security token service. Therefore, ensure that the endpoint for the security token service in the [\](../../configure-apps/file-schema/wcf/issuedtokenparameters.md) is the expected security token service and not an unknown security token service. - -### To configure an IssuedTokenClientCredential in code - -1. Access the through the property of the class (returned by the property of the class, or through the class), as shown in the following example code. - + > Where multiple security token services must be traversed before communicating with the service, it is possible for an intermediate security token service to direct the client to an incorrect security token service. Therefore, ensure that the endpoint for the security token service in the [\](../../configure-apps/file-schema/wcf/issuedtokenparameters.md) is the expected security token service and not an unknown security token service. + +### To configure an IssuedTokenClientCredential in code + +1. Access the through the property of the class (returned by the property of the class, or through the class), as shown in the following example code. + [!code-csharp[c_CreateSTS#9](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_creatests/cs/source.cs#9)] - [!code-vb[c_CreateSTS#9](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#9)] - -2. If token caching is not required, set the property to `false`. The property controls whether such tokens from a security token service are cached. If this property is set to `false`, the client requests a new token from the security token service whenever it must re-authenticate itself to the federated service, regardless of whether a previous token is still valid. If this property is set to `true`, the client reuses an existing token whenever it must re-authenticate itself to the federated service (as long as the token has not expired). The default is `true`. - -3. If a time limit is required on cached tokens, set the property to a value. The property specifies how long a token can be cached. After the specified time span has elapsed, the token is removed from the client cache. By default, tokens are cached indefinitely. The following example sets the time span to 10 minutes. - + [!code-vb[c_CreateSTS#9](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#9)] + +2. If token caching is not required, set the property to `false`. The property controls whether such tokens from a security token service are cached. If this property is set to `false`, the client requests a new token from the security token service whenever it must re-authenticate itself to the federated service, regardless of whether a previous token is still valid. If this property is set to `true`, the client reuses an existing token whenever it must re-authenticate itself to the federated service (as long as the token has not expired). The default is `true`. + +3. If a time limit is required on cached tokens, set the property to a value. The property specifies how long a token can be cached. After the specified time span has elapsed, the token is removed from the client cache. By default, tokens are cached indefinitely. The following example sets the time span to 10 minutes. + [!code-csharp[c_CreateSTS#15](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_creatests/cs/source.cs#15)] - [!code-vb[c_CreateSTS#15](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#15)] - -4. Optional. Set the to a percentage. The default is 60 (percent). The property specifies a percentage of the token's validity period. For example, if the issued token is valid for 10 hours and is set to 80, then the token is renewed after eight hours. The following example sets the value to 80 percent. - + [!code-vb[c_CreateSTS#15](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#15)] + +4. Optional. Set the to a percentage. The default is 60 (percent). The property specifies a percentage of the token's validity period. For example, if the issued token is valid for 10 hours and is set to 80, then the token is renewed after eight hours. The following example sets the value to 80 percent. + [!code-csharp[c_CreateSTS#16](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_creatests/cs/source.cs#16)] - [!code-vb[c_CreateSTS#16](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#16)] - - The renewal interval determined by the token validity period and the `IssuedTokenRenewalThresholdPercentage` value is overridden by the `MaxIssuedTokenCachingTime` value in cases where the caching time is shorter than the renewal threshold time. For example, if the product of `IssuedTokenRenewalThresholdPercentage` and the token's duration is eight hours, and the `MaxIssuedTokenCachingTime` value is 10 minutes, the client contacts the security token service for an updated token every 10 minutes. - -5. If a key entropy mode other than is needed on a binding that does not use message security or transport security with message credentials (for example. the binding does not have a ), set the property to an appropriate value. The *entropy* mode determines whether symmetric keys can be controlled using the property. This default is , where both the client and the token issuer provide data that is combined to produce the actual key. Other values are and , which means the entire key is specified by the client or the server, respectively. The following example sets the property to use only the server data for the key. - + [!code-vb[c_CreateSTS#16](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#16)] + + The renewal interval determined by the token validity period and the `IssuedTokenRenewalThresholdPercentage` value is overridden by the `MaxIssuedTokenCachingTime` value in cases where the caching time is shorter than the renewal threshold time. For example, if the product of `IssuedTokenRenewalThresholdPercentage` and the token's duration is eight hours, and the `MaxIssuedTokenCachingTime` value is 10 minutes, the client contacts the security token service for an updated token every 10 minutes. + +5. If a key entropy mode other than is needed on a binding that does not use message security or transport security with message credentials (for example. the binding does not have a ), set the property to an appropriate value. The *entropy* mode determines whether symmetric keys can be controlled using the property. This default is , where both the client and the token issuer provide data that is combined to produce the actual key. Other values are and , which means the entire key is specified by the client or the server, respectively. The following example sets the property to use only the server data for the key. + [!code-csharp[c_CreateSTS#17](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_creatests/cs/source.cs#17)] - [!code-vb[c_CreateSTS#17](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#17)] - + [!code-vb[c_CreateSTS#17](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#17)] + > [!NOTE] - > If a is present in a security token service or service binding, the set on is overridden by the property of the `SecurityBindingElement`. - -6. Configure any issuer-specific endpoint behaviors by adding them to the collection returned by the property. - + > If a is present in a security token service or service binding, the set on is overridden by the property of the `SecurityBindingElement`. + +6. Configure any issuer-specific endpoint behaviors by adding them to the collection returned by the property. + [!code-csharp[c_CreateSTS#14](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_creatests/cs/source.cs#14)] - [!code-vb[c_CreateSTS#14](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#14)] - -### To configure the IssuedTokenClientCredential in configuration - -1. Create an [\](../../configure-apps/file-schema/wcf/issuedtoken.md) element as a child of the [\](../../configure-apps/file-schema/wcf/issuedtoken.md) element in an endpoint behavior. - -2. If token caching is not required, set the `cacheIssuedTokens` attribute (of the <`issuedToken`> element) to `false`. - -3. If a time limit is required on cached tokens, set the `maxIssuedTokenCachingTime` attribute on the <`issuedToken`> element to an appropriate value. For example: - `` - -4. If a value other than the default is preferred, set the `issuedTokenRenewalThresholdPercentage` attribute on the <`issuedToken`> element to an appropriate value, for example: - - ```xml - - ``` - -5. If a key entropy mode other than `CombinedEntropy` is on a binding that does not use message security or transport security with message credentials (for example, the binding does not have a `SecurityBindingElement`), set the `defaultKeyEntropyMode` attribute on the `` element to a either `ServerEntropy` or `ClientEntropy` as required. - - ```xml - - ``` - -6. Optional. Configure any issuer-specific custom endpoint behavior by creating an <`issuerChannelBehaviors`> element as a child of the <`issuedToken`> element. For each behavior, create an <`add`> element as a child of the <`issuerChannelBehaviors`> element. Specify the issuer address of the behavior by setting the `issuerAddress` attribute on the <`add`> element. Specify the behavior itself by setting the `behaviorConfiguration` attribute on the <`add`> element. - - ```xml - - - - ``` - -### To configure an X509CertificateRecipientClientCredential in code - -1. Access the through the property of the property of the class or the property. - + [!code-vb[c_CreateSTS#14](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#14)] + +### To configure the IssuedTokenClientCredential in configuration + +1. Create an [\](../../configure-apps/file-schema/wcf/issuedtoken.md) element as a child of the [\](../../configure-apps/file-schema/wcf/issuedtoken.md) element in an endpoint behavior. + +2. If token caching is not required, set the `cacheIssuedTokens` attribute (of the `` element) to `false`. + +3. If a time limit is required on cached tokens, set the `maxIssuedTokenCachingTime` attribute on the `` element to an appropriate value. For example: + `` + +4. If a value other than the default is preferred, set the `issuedTokenRenewalThresholdPercentage` attribute on the `` element to an appropriate value, for example: + + ```xml + + ``` + +5. If a key entropy mode other than `CombinedEntropy` is on a binding that does not use message security or transport security with message credentials (for example, the binding does not have a `SecurityBindingElement`), set the `defaultKeyEntropyMode` attribute on the `` element to a either `ServerEntropy` or `ClientEntropy` as required. + + ```xml + + ``` + +6. Optional. Configure any issuer-specific custom endpoint behavior by creating an `` element as a child of the `` element. For each behavior, create an `` element as a child of the `` element. Specify the issuer address of the behavior by setting the `issuerAddress` attribute on the `` element. Specify the behavior itself by setting the `behaviorConfiguration` attribute on the `` element. + + ```xml + + + + ``` + +### To configure an X509CertificateRecipientClientCredential in code + +1. Access the through the property of the property of the class or the property. + [!code-csharp[c_CreateSTS#18](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_creatests/cs/source.cs#18)] - [!code-vb[c_CreateSTS#18](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#18)] - -2. If an instance is available for the certificate for a given endpoint, use the method of the collection returned by the property. - + [!code-vb[c_CreateSTS#18](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#18)] + +2. If an instance is available for the certificate for a given endpoint, use the method of the collection returned by the property. + [!code-csharp[c_CreateSTS#19](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_creatests/cs/source.cs#19)] - [!code-vb[c_CreateSTS#19](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#19)] - -3. If an instance is not available, use the method of the class as shown in the following example. - + [!code-vb[c_CreateSTS#19](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#19)] + +3. If an instance is not available, use the method of the class as shown in the following example. + [!code-csharp[c_CreateSTS#20](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_creatests/cs/source.cs#20)] - [!code-vb[c_CreateSTS#20](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#20)] - -### To configure an X509CertificateRecipientClientCredential in configuration - -1. Create a [\](../../configure-apps/file-schema/wcf/scopedcertificates-element.md) element as a child of the [\](../../configure-apps/file-schema/wcf/servicecertificate-of-clientcredentials-element.md) element that is itself a child of the [\](../../configure-apps/file-schema/wcf/clientcredentials.md) element in an endpoint behavior. - -2. Create an `` element as a child of the `` element. Specify values for the `storeLocation`, `storeName`, `x509FindType`, and `findValue` attributes to refer to the appropriate certificate. Set the `targetUri` attribute to a value that provides the address of the endpoint that the certificate is to be used for, as shown in the following example. - - ```xml - + [!code-vb[c_CreateSTS#20](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_creatests/vb/source.vb#20)] + +### To configure an X509CertificateRecipientClientCredential in configuration + +1. Create a [\](../../configure-apps/file-schema/wcf/scopedcertificates-element.md) element as a child of the [\](../../configure-apps/file-schema/wcf/servicecertificate-of-clientcredentials-element.md) element that is itself a child of the [\](../../configure-apps/file-schema/wcf/clientcredentials.md) element in an endpoint behavior. + +2. Create an `` element as a child of the `` element. Specify values for the `storeLocation`, `storeName`, `x509FindType`, and `findValue` attributes to refer to the appropriate certificate. Set the `targetUri` attribute to a value that provides the address of the endpoint that the certificate is to be used for, as shown in the following example. + + ```xml + - - ``` - -## Example - - The following code sample configures an instance of the class in code. - + storeLocation="CurrentUser" + storeName="TrustedPeople" + x509FindType="FindBySubjectName" + findValue="FabrikamSTS" /> + + ``` + +## Example + + The following code sample configures an instance of the class in code. + [!code-csharp[c_FederatedClient#2](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_federatedclient/cs/source.cs#2)] - [!code-vb[c_FederatedClient#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federatedclient/vb/source.vb#2)] - -## .NET Framework Security - - To prevent possible information disclosure, clients that are running the Svcutil.exe tool to process metadata from federated endpoints should ensure that the resulting security token service addresses are what they expect. This is especially important when a security token service exposes multiple endpoints, because the Svcutil.exe tool generates the resulting configuration file to use the first such endpoint, which may not be the one the client should be using. - -## LocalIssuer Required - - If clients are expected to always use a local issuer, note the following: the default output of Svcutil.exe results in the local issuer not being used if the second-to-last security token service in the chain specifies an issuer address or issuer metadata address. - - For more information about setting the , , and properties of the class, see [How to: Configure a Local Issuer](how-to-configure-a-local-issuer.md). - -## Scoped Certificates - - If service certificates must be specified for communicating with any of the security token services, typically because certificate negotiation is not being used, they can be specified using the property of the class. The method takes a and an as parameters. The specified certificate is used when communicating with endpoints at the specified URI. Alternatively, you can use the method to add a certificate to the collection returned by the property. - + [!code-vb[c_FederatedClient#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_federatedclient/vb/source.vb#2)] + +## .NET Framework Security + + To prevent possible information disclosure, clients that are running the Svcutil.exe tool to process metadata from federated endpoints should ensure that the resulting security token service addresses are what they expect. This is especially important when a security token service exposes multiple endpoints, because the Svcutil.exe tool generates the resulting configuration file to use the first such endpoint, which may not be the one the client should be using. + +## LocalIssuer Required + + If clients are expected to always use a local issuer, note the following: the default output of Svcutil.exe results in the local issuer not being used if the second-to-last security token service in the chain specifies an issuer address or issuer metadata address. + + For more information about setting the , , and properties of the class, see [How to: Configure a Local Issuer](how-to-configure-a-local-issuer.md). + +## Scoped Certificates + + If service certificates must be specified for communicating with any of the security token services, typically because certificate negotiation is not being used, they can be specified using the property of the class. The method takes a and an as parameters. The specified certificate is used when communicating with endpoints at the specified URI. Alternatively, you can use the method to add a certificate to the collection returned by the property. + > [!NOTE] -> The client idea of certificates that are scoped to a given URI applies only to applications that are making outbound calls to services that expose endpoints at those URIs. It does not apply to certificates that are used to sign issued tokens, such as those configured on the server in the collection returned by the of the class. For more information, see [How to: Configure Credentials on a Federation Service](how-to-configure-credentials-on-a-federation-service.md). - +> The client idea of certificates that are scoped to a given URI applies only to applications that are making outbound calls to services that expose endpoints at those URIs. It does not apply to certificates that are used to sign issued tokens, such as those configured on the server in the collection returned by the of the class. For more information, see [How to: Configure Credentials on a Federation Service](how-to-configure-credentials-on-a-federation-service.md). + ## See also - [Federation Sample](../samples/federation-sample.md) diff --git a/docs/framework/wcf/feature-details/how-to-create-a-wsfederationhttpbinding.md b/docs/framework/wcf/feature-details/how-to-create-a-wsfederationhttpbinding.md index 5a7d582069ff9..fd68704f91e7b 100644 --- a/docs/framework/wcf/feature-details/how-to-create-a-wsfederationhttpbinding.md +++ b/docs/framework/wcf/feature-details/how-to-create-a-wsfederationhttpbinding.md @@ -2,10 +2,10 @@ description: "Learn more about: How to: Create a WSFederationHttpBinding" title: "How to: Create a WSFederationHttpBinding" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "WCF, federation" - "federation" ms.assetid: e54897d7-aa6c-46ec-a278-b2430c8c2e10 @@ -90,7 +90,7 @@ In Windows Communication Foundation (WCF), the ` element. -15. Not used on the client; optional on the service. Create an `` element as a child of the <`message`> element. Then, in an `address` attribute on the `` element, specify the address at which the security token service is to publish its metadata. Optionally, add an `` child element and specify the identity of the security token service. +15. Not used on the client; optional on the service. Create an `` element as a child of the `` element. Then, in an `address` attribute on the `` element, specify the address at which the security token service is to publish its metadata. Optionally, add an `` child element and specify the identity of the security token service. 16. Optional on both the client and the service. Add a `` element as a child of the `` element. Specify required and optional claims that the service relies on by adding [\](../../configure-apps/file-schema/wcf/add-of-claimtyperequirements.md) elements to the `` element and specifying the claim type with the `claimType` attribute. Specify whether a given claim is required or optional by setting the `isOptional` attribute. diff --git a/docs/framework/wcf/feature-details/how-to-use-svcutil-exe-to-download-metadata-documents.md b/docs/framework/wcf/feature-details/how-to-use-svcutil-exe-to-download-metadata-documents.md index d2f5c1ebc9980..88f4f0c3c83c4 100644 --- a/docs/framework/wcf/feature-details/how-to-use-svcutil-exe-to-download-metadata-documents.md +++ b/docs/framework/wcf/feature-details/how-to-use-svcutil-exe-to-download-metadata-documents.md @@ -6,43 +6,43 @@ ms.assetid: 15524274-3167-4627-b722-d6cedb9fa8c6 --- # How to: Use Svcutil.exe to Download Metadata Documents -You can use Svcutil.exe to download metadata from running services and to save the metadata to local files. For HTTP and HTTPS URL schemes, Svcutil.exe attempts to retrieve metadata using WS-MetadataExchange and [XML Web Service Discovery](/previous-versions/dotnet/netframework-4.0/fxx6cfx2(v=vs.100)). For all other URL schemes, Svcutil.exe uses only WS-MetadataExchange. - - By default, Svcutil.exe uses the bindings defined in the class. To configure the binding used for WS-MetadataExchange, you must define a client endpoint in the configuration file for Svcutil.exe (svcutil.exe.config) that uses the `IMetadataExchange` contract and that has the same name as the Uniform Resource Identifier (URI) scheme of the metadata endpoint address. - +You can use Svcutil.exe to download metadata from running services and to save the metadata to local files. For HTTP and HTTPS URL schemes, Svcutil.exe attempts to retrieve metadata using WS-MetadataExchange and [XML Web Service Discovery](/previous-versions/dotnet/netframework-4.0/fxx6cfx2(v=vs.100)). For all other URL schemes, Svcutil.exe uses only WS-MetadataExchange. + + By default, Svcutil.exe uses the bindings defined in the class. To configure the binding used for WS-MetadataExchange, you must define a client endpoint in the configuration file for Svcutil.exe (svcutil.exe.config) that uses the `IMetadataExchange` contract and that has the same name as the Uniform Resource Identifier (URI) scheme of the metadata endpoint address. + > [!CAUTION] > When running Svcutil.exe to get metadata for a service that exposes two different service contracts that each contain an operation of the same name, Svcutil.exe displays an error saying, "Cannot obtain Metadata from ...." For example, if you have a service that exposes a service contract called `ICarService` that has an operation `Get(Car c)` and the same service exposes a service contract called `IBookService` that has an operation `Get(Book b)`. To work around this issue, do one of the following: > > - Rename one of the operations. > - Set the to a different name. > - Set one of the operations' namespaces to a different namespace using the property. - -## To download metadata using Svcutil.exe - -1. Locate the Svcutil.exe tool at the following location: - - C:\Program Files\Microsoft SDKs\Windows\v1.0.\bin - -2. At the command prompt, launch the tool using the following format. - + +## To download metadata using Svcutil.exe + +1. Locate the Svcutil.exe tool at the following location: + + C:\Program Files\Microsoft SDKs\Windows\v1.0.\bin + +2. At the command prompt, launch the tool using the following format. + ```console - svcutil.exe /t:metadata * | - ``` - - You must specify the `/t:metadata` option to download metadata. Otherwise, client code and configuration are generated. - -3. The <`url`>argument specifies the URL to a service endpoint that provides metadata or to a metadata document hosted online. The <`epr`> argument specifies the path to an XML file that contains a WS-Addressing `EndpointAddress` for a service endpoint that supports WS-MetadataExchange. - - For more options about using this tool for metadata download, see [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md). - -## Example - - The following command downloads metadata documents from a running service. - + svcutil.exe /t:metadata * | + ``` + + You must specify the `/t:metadata` option to download metadata. Otherwise, client code and configuration are generated. + +3. The ``argument specifies the URL to a service endpoint that provides metadata or to a metadata document hosted online. The `` argument specifies the path to an XML file that contains a WS-Addressing `EndpointAddress` for a service endpoint that supports WS-MetadataExchange. + + For more options about using this tool for metadata download, see [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md). + +## Example + + The following command downloads metadata documents from a running service. + ```console -svcutil /t:metadata http://service/metadataEndpoint -``` - +svcutil /t:metadata http://service/metadataEndpoint +``` + ## See also - [ServiceModel Metadata Utility Tool (Svcutil.exe)](../servicemodel-metadata-utility-tool-svcutil-exe.md) diff --git a/docs/framework/wcf/feature-details/how-to-use-the-aspnet-authorization-manager-role-provider-with-a-service.md b/docs/framework/wcf/feature-details/how-to-use-the-aspnet-authorization-manager-role-provider-with-a-service.md index 56ff9d951f828..62ffd47686ab6 100644 --- a/docs/framework/wcf/feature-details/how-to-use-the-aspnet-authorization-manager-role-provider-with-a-service.md +++ b/docs/framework/wcf/feature-details/how-to-use-the-aspnet-authorization-manager-role-provider-with-a-service.md @@ -7,7 +7,7 @@ ms.date: "03/30/2017" When ASP.NET hosts a Web service, you can integrate Authorization Manager into the application to provide authorization to the service. Authorization Manager enables an application developer to define individual operations, which can be grouped together to form tasks. An administrator can then authorize roles to perform specific tasks or individual operations. Authorization Manager provides an administration tool as a Microsoft Management Console (MMC) snap-in to manage roles, tasks, operations, and users. Administrators configure an Authorization Manager policy store in an XML file, Active Directory, or in an Active Directory Application Mode (ADAM) store. - Authorization Manager is Integrated into the application by configuring the Authorization Manager ASP.NET role provider for the ASP.NET application that is hosting the Web service. Like other ASP.NET role providers, the Authorization Manager ASP.NET role provider is configured using the <`providers`> element. + Authorization Manager is Integrated into the application by configuring the Authorization Manager ASP.NET role provider for the ASP.NET application that is hosting the Web service. Like other ASP.NET role providers, the Authorization Manager ASP.NET role provider is configured using the `` element. The following code example is a portion of a configuration file for a Web service that is integrating Authorization Manager into the application. diff --git a/docs/framework/wcf/feature-details/how-to-use-the-aspnet-membership-provider.md b/docs/framework/wcf/feature-details/how-to-use-the-aspnet-membership-provider.md index 68e0726b1587d..f1b578bc5f07c 100644 --- a/docs/framework/wcf/feature-details/how-to-use-the-aspnet-membership-provider.md +++ b/docs/framework/wcf/feature-details/how-to-use-the-aspnet-membership-provider.md @@ -22,13 +22,13 @@ Windows Communication Foundation (WCF) developers can take advantage of these fe ## To configure the membership provider -1. In the Web.config file, under the <`system.web`> element, create a <`membership`> element. +1. In the Web.config file, under the `` element, create a `` element. 2. Under the `` element, create a `` element. -3. As a child to the <`providers`> element, add a `` element to flush the collection of providers. +3. As a child to the `` element, add a `` element to flush the collection of providers. -4. Under the `` element, create an <`add`> element with the following attributes set to appropriate values: `name`, `type`, `connectionStringName`, `applicationName`, `enablePasswordRetrieval`, `enablePasswordReset`, `requiresQuestionAndAnswer`, `requiresUniqueEmail`, and `passwordFormat`. The `name` attribute is used later as a value in the configuration file. The following example sets it to `SqlMembershipProvider`. +4. Under the `` element, create an `` element with the following attributes set to appropriate values: `name`, `type`, `connectionStringName`, `applicationName`, `enablePasswordRetrieval`, `enablePasswordReset`, `requiresQuestionAndAnswer`, `requiresUniqueEmail`, and `passwordFormat`. The `name` attribute is used later as a value in the configuration file. The following example sets it to `SqlMembershipProvider`. The following example shows the configuration section. @@ -59,7 +59,7 @@ Windows Communication Foundation (WCF) developers can take advantage of these fe 3. Set the `mode` attribute of the `` element to `Message`. -4. Set the `clientCredentialType` attribute of the <`message`> element to `UserName`. This specifies that a user name/password pair will be used as the client's credential. +4. Set the `clientCredentialType` attribute of the `` element to `UserName`. This specifies that a user name/password pair will be used as the client's credential. The following example shows the configuration code for the binding. @@ -82,11 +82,11 @@ Windows Communication Foundation (WCF) developers can take advantage of these fe 1. As a child to the `` element, add a [\](../../configure-apps/file-schema/wcf/behaviors.md) element -2. Add a [\](../../configure-apps/file-schema/wcf/servicebehaviors.md) to the <`behaviors`> element. +2. Add a [\](../../configure-apps/file-schema/wcf/servicebehaviors.md) to the `` element. 3. Add a [\](../../configure-apps/file-schema/wcf/behavior-of-endpointbehaviors.md) and set the `name` attribute to an appropriate value. -4. Add a [\](../../configure-apps/file-schema/wcf/servicecredentials.md) to the <`behavior`> element. +4. Add a [\](../../configure-apps/file-schema/wcf/servicecredentials.md) to the `` element. 5. Add a [\](../../configure-apps/file-schema/wcf/usernameauthentication.md) to the `` element. diff --git a/docs/framework/wcf/feature-details/how-to-use-the-aspnet-role-provider-with-a-service.md b/docs/framework/wcf/feature-details/how-to-use-the-aspnet-role-provider-with-a-service.md index 5f6959fca9d5f..7106bb5c60411 100644 --- a/docs/framework/wcf/feature-details/how-to-use-the-aspnet-role-provider-with-a-service.md +++ b/docs/framework/wcf/feature-details/how-to-use-the-aspnet-role-provider-with-a-service.md @@ -13,13 +13,13 @@ The role provider feature uses a SQL Server database to store user information. ## Configure the role provider -1. In the Web.config file, under the <`system.web`> element, add a <`roleManager`> element and set its `enabled` attribute to `true`. +1. In the Web.config file, under the `` element, add a `` element and set its `enabled` attribute to `true`. 2. Set the `defaultProvider` attribute to `SqlRoleProvider`. -3. As a child to the <`roleManager`> element, add a <`providers`> element. +3. As a child to the `` element, add a `` element. -4. As a child to the <`providers`> element, add an <`add`> element with the following attributes set to appropriate values: `name`, `type`, `connectionStringName`, and `applicationName`, as shown in the following example. +4. As a child to the `` element, add an `` element with the following attributes set to appropriate values: `name`, `type`, `connectionStringName`, and `applicationName`, as shown in the following example. ```xml @@ -38,13 +38,13 @@ The role provider feature uses a SQL Server database to store user information. 1. In the Web.config file, add a [\](../../configure-apps/file-schema/wcf/system-servicemodel.md) element. -2. Add a [\](../../configure-apps/file-schema/wcf/behaviors.md) element to the <`system.ServiceModel`> element. +2. Add a [\](../../configure-apps/file-schema/wcf/behaviors.md) element to the `` element. -3. Add a [\](../../configure-apps/file-schema/wcf/servicebehaviors.md) to the <`behaviors`> element. +3. Add a [\](../../configure-apps/file-schema/wcf/servicebehaviors.md) to the `` element. 4. Add a [\](../../configure-apps/file-schema/wcf/behavior-of-endpointbehaviors.md) element and set the `name` attribute to an appropriate value. -5. Add a [\](../../configure-apps/file-schema/wcf/serviceauthorization-element.md) to the <`behavior`> element. +5. Add a [\](../../configure-apps/file-schema/wcf/serviceauthorization-element.md) to the `` element. 6. Set the `principalPermissionMode` attribute to `UseAspNetRoles`. diff --git a/docs/framework/wcf/feature-details/how-to-use-transport-security-and-message-credentials.md b/docs/framework/wcf/feature-details/how-to-use-transport-security-and-message-credentials.md index b4cba0368994a..d8a3b40ab3730 100644 --- a/docs/framework/wcf/feature-details/how-to-use-transport-security-and-message-credentials.md +++ b/docs/framework/wcf/feature-details/how-to-use-transport-security-and-message-credentials.md @@ -2,160 +2,160 @@ title: "How to: Use Transport Security and Message Credentials" description: Learn how to implement transport security with message credentials, which offers the best of Transport and Message security modes in WCF. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "TransportWithMessageCredentials" ms.assetid: 6cc35346-c37a-4859-b82b-946c0ba6e68f --- # How to: Use Transport Security and Message Credentials -Securing a service with both transport and message credentials uses the best of both Transport and Message security modes in Windows Communication Foundation (WCF). In sum, transport-layer security provides integrity and confidentiality, while message-layer security provides a variety of credentials that are not possible with strict transport security mechanisms. This topic shows the basic steps for implementing transport with message credentials using the and bindings. For more information about setting the security mode, see [How to: Set the Security Mode](../how-to-set-the-security-mode.md). - - When setting the security mode to `TransportWithMessageCredential`, the transport determines the actual mechanism that provides the transport-level security. For HTTP, the mechanism is Secure Sockets Layer (SSL) over HTTP (HTTPS); for TCP, it is SSL over TCP or Windows. - - If the transport is HTTP (using the ), SSL over HTTP provides the transport-level security. In that case, you must configure the computer hosting the service with an SSL certificate bound to a port, as shown later in this topic. - - If the transport is TCP (using the ), by default the transport-level security provided is Windows security, or SSL over TCP. When using SSL over TCP, you must specify the certificate using the method, as shown later in this topic. - -### To use the WSHttpBinding with a certificate for transport security (in code) - -1. Use the HttpCfg.exe tool to bind an SSL certificate to a port on the machine. For more information, see [How to: Configure a Port with an SSL Certificate](how-to-configure-a-port-with-an-ssl-certificate.md). - -2. Create an instance of the class and set the property to . - -3. Set the property to an appropriate value. (For more information, see [Selecting a Credential Type](selecting-a-credential-type.md).) The following code uses the value. - -4. Create an instance of the class with an appropriate base address. Note that the address must use the "HTTPS" scheme and must contain the actual name of the machine and the port number that the SSL certificate is bound to. (Alternatively, you can set the base address in configuration.) - -5. Add a service endpoint using the method. - -6. Create the instance of the and call the method, as shown in the following code. - +Securing a service with both transport and message credentials uses the best of both Transport and Message security modes in Windows Communication Foundation (WCF). In sum, transport-layer security provides integrity and confidentiality, while message-layer security provides a variety of credentials that are not possible with strict transport security mechanisms. This topic shows the basic steps for implementing transport with message credentials using the and bindings. For more information about setting the security mode, see [How to: Set the Security Mode](../how-to-set-the-security-mode.md). + + When setting the security mode to `TransportWithMessageCredential`, the transport determines the actual mechanism that provides the transport-level security. For HTTP, the mechanism is Secure Sockets Layer (SSL) over HTTP (HTTPS); for TCP, it is SSL over TCP or Windows. + + If the transport is HTTP (using the ), SSL over HTTP provides the transport-level security. In that case, you must configure the computer hosting the service with an SSL certificate bound to a port, as shown later in this topic. + + If the transport is TCP (using the ), by default the transport-level security provided is Windows security, or SSL over TCP. When using SSL over TCP, you must specify the certificate using the method, as shown later in this topic. + +### To use the WSHttpBinding with a certificate for transport security (in code) + +1. Use the HttpCfg.exe tool to bind an SSL certificate to a port on the machine. For more information, see [How to: Configure a Port with an SSL Certificate](how-to-configure-a-port-with-an-ssl-certificate.md). + +2. Create an instance of the class and set the property to . + +3. Set the property to an appropriate value. (For more information, see [Selecting a Credential Type](selecting-a-credential-type.md).) The following code uses the value. + +4. Create an instance of the class with an appropriate base address. Note that the address must use the "HTTPS" scheme and must contain the actual name of the machine and the port number that the SSL certificate is bound to. (Alternatively, you can set the base address in configuration.) + +5. Add a service endpoint using the method. + +6. Create the instance of the and call the method, as shown in the following code. + [!code-csharp[c_SettingSecurityMode#7](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_settingsecuritymode/cs/source.cs#7)] - [!code-vb[c_SettingSecurityMode#7](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_settingsecuritymode/vb/source.vb#7)] - -### To use the NetTcpBinding with a certificate for transport security (in code) - -1. Create an instance of the class and set the property to . - -2. Set the to an appropriate value. The following code uses the value. - -3. Create an instance of the class with an appropriate base address. Note that the address must use the "net.tcp" scheme. (Alternatively, you can set the base address in configuration.) - -4. Create the instance of the class. - -5. Use the method of the class to explicitly set the X.509 certificate for the service. - -6. Add a service endpoint using the method. - -7. Call the method, as shown in the following code. - + [!code-vb[c_SettingSecurityMode#7](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_settingsecuritymode/vb/source.vb#7)] + +### To use the NetTcpBinding with a certificate for transport security (in code) + +1. Create an instance of the class and set the property to . + +2. Set the to an appropriate value. The following code uses the value. + +3. Create an instance of the class with an appropriate base address. Note that the address must use the "net.tcp" scheme. (Alternatively, you can set the base address in configuration.) + +4. Create the instance of the class. + +5. Use the method of the class to explicitly set the X.509 certificate for the service. + +6. Add a service endpoint using the method. + +7. Call the method, as shown in the following code. + [!code-csharp[c_SettingSecurityMode#8](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_settingsecuritymode/cs/source.cs#8)] - [!code-vb[c_SettingSecurityMode#8](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_settingsecuritymode/vb/source.vb#8)] - -### To use the NetTcpBinding with Windows for transport security (in code) - -1. Create an instance of the class and set the property to . - -2. Set the transport security to use Windows by setting the to . (Note that this is the default.) - -3. Set the to an appropriate value. The following code uses the value. - -4. Create an instance of the class with an appropriate base address. Note that the address must use the "net.tcp" scheme. (Alternatively, you can set the base address in configuration.) - -5. Create the instance of the class. - -6. Use the method of the class to explicitly set the X.509 certificate for the service. - -7. Add a service endpoint using the method. - -8. Call the method, as shown in the following code. - + [!code-vb[c_SettingSecurityMode#8](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_settingsecuritymode/vb/source.vb#8)] + +### To use the NetTcpBinding with Windows for transport security (in code) + +1. Create an instance of the class and set the property to . + +2. Set the transport security to use Windows by setting the to . (Note that this is the default.) + +3. Set the to an appropriate value. The following code uses the value. + +4. Create an instance of the class with an appropriate base address. Note that the address must use the "net.tcp" scheme. (Alternatively, you can set the base address in configuration.) + +5. Create the instance of the class. + +6. Use the method of the class to explicitly set the X.509 certificate for the service. + +7. Add a service endpoint using the method. + +8. Call the method, as shown in the following code. + [!code-csharp[c_SettingSecurityMode#9](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_settingsecuritymode/cs/source.cs#9)] - [!code-vb[c_SettingSecurityMode#9](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_settingsecuritymode/vb/source.vb#9)] - -## Using Configuration - -#### To use the WSHttpBinding - -1. Configure the computer with an SSL certificate bound to a port. (For more information, see [How to: Configure a Port with an SSL Certificate](how-to-configure-a-port-with-an-ssl-certificate.md)). You do not need to set a <`transport`> element value with this configuration. - -2. Specify the client credential type for the message-level security. The following example sets the `clientCredentialType` attribute of the <`message`> element to `UserName`. - - ```xml - - - - - - - - ``` - -#### To use the NetTcpBinding with a certificate for transport security - -1. For SSL over TCP, you must explicitly specify the certificate in the `` element. The following example specifies a certificate by its issuer in the default store location (local machine and personal stores). - - ```xml - - - - - - - - - - ``` - -2. Add a [\](../../configure-apps/file-schema/wcf/nettcpbinding.md) to the bindings section - -3. Add a binding element, and set the `name` attribute to an appropriate value. - -4. Add a <`security`> element, and set the `mode` attribute to `TransportWithMessageCredential`. - -5. Add a <`message>` element, and set the `clientCredentialType` attribute to an appropriate value. - - ```xml - - - - - - - - - - ``` - -#### To use the NetTcpBinding with Windows for transport security - -1. Add a [\](../../configure-apps/file-schema/wcf/nettcpbinding.md) to the bindings section, - -2. Add a <`binding`> element and set the `name` attribute to an appropriate value. - -3. Add a <`security`> element, and set the `mode` attribute to `TransportWithMessageCredential`. - -4. Add a <`transport`> element and set the `clientCredentialType` attribute to `Windows`. - -5. Add a <`message`> element and set the `clientCredentialType` attribute to an appropriate value. The following code sets the value to a certificate. - - ```xml - - - - - - - - - - - ``` - + [!code-vb[c_SettingSecurityMode#9](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_settingsecuritymode/vb/source.vb#9)] + +## Using Configuration + +#### To use the WSHttpBinding + +1. Configure the computer with an SSL certificate bound to a port. (For more information, see [How to: Configure a Port with an SSL Certificate](how-to-configure-a-port-with-an-ssl-certificate.md)). You do not need to set a `` element value with this configuration. + +2. Specify the client credential type for the message-level security. The following example sets the `clientCredentialType` attribute of the `` element to `UserName`. + + ```xml + + + + + + + + ``` + +#### To use the NetTcpBinding with a certificate for transport security + +1. For SSL over TCP, you must explicitly specify the certificate in the `` element. The following example specifies a certificate by its issuer in the default store location (local machine and personal stores). + + ```xml + + + + + + + + + + ``` + +2. Add a [\](../../configure-apps/file-schema/wcf/nettcpbinding.md) to the bindings section + +3. Add a binding element, and set the `name` attribute to an appropriate value. + +4. Add a `` element, and set the `mode` attribute to `TransportWithMessageCredential`. + +5. Add a <`message>` element, and set the `clientCredentialType` attribute to an appropriate value. + + ```xml + + + + + + + + + + ``` + +#### To use the NetTcpBinding with Windows for transport security + +1. Add a [\](../../configure-apps/file-schema/wcf/nettcpbinding.md) to the bindings section, + +2. Add a `` element and set the `name` attribute to an appropriate value. + +3. Add a `` element, and set the `mode` attribute to `TransportWithMessageCredential`. + +4. Add a `` element and set the `clientCredentialType` attribute to `Windows`. + +5. Add a `` element and set the `clientCredentialType` attribute to an appropriate value. The following code sets the value to a certificate. + + ```xml + + + + + + + + + + + ``` + ## See also - [How to: Set the Security Mode](../how-to-set-the-security-mode.md) diff --git a/docs/framework/wcf/feature-details/integrating-with-com-plus-applications-overview.md b/docs/framework/wcf/feature-details/integrating-with-com-plus-applications-overview.md index f007fde5d5556..804ca57fd60bc 100644 --- a/docs/framework/wcf/feature-details/integrating-with-com-plus-applications-overview.md +++ b/docs/framework/wcf/feature-details/integrating-with-com-plus-applications-overview.md @@ -2,105 +2,105 @@ description: "Learn more about: Integrating with COM+ Applications Overview" title: "Integrating with COM+ Applications Overview" ms.date: "03/30/2017" -helpviewer_keywords: +helpviewer_keywords: - "Windows Communication Foundation, COM+ integration" - "WCF, COM+ integration" ms.assetid: e481e48f-7096-40eb-9f20-7f0098412941 --- # Integrating with COM+ Applications Overview -Windows Communication Foundation (WCF) provides a rich environment for creating distributed applications. If you are already using component-based application logic hosted in COM+, you can use WCF to extend your existing logic rather than having to rewrite it. A common scenario is when you want to expose existing COM+ or Enterprise Services business logic through Web Services. - - When an interface on a COM+ component is exposed as a Web service, the specification and contract of these services are determined by an automatic mapping that is performed at application initialization time. The following list shows the conceptual model for this mapping: - -- One service is defined for each exposed COM class. - -- The contract for the service is derived directly from the selected component's interface definition with the possibility of method exclusion defined in configuration. - -- The operations in that contract are derived directly from the methods on the component's interface definition. - -- The parameters for those operations are derived directly from the COM interoperability type that corresponds to the component's method parameters. - - Default addresses and transport bindings for the service are provided in a service configuration file, but these can be reconfigured as required. - +Windows Communication Foundation (WCF) provides a rich environment for creating distributed applications. If you are already using component-based application logic hosted in COM+, you can use WCF to extend your existing logic rather than having to rewrite it. A common scenario is when you want to expose existing COM+ or Enterprise Services business logic through Web Services. + + When an interface on a COM+ component is exposed as a Web service, the specification and contract of these services are determined by an automatic mapping that is performed at application initialization time. The following list shows the conceptual model for this mapping: + +- One service is defined for each exposed COM class. + +- The contract for the service is derived directly from the selected component's interface definition with the possibility of method exclusion defined in configuration. + +- The operations in that contract are derived directly from the methods on the component's interface definition. + +- The parameters for those operations are derived directly from the COM interoperability type that corresponds to the component's method parameters. + + Default addresses and transport bindings for the service are provided in a service configuration file, but these can be reconfigured as required. + > [!NOTE] -> The contracts for the exposed Web services remain constant as long as the COM+ interfaces and configuration remain unchanged. A modification to several interfaces does not automatically update the available services and requires re-running the COM+ Service Model Configuration tool (ComSvcConfig.exe). - - The authentication and authorization requirements of the COM+ application and its components continue to be enforced when used as a Web service. - - If the caller initiates a Web service transaction, components marked as transactional enlist within that transaction scope. - - The following steps are required to expose a COM+ component's interface as a Web service without modifying the component: - -1. Determine whether the COM+ component's interface can be exposed as a Web service. - -2. Select an appropriate hosting mode. - -3. Use the COM+ Service Model Configuration tool (ComSvcConfig.exe) to add a Web service for the interface. For more information about how to use ComSvcConfig.exe, see [How to: Use the COM+ Service Model Configuration Tool](how-to-use-the-com-service-model-configuration-tool.md). - -4. Configure any additional service settings in the application configuration file. For more information about how to configure a component, see [How to: Configure COM+ Service Settings](how-to-configure-com-service-settings.md). - -## Supported Interfaces - - There are some restrictions on the type of interfaces that can be exposed as a Web service. The following types of interfaces are not supported: - -- Interfaces that pass object references as parameters - the following limited object reference approach is described in the Limited Object Reference Support section. - -- Interfaces that pass types that are not compatible with the .NET Framework COM interoperability conversions. - -- Interfaces for applications that have application pooling enabled when hosted by COM+. - -- Interfaces of components that are marked as private to the application. - -- COM+ infrastructure interfaces. - -- Interfaces from the system application. - -- Interfaces from Enterprise Services components that have not been added to the global assembly cache. - -### Limited Object Reference Support - - Because a number of deployed COM+ components do use objects by reference parameters, such as returning an ADO Recordset object, COM+ integration includes limited support for object reference parameters. The support is limited to objects that implement the `IPersistStream` COM interface. This includes ADO Recordset objects and can be implemented for application specific COM objects. - - To enable this support, the ComSvcConfig.exe tool provides the **allowreferences** switch that disables the regular method signature parameter and checks that the tool runs to ensure that object reference parameters are not being used. In addition, the object types that you pass as parameters must be named and identified within the <`persistableTypes`> configuration element that is a child of the <`comContract`> element. - - When this feature is used, the COM+ integration service uses the `IPersistStream` interface to serialize or deserialize the object instance. If the object instance does not support `IPersistStream`, an exception is thrown. - - Within a client application, the methods on the object can be used to pass an object in to a service and similarly to retrieve an object. - +> The contracts for the exposed Web services remain constant as long as the COM+ interfaces and configuration remain unchanged. A modification to several interfaces does not automatically update the available services and requires re-running the COM+ Service Model Configuration tool (ComSvcConfig.exe). + + The authentication and authorization requirements of the COM+ application and its components continue to be enforced when used as a Web service. + + If the caller initiates a Web service transaction, components marked as transactional enlist within that transaction scope. + + The following steps are required to expose a COM+ component's interface as a Web service without modifying the component: + +1. Determine whether the COM+ component's interface can be exposed as a Web service. + +2. Select an appropriate hosting mode. + +3. Use the COM+ Service Model Configuration tool (ComSvcConfig.exe) to add a Web service for the interface. For more information about how to use ComSvcConfig.exe, see [How to: Use the COM+ Service Model Configuration Tool](how-to-use-the-com-service-model-configuration-tool.md). + +4. Configure any additional service settings in the application configuration file. For more information about how to configure a component, see [How to: Configure COM+ Service Settings](how-to-configure-com-service-settings.md). + +## Supported Interfaces + + There are some restrictions on the type of interfaces that can be exposed as a Web service. The following types of interfaces are not supported: + +- Interfaces that pass object references as parameters - the following limited object reference approach is described in the Limited Object Reference Support section. + +- Interfaces that pass types that are not compatible with the .NET Framework COM interoperability conversions. + +- Interfaces for applications that have application pooling enabled when hosted by COM+. + +- Interfaces of components that are marked as private to the application. + +- COM+ infrastructure interfaces. + +- Interfaces from the system application. + +- Interfaces from Enterprise Services components that have not been added to the global assembly cache. + +### Limited Object Reference Support + + Because a number of deployed COM+ components do use objects by reference parameters, such as returning an ADO Recordset object, COM+ integration includes limited support for object reference parameters. The support is limited to objects that implement the `IPersistStream` COM interface. This includes ADO Recordset objects and can be implemented for application specific COM objects. + + To enable this support, the ComSvcConfig.exe tool provides the **allowreferences** switch that disables the regular method signature parameter and checks that the tool runs to ensure that object reference parameters are not being used. In addition, the object types that you pass as parameters must be named and identified within the `` configuration element that is a child of the `` element. + + When this feature is used, the COM+ integration service uses the `IPersistStream` interface to serialize or deserialize the object instance. If the object instance does not support `IPersistStream`, an exception is thrown. + + Within a client application, the methods on the object can be used to pass an object in to a service and similarly to retrieve an object. + > [!NOTE] -> Due to the custom and platform-specific nature of the serialization approach, this is best suited for use between WCF clients and WCF services. - -## Selecting the Hosting Mode - - COM+ exposes Web services in one of the following hosting modes: - -- COM+-hosted - - The Web service is hosted within the application's dedicated COM+ server process (Dllhost.exe). This mode requires the application to be explicitly started before it can receive Web service requests. The COM+ options "Run as an NT Service" or "Leave running when idle" can be used to prevent idle shutdown of the application and its services. This mode provides both Web service and DCOM access to the server application. - -- Web-hosted - - The Web service is hosted within a Web server worker process. This mode does not require COM+ to be active when the initial request is received. If the application is not active when this request is received, it is automatically activated prior to processing the request. This mode also provides both Web service and DCOM access to the server application, but causes a process hop for Web service requests. This typically requires the client to enable impersonation. In WCF, this can be done with the property of the class, which is accessed as a property of the generic class, as well as the enumeration value. - -- Web-hosted in-process - - The Web service and the COM+ application logic are hosted within the Web server worker process. This provides automatic activation of the Web-hosted mode without causing a process hop for Web service requests. The disadvantage is that the server application cannot be accessed through DCOM. - -### Security Considerations - - Like other WCF services, the security settings for the exposed service are administered through configuration settings for the WCF channel. Traditional DCOM security settings such as the DCOM machine-wide permissions settings are not enforced. To enforce COM+ application roles, "component-level access checks" authorization must be enabled for the component. - - The use of a non-secured binding can leave communication open to tampering or information disclosure. To prevent this, it is recommended that you use a secured binding. - - For the COM+-hosted and Web-hosted modes, client applications must permit the server process to impersonate the client user. This can be done in WCF clients by setting the impersonation level to . - - With Internet Information Services (IIS) or Windows Process Activation Service (WAS) using the HTTP transport, the Httpcfg.exe tool can be used to reserve a transport endpoint address. In other configurations, it is important to protect against rogue services that act as the intended service. To prevent a rogue service from starting at the desired endpoint, the legitimate service can be configured to run as an NT service. This enables the legitimate service to claim the endpoint address prior to any rogue services. - - When exposing a COM+ application with configured COM+ roles as a Web-hosted service, the "Launch IIS Process Account" must be added to one of the application’s roles. This account, typically with the name IWAM_machinename, must be added to enable clean shutdown of objects after use. The account should not be granted any additional permissions. - - The COM+ process recycling features cannot be used on integrated applications. If the application is configured to use process recycling and the components are running in a COM+ hosted process, the service fails to start. This requirement does not include services using the Web-hosted in-process mode because the process recycling settings are not applied. - +> Due to the custom and platform-specific nature of the serialization approach, this is best suited for use between WCF clients and WCF services. + +## Selecting the Hosting Mode + + COM+ exposes Web services in one of the following hosting modes: + +- COM+-hosted + + The Web service is hosted within the application's dedicated COM+ server process (Dllhost.exe). This mode requires the application to be explicitly started before it can receive Web service requests. The COM+ options "Run as an NT Service" or "Leave running when idle" can be used to prevent idle shutdown of the application and its services. This mode provides both Web service and DCOM access to the server application. + +- Web-hosted + + The Web service is hosted within a Web server worker process. This mode does not require COM+ to be active when the initial request is received. If the application is not active when this request is received, it is automatically activated prior to processing the request. This mode also provides both Web service and DCOM access to the server application, but causes a process hop for Web service requests. This typically requires the client to enable impersonation. In WCF, this can be done with the property of the class, which is accessed as a property of the generic class, as well as the enumeration value. + +- Web-hosted in-process + + The Web service and the COM+ application logic are hosted within the Web server worker process. This provides automatic activation of the Web-hosted mode without causing a process hop for Web service requests. The disadvantage is that the server application cannot be accessed through DCOM. + +### Security Considerations + + Like other WCF services, the security settings for the exposed service are administered through configuration settings for the WCF channel. Traditional DCOM security settings such as the DCOM machine-wide permissions settings are not enforced. To enforce COM+ application roles, "component-level access checks" authorization must be enabled for the component. + + The use of a non-secured binding can leave communication open to tampering or information disclosure. To prevent this, it is recommended that you use a secured binding. + + For the COM+-hosted and Web-hosted modes, client applications must permit the server process to impersonate the client user. This can be done in WCF clients by setting the impersonation level to . + + With Internet Information Services (IIS) or Windows Process Activation Service (WAS) using the HTTP transport, the Httpcfg.exe tool can be used to reserve a transport endpoint address. In other configurations, it is important to protect against rogue services that act as the intended service. To prevent a rogue service from starting at the desired endpoint, the legitimate service can be configured to run as an NT service. This enables the legitimate service to claim the endpoint address prior to any rogue services. + + When exposing a COM+ application with configured COM+ roles as a Web-hosted service, the "Launch IIS Process Account" must be added to one of the application’s roles. This account, typically with the name IWAM_machinename, must be added to enable clean shutdown of objects after use. The account should not be granted any additional permissions. + + The COM+ process recycling features cannot be used on integrated applications. If the application is configured to use process recycling and the components are running in a COM+ hosted process, the service fails to start. This requirement does not include services using the Web-hosted in-process mode because the process recycling settings are not applied. + ## See also - [Integrating with COM Applications Overview](integrating-with-com-applications-overview.md) diff --git a/docs/framework/wcf/feature-details/mapping-between-json-and-xml.md b/docs/framework/wcf/feature-details/mapping-between-json-and-xml.md index b19a71277ef2b..156596cc2ac58 100644 --- a/docs/framework/wcf/feature-details/mapping-between-json-and-xml.md +++ b/docs/framework/wcf/feature-details/mapping-between-json-and-xml.md @@ -54,7 +54,7 @@ And the following element: 42 ``` -Both have a mapping to JSON. The <`root`> element is the Root JSON Element in both cases. +Both have a mapping to JSON. The `` element is the Root JSON Element in both cases. Furthermore, in the case of a DII, the following should be considered: diff --git a/docs/framework/wcf/feature-details/message-security-with-a-certificate-client.md b/docs/framework/wcf/feature-details/message-security-with-a-certificate-client.md index aca9afa414b81..96b344b5368b9 100644 --- a/docs/framework/wcf/feature-details/message-security-with-a-certificate-client.md +++ b/docs/framework/wcf/feature-details/message-security-with-a-certificate-client.md @@ -2,7 +2,7 @@ description: "Learn more about: Message Security with a Certificate Client" title: "Message Security with a Certificate Client" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 99770573-c815-4428-a38c-e4335c8bd7ce @@ -11,140 +11,140 @@ ms.assetid: 99770573-c815-4428-a38c-e4335c8bd7ce The following scenario shows a Windows Communication Foundation (WCF) client and service secured using message security mode. Both the client and the service are authenticated with certificates. For more information, see [Distributed Application Security](distributed-application-security.md). - ![Screenshot that shows a client with certificate.](./media/message-security-with-a-certificate-client/client-with-certificate.gif) - - For a sample application, see [Message Security Certificate](../samples/message-security-certificate.md). - -|Characteristic|Description| -|--------------------|-----------------| -|Security Mode|Message| -|Interoperability|WCF only| -|Authentication (Server)|Using service certificate| -|Authentication (Client)|Using client certificate| -|Integrity|Yes| -|Confidentiality|Yes| -|Transport|HTTP| -|Binding|| - -## Service - - The following code and configuration are meant to run independently. Do one of the following: - -- Create a stand-alone service using the code with no configuration. - -- Create a service using the supplied configuration, but do not define any endpoints. - -### Code - - The following code shows how to create a service endpoint that uses message security to establish a secure context. - + ![Screenshot that shows a client with certificate.](./media/message-security-with-a-certificate-client/client-with-certificate.gif) + + For a sample application, see [Message Security Certificate](../samples/message-security-certificate.md). + +|Characteristic|Description| +|--------------------|-----------------| +|Security Mode|Message| +|Interoperability|WCF only| +|Authentication (Server)|Using service certificate| +|Authentication (Client)|Using client certificate| +|Integrity|Yes| +|Confidentiality|Yes| +|Transport|HTTP| +|Binding|| + +## Service + + The following code and configuration are meant to run independently. Do one of the following: + +- Create a stand-alone service using the code with no configuration. + +- Create a service using the supplied configuration, but do not define any endpoints. + +### Code + + The following code shows how to create a service endpoint that uses message security to establish a secure context. + [!code-csharp[C_SecurityScenarios#10](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_securityscenarios/cs/source.cs#10)] - [!code-vb[C_SecurityScenarios#10](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_securityscenarios/vb/source.vb#10)] - -### Configuration - - The following configuration can be used instead of the code. - -```xml - - - - - - - - - - - - - + [!code-vb[C_SecurityScenarios#10](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_securityscenarios/vb/source.vb#10)] + +### Configuration + + The following configuration can be used instead of the code. + +```xml + + + + + + + + + + + + + + name="ServiceModel.Calculator"> - - - - - - - - - - - - - - -``` - -## Client - - The following code and configuration are meant to run independently. Do one of the following: - -- Create a stand-alone client using the code (and client code). - -- Create a client that does not define any endpoint addresses. Instead, use the client constructor that takes the configuration name as an argument. For example: - + name="SecuredByClientCertificate" + contract="ServiceModel.ICalculator" /> + + + + + + + + + + + + + + +``` + +## Client + + The following code and configuration are meant to run independently. Do one of the following: + +- Create a stand-alone client using the code (and client code). + +- Create a client that does not define any endpoint addresses. Instead, use the client constructor that takes the configuration name as an argument. For example: + [!code-csharp[C_SecurityScenarios#0](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_securityscenarios/cs/source.cs#0)] - [!code-vb[C_SecurityScenarios#0](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_securityscenarios/vb/source.vb#0)] - -### Code + [!code-vb[C_SecurityScenarios#0](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_securityscenarios/vb/source.vb#0)] + +### Code + + The following code creates the client. The binding is to message mode security, and the client credential type is set to `Certificate`. - The following code creates the client. The binding is to message mode security, and the client credential type is set to `Certificate`. - [!code-csharp[C_SecurityScenarios#17](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_securityscenarios/cs/source.cs#17)] - [!code-vb[C_SecurityScenarios#17](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_securityscenarios/vb/source.vb#17)] - -### Configuration - - The following configuration specifies the client certificate using an endpoint behavior. For more information about certificates, see [Working with Certificates](working-with-certificates.md). The code also uses an <`identity`> element to specify a Domain Name System (DNS) of the expected server identity. For more information about identity, see [Service Identity and Authentication](service-identity-and-authentication.md). - -```xml - - - - - - - + [!code-vb[C_SecurityScenarios#17](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_securityscenarios/vb/source.vb#17)] + +### Configuration + + The following configuration specifies the client certificate using an endpoint behavior. For more information about certificates, see [Working with Certificates](working-with-certificates.md). The code also uses an `` element to specify a Domain Name System (DNS) of the expected server identity. For more information about identity, see [Service Identity and Authentication](service-identity-and-authentication.md). + +```xml + + + + + + + - - - - - - - - - - - - - - + storeLocation="LocalMachine" + x509FindType="FindBySubjectName" /> + + + + + + + + + + + + + + - - - - - - - -``` - + behaviorConfiguration="endpointCredentialsBehavior" + binding="wsHttpBinding" + bindingConfiguration="WSHttpBinding_ICalculator" + contract="ICalculator" + name="WSHttpBinding_ICalculator"> + + + + + + + +``` + ## See also - [Security Overview](security-overview.md) diff --git a/docs/framework/wcf/feature-details/partial-trust-feature-compatibility.md b/docs/framework/wcf/feature-details/partial-trust-feature-compatibility.md index 37c0234f59faf..f6e260b767fd8 100644 --- a/docs/framework/wcf/feature-details/partial-trust-feature-compatibility.md +++ b/docs/framework/wcf/feature-details/partial-trust-feature-compatibility.md @@ -6,174 +6,174 @@ ms.assetid: a36a540b-1606-4e63-88e0-b7c59e0e6ab7 --- # Partial Trust Feature Compatibility -Windows Communication Foundation (WCF) supports a limited subset of functionality when running in a partially-trusted environment. The features supported in partial trust are designed around a specific set of scenarios as described in the [Supported Deployment Scenarios](supported-deployment-scenarios.md) topic. - -## Minimum Permission Requirements - -WCF supports a subset of features in applications running under either of the following standard named permission sets: - -- Medium Trust permissions - -- Internet Zone permissions - - Attempting to use WCF in partially-trusted applications with more restrictive permissions may result in security exceptions at run time. - -## Contracts - - Contracts are subject to the following restrictions when running under partial trust: - -- The service class that implements the `[ServiceContract]` interface must be `public` and have a `public` constructor. If it defines `[OperationContract]` methods, these must be `public`. If it instead implements a `[ServiceContract]` interface, those method implementations can be explicit or `private`, provided that the `[ServiceContract]` interface is `public`. - -- When using the `[ServiceKnownType]` attribute, the method specified must be `public`. - -- `[MessageContract]` classes and their members can be `public`. If the `[MessageContract]` class is defined in the application assembly it can be `internal` and have `internal` members. - -## System-Provided Bindings - - The and are fully supported in a partial trust environment. The is supported for Transport security mode only. - - Bindings that use transports other than HTTP, such as the , the , or the , are not supported when running in a partial trust environment. - -## Custom Bindings - - Custom bindings can be created and used in a partial trust environment, but must follow the restrictions specified in this section. - -### Transports - - The only allowed transport binding elements are and . - -### Encoders - - The following encoders are allowed: - -- The text encoder (). - -- The binary encoder (). - -- The Web Message encoder (). - - The Message Transmission Optimization Mechanism (MTOM) encoders are not supported. - -### Security - - Partially-trusted applications can use WCF's transport-level security features for securing their communication. Message-level security is not supported. Configuring a binding to use message-level security results in an exception at run time. - -### Unsupported Bindings - - Bindings that use reliable messaging, transactions, or message-level security are not supported. - -## Serialization - - Both the and the are supported in a partial trust environment. However, use of the is subject to the following conditions: - -- All serializable `[DataContract]` types must be `public`. - -- All serializable `[DataMember]` fields or properties in a `[DataContract]` type must be public and read/write. The serialization and deserialization of `readonly` fields is not supported when running WCF in a partially trusted application. - -- The `[Serializable]`/ISerializable programming model is not supported in a partial trust environment. - -- Known types must be specified in code or machine-level configuration (machine.config). Known types cannot be specified in application-level configuration for security reasons. - -- Types that implement throw an exception in a partially-trusted environment. - - See the Serialization section in [Partial Trust Best Practices](partial-trust-best-practices.md) for more information about security when using safely in a partially-trusted application. - -### Collection Types - - Some collection types implement both and . Examples include types that implement . Such types can implement a `public` implementation of `GetEnumerator()`, and an explicit implementation of `GetEnumerator()`. In this case, invokes the `public` implementation of `GetEnumerator()`, and not the explicit implementation of `GetEnumerator()`. If none of the `GetEnumerator()` implementations are `public` and all are explicit implementations, then invokes `IEnumerable.GetEnumerator()`. - - For collection types when WCF is running in a partial trust environment, if none of the `GetEnumerator()` implementations are `public`, or none of them are explicit interface implementations, then a security exception is thrown. - -### NetDataContractSerializer - - Many .NET Framework collection types such as , , and are not supported by the in partial trust. These types have the `[Serializable]` attribute set, and as stated previously in the Serialization section, this attribute is not supported in partial trust. The treats collections in a special way and is thus able to get around this restriction, but the has no such mechanism to circumvent this restriction. - - The type is not supported by the in partial trust. - - A surrogate cannot be used with the (using the mechanism) when running in partial trust. Note that this restriction applies to using a surrogate, not to serializing it. - -## Enabling Common Behaviors to Run - - Service or endpoint behaviors not marked with the attribute (APTCA) that are added to the [\](../../configure-apps/file-schema/wcf/commonbehaviors.md) section of a configuration file are not run when the application runs in a partial trust environment and no exception is thrown when this occurs. To enforce the running of common behaviors, you must do one of the following options: - -- Mark your common behavior with the attribute so that it can run when deployed as a partial trust application. Note that a registry entry can be set on the computer to prevent APTCA-marked assemblies from running. . - -- Ensure that if the application is deployed as a fully-trusted application that users cannot modify the code-access security settings to run the application in a partial trust environment. If they can do so, the behavior does not run and no exception is thrown. To ensure this, see the **levelfinal** option using [Caspol.exe (Code Access Security Policy Tool)](../../tools/caspol-exe-code-access-security-policy-tool.md). - - For an example of a common behavior, see [How to: Lock Down Endpoints in the Enterprise](../extending/how-to-lock-down-endpoints-in-the-enterprise.md). - -## Configuration - - With one exception, partially-trusted code can only load WCF configuration sections in the local `app.config` file. To load WCF configuration sections that reference WCF sections in machine.config or in a root web.config file requires ConfigurationPermission(Unrestricted). Without this permission, references to WCF configuration sections (behaviors, bindings) outside of the local configuration file results in an exception when the configuration is loaded. - - The one exception is known-type configuration for serialization, as described in the Serialization section of this topic. - +Windows Communication Foundation (WCF) supports a limited subset of functionality when running in a partially-trusted environment. The features supported in partial trust are designed around a specific set of scenarios as described in the [Supported Deployment Scenarios](supported-deployment-scenarios.md) topic. + +## Minimum Permission Requirements + +WCF supports a subset of features in applications running under either of the following standard named permission sets: + +- Medium Trust permissions + +- Internet Zone permissions + + Attempting to use WCF in partially-trusted applications with more restrictive permissions may result in security exceptions at run time. + +## Contracts + + Contracts are subject to the following restrictions when running under partial trust: + +- The service class that implements the `[ServiceContract]` interface must be `public` and have a `public` constructor. If it defines `[OperationContract]` methods, these must be `public`. If it instead implements a `[ServiceContract]` interface, those method implementations can be explicit or `private`, provided that the `[ServiceContract]` interface is `public`. + +- When using the `[ServiceKnownType]` attribute, the method specified must be `public`. + +- `[MessageContract]` classes and their members can be `public`. If the `[MessageContract]` class is defined in the application assembly it can be `internal` and have `internal` members. + +## System-Provided Bindings + + The and are fully supported in a partial trust environment. The is supported for Transport security mode only. + + Bindings that use transports other than HTTP, such as the , the , or the , are not supported when running in a partial trust environment. + +## Custom Bindings + + Custom bindings can be created and used in a partial trust environment, but must follow the restrictions specified in this section. + +### Transports + + The only allowed transport binding elements are and . + +### Encoders + + The following encoders are allowed: + +- The text encoder (). + +- The binary encoder (). + +- The Web Message encoder (). + + The Message Transmission Optimization Mechanism (MTOM) encoders are not supported. + +### Security + + Partially-trusted applications can use WCF's transport-level security features for securing their communication. Message-level security is not supported. Configuring a binding to use message-level security results in an exception at run time. + +### Unsupported Bindings + + Bindings that use reliable messaging, transactions, or message-level security are not supported. + +## Serialization + + Both the and the are supported in a partial trust environment. However, use of the is subject to the following conditions: + +- All serializable `[DataContract]` types must be `public`. + +- All serializable `[DataMember]` fields or properties in a `[DataContract]` type must be public and read/write. The serialization and deserialization of `readonly` fields is not supported when running WCF in a partially trusted application. + +- The `[Serializable]`/ISerializable programming model is not supported in a partial trust environment. + +- Known types must be specified in code or machine-level configuration (machine.config). Known types cannot be specified in application-level configuration for security reasons. + +- Types that implement throw an exception in a partially-trusted environment. + + See the Serialization section in [Partial Trust Best Practices](partial-trust-best-practices.md) for more information about security when using safely in a partially-trusted application. + +### Collection Types + + Some collection types implement both and . Examples include types that implement . Such types can implement a `public` implementation of `GetEnumerator()`, and an explicit implementation of `GetEnumerator()`. In this case, invokes the `public` implementation of `GetEnumerator()`, and not the explicit implementation of `GetEnumerator()`. If none of the `GetEnumerator()` implementations are `public` and all are explicit implementations, then invokes `IEnumerable.GetEnumerator()`. + + For collection types when WCF is running in a partial trust environment, if none of the `GetEnumerator()` implementations are `public`, or none of them are explicit interface implementations, then a security exception is thrown. + +### NetDataContractSerializer + + Many .NET Framework collection types such as , , and are not supported by the in partial trust. These types have the `[Serializable]` attribute set, and as stated previously in the Serialization section, this attribute is not supported in partial trust. The treats collections in a special way and is thus able to get around this restriction, but the has no such mechanism to circumvent this restriction. + + The type is not supported by the in partial trust. + + A surrogate cannot be used with the (using the mechanism) when running in partial trust. Note that this restriction applies to using a surrogate, not to serializing it. + +## Enabling Common Behaviors to Run + + Service or endpoint behaviors not marked with the attribute (APTCA) that are added to the [\](../../configure-apps/file-schema/wcf/commonbehaviors.md) section of a configuration file are not run when the application runs in a partial trust environment and no exception is thrown when this occurs. To enforce the running of common behaviors, you must do one of the following options: + +- Mark your common behavior with the attribute so that it can run when deployed as a partial trust application. Note that a registry entry can be set on the computer to prevent APTCA-marked assemblies from running. . + +- Ensure that if the application is deployed as a fully-trusted application that users cannot modify the code-access security settings to run the application in a partial trust environment. If they can do so, the behavior does not run and no exception is thrown. To ensure this, see the **levelfinal** option using [Caspol.exe (Code Access Security Policy Tool)](../../tools/caspol-exe-code-access-security-policy-tool.md). + + For an example of a common behavior, see [How to: Lock Down Endpoints in the Enterprise](../extending/how-to-lock-down-endpoints-in-the-enterprise.md). + +## Configuration + + With one exception, partially-trusted code can only load WCF configuration sections in the local `app.config` file. To load WCF configuration sections that reference WCF sections in machine.config or in a root web.config file requires ConfigurationPermission(Unrestricted). Without this permission, references to WCF configuration sections (behaviors, bindings) outside of the local configuration file results in an exception when the configuration is loaded. + + The one exception is known-type configuration for serialization, as described in the Serialization section of this topic. + > [!IMPORTANT] -> Configuration extensions are only supported when running under Full Trust. - -## Diagnostics - -### Event Logging - - Limited event logging is supported under partial trust. Only service activation faults and tracing/message logging failures are logged to the Event Log. The maximum number of events that can be logged by a process is 5, to avoid writing excessive messages to the Event Log. - -### Message Logging - - Message logging does not work when WCF is run in a partial trust environment. If enabled under partial trust, it does not fail service activation, but no message is logged. - -### Tracing - - Restricted tracing functionality is available when running in a partial trust environment. In the <`listeners`> element in the configuration file, the only types that you can add are and the new . Use of the standard may result in incomplete or incorrect logs. - - Supported trace sources are: - -- - -- - -- , , , and . - - The following trace sources are not supported: - -- CardSpace - -- +> Configuration extensions are only supported when running under Full Trust. + +## Diagnostics + +### Event Logging + + Limited event logging is supported under partial trust. Only service activation faults and tracing/message logging failures are logged to the Event Log. The maximum number of events that can be logged by a process is 5, to avoid writing excessive messages to the Event Log. + +### Message Logging + + Message logging does not work when WCF is run in a partial trust environment. If enabled under partial trust, it does not fail service activation, but no message is logged. + +### Tracing + + Restricted tracing functionality is available when running in a partial trust environment. In the `` element in the configuration file, the only types that you can add are and the new . Use of the standard may result in incomplete or incorrect logs. + + Supported trace sources are: + +- + +- + +- , , , and . + + The following trace sources are not supported: + +- CardSpace + +- - [System.ServiceModel.Internal.TransactionBridge](/previous-versions/aa346556(v=vs.110))] - - The following members of the enumeration should not be specified: - -- - -- - - When using tracing in a partial trust environment, ensure that the application has sufficient permissions to store the output of the trace listener. For example, when using the to write trace output to a text file, ensure that the application has the necessary FileIOPermission required to successfully write to the trace file. - + + The following members of the enumeration should not be specified: + +- + +- + + When using tracing in a partial trust environment, ensure that the application has sufficient permissions to store the output of the trace listener. For example, when using the to write trace output to a text file, ensure that the application has the necessary FileIOPermission required to successfully write to the trace file. + > [!NOTE] -> To avoid flooding the trace files with duplicate errors, WCF disables tracing of the resource or action after the first security failure. There is one exception trace for each failed resource access, the first time an attempt is made to access the resource or perform the action. - -## WCF Service Host - - WCF service host does not support partial trust. If you want to use a WCF service in partial trust, do not use the WCF Service Library Project template in Visual Studio to build your service. Instead, create a new Web site in Visual Studio by choosing the WCF service Web site template, which can host the service in a Web server on which WCF partial trust is supported. - -## Other Limitations - - WCF is generally limited to the security considerations imposed upon it by the hosting application. For example, if WCF is hosted in a XAML Browser Application (XBAP), it is subject to XBAP limitations, as described in [Windows Presentation Foundation Partial Trust Security](/dotnet/desktop/wpf/wpf-partial-trust-security). - - The following additional features are not enabled when running indigo2 in a partial trust environment: - -- Windows Management Instrumentation (WMI) - -- Event logging is only partially enabled (see discussion in **Diagnostics** section). - -- Performance counters - - Use of WCF features that are not supported in a partial trust environment may result in exceptions at run time. - -## Unlisted Features - - The best way to discover that a piece of information or action is unavailable when running in a partial trust environment is to try to access the resource or do the action inside of a `try` block, and then `catch` the failure. To avoid flooding the trace files with duplicate errors, WCF disables tracing of the resource or action after the first security failure. There is one exception trace for each failed resource access, the first time an attempt is made to access the resource or perform the action. - +> To avoid flooding the trace files with duplicate errors, WCF disables tracing of the resource or action after the first security failure. There is one exception trace for each failed resource access, the first time an attempt is made to access the resource or perform the action. + +## WCF Service Host + + WCF service host does not support partial trust. If you want to use a WCF service in partial trust, do not use the WCF Service Library Project template in Visual Studio to build your service. Instead, create a new Web site in Visual Studio by choosing the WCF service Web site template, which can host the service in a Web server on which WCF partial trust is supported. + +## Other Limitations + + WCF is generally limited to the security considerations imposed upon it by the hosting application. For example, if WCF is hosted in a XAML Browser Application (XBAP), it is subject to XBAP limitations, as described in [Windows Presentation Foundation Partial Trust Security](/dotnet/desktop/wpf/wpf-partial-trust-security). + + The following additional features are not enabled when running indigo2 in a partial trust environment: + +- Windows Management Instrumentation (WMI) + +- Event logging is only partially enabled (see discussion in **Diagnostics** section). + +- Performance counters + + Use of WCF features that are not supported in a partial trust environment may result in exceptions at run time. + +## Unlisted Features + + The best way to discover that a piece of information or action is unavailable when running in a partial trust environment is to try to access the resource or do the action inside of a `try` block, and then `catch` the failure. To avoid flooding the trace files with duplicate errors, WCF disables tracing of the resource or action after the first security failure. There is one exception trace for each failed resource access, the first time an attempt is made to access the resource or perform the action. + ## See also - diff --git a/docs/framework/wcf/feature-details/security-behaviors-in-wcf.md b/docs/framework/wcf/feature-details/security-behaviors-in-wcf.md index 27f95ad826589..0b77322c86a7f 100644 --- a/docs/framework/wcf/feature-details/security-behaviors-in-wcf.md +++ b/docs/framework/wcf/feature-details/security-behaviors-in-wcf.md @@ -134,7 +134,7 @@ This article focuses on configuring the following behaviors related to security #### \ - Use the [\](../../configure-apps/file-schema/wcf/issuerchannelbehaviors-element.md) to add WCF client behaviors used when communicating with a security token service. Define client behaviors in the [\](../../configure-apps/file-schema/wcf/endpointbehaviors.md) section. To use a defined behavior, add an <`add`> element to the `` element with two attributes. Set the `issuerAddress` to the URL of the security token service and set the `behaviorConfiguration` attribute to the name of the defined endpoint behavior, as shown in the following example. + Use the [\](../../configure-apps/file-schema/wcf/issuerchannelbehaviors-element.md) to add WCF client behaviors used when communicating with a security token service. Define client behaviors in the [\](../../configure-apps/file-schema/wcf/endpointbehaviors.md) section. To use a defined behavior, add an `` element to the `` element with two attributes. Set the `issuerAddress` to the URL of the security token service and set the `behaviorConfiguration` attribute to the name of the defined endpoint behavior, as shown in the following example. ```xml diff --git a/docs/framework/wcf/feature-details/securitybindingelement-authentication-modes.md b/docs/framework/wcf/feature-details/securitybindingelement-authentication-modes.md index 66010fa5b96f4..88afef52bb1f6 100644 --- a/docs/framework/wcf/feature-details/securitybindingelement-authentication-modes.md +++ b/docs/framework/wcf/feature-details/securitybindingelement-authentication-modes.md @@ -2,139 +2,139 @@ description: "Learn more about: SecurityBindingElement Authentication Modes" title: "SecurityBindingElement Authentication Modes" ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: 12300bf4-c730-4405-9f65-d286f68b5a43 --- # SecurityBindingElement Authentication Modes -Windows Communication Foundation (WCF) provides several modes by which clients and services authenticate to one another. You can create security binding elements for these authentication modes by using static methods on the class or through configuration. This topic briefly describes the 18 authentication modes. - - For an example of using the element for one of the authentication modes, see [How to: Create a SecurityBindingElement for a Specified Authentication Mode](how-to-create-a-securitybindingelement-for-a-specified-authentication-mode.md). - -## Basic Configuration Programming - - The following procedure describes how to set the authentication mode in a configuration file. - -#### To set the authentication mode in configuration - -1. To the [\](../../configure-apps/file-schema/wcf/bindings.md) element, add a [\](../../configure-apps/file-schema/wcf/custombinding.md). - -2. As a child element, add a [\](../../configure-apps/file-schema/wcf/bindings.md) element to the `` element. - -3. Add a `` element to the `` element. - -4. Set the `authenticationMode` attribute to one of the values described below. For example, the following code sets the mode to `AnonymousForCertificate`. - - ```xml - - - - - - - - ``` - -#### To set the mode programmatically - -1. Determine the return type, which can be one of the following: , , , or . - -2. Call the appropriate static method of the class. For example, the following code calls the method. - +Windows Communication Foundation (WCF) provides several modes by which clients and services authenticate to one another. You can create security binding elements for these authentication modes by using static methods on the class or through configuration. This topic briefly describes the 18 authentication modes. + + For an example of using the element for one of the authentication modes, see [How to: Create a SecurityBindingElement for a Specified Authentication Mode](how-to-create-a-securitybindingelement-for-a-specified-authentication-mode.md). + +## Basic Configuration Programming + + The following procedure describes how to set the authentication mode in a configuration file. + +#### To set the authentication mode in configuration + +1. To the [\](../../configure-apps/file-schema/wcf/bindings.md) element, add a [\](../../configure-apps/file-schema/wcf/custombinding.md). + +2. As a child element, add a [\](../../configure-apps/file-schema/wcf/bindings.md) element to the `` element. + +3. Add a `` element to the `` element. + +4. Set the `authenticationMode` attribute to one of the values described below. For example, the following code sets the mode to `AnonymousForCertificate`. + + ```xml + + + + + + + + ``` + +#### To set the mode programmatically + +1. Determine the return type, which can be one of the following: , , , or . + +2. Call the appropriate static method of the class. For example, the following code calls the method. + [!code-csharp[c_CustomBindingsAuthMode#3](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_custombindingsauthmode/cs/source.cs#3)] - [!code-vb[c_CustomBindingsAuthMode#3](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_custombindingsauthmode/vb/source.vb#3)] - -3. Use the binding element to create the custom binding. For more information, see [Custom Bindings](../extending/custom-bindings.md). - -## Mode Descriptions - -### AnonymousForCertificate - - With this authentication mode, the client is anonymous and the service is authenticated using an X.509 certificate. The security binding element is a returned by the method. Alternatively, set the `authenticationMode` attribute of the <`security`> element to `AnonymousForCertificate`. - -### AnonymousForSslNegotiated - - With this authentication mode, the client is anonymous and the service is authenticated using an X.509 certificate that is negotiated at run time. The security binding element is a returned by the method when a value of `false` is passed for the first parameter. Alternatively, set the `authenticationMode` attribute to `AnonymousForSslNegotiated`. - -### CertificateOverTransport - - With this authentication mode, the client authenticates using an X.509 certificate that appears at the SOAP layer as an endorsing supporting token; that is, a token that signs the message signature. The service is authenticated using an X.509 certificate at the transport layer. The security binding element is a returned by the method. Alternatively, set the `authenticationMode` attribute to `CertificateOverTransport`. - -### IssuedToken - - With this authentication mode, the client does not authenticate to the service, as such; instead, the client authenticates to a security token service and receives a SAML token, which it then presents to the server to prove its knowledge of a shared key. The service is not authenticated to the client, as such, but the security token service encrypts the shared key as part of the issued token so that only the service can decrypt the key. The security binding element is a returned by the method. Alternatively, set the `authenticationMode` attribute to `IssuedToken`. - -### IssuedTokenForCertificate - - With this authentication mode, the client does not authenticate to the service, as such; instead, the client authenticates to a security token service and receives a SAML token, which it then presents to the server to prove its knowledge of a shared key. The issued token appears at the SOAP layer as either an endorsing supporting token or a bearer token; that is, a token that signs the message signature. The service authenticates to the client using an X.509 certificate. The security binding element is a returned by the method. Alternatively, set the `authenticationMode` attribute to `IssuedTokenForCertificate`. - -### IssuedTokenForSslNegotiated - - With this authentication mode, the client does not authenticate to the service, as such; instead, the client authenticates to a security token service and receives a SAML token, which it then presents to the server to prove its knowledge of a shared key. The issued token appears at the SOAP layer as either an endorsing supporting token or a bearer token; that is, a token that signs the message signature. The service is authenticated using an X.509 certificate. The security binding element is a returned by the method. Alternatively, set the `authenticationMode` attribute to `IssuedTokenForSslNegotiated`. - -### IssuedTokenOverTransport - - With this authentication mode, the client does not authenticate to the service, as such; instead, the client authenticates to a security token service and receives a SAML token, which it then presents to the server to prove its knowledge of a shared key. The issued token appears at the SOAP layer as either an endorsing supporting token or a bearer token; that is, a token that signs the message signature. The service is authenticated using an X.509 certificate at the transport layer. The security binding element is a `TransportSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `IssuedTokenOverTransport`. - -### Kerberos - - With this authentication mode, the client authenticates to the service using a Kerberos ticket. That same ticket also provides server authentication. The security binding element is a `SymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `Kerberos`. - + [!code-vb[c_CustomBindingsAuthMode#3](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_custombindingsauthmode/vb/source.vb#3)] + +3. Use the binding element to create the custom binding. For more information, see [Custom Bindings](../extending/custom-bindings.md). + +## Mode Descriptions + +### AnonymousForCertificate + + With this authentication mode, the client is anonymous and the service is authenticated using an X.509 certificate. The security binding element is a returned by the method. Alternatively, set the `authenticationMode` attribute of the `` element to `AnonymousForCertificate`. + +### AnonymousForSslNegotiated + + With this authentication mode, the client is anonymous and the service is authenticated using an X.509 certificate that is negotiated at run time. The security binding element is a returned by the method when a value of `false` is passed for the first parameter. Alternatively, set the `authenticationMode` attribute to `AnonymousForSslNegotiated`. + +### CertificateOverTransport + + With this authentication mode, the client authenticates using an X.509 certificate that appears at the SOAP layer as an endorsing supporting token; that is, a token that signs the message signature. The service is authenticated using an X.509 certificate at the transport layer. The security binding element is a returned by the method. Alternatively, set the `authenticationMode` attribute to `CertificateOverTransport`. + +### IssuedToken + + With this authentication mode, the client does not authenticate to the service, as such; instead, the client authenticates to a security token service and receives a SAML token, which it then presents to the server to prove its knowledge of a shared key. The service is not authenticated to the client, as such, but the security token service encrypts the shared key as part of the issued token so that only the service can decrypt the key. The security binding element is a returned by the method. Alternatively, set the `authenticationMode` attribute to `IssuedToken`. + +### IssuedTokenForCertificate + + With this authentication mode, the client does not authenticate to the service, as such; instead, the client authenticates to a security token service and receives a SAML token, which it then presents to the server to prove its knowledge of a shared key. The issued token appears at the SOAP layer as either an endorsing supporting token or a bearer token; that is, a token that signs the message signature. The service authenticates to the client using an X.509 certificate. The security binding element is a returned by the method. Alternatively, set the `authenticationMode` attribute to `IssuedTokenForCertificate`. + +### IssuedTokenForSslNegotiated + + With this authentication mode, the client does not authenticate to the service, as such; instead, the client authenticates to a security token service and receives a SAML token, which it then presents to the server to prove its knowledge of a shared key. The issued token appears at the SOAP layer as either an endorsing supporting token or a bearer token; that is, a token that signs the message signature. The service is authenticated using an X.509 certificate. The security binding element is a returned by the method. Alternatively, set the `authenticationMode` attribute to `IssuedTokenForSslNegotiated`. + +### IssuedTokenOverTransport + + With this authentication mode, the client does not authenticate to the service, as such; instead, the client authenticates to a security token service and receives a SAML token, which it then presents to the server to prove its knowledge of a shared key. The issued token appears at the SOAP layer as either an endorsing supporting token or a bearer token; that is, a token that signs the message signature. The service is authenticated using an X.509 certificate at the transport layer. The security binding element is a `TransportSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `IssuedTokenOverTransport`. + +### Kerberos + + With this authentication mode, the client authenticates to the service using a Kerberos ticket. That same ticket also provides server authentication. The security binding element is a `SymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `Kerberos`. + > [!NOTE] -> In order to use this authentication mode, the service account must be associated with a service principal name (SPN). To do this, run the service under the NETWORK SERVICE account or the LOCAL SYSTEM account. Alternatively, use the SetSpn.exe tool to create an SPN for the service account. In either case, the client must use the correct SPN in the [\](../../configure-apps/file-schema/wcf/serviceprincipalname.md) element, or by using the constructor. For more information, see [Service Identity and Authentication](service-identity-and-authentication.md). - +> In order to use this authentication mode, the service account must be associated with a service principal name (SPN). To do this, run the service under the NETWORK SERVICE account or the LOCAL SYSTEM account. Alternatively, use the SetSpn.exe tool to create an SPN for the service account. In either case, the client must use the correct SPN in the [\](../../configure-apps/file-schema/wcf/serviceprincipalname.md) element, or by using the constructor. For more information, see [Service Identity and Authentication](service-identity-and-authentication.md). + > [!NOTE] -> When the `Kerberos` authentication mode is used, the and impersonation levels are not supported. - -### KerberosOverTransport +> When the `Kerberos` authentication mode is used, the and impersonation levels are not supported. + +### KerberosOverTransport + + With this authentication mode, the client authenticates to the service using a Kerberos ticket. The Kerberos token appears at the SOAP layer as an endorsing supporting token; that is, a token that signs the message signature. The service is authenticated using an X.509 certificate at the transport layer. The security binding element is a `TransportSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `KerberosOverTransport`. - With this authentication mode, the client authenticates to the service using a Kerberos ticket. The Kerberos token appears at the SOAP layer as an endorsing supporting token; that is, a token that signs the message signature. The service is authenticated using an X.509 certificate at the transport layer. The security binding element is a `TransportSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `KerberosOverTransport`. - > [!NOTE] -> In order to use this authentication mode, the service account must be associated with an SPN. To do this, run the service under the NETWORK SERVICE account or the LOCAL SYSTEM account. Alternatively, use the SetSpn.exe tool to create an SPN for the service account. In either case, the client must use the correct SPN in the [\](../../configure-apps/file-schema/wcf/serviceprincipalname.md) element, or by using the constructor. For more information, see [Service Identity and Authentication](service-identity-and-authentication.md). - -### MutualCertificate - - With this authentication mode, the client authenticates using an X.509 certificate that appears at the SOAP layer as an endorsing supporting token; that is, a token that signs the message signature. The service is also authenticated using an X.509 certificate. The security binding element is a `SymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `MutualCertificate`. - -### MutualCertificateDuplex - - With this authentication mode, the client authenticates using an X.509 certificate that appears at the SOAP layer as an endorsing supporting token; that is, a token that signs the message signature. The service is also authenticated using an X.509 certificate. The binding is a `AsymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `MutualCertificateDuplex`. - -### MutualSslNegotiated - - With this authentication mode, the client and the service authenticate using X.509 certificates. The security binding element is a `SymmetricSecurityBindingElement` returned by the method when a value of `true` is passed for the first parameter. Alternatively, set the `authenticationMode` attribute to `MutualSslNegotiated`. - -### SecureConversation - - The security binding element is a `SymmetricSecurityBindingElement` returned by the method. This method takes a as a parameter, which is used during initialization to establish the secure session. Alternatively, set the `authenticationMode` attribute to `SecureConversation`. - - If no bootstrap binding is specified, then the `SspiNegotiated` authentication mode is used for bootstrap. - -### SspiNegotiation - - With this authentication mode, a negotiation protocol is used to perform client and server authentication. Kerberos is used if possible; otherwise, NT LanMan (NTLM) is used. The security binding element is a `SymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `SspiNegotiated`. - -### SspiNegotiatedOverTransport - - With this authentication mode, a negotiation protocol is used to perform client and server authentication. Kerberos protocol is used if possible; otherwise, NTLM is used. The resulting token appears at the SOAP layer as an endorsing supporting token; that is, a token that signs the message signature. The service is additionally authenticated at the transport layer by an X.509 certificate. The security binding element is a `TransportSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `SspiNegotiatedOverTransport`. - -### UserNameForCertificate - - With this authentication mode, the client authenticates to the service using a Username Token that appears at the SOAP layer as a signed supporting token; that is, a token that is signed by the message signature. The service authenticates to the client using an X.509 certificate. The security binding element is a `SymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `UserNameForCertificate`. - - For the `UserNameForCertificate` authentication mode, both the client and service must be using WS-Security 1.1. - -### UserNameForSslNegotiated - - With this authentication mode, the client is authenticates using a Username Token which appears at the SOAP layer as a signed supporting token; that is, a token that is signed by the message signature. The service is authenticated using an X.509 certificate. The security binding element is a `SymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `UserNameForSslNegotiated`. - -### UserNameOverTransport - - With this authentication mode, the client authenticates using a Username Token that appears at the SOAP layer as a signed supporting token; that is, a token that is signed by the message signature. The service is authenticated using an X.509 certificate at the transport layer. The security binding element is a `TransportSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `UserNameOverTransport`. - +> In order to use this authentication mode, the service account must be associated with an SPN. To do this, run the service under the NETWORK SERVICE account or the LOCAL SYSTEM account. Alternatively, use the SetSpn.exe tool to create an SPN for the service account. In either case, the client must use the correct SPN in the [\](../../configure-apps/file-schema/wcf/serviceprincipalname.md) element, or by using the constructor. For more information, see [Service Identity and Authentication](service-identity-and-authentication.md). + +### MutualCertificate + + With this authentication mode, the client authenticates using an X.509 certificate that appears at the SOAP layer as an endorsing supporting token; that is, a token that signs the message signature. The service is also authenticated using an X.509 certificate. The security binding element is a `SymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `MutualCertificate`. + +### MutualCertificateDuplex + + With this authentication mode, the client authenticates using an X.509 certificate that appears at the SOAP layer as an endorsing supporting token; that is, a token that signs the message signature. The service is also authenticated using an X.509 certificate. The binding is a `AsymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `MutualCertificateDuplex`. + +### MutualSslNegotiated + + With this authentication mode, the client and the service authenticate using X.509 certificates. The security binding element is a `SymmetricSecurityBindingElement` returned by the method when a value of `true` is passed for the first parameter. Alternatively, set the `authenticationMode` attribute to `MutualSslNegotiated`. + +### SecureConversation + + The security binding element is a `SymmetricSecurityBindingElement` returned by the method. This method takes a as a parameter, which is used during initialization to establish the secure session. Alternatively, set the `authenticationMode` attribute to `SecureConversation`. + + If no bootstrap binding is specified, then the `SspiNegotiated` authentication mode is used for bootstrap. + +### SspiNegotiation + + With this authentication mode, a negotiation protocol is used to perform client and server authentication. Kerberos is used if possible; otherwise, NT LanMan (NTLM) is used. The security binding element is a `SymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `SspiNegotiated`. + +### SspiNegotiatedOverTransport + + With this authentication mode, a negotiation protocol is used to perform client and server authentication. Kerberos protocol is used if possible; otherwise, NTLM is used. The resulting token appears at the SOAP layer as an endorsing supporting token; that is, a token that signs the message signature. The service is additionally authenticated at the transport layer by an X.509 certificate. The security binding element is a `TransportSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `SspiNegotiatedOverTransport`. + +### UserNameForCertificate + + With this authentication mode, the client authenticates to the service using a Username Token that appears at the SOAP layer as a signed supporting token; that is, a token that is signed by the message signature. The service authenticates to the client using an X.509 certificate. The security binding element is a `SymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `UserNameForCertificate`. + + For the `UserNameForCertificate` authentication mode, both the client and service must be using WS-Security 1.1. + +### UserNameForSslNegotiated + + With this authentication mode, the client is authenticates using a Username Token which appears at the SOAP layer as a signed supporting token; that is, a token that is signed by the message signature. The service is authenticated using an X.509 certificate. The security binding element is a `SymmetricSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `UserNameForSslNegotiated`. + +### UserNameOverTransport + + With this authentication mode, the client authenticates using a Username Token that appears at the SOAP layer as a signed supporting token; that is, a token that is signed by the message signature. The service is authenticated using an X.509 certificate at the transport layer. The security binding element is a `TransportSecurityBindingElement` returned by the method. Alternatively, set the `authenticationMode` attribute to `UserNameOverTransport`. + ## See also - diff --git a/docs/framework/wcf/feature-details/standard-endpoints.md b/docs/framework/wcf/feature-details/standard-endpoints.md index a0bab9e7e2638..690789779fbe2 100644 --- a/docs/framework/wcf/feature-details/standard-endpoints.md +++ b/docs/framework/wcf/feature-details/standard-endpoints.md @@ -6,26 +6,26 @@ ms.assetid: 3fcb4225-addc-44f2-935d-30e4943a8812 --- # Standard Endpoints -Endpoints are defined by specifying an address, a binding, and a contract. Other parameters that may be set on an endpoint include behavior configuration, headers, and listen URIs. For certain types of endpoints these values do not change. For example, metadata exchange endpoints always use the contract. Other endpoints, such as always require a specified endpoint behavior. The usability of an endpoint can be improved by having endpoints with default values for commonly used endpoint properties. Standard endpoints enable a developer to define an endpoint that has default values or where one or more endpoint’s properties does not change. These endpoints allow you to use such an endpoint without having to specify information of a static nature. Standard endpoints can be used for infrastructure and application endpoints. - -## Infrastructure Endpoints +Endpoints are defined by specifying an address, a binding, and a contract. Other parameters that may be set on an endpoint include behavior configuration, headers, and listen URIs. For certain types of endpoints these values do not change. For example, metadata exchange endpoints always use the contract. Other endpoints, such as always require a specified endpoint behavior. The usability of an endpoint can be improved by having endpoints with default values for commonly used endpoint properties. Standard endpoints enable a developer to define an endpoint that has default values or where one or more endpoint’s properties does not change. These endpoints allow you to use such an endpoint without having to specify information of a static nature. Standard endpoints can be used for infrastructure and application endpoints. - A service may expose endpoints with some of the properties not explicitly implemented by the service author. For example, the metadata exchange endpoint exposes the contract but as a service author you do not implement that interface, it is implemented by WCF. Such infrastructure endpoints have default values for one or more endpoint properties, some of which may be unalterable. The property of the metadata exchange endpoint must be , while other properties like binding can be supplied by the developer. Infrastructure endpoints are identified by setting the property to `true`. - -## Application Endpoints +## Infrastructure Endpoints + + A service may expose endpoints with some of the properties not explicitly implemented by the service author. For example, the metadata exchange endpoint exposes the contract but as a service author you do not implement that interface, it is implemented by WCF. Such infrastructure endpoints have default values for one or more endpoint properties, some of which may be unalterable. The property of the metadata exchange endpoint must be , while other properties like binding can be supplied by the developer. Infrastructure endpoints are identified by setting the property to `true`. + +## Application Endpoints + + Application developers can define their own standard endpoints which specify default values for the address, binding, or contract. You define a standard endpoint by deriving a class from and setting the appropriate endpoint properties. You can provide default values for properties that can be changed. Some other properties will have static values that cannot change. The following example shows how to implement a standard endpoint. - Application developers can define their own standard endpoints which specify default values for the address, binding, or contract. You define a standard endpoint by deriving a class from and setting the appropriate endpoint properties. You can provide default values for properties that can be changed. Some other properties will have static values that cannot change. The following example shows how to implement a standard endpoint. - ```csharp public class CustomEndpoint : ServiceEndpoint { public CustomEndpoint() : this(string.Empty) - { } + { } public CustomEndpoint(string address) : this(address, ContractDescription.GetContract(typeof(ICalculator))) - { } + { } // Create the custom endpoint with a fixed binding public CustomEndpoint(string address, ContractDescription contract) @@ -39,9 +39,9 @@ public class CustomEndpoint : ServiceEndpoint public bool Property { get; set; } } ``` - - To use a user-defined custom endpoint in a configuration file you must derive a class from , derive a class from , and register the new standard endpoint in the extensions section in app.config or machine.config. The provides configuration support for the standard endpoint, as shown in the following example. - + + To use a user-defined custom endpoint in a configuration file you must derive a class from , derive a class from , and register the new standard endpoint in the extensions section in app.config or machine.config. The provides configuration support for the standard endpoint, as shown in the following example. + ```csharp public class CustomEndpointElement : StandardEndpointElement { @@ -99,10 +99,10 @@ public class CustomEndpointElement : StandardEndpointElement { } } -``` - - The provides the backing type for the collection that appears under the <`standardEndpoints`> section in the configuration for the standard endpoint. The following example shows how to implement this class. - +``` + + The provides the backing type for the collection that appears under the `` section in the configuration for the standard endpoint. The following example shows how to implement this class. + ```csharp public class CustomEndpointCollectionElement : StandardEndpointCollectionElement { @@ -112,78 +112,78 @@ public class CustomEndpointCollectionElement : StandardEndpointCollectionElement The following example shows how to register a standard endpoint in the extensions section. -```xml - - - +```xml + + + - -``` - -## Configuring a Standard Endpoint - - Standard endpoints can be added in code or in configuration. To add a standard endpoint in code simply instantiate the appropriate standard endpoint type and add it to the service host as shown in the following example: - -```csharp -serviceHost.AddServiceEndpoint(new CustomEndpoint()); -``` - - To add a standard endpoint in configuration, add an <`endpoint`> element to the <`service`> element and any needed configuration settings in the <`standardEndpoints`> element. The following example shows how to add a , one of the standard endpoints that ships with [!INCLUDE[netfx_current_long](../../../../includes/netfx-current-long-md.md)]. - -```xml - - - - - + +``` + +## Configuring a Standard Endpoint + + Standard endpoints can be added in code or in configuration. To add a standard endpoint in code simply instantiate the appropriate standard endpoint type and add it to the service host as shown in the following example: + +```csharp +serviceHost.AddServiceEndpoint(new CustomEndpoint()); +``` + + To add a standard endpoint in configuration, add an `` element to the `` element and any needed configuration settings in the `` element. The following example shows how to add a , one of the standard endpoints that ships with [!INCLUDE[netfx_current_long](../../../../includes/netfx-current-long-md.md)]. + +```xml + + + + + - + -``` - - The type of standard endpoint is specified using the kind attribute in the <`endpoint`> element. The endpoint is configured within the <`standardEndpoints`> element. In the example above, a endpoint is added and configured. The <`udpDiscoveryEndpoint`> element contains a <`standardEndpoint`> that sets the property of the . - -## Standard Endpoints Shipped with the .NET Framework - - The following table lists the standard endpoints shipped with [!INCLUDE[netfx_current_long](../../../../includes/netfx-current-long-md.md)]. - - `Mex Endpoint` - A standard endpoint that is used to expose service metadata. - - - A standard endpoint that is used by services to send announcement messages. - - - A standard endpoint that is used by services to send discovery messages. - - - A standard endpoint that is pre-configured for discovery operations over a UDP multicast binding. - - - A standard endpoint that is used by services to send announcement messages over a UDP binding. - - - A standard endpoint that uses WS-Discovery to find the endpoint address dynamically at run time. - - - A standard endpoint for metadata exchange. - - - A standard endpoint with a binding that automatically adds the behavior - - - A standard endpoint with a binding that automatically adds the behavior. - - - A standard endpoint with a binding. - - - A standard endpoint that enables you to call control operations on workflow instances. - - +``` + + The type of standard endpoint is specified using the kind attribute in the `` element. The endpoint is configured within the `` element. In the example above, a endpoint is added and configured. The `` element contains a `` that sets the property of the . + +## Standard Endpoints Shipped with the .NET Framework + + The following table lists the standard endpoints shipped with [!INCLUDE[netfx_current_long](../../../../includes/netfx-current-long-md.md)]. + + `Mex Endpoint` + A standard endpoint that is used to expose service metadata. + + + A standard endpoint that is used by services to send announcement messages. + + + A standard endpoint that is used by services to send discovery messages. + + + A standard endpoint that is pre-configured for discovery operations over a UDP multicast binding. + + + A standard endpoint that is used by services to send announcement messages over a UDP binding. + + + A standard endpoint that uses WS-Discovery to find the endpoint address dynamically at run time. + + + A standard endpoint for metadata exchange. + + + A standard endpoint with a binding that automatically adds the behavior + + + A standard endpoint with a binding that automatically adds the behavior. + + + A standard endpoint with a binding. + + + A standard endpoint that enables you to call control operations on workflow instances. + + A standard endpoint that supports workflow creation and bookmark resumption. diff --git a/docs/framework/wcf/feature-details/supporting-multiple-iis-site-bindings.md b/docs/framework/wcf/feature-details/supporting-multiple-iis-site-bindings.md index 3c649df821ae4..9eaac7369ef3f 100644 --- a/docs/framework/wcf/feature-details/supporting-multiple-iis-site-bindings.md +++ b/docs/framework/wcf/feature-details/supporting-multiple-iis-site-bindings.md @@ -6,22 +6,22 @@ ms.assetid: 40440495-254d-45c8-a8c6-b29f364892ba --- # Supporting Multiple IIS Site Bindings -When hosting a Windows Communication Foundation (WCF) service under Internet Information Services (IIS) 7.0, you may want to provide multiple base addresses that use the same protocol on the same site. This allows the same service to respond to a number of different URIs. This is useful when you want to host a service that listens on `http://www.contoso.com` and `http://contoso.com`. It is also useful to create a service that has a base address for internal users and a separate base address for external users. For example: `http://internal.contoso.com` and `http://www.contoso.com`. - +When hosting a Windows Communication Foundation (WCF) service under Internet Information Services (IIS) 7.0, you may want to provide multiple base addresses that use the same protocol on the same site. This allows the same service to respond to a number of different URIs. This is useful when you want to host a service that listens on `http://www.contoso.com` and `http://contoso.com`. It is also useful to create a service that has a base address for internal users and a separate base address for external users. For example: `http://internal.contoso.com` and `http://www.contoso.com`. + > [!NOTE] -> This functionality is only available using the HTTP protocol. - -## Multiple Base Addresses - - This feature is only available to WCF services that are hosted under IIS. This feature is not enabled by default. To enable it you must add the `multipleSiteBindingsEnabled` attribute to the <`serviceHostingEnvironment`> element in your Web.config file and set it to `true`, as shown in the following example. - -```xml - -``` - - When hosting a WCF service under IIS, IIS creates one base address for you based on the URI to the virtual directory that contains the application. You can add additional base addresses that use the same protocol by using Internet Information Services Manager to add one or more bindings to your Web site. For each binding specify a protocol (HTTP or HTTPS), an IP address, a port, and a host name. For more information about using Internet Information Services Manager, see [IIS Manager (IIS 7)](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc753842(v=ws.10)). For more information about adding bindings to a site, see [Create a Web Site (IIS 7)](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc772350(v=ws.10)) - - Specifying multiple base addresses for the same site affects the content of the WCF Help page, importing schema, and the WSDL/MEX information generated by the service. The WCF Help page displays the command line to use to generate a WCF client that can communicate with the service. This command line contains only the first address specified in the IIS binding for the Web site. Similarly when importing schema, only the first base address specified in the IIS binding is used. WSDL and MEX data contain all the base addresses specified in the IIS bindings. - +> This functionality is only available using the HTTP protocol. + +## Multiple Base Addresses + + This feature is only available to WCF services that are hosted under IIS. This feature is not enabled by default. To enable it you must add the `multipleSiteBindingsEnabled` attribute to the `` element in your Web.config file and set it to `true`, as shown in the following example. + +```xml + +``` + + When hosting a WCF service under IIS, IIS creates one base address for you based on the URI to the virtual directory that contains the application. You can add additional base addresses that use the same protocol by using Internet Information Services Manager to add one or more bindings to your Web site. For each binding specify a protocol (HTTP or HTTPS), an IP address, a port, and a host name. For more information about using Internet Information Services Manager, see [IIS Manager (IIS 7)](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc753842(v=ws.10)). For more information about adding bindings to a site, see [Create a Web Site (IIS 7)](/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc772350(v=ws.10)) + + Specifying multiple base addresses for the same site affects the content of the WCF Help page, importing schema, and the WSDL/MEX information generated by the service. The WCF Help page displays the command line to use to generate a WCF client that can communicate with the service. This command line contains only the first address specified in the IIS binding for the Web site. Similarly when importing schema, only the first base address specified in the IIS binding is used. WSDL and MEX data contain all the base addresses specified in the IIS bindings. + > [!WARNING] > This means that if a service has two base addresses, one for internal users and one for external users, both are specified in the WSDL/MEX information generated by the service. diff --git a/docs/framework/wcf/feature-details/unsupported-scenarios.md b/docs/framework/wcf/feature-details/unsupported-scenarios.md index d413b91701d6e..c33c08a09e497 100644 --- a/docs/framework/wcf/feature-details/unsupported-scenarios.md +++ b/docs/framework/wcf/feature-details/unsupported-scenarios.md @@ -28,7 +28,7 @@ WCF does not support impersonation and an or ) using the or the method and setting the `requireCancellation` parameter to `false`. The parameter refers to the caching of the SCT. Setting the value to `false` enables the state-based SCT feature. - Alternatively, in configuration, the token is enabled by creating a <`customBinding`>, then adding a <`security`> element, and setting the `authenticationMode` attribute to SecureConversation and the `requireSecurityContextCancellation` attribute to `true`. + Alternatively, in configuration, the token is enabled by creating a ``, then adding a `` element, and setting the `authenticationMode` attribute to SecureConversation and the `requireSecurityContextCancellation` attribute to `true`. > [!NOTE] > The preceding requirements are specific. For example, the creates a binding element that results in a Windows identity, but does not establish an SCT. Therefore, you can use it with the `Required` option on Windows XP. @@ -82,7 +82,7 @@ FIPS-compliant AES encryption does not work in duplex callbacks under identifica WCF does not support the following combination of settings because they can prevent client authentication from occurring: -- ASP.NET Impersonation is enabled. This is done in the Web.config file by setting the `impersonate` attribute of the <`identity`> element to `true`. +- ASP.NET Impersonation is enabled. This is done in the Web.config file by setting the `impersonate` attribute of the `` element to `true`. - ASP.NET compatibility mode is enabled by setting the `aspNetCompatibilityEnabled` attribute of the [\](../../configure-apps/file-schema/wcf/servicehostingenvironment.md) to `true`. diff --git a/docs/framework/wcf/feature-details/using-the-message-class.md b/docs/framework/wcf/feature-details/using-the-message-class.md index d02e78034707a..52566dc5307b5 100644 --- a/docs/framework/wcf/feature-details/using-the-message-class.md +++ b/docs/framework/wcf/feature-details/using-the-message-class.md @@ -2,222 +2,222 @@ title: "Using the Message Class" description: Learn about the Message class, which is fundamental to WCF. You need to program using Message class directly only in some advanced scenarios. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" ms.assetid: d1d62bfb-2aa3-4170-b6f8-c93d3afdbbed --- # Using the Message Class -The class is fundamental to Windows Communication Foundation (WCF). All communication between clients and services ultimately results in instances being sent and received. - - You would not usually interact with the class directly. Instead, WCF service model constructs, such as data contracts, message contracts, and operation contracts, are used to describe incoming and outgoing messages. However, in some advanced scenarios you can program using the class directly. For example, you might want to use the class: - -- When you need an alternative way of creating outgoing message contents (for example, creating a message directly from a file on disk) instead of serializing .NET Framework objects. - -- When you need an alternative way of using incoming message contents (for example, when you want to apply an XSLT transformation to the raw XML contents) instead of deserializing into .NET Framework objects. - -- When you need to deal with messages in a general way regardless of message contents (for example, when routing or forwarding messages when building a router, load-balancer, or a publish-subscribe system). - - Before using the class, familiarize yourself with the WCF data transfer architecture in [Data Transfer Architectural Overview](data-transfer-architectural-overview.md). - - A is a general-purpose container for data, but its design closely follows the design of a message in the SOAP protocol. Just like in SOAP, a message has both a message body and headers. The message body contains the actual payload data, while the headers contain additional named data containers. The rules for reading and writing the body and the headers are different, for example, the headers are always buffered in memory and may be accessed in any order any number of times, while the body may be read only once and may be streamed. Normally, when using SOAP, the message body is mapped to the SOAP body and the message headers are mapped to the SOAP headers. - -## Using the Message Class in Operations - - You can use the class as an input parameter of an operation, the return value of an operation, or both. If is used anywhere in an operation, the following restrictions apply: - -- The operation cannot have any `out` or `ref` parameters. - -- There cannot be more than one `input` parameter. If the parameter is present, it must be either Message or a message contract type. - -- The return type must be either `void`, `Message`, or a message contract type. - - The following code example contains a valid operation contract. - +The class is fundamental to Windows Communication Foundation (WCF). All communication between clients and services ultimately results in instances being sent and received. + + You would not usually interact with the class directly. Instead, WCF service model constructs, such as data contracts, message contracts, and operation contracts, are used to describe incoming and outgoing messages. However, in some advanced scenarios you can program using the class directly. For example, you might want to use the class: + +- When you need an alternative way of creating outgoing message contents (for example, creating a message directly from a file on disk) instead of serializing .NET Framework objects. + +- When you need an alternative way of using incoming message contents (for example, when you want to apply an XSLT transformation to the raw XML contents) instead of deserializing into .NET Framework objects. + +- When you need to deal with messages in a general way regardless of message contents (for example, when routing or forwarding messages when building a router, load-balancer, or a publish-subscribe system). + + Before using the class, familiarize yourself with the WCF data transfer architecture in [Data Transfer Architectural Overview](data-transfer-architectural-overview.md). + + A is a general-purpose container for data, but its design closely follows the design of a message in the SOAP protocol. Just like in SOAP, a message has both a message body and headers. The message body contains the actual payload data, while the headers contain additional named data containers. The rules for reading and writing the body and the headers are different, for example, the headers are always buffered in memory and may be accessed in any order any number of times, while the body may be read only once and may be streamed. Normally, when using SOAP, the message body is mapped to the SOAP body and the message headers are mapped to the SOAP headers. + +## Using the Message Class in Operations + + You can use the class as an input parameter of an operation, the return value of an operation, or both. If is used anywhere in an operation, the following restrictions apply: + +- The operation cannot have any `out` or `ref` parameters. + +- There cannot be more than one `input` parameter. If the parameter is present, it must be either Message or a message contract type. + +- The return type must be either `void`, `Message`, or a message contract type. + + The following code example contains a valid operation contract. + [!code-csharp[C_UsingTheMessageClass#1](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_usingthemessageclass/cs/source.cs#1)] - [!code-vb[C_UsingTheMessageClass#1](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#1)] - -## Creating Basic Messages - - The class provides static `CreateMessage` factory methods that you can use to create basic messages. - - All `CreateMessage` overloads take a version parameter of type that indicates the SOAP and WS-Addressing versions to use for the message. If you want to use the same protocol versions as the incoming message, you can use the property on the instance obtained from the property. Most `CreateMessage` overloads also have a string parameter that indicates the SOAP action to use for the message. Version can be set to `None` to disable SOAP envelope generation; the message consists of only the body. - -## Creating Messages from Objects - - The most basic `CreateMessage` overload that takes only a version and an action creates a message with an empty body. Another overload takes an additional parameter; this creates a message whose body is the serialized representation of the given object. Use the with default settings for serialization. If you want to use a different serializer, or you want the `DataContractSerializer` configured differently, use the `CreateMessage` overload that also takes an `XmlObjectSerializer` parameter. - - For example, to return an object in a message, you can use the following code. - + [!code-vb[C_UsingTheMessageClass#1](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#1)] + +## Creating Basic Messages + + The class provides static `CreateMessage` factory methods that you can use to create basic messages. + + All `CreateMessage` overloads take a version parameter of type that indicates the SOAP and WS-Addressing versions to use for the message. If you want to use the same protocol versions as the incoming message, you can use the property on the instance obtained from the property. Most `CreateMessage` overloads also have a string parameter that indicates the SOAP action to use for the message. Version can be set to `None` to disable SOAP envelope generation; the message consists of only the body. + +## Creating Messages from Objects + + The most basic `CreateMessage` overload that takes only a version and an action creates a message with an empty body. Another overload takes an additional parameter; this creates a message whose body is the serialized representation of the given object. Use the with default settings for serialization. If you want to use a different serializer, or you want the `DataContractSerializer` configured differently, use the `CreateMessage` overload that also takes an `XmlObjectSerializer` parameter. + + For example, to return an object in a message, you can use the following code. + [!code-csharp[C_UsingTheMessageClass#2](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_usingthemessageclass/cs/source.cs#2)] - [!code-vb[C_UsingTheMessageClass#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#2)] - -## Creating Messages from XML Readers + [!code-vb[C_UsingTheMessageClass#2](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#2)] + +## Creating Messages from XML Readers + + There are `CreateMessage` overloads that take an or an for the body instead of an object. In this case, the body of the message contains the XML that results from reading from the passed XML reader. For example, the following code returns a message with body contents read from an XML file. - There are `CreateMessage` overloads that take an or an for the body instead of an object. In this case, the body of the message contains the XML that results from reading from the passed XML reader. For example, the following code returns a message with body contents read from an XML file. - [!code-csharp[C_UsingTheMessageClass#3](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_usingthemessageclass/cs/source.cs#3)] - [!code-vb[C_UsingTheMessageClass#3](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#3)] - - Additionally, there are `CreateMessage` overloads that take an or an that represents the entire message and not just the body. These overloads also take an integer `maxSizeOfHeaders` parameter. Headers are always buffered into memory as soon as the message is created, and this parameter limits the amount of buffering that takes place. It is important to set this parameter to a safe value if the XML is coming from an untrusted source to mitigate the possibility of a denial of service attack. The SOAP and WS-Addressing versions of the message the XML reader represents must match the versions indicated using the version parameter. - -## Creating Messages with BodyWriter - - One `CreateMessage` overload takes a `BodyWriter` instance to describe the body of the message. A `BodyWriter` is an abstract class that can be derived to customize how message bodies are created. You can create your own `BodyWriter` derived class to describe message bodies in a custom way. You must override the `BodyWriter.OnWriteBodyContents` method that takes an ; this method is responsible for writing out the body. - - Body writers can be buffered or non-buffered (streamed). Buffered body writers can write out their contents any number of times, while streamed ones can write out their contents only once. The `IsBuffered` property indicates whether a body writer is buffered or not. You can set this for your body writer by calling the protected `BodyWriter` constructor that takes an `isBuffered` boolean parameter. Body writers support creating a buffered body writer from a non-buffered body writer. You can override the `OnCreateBufferedCopy` method to customize this process. By default, an in-memory buffer that contains the XML returned by `OnWriteBodyContents` is used. `OnCreateBufferedCopy` takes a `maxBufferSize` integer parameter; if you override this method, you must not create buffers larger than this maximum size. - - The `BodyWriter` class provides the `WriteBodyContents` and `CreateBufferedCopy` methods, which are essentially thin wrappers around `OnWriteBodyContents` and `OnCreateBufferedCopy` methods, respectively. These methods perform state checking to ensure that a non-buffered body writer is not accessed more than once. These methods are called directly only when creating custom `Message` derived classes based on `BodyWriters`. - -## Creating Fault Messages - - You can use certain `CreateMessage` overloads to create SOAP fault messages. The most basic of these takes a object that describes the fault. Other overloads are provided for convenience. The first such overload takes a `FaultCode` and a reason string and creates a `MessageFault` using `MessageFault.CreateFault` using this information. The other overload takes a detail object and also passes it to `CreateFault` together with the fault code and the reason. For example, the following operation returns a fault. - + [!code-vb[C_UsingTheMessageClass#3](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#3)] + + Additionally, there are `CreateMessage` overloads that take an or an that represents the entire message and not just the body. These overloads also take an integer `maxSizeOfHeaders` parameter. Headers are always buffered into memory as soon as the message is created, and this parameter limits the amount of buffering that takes place. It is important to set this parameter to a safe value if the XML is coming from an untrusted source to mitigate the possibility of a denial of service attack. The SOAP and WS-Addressing versions of the message the XML reader represents must match the versions indicated using the version parameter. + +## Creating Messages with BodyWriter + + One `CreateMessage` overload takes a `BodyWriter` instance to describe the body of the message. A `BodyWriter` is an abstract class that can be derived to customize how message bodies are created. You can create your own `BodyWriter` derived class to describe message bodies in a custom way. You must override the `BodyWriter.OnWriteBodyContents` method that takes an ; this method is responsible for writing out the body. + + Body writers can be buffered or non-buffered (streamed). Buffered body writers can write out their contents any number of times, while streamed ones can write out their contents only once. The `IsBuffered` property indicates whether a body writer is buffered or not. You can set this for your body writer by calling the protected `BodyWriter` constructor that takes an `isBuffered` boolean parameter. Body writers support creating a buffered body writer from a non-buffered body writer. You can override the `OnCreateBufferedCopy` method to customize this process. By default, an in-memory buffer that contains the XML returned by `OnWriteBodyContents` is used. `OnCreateBufferedCopy` takes a `maxBufferSize` integer parameter; if you override this method, you must not create buffers larger than this maximum size. + + The `BodyWriter` class provides the `WriteBodyContents` and `CreateBufferedCopy` methods, which are essentially thin wrappers around `OnWriteBodyContents` and `OnCreateBufferedCopy` methods, respectively. These methods perform state checking to ensure that a non-buffered body writer is not accessed more than once. These methods are called directly only when creating custom `Message` derived classes based on `BodyWriters`. + +## Creating Fault Messages + + You can use certain `CreateMessage` overloads to create SOAP fault messages. The most basic of these takes a object that describes the fault. Other overloads are provided for convenience. The first such overload takes a `FaultCode` and a reason string and creates a `MessageFault` using `MessageFault.CreateFault` using this information. The other overload takes a detail object and also passes it to `CreateFault` together with the fault code and the reason. For example, the following operation returns a fault. + [!code-csharp[C_UsingTheMessageClass#4](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_usingthemessageclass/cs/source.cs#4)] - [!code-vb[C_UsingTheMessageClass#4](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#4)] - -## Extracting Message Body Data - - The `Message` class supports multiple ways of extracting information from its body. These can be classified into the following categories: - -- Getting the entire message body written out at once to an XML writer. This is referred to as *writing a message*. - -- Getting an XML reader over the message body. This enables you to later access the message body piece-by-piece as required. This is referred to as *reading a message*. - -- The entire message, including its body, can be copied to an in-memory buffer of the type. This is referred to as *copying a message*. - - You can access the body of a `Message` only once, regardless of how it is accessed. A message object has a `State` property, which is initially set to Created. The three access methods described in the preceding list set the state to Written, Read, and Copied, respectively. Additionally, a `Close` method can set the state to Closed when the message body contents are no longer required. The message body can be accessed only in the Created state, and there is no way to go back to the Created state after the state has changed. - -## Writing Messages - - The method writes out the body contents of a given `Message` instance to a given XML writer. The method does the same, except that it encloses the body contents in the appropriate wrapper element (for example, <`soap:body`>). Finally, writes out the entire message, including the wrapping SOAP envelope and the headers. If SOAP is turned off ( is ), all three methods do the same thing: they write out the message body contents. - - For example, the following code writes out the body of an incoming message to a file. - + [!code-vb[C_UsingTheMessageClass#4](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#4)] + +## Extracting Message Body Data + + The `Message` class supports multiple ways of extracting information from its body. These can be classified into the following categories: + +- Getting the entire message body written out at once to an XML writer. This is referred to as *writing a message*. + +- Getting an XML reader over the message body. This enables you to later access the message body piece-by-piece as required. This is referred to as *reading a message*. + +- The entire message, including its body, can be copied to an in-memory buffer of the type. This is referred to as *copying a message*. + + You can access the body of a `Message` only once, regardless of how it is accessed. A message object has a `State` property, which is initially set to Created. The three access methods described in the preceding list set the state to Written, Read, and Copied, respectively. Additionally, a `Close` method can set the state to Closed when the message body contents are no longer required. The message body can be accessed only in the Created state, and there is no way to go back to the Created state after the state has changed. + +## Writing Messages + + The method writes out the body contents of a given `Message` instance to a given XML writer. The method does the same, except that it encloses the body contents in the appropriate wrapper element (for example, ``). Finally, writes out the entire message, including the wrapping SOAP envelope and the headers. If SOAP is turned off ( is ), all three methods do the same thing: they write out the message body contents. + + For example, the following code writes out the body of an incoming message to a file. + [!code-csharp[C_UsingTheMessageClass#5](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_usingthemessageclass/cs/source.cs#5)] - [!code-vb[C_UsingTheMessageClass#5](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#5)] - - Two additional helper methods write out certain SOAP start element tags. These methods do not access the message body and so they do not change the message state. These include: - -- writes the start body element, for example, ``. - -- writes the start envelope element, for example, ``. - - To write the corresponding end element tags, call `WriteEndElement` on the corresponding XML writer. These methods are rarely called directly. - -## Reading Messages - - The primary way to read a message body is to call . You get back an that you can use to read the message body. Note that the transitions to the Read state as soon as is called, and not when you use the returned XML reader. - - The method also enables you to access the message body as a typed object. Internally, this method uses `GetReaderAtBodyContents`, and so it also transitions the message state to the state (see the property). - - It is good practice to check the property, in which case the message body is empty and throws an . Also, if it is a received message (for example, the reply), you may also want to check , which indicates whether the message contains a fault. - - The most basic overload of deserializes the message body into an instance of a type (indicated by the generic parameter) using a configured with the default settings and with the quota disabled. If you want to use a different serialization engine, or configure the `DataContractSerializer` in a non-default way, use the overload that takes an . - - For example, the following code extracts data from a message body that contains a serialized `Person` object and prints out the person’s name. - + [!code-vb[C_UsingTheMessageClass#5](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#5)] + + Two additional helper methods write out certain SOAP start element tags. These methods do not access the message body and so they do not change the message state. These include: + +- writes the start body element, for example, ``. + +- writes the start envelope element, for example, ``. + + To write the corresponding end element tags, call `WriteEndElement` on the corresponding XML writer. These methods are rarely called directly. + +## Reading Messages + + The primary way to read a message body is to call . You get back an that you can use to read the message body. Note that the transitions to the Read state as soon as is called, and not when you use the returned XML reader. + + The method also enables you to access the message body as a typed object. Internally, this method uses `GetReaderAtBodyContents`, and so it also transitions the message state to the state (see the property). + + It is good practice to check the property, in which case the message body is empty and throws an . Also, if it is a received message (for example, the reply), you may also want to check , which indicates whether the message contains a fault. + + The most basic overload of deserializes the message body into an instance of a type (indicated by the generic parameter) using a configured with the default settings and with the quota disabled. If you want to use a different serialization engine, or configure the `DataContractSerializer` in a non-default way, use the overload that takes an . + + For example, the following code extracts data from a message body that contains a serialized `Person` object and prints out the person’s name. + [!code-csharp[C_UsingTheMessageClass#6](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_usingthemessageclass/cs/source.cs#6)] - [!code-vb[C_UsingTheMessageClass#6](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#6)] - -## Copying a Message into a Buffer - - Sometimes it is necessary to access the message body more than once, for example, to forward the same message to multiple destinations as part of a publisher-subscriber system. In this case, it is necessary to buffer the entire message (including the body) in memory. You can do this by calling . This method takes an integer parameter that represents the maximum buffer size, and creates a buffer not larger than this size. It is important to set this to a safe value if the message is coming from an untrusted source. - - The buffer is returned as a instance. You can access data in the buffer in several ways. The primary way is to call to create `Message` instances from the buffer. - - Another way to access the data in the buffer is to implement the interface that the class implements to access the underlying XML directly. Some overloads allow you to create navigators protected by a node quota, limiting the number of XML nodes that can be visited. This helps prevent denial of service attacks based on lengthy processing time. This quote is disabled by default. Some `CreateNavigator` overloads allow you to specify how white space should be handled in the XML using the enumeration, with the default being `XmlSpace.None`. - - A final way to access the contents of a message buffer is to write out its contents to a stream using . - - The following example demonstrates the process of working with a `MessageBuffer`: an incoming message is forwarded to multiple recipients, and then logged to a file. Without buffering, this is not possible, because the message body can then be accessed only once. - + [!code-vb[C_UsingTheMessageClass#6](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#6)] + +## Copying a Message into a Buffer + + Sometimes it is necessary to access the message body more than once, for example, to forward the same message to multiple destinations as part of a publisher-subscriber system. In this case, it is necessary to buffer the entire message (including the body) in memory. You can do this by calling . This method takes an integer parameter that represents the maximum buffer size, and creates a buffer not larger than this size. It is important to set this to a safe value if the message is coming from an untrusted source. + + The buffer is returned as a instance. You can access data in the buffer in several ways. The primary way is to call to create `Message` instances from the buffer. + + Another way to access the data in the buffer is to implement the interface that the class implements to access the underlying XML directly. Some overloads allow you to create navigators protected by a node quota, limiting the number of XML nodes that can be visited. This helps prevent denial of service attacks based on lengthy processing time. This quote is disabled by default. Some `CreateNavigator` overloads allow you to specify how white space should be handled in the XML using the enumeration, with the default being `XmlSpace.None`. + + A final way to access the contents of a message buffer is to write out its contents to a stream using . + + The following example demonstrates the process of working with a `MessageBuffer`: an incoming message is forwarded to multiple recipients, and then logged to a file. Without buffering, this is not possible, because the message body can then be accessed only once. + [!code-csharp[C_UsingTheMessageClass#7](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_usingthemessageclass/cs/source.cs#7)] - [!code-vb[C_UsingTheMessageClass#7](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#7)] - - The `MessageBuffer` class has other members worth noting. The method can be called to free resources when the buffer contents are no longer required. The property returns the size of the allocated buffer. The property returns the MIME content type of the message. - -## Accessing the Message Body for Debugging - - For debugging purposes, you can call the method to get a representation of the message as a string. This representation generally matches the way a message would look on the wire if it were encoded with the text encoder, except that the XML would be better formatted for human readability. The one exception to this is the message body. The body can be read only once, and `ToString` does not change the message state. Therefore, the `ToString` method might not be able to access the body and might substitute a placeholder (for example, "…" or three dots) instead of the message body. Therefore, do not use `ToString` to log messages if the body content of the messages is important. - -## Accessing Other Message Parts - - Various properties are provided to access information about the message other than its body contents. However, these cannot be called once the message has been closed: - -- The property represents the message headers. See the section on "Working with Headers" later in this topic. - -- The property represents the message properties, which are pieces of named data attached to the message that do not generally get emitted when the message is sent. See the section on "Working with Properties" later in this topic. - -- The property indicates the SOAP and WS-Addressing version associated with the message, or `None` if SOAP is disabled. - -- The property returns `true` if the message is a SOAP fault message. - -- The property returns `true` if the message is empty. - - You can use the method to access a particular attribute on the body wrapper element (for example, ``) identified by a particular name and namespace. If such an attribute is not found, `null` is returned. This method can be called only when the `Message` is in the Created state (when the message body has not yet been accessed). - -## Working with Headers - - A `Message` can contain any number of named XML fragments, called *headers*. Each fragment normally maps to a SOAP header. Headers are accessed through the `Headers` property of type . is a collection of objects, and individual headers can be accessed through its interface or through its indexer. For example, the following code lists the names of all the headers in a `Message`. - + [!code-vb[C_UsingTheMessageClass#7](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#7)] + + The `MessageBuffer` class has other members worth noting. The method can be called to free resources when the buffer contents are no longer required. The property returns the size of the allocated buffer. The property returns the MIME content type of the message. + +## Accessing the Message Body for Debugging + + For debugging purposes, you can call the method to get a representation of the message as a string. This representation generally matches the way a message would look on the wire if it were encoded with the text encoder, except that the XML would be better formatted for human readability. The one exception to this is the message body. The body can be read only once, and `ToString` does not change the message state. Therefore, the `ToString` method might not be able to access the body and might substitute a placeholder (for example, "…" or three dots) instead of the message body. Therefore, do not use `ToString` to log messages if the body content of the messages is important. + +## Accessing Other Message Parts + + Various properties are provided to access information about the message other than its body contents. However, these cannot be called once the message has been closed: + +- The property represents the message headers. See the section on "Working with Headers" later in this topic. + +- The property represents the message properties, which are pieces of named data attached to the message that do not generally get emitted when the message is sent. See the section on "Working with Properties" later in this topic. + +- The property indicates the SOAP and WS-Addressing version associated with the message, or `None` if SOAP is disabled. + +- The property returns `true` if the message is a SOAP fault message. + +- The property returns `true` if the message is empty. + + You can use the method to access a particular attribute on the body wrapper element (for example, ``) identified by a particular name and namespace. If such an attribute is not found, `null` is returned. This method can be called only when the `Message` is in the Created state (when the message body has not yet been accessed). + +## Working with Headers + + A `Message` can contain any number of named XML fragments, called *headers*. Each fragment normally maps to a SOAP header. Headers are accessed through the `Headers` property of type . is a collection of objects, and individual headers can be accessed through its interface or through its indexer. For example, the following code lists the names of all the headers in a `Message`. + [!code-csharp[C_UsingTheMessageClass#8](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_usingthemessageclass/cs/source.cs#8)] - [!code-vb[C_UsingTheMessageClass#8](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#8)] - -#### Adding, Removing, Finding Headers - - You can add a new header at the end of all existing headers using the method. You can use the method to insert a header at a particular index. Existing headers are shifted for the inserted item. Headers are ordered according to their index, and the first available index is 0. You can use the various method overloads to add headers from a different `Message` or `MessageHeaders` instance. Some overloads copy one individual header, while others copy all of them. The method removes all headers. The method removes a header at a particular index (shifting all headers after it). The method removes all headers with a particular name and namespace. - - Retrieve a particular header using the method. This method takes the name and namespace of the header to find, and returns its index. If the header occurs more than once, an exception is thrown. If the header is not found, it returns -1. - - In the SOAP header model, headers can have an `Actor` value that specifies the intended recipient of the header. The most basic `FindHeader` overload searches only headers intended for the ultimate receiver of the message. However, another overload enables you to specify which `Actor` values are included in the search. For more information, see the SOAP specification. - - A method is provided to copy headers from a collection to an array of objects. - - To access the XML data in a header, you can call and return an XML reader for the specific header index. If you want to deserialize the header contents into an object, use or one of the other overloads. The most basic overloads deserialize headers using the configured in the default way. If you want to use a different serializer or a different configuration of the `DataContractSerializer`, use one of the overloads that take an `XmlObjectSerializer`. There are also overloads that take the header name, namespace, and optionally a list of `Actor` values instead of an index; this is a combination of `FindHeader` and `GetHeader`. - -## Working with Properties - - A `Message` instance can contain an arbitrary number of named objects of arbitrary types. This collection is accessed through the `Properties` property of type `MessageProperties`. The collection implements the interface and acts as a mapping from to . Normally, property values do not map directly to any part of the message on the wire, but rather provide various message processing hints to the various channels in the WCF channel stack or to the service framework. For an example, see [Data Transfer Architectural Overview](data-transfer-architectural-overview.md). - -## Inheriting from the Message Class - - If the built-in message types created using `CreateMessage` do not meet your requirements, create a class that derives from the `Message` class. - -### Defining the Message Body Contents - - Three primary techniques exist for accessing data within a message body: writing, reading, and copying it to a buffer. These operations ultimately result in the , , and methods being called, respectively, on your derived class of `Message`. The base `Message` class guarantees that only one of these methods is called for each `Message` instance, and that it is not called more than once. The base class also ensures that the methods are not called on a closed message. There is no need to track the message state in your implementation. - - is an abstract method and must be implemented. The most basic way to define the body contents of your message is to write using this method. For example, the following message contains 100,000 random numbers from 1 to 20. - + [!code-vb[C_UsingTheMessageClass#8](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#8)] + +#### Adding, Removing, Finding Headers + + You can add a new header at the end of all existing headers using the method. You can use the method to insert a header at a particular index. Existing headers are shifted for the inserted item. Headers are ordered according to their index, and the first available index is 0. You can use the various method overloads to add headers from a different `Message` or `MessageHeaders` instance. Some overloads copy one individual header, while others copy all of them. The method removes all headers. The method removes a header at a particular index (shifting all headers after it). The method removes all headers with a particular name and namespace. + + Retrieve a particular header using the method. This method takes the name and namespace of the header to find, and returns its index. If the header occurs more than once, an exception is thrown. If the header is not found, it returns -1. + + In the SOAP header model, headers can have an `Actor` value that specifies the intended recipient of the header. The most basic `FindHeader` overload searches only headers intended for the ultimate receiver of the message. However, another overload enables you to specify which `Actor` values are included in the search. For more information, see the SOAP specification. + + A method is provided to copy headers from a collection to an array of objects. + + To access the XML data in a header, you can call and return an XML reader for the specific header index. If you want to deserialize the header contents into an object, use or one of the other overloads. The most basic overloads deserialize headers using the configured in the default way. If you want to use a different serializer or a different configuration of the `DataContractSerializer`, use one of the overloads that take an `XmlObjectSerializer`. There are also overloads that take the header name, namespace, and optionally a list of `Actor` values instead of an index; this is a combination of `FindHeader` and `GetHeader`. + +## Working with Properties + + A `Message` instance can contain an arbitrary number of named objects of arbitrary types. This collection is accessed through the `Properties` property of type `MessageProperties`. The collection implements the interface and acts as a mapping from to . Normally, property values do not map directly to any part of the message on the wire, but rather provide various message processing hints to the various channels in the WCF channel stack or to the service framework. For an example, see [Data Transfer Architectural Overview](data-transfer-architectural-overview.md). + +## Inheriting from the Message Class + + If the built-in message types created using `CreateMessage` do not meet your requirements, create a class that derives from the `Message` class. + +### Defining the Message Body Contents + + Three primary techniques exist for accessing data within a message body: writing, reading, and copying it to a buffer. These operations ultimately result in the , , and methods being called, respectively, on your derived class of `Message`. The base `Message` class guarantees that only one of these methods is called for each `Message` instance, and that it is not called more than once. The base class also ensures that the methods are not called on a closed message. There is no need to track the message state in your implementation. + + is an abstract method and must be implemented. The most basic way to define the body contents of your message is to write using this method. For example, the following message contains 100,000 random numbers from 1 to 20. + [!code-csharp[C_UsingTheMessageClass#9](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_usingthemessageclass/cs/source.cs#9)] - [!code-vb[C_UsingTheMessageClass#9](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#9)] - - The and methods have default implementations that work for most cases. The default implementations call , buffer the results, and work with the resulting buffer. However, in some cases this may not be enough. In the preceding example, reading the message results in 100,000 XML elements being buffered, which might not be desirable. You might want to override to return a custom derived class that serves up random numbers. You can then override to use the reader that the method returns, as shown in the following example. - + [!code-vb[C_UsingTheMessageClass#9](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#9)] + + The and methods have default implementations that work for most cases. The default implementations call , buffer the results, and work with the resulting buffer. However, in some cases this may not be enough. In the preceding example, reading the message results in 100,000 XML elements being buffered, which might not be desirable. You might want to override to return a custom derived class that serves up random numbers. You can then override to use the reader that the method returns, as shown in the following example. + [!code-csharp[C_UsingTheMessageClass#10](../../../../samples/snippets/csharp/VS_Snippets_CFX/c_usingthemessageclass/cs/source.cs#10)] - [!code-vb[C_UsingTheMessageClass#10](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#10)] - - Similarly, you might want to override `OnCreateBufferedCopy` to return your own `MessageBuffer` derived class. - - In addition to providing message body contents, your message derived class must also override the `Version`, `Headers`, and `Properties` properties. - - Note that if you create a copy of a message, the copy uses the message headers from the original. - -### Other Members that Can Be Overridden - - You can override the , , and methods to specify how the SOAP envelope, SOAP headers, and SOAP body element start tags are written out. These normally correspond to ``, ``, and ``. These methods should normally not write anything out if the property returns . - + [!code-vb[C_UsingTheMessageClass#10](../../../../samples/snippets/visualbasic/VS_Snippets_CFX/c_usingthemessageclass/vb/source.vb#10)] + + Similarly, you might want to override `OnCreateBufferedCopy` to return your own `MessageBuffer` derived class. + + In addition to providing message body contents, your message derived class must also override the `Version`, `Headers`, and `Properties` properties. + + Note that if you create a copy of a message, the copy uses the message headers from the original. + +### Other Members that Can Be Overridden + + You can override the , , and methods to specify how the SOAP envelope, SOAP headers, and SOAP body element start tags are written out. These normally correspond to ``, ``, and ``. These methods should normally not write anything out if the property returns . + > [!NOTE] -> The default implementation of `OnGetReaderAtBodyContents` calls `OnWriteStartEnvelope` and `OnWriteStartBody` before calling `OnWriteBodyContents` and buffering the results. Headers are not written out. - - Override the method to change the way the entire message is constructed from its various pieces. The `OnWriteMessage` method is called from and from the default implementation. Note that overriding is not a best practice. It is better to override the appropriate `On` methods (for example, , , and . - - Override to override how your message body is represented during debugging. The default is to represent it as three dots ("…"). Note that this method can be called multiple times when the message state is anything other than Closed. An implementation of this method should never cause any action that must be performed only once (such as reading from a forward-only stream). - - Override the method to allow access to attributes on the SOAP body element. This method can be called any number of times, but the `Message` base type guarantees that it is only called when the message is in the Created state. It is not required to check the state in an implementation. The default implementation always returns `null`, which indicates that there are no attributes on the body element. - - If your `Message` object must do any special cleanup when the message body is no longer required, you can override . The default implementation does nothing. - +> The default implementation of `OnGetReaderAtBodyContents` calls `OnWriteStartEnvelope` and `OnWriteStartBody` before calling `OnWriteBodyContents` and buffering the results. Headers are not written out. + + Override the method to change the way the entire message is constructed from its various pieces. The `OnWriteMessage` method is called from and from the default implementation. Note that overriding is not a best practice. It is better to override the appropriate `On` methods (for example, , , and . + + Override to override how your message body is represented during debugging. The default is to represent it as three dots ("…"). Note that this method can be called multiple times when the message state is anything other than Closed. An implementation of this method should never cause any action that must be performed only once (such as reading from a forward-only stream). + + Override the method to allow access to attributes on the SOAP body element. This method can be called any number of times, but the `Message` base type guarantees that it is only called when the message is in the Created state. It is not required to check the state in an implementation. The default implementation always returns `null`, which indicates that there are no attributes on the body element. + + If your `Message` object must do any special cleanup when the message body is no longer required, you can override . The default implementation does nothing. + The `IsEmpty` and `IsFault` properties can be overridden. By default, both return `false`. diff --git a/docs/framework/wcf/host-a-wcf-service-net-framework-3-5-iis--net-framework-4.md b/docs/framework/wcf/host-a-wcf-service-net-framework-3-5-iis--net-framework-4.md index 9176c0732a05f..f776b58e72ff1 100644 --- a/docs/framework/wcf/host-a-wcf-service-net-framework-3-5-iis--net-framework-4.md +++ b/docs/framework/wcf/host-a-wcf-service-net-framework-3-5-iis--net-framework-4.md @@ -21,7 +21,7 @@ The application domain or application pool is currently running version 4.0 or l These errors occur because the application domain IIS is running within is running .NET Framework 4 and the WCF service is expecting to run under .NET Framework 3.5. This topic explains the modifications required to get the service to run. - Next find the <`compilers`> element and change the CompilerVersion provider option to have a value of 4.0. By default, there are two <`compiler`> elements under the <`compilers`> element. You must update the CompilerVersion provider option for both as shown in the following example. + Next find the `` element and change the CompilerVersion provider option to have a value of 4.0. By default, there are two `` elements under the `` element. You must update the CompilerVersion provider option for both as shown in the following example. ```xml @@ -43,9 +43,9 @@ The application domain or application pool is currently running version 4.0 or l ### Add the required targetFramework attribute -1. Open the service's Web.config file and look for the <`compilation`> element. +1. Open the service's Web.config file and look for the `` element. -2. Add the `targetFramework` attribute to the <`compilation`> element as shown in the following example. +2. Add the `targetFramework` attribute to the `` element as shown in the following example. ```xml ``` -3. Find the <`compilers`> element and change the CompilerVersion provider option to have a value of 4.0. By default, there are two <`compiler`> elements under the <`compilers`> element. You must update the CompilerVersion provider option for both as shown in the following example. +3. Find the `` element and change the CompilerVersion provider option to have a value of 4.0. By default, there are two `` elements under the `` element. You must update the CompilerVersion provider option for both as shown in the following example. ```xml diff --git a/docs/framework/wcf/how-to-secure-a-service-with-windows-credentials.md b/docs/framework/wcf/how-to-secure-a-service-with-windows-credentials.md index 2a45bc22746a8..55ce4ff640666 100644 --- a/docs/framework/wcf/how-to-secure-a-service-with-windows-credentials.md +++ b/docs/framework/wcf/how-to-secure-a-service-with-windows-credentials.md @@ -1,6 +1,6 @@ --- title: "How to: Secure a Service with Windows Credentials" -description: Learn how to enable transport security on a WCF service that resides in a Windows domain and is called by clients in the same domain. +description: Learn how to enable transport security on a WCF service that resides in a Windows domain and is called by clients in the same domain. ms.date: "03/30/2017" dev_langs: - "csharp" @@ -103,11 +103,11 @@ If you do not already have a service defined, see [Designing and Implementing Se 1. Add a [\](../configure-apps/file-schema/wcf/wshttpbinding.md) element to the [\](../configure-apps/file-schema/wcf/bindings.md) element section of the configuration file. -2. Add a <`binding`> element to the <`WSHttpBinding`> element and set the `configurationName` attribute to a value appropriate to your application. +2. Add a `` element to the `` element and set the `configurationName` attribute to a value appropriate to your application. -3. Add a <`security`> element and set the `mode` attribute to Message. +3. Add a `` element and set the `mode` attribute to Message. -4. Add a <`message`> element and set the `clientCredentialType` attribute to Windows. +4. Add a `` element and set the `clientCredentialType` attribute to Windows. 5. In the service's configuration file, replace the `` section with the following code. If you do not already have a service configuration file, see [Using Bindings to Configure Services and Clients](using-bindings-to-configure-services-and-clients.md). diff --git a/docs/framework/wcf/samples/aspnet-caching-integration.md b/docs/framework/wcf/samples/aspnet-caching-integration.md index e433f7001ab53..fcc96c4ea1ffa 100644 --- a/docs/framework/wcf/samples/aspnet-caching-integration.md +++ b/docs/framework/wcf/samples/aspnet-caching-integration.md @@ -16,7 +16,7 @@ Integration with the ASP.NET Output Cache. The sample uses the to utilize ASP.NET output caching with the Windows Communication Foundation (WCF) service. The is applied to service operations, and provides the name of a cache profile in a configuration file that should be applied to responses from the given operation. -In the Service.cs file of the sample Service project, both the `GetCustomer` and `GetCustomers` operations are marked with the , which provides the cache profile name "CacheFor60Seconds". In the Web.config file of the Service project, the cache profile "CacheFor60Seconds" is provided under the <`caching`> element of <`system.web`>. For this cache profile, the value of the `duration` attribute is "60", so responses associated with this profile are cached in the ASP.NET output cache for 60 seconds. Also, for this cache profile, the `varmByParam` attribute is set to "format" so requests with different values for the `format` query string parameter have their responses cached separately. Lastly, the cache profile's `varyByHeader` attribute is set to "Accept", so requests with different Accept header values have their responses cached separately. +In the Service.cs file of the sample Service project, both the `GetCustomer` and `GetCustomers` operations are marked with the , which provides the cache profile name "CacheFor60Seconds". In the Web.config file of the Service project, the cache profile "CacheFor60Seconds" is provided under the `` element of ``. For this cache profile, the value of the `duration` attribute is "60", so responses associated with this profile are cached in the ASP.NET output cache for 60 seconds. Also, for this cache profile, the `varmByParam` attribute is set to "format" so requests with different values for the `format` query string parameter have their responses cached separately. Lastly, the cache profile's `varyByHeader` attribute is set to "Accept", so requests with different Accept header values have their responses cached separately. Program.cs in the Client project demonstrates how such a client can be authored using . Note that this is just one way to access a WCF service. It is also possible to access the service using other .NET Framework classes like the WCF channel factory and . Other samples in the SDK (such as the [Basic HTTP Service](basic-http-service.md) sample) illustrate how to use these classes to communicate with a WCF service. diff --git a/docs/framework/wcf/samples/basicbinding.md b/docs/framework/wcf/samples/basicbinding.md index bb19b02326d80..35d6c8ef68249 100644 --- a/docs/framework/wcf/samples/basicbinding.md +++ b/docs/framework/wcf/samples/basicbinding.md @@ -15,7 +15,7 @@ The [Http sample](https://github.com/dotnet/samples/tree/main/framework/wcf/Basi This sample is based on the [Getting Started](getting-started-sample.md) that implements a calculator service. -To use the basic binding with default behavior, only the binding section name is required. If you want to configure the basic binding and change some of its settings, it is necessary to define a binding configuration. The endpoint must reference the binding configuration by name by using the `bindingConfiguration` attribute of the <`endpoint`> element, as shown in the following sample code. +To use the basic binding with default behavior, only the binding section name is required. If you want to configure the basic binding and change some of its settings, it is necessary to define a binding configuration. The endpoint must reference the binding configuration by name by using the `bindingConfiguration` attribute of the `` element, as shown in the following sample code. ```xml diff --git a/docs/framework/wcf/samples/soap-and-http-endpoints.md b/docs/framework/wcf/samples/soap-and-http-endpoints.md index ec2205ae4e444..05eae88cfc5f7 100644 --- a/docs/framework/wcf/samples/soap-and-http-endpoints.md +++ b/docs/framework/wcf/samples/soap-and-http-endpoints.md @@ -26,7 +26,7 @@ The Web.config file configures the WCF service with 3 endpoints: - The ~/service.svc/soap endpoint that allows the clients to access the service using the SOAP over HTTP binding. -The HTTP endpoint is configured with a <`webHttp`> standard endpoint which has `helpEnabled` set to `true`. As a result, the service exposes an XHTML based help page at ~/service.svc/http/help that HTTP-based clients can use to access the service. +The HTTP endpoint is configured with a `` standard endpoint which has `helpEnabled` set to `true`. As a result, the service exposes an XHTML based help page at ~/service.svc/http/help that HTTP-based clients can use to access the service. The client project demonstrates accessing the service using a SOAP proxy (generated through **Add Service Reference**) and accessing the service using . diff --git a/docs/framework/wcf/samples/udp-activation.md b/docs/framework/wcf/samples/udp-activation.md index 5022073ce11be..bf6ce823214bf 100644 --- a/docs/framework/wcf/samples/udp-activation.md +++ b/docs/framework/wcf/samples/udp-activation.md @@ -44,7 +44,7 @@ When the callback `ConfigManagerInitializationCompleted` is received, it indicat When a new request comes in the first time for an application, the listener adapter calls `WebhostOpenListenerChannelInstance` into WAS, which starts the worker process if it is not started yet. Then the protocol handlers are loaded and the communication between the listener adapter and the virtual application can start. -The listener adapter is registered in the %SystemRoot%\System32\inetsrv\ApplicationHost.config in the <`listenerAdapters`> section as following: +The listener adapter is registered in the %SystemRoot%\System32\inetsrv\ApplicationHost.config in the `` section as following: ```xml diff --git a/docs/framework/wcf/simplified-configuration.md b/docs/framework/wcf/simplified-configuration.md index 4c42a00d5ac18..013864f6e4c6e 100644 --- a/docs/framework/wcf/simplified-configuration.md +++ b/docs/framework/wcf/simplified-configuration.md @@ -9,7 +9,7 @@ Configuring Windows Communication Foundation (WCF) services can be a complex tas ## Simplified Configuration - In WCF service configuration files, the <`system.serviceModel`> section contains a <`service`> element for each service hosted. The <`service`> element contains a collection of <`endpoint`> elements that specify the endpoints exposed for each service and optionally a set of service behaviors. The <`endpoint`> elements specify the address, binding, and contract exposed by the endpoint, and optionally binding configuration and endpoint behaviors. The <`system.serviceModel`> section also contains a <`behaviors`> element that allows you to specify service or endpoint behaviors. The following example shows the <`system.serviceModel`> section of a configuration file. + In WCF service configuration files, the `` section contains a `` element for each service hosted. The `` element contains a collection of `` elements that specify the endpoints exposed for each service and optionally a set of service behaviors. The `` elements specify the address, binding, and contract exposed by the endpoint, and optionally binding configuration and endpoint behaviors. The `` section also contains a `` element that allows you to specify service or endpoint behaviors. The following example shows the `` section of a configuration file. ```xml @@ -42,7 +42,7 @@ Configuring Windows Communication Foundation (WCF) services can be a complex tas ``` - .NET Framework 4.6.1 makes configuring a WCF service easier by removing the requirement for the <`service`> element. If you do not add a <`service`> section or add any endpoints in a <`service`> section and your service does not programmatically define any endpoints, then a set of default endpoints are automatically added to your service, one for each service base address and for each contract implemented by your service. In each of these endpoints, the endpoint address corresponds to the base address, the binding is determined by the base address scheme and the contract is the one implemented by your service. If you do not need to specify any endpoints or service behaviors or make any binding setting changes, you do not need to specify a service configuration file at all. If a service implements two contracts and the host enables both HTTP and TCP transports the service host creates four default endpoints, one for each contract using each transport. To create default endpoints the service host must know what bindings to use. These settings are specified in a <`protocolMappings`> section within the <`system.serviceModel`> section. The <`protocolMappings`> section contains a list of transport protocol schemes mapped to binding types. The service host uses the base addresses passed to it to determine which binding to use. The following example uses the <`protocolMappings`> element. + .NET Framework 4.6.1 makes configuring a WCF service easier by removing the requirement for the `` element. If you do not add a `` section or add any endpoints in a `` section and your service does not programmatically define any endpoints, then a set of default endpoints are automatically added to your service, one for each service base address and for each contract implemented by your service. In each of these endpoints, the endpoint address corresponds to the base address, the binding is determined by the base address scheme and the contract is the one implemented by your service. If you do not need to specify any endpoints or service behaviors or make any binding setting changes, you do not need to specify a service configuration file at all. If a service implements two contracts and the host enables both HTTP and TCP transports the service host creates four default endpoints, one for each contract using each transport. To create default endpoints the service host must know what bindings to use. These settings are specified in a `` section within the `` section. The `` section contains a list of transport protocol schemes mapped to binding types. The service host uses the base addresses passed to it to determine which binding to use. The following example uses the `` element. > [!WARNING] > Changing default configuration elements, such as bindings or behaviors, might affect services defined in lower levels of the configuration hierarchy, since they might be using these default bindings and behaviors. Thus, whoever changes default bindings and behaviors needs to be aware that these changes might affect other services in the hierarchy. @@ -61,9 +61,9 @@ Configuring Windows Communication Foundation (WCF) services can be a complex tas In the previous example, an endpoint with a base address that starts with the "http" scheme uses the . An endpoint with a base address that starts with the "net.tcp" scheme uses the . You can override settings in a local App.config or Web.config file. - Each element within the <`protocolMappings`> section must specify a scheme and a binding. Optionally it can specify a `bindingConfiguration` attribute that specifies a binding configuration within the <`bindings`> section of the configuration file. If no `bindingConfiguration` is specified, the anonymous binding configuration of the appropriate binding type is used. + Each element within the `` section must specify a scheme and a binding. Optionally it can specify a `bindingConfiguration` attribute that specifies a binding configuration within the `` section of the configuration file. If no `bindingConfiguration` is specified, the anonymous binding configuration of the appropriate binding type is used. - Service behaviors are configured for the default endpoints by using anonymous <`behavior`> sections within <`serviceBehaviors`> sections. Any unnamed <`behavior`> elements within <`serviceBehaviors`> are used to configure service behaviors. For example, the following configuration file enables service metadata publishing for all services within the host. + Service behaviors are configured for the default endpoints by using anonymous `` sections within `` sections. Any unnamed `` elements within `` are used to configure service behaviors. For example, the following configuration file enables service metadata publishing for all services within the host. ```xml @@ -78,7 +78,7 @@ Configuring Windows Communication Foundation (WCF) services can be a complex tas ``` - Endpoint behaviors are configured by using anonymous <`behavior`> sections within <`serviceBehaviors`> sections. + Endpoint behaviors are configured by using anonymous `` sections within `` sections. The following example is a configuration file equivalent to the one at the beginning of this topic that uses the simplified configuration model. diff --git a/docs/framework/wcf/synchronous-and-asynchronous-operations.md b/docs/framework/wcf/synchronous-and-asynchronous-operations.md index ffdde821d90b2..f8fad831dfe37 100644 --- a/docs/framework/wcf/synchronous-and-asynchronous-operations.md +++ b/docs/framework/wcf/synchronous-and-asynchronous-operations.md @@ -2,201 +2,201 @@ title: "Synchronous and Asynchronous Operations" description: Learn about implementing and calling asynchronous service operations. WCF services and clients can use asynchronous operations at two levels of the application. ms.date: "03/30/2017" -dev_langs: +dev_langs: - "csharp" - "vb" -helpviewer_keywords: +helpviewer_keywords: - "service contracts [WCF], synchronous operations" - "service contracts [WCF], asynchronous operations" ms.assetid: db8a51cb-67e6-411b-9035-e5821ed350c9 --- # Synchronous and Asynchronous Operations -This topic discusses implementing and calling asynchronous service operations. - - Many applications call methods asynchronously because it enables the application to continue doing useful work while the method call runs. Windows Communication Foundation (WCF) services and clients can participate in asynchronous operation calls at two distinct levels of the application, which provide WCF applications even more flexibility to maximize throughput balanced against interactivity. - -## Types of Asynchronous Operations - - All service contracts in WCF, no matter the parameters types and return values, use WCF attributes to specify a particular message exchange pattern between client and service. WCF automatically routes inbound and outbound messages to the appropriate service operation or running client code. - - The client possesses only the service contract, which specifies the message exchange pattern for a particular operation. Clients can offer the developer any programming model they choose, so long as the underlying message exchange pattern is observed. So, too, can services implement operations in any manner, so long as the specified message pattern is observed. - - The independence of the service contract from either the service or client implementation enables the following forms of asynchronous execution in WCF applications: - -- Clients can invoke request/response operations asynchronously using a synchronous message exchange. - -- Services can implement a request/response operation asynchronously using a synchronous message exchange. - -- Message exchanges can be one-way, regardless of the implementation of the client or service. - -### Suggested Asynchronous Scenarios - - Use an asynchronous approach in a service operation implementation if the operation service implementation makes a blocking call, such as doing I/O work. When you are in an asynchronous operation implementation, try to call asynchronous operations and methods to extend the asynchronous call path as far as possible. For example, call a `BeginOperationTwo()` from within `BeginOperationOne()`. - -- Use an asynchronous approach in a client or calling application in the following cases: - -- If you are invoking operations from a middle-tier application. (For more information about such scenarios, see [Middle-Tier Client Applications](./feature-details/middle-tier-client-applications.md).) - -- If you are invoking operations within an ASP.NET page, use asynchronous pages. - -- If you are invoking operations from any application that is single threaded, such as Windows Forms or Windows Presentation Foundation (WPF). When using the event-based asynchronous calling model, the result event is raised on the UI thread, adding responsiveness to the application without requiring you to handle multiple threads yourself. - -- In general, if you have a choice between a synchronous and asynchronous call, choose the asynchronous call. - -### Implementing an Asynchronous Service Operation - - Asynchronous operations can be implemented by using one of the three following methods: - -1. The task-based asynchronous pattern - -2. The event-based asynchronous pattern - -3. The IAsyncResult asynchronous pattern - -#### Task-Based Asynchronous Pattern - - The task-based asynchronous pattern is the preferred way to implement asynchronous operations because it is the easiest and most straight forward. To use this method simply implement your service operation and specify a return type of Task\, where T is the type returned by the logical operation. For example: - -```csharp +This topic discusses implementing and calling asynchronous service operations. + + Many applications call methods asynchronously because it enables the application to continue doing useful work while the method call runs. Windows Communication Foundation (WCF) services and clients can participate in asynchronous operation calls at two distinct levels of the application, which provide WCF applications even more flexibility to maximize throughput balanced against interactivity. + +## Types of Asynchronous Operations + + All service contracts in WCF, no matter the parameters types and return values, use WCF attributes to specify a particular message exchange pattern between client and service. WCF automatically routes inbound and outbound messages to the appropriate service operation or running client code. + + The client possesses only the service contract, which specifies the message exchange pattern for a particular operation. Clients can offer the developer any programming model they choose, so long as the underlying message exchange pattern is observed. So, too, can services implement operations in any manner, so long as the specified message pattern is observed. + + The independence of the service contract from either the service or client implementation enables the following forms of asynchronous execution in WCF applications: + +- Clients can invoke request/response operations asynchronously using a synchronous message exchange. + +- Services can implement a request/response operation asynchronously using a synchronous message exchange. + +- Message exchanges can be one-way, regardless of the implementation of the client or service. + +### Suggested Asynchronous Scenarios + + Use an asynchronous approach in a service operation implementation if the operation service implementation makes a blocking call, such as doing I/O work. When you are in an asynchronous operation implementation, try to call asynchronous operations and methods to extend the asynchronous call path as far as possible. For example, call a `BeginOperationTwo()` from within `BeginOperationOne()`. + +- Use an asynchronous approach in a client or calling application in the following cases: + +- If you are invoking operations from a middle-tier application. (For more information about such scenarios, see [Middle-Tier Client Applications](./feature-details/middle-tier-client-applications.md).) + +- If you are invoking operations within an ASP.NET page, use asynchronous pages. + +- If you are invoking operations from any application that is single threaded, such as Windows Forms or Windows Presentation Foundation (WPF). When using the event-based asynchronous calling model, the result event is raised on the UI thread, adding responsiveness to the application without requiring you to handle multiple threads yourself. + +- In general, if you have a choice between a synchronous and asynchronous call, choose the asynchronous call. + +### Implementing an Asynchronous Service Operation + + Asynchronous operations can be implemented by using one of the three following methods: + +1. The task-based asynchronous pattern + +2. The event-based asynchronous pattern + +3. The IAsyncResult asynchronous pattern + +#### Task-Based Asynchronous Pattern + + The task-based asynchronous pattern is the preferred way to implement asynchronous operations because it is the easiest and most straight forward. To use this method simply implement your service operation and specify a return type of Task\, where T is the type returned by the logical operation. For example: + +```csharp public class SampleService:ISampleService { - // ... + // ... public async Task SampleMethodTaskAsync(string msg) { return Task.Factory.StartNew(() => { return msg; }); - } - // ... -} -``` - - The SampleMethodTaskAsync operation returns Task\ because the logical operation returns a string. For more information about the task-based asynchronous pattern, see [The Task-Based Asynchronous Pattern](https://go.microsoft.com/fwlink/?LinkId=232504). - + } + // ... +} +``` + + The SampleMethodTaskAsync operation returns Task\ because the logical operation returns a string. For more information about the task-based asynchronous pattern, see [The Task-Based Asynchronous Pattern](https://go.microsoft.com/fwlink/?LinkId=232504). + > [!WARNING] -> When using the task-based asynchronous pattern, a T:System.AggregateException may be thrown if an exception occurs while waiting on the completion of the operation. This exception may occur on the client or services - -#### Event-Based Asynchronous Pattern - - A service that supports the Event-based Asynchronous Pattern will have one or more operations named MethodNameAsync. These methods may mirror synchronous versions, which perform the same operation on the current thread. The class may also have a MethodNameCompleted event and it may have a MethodNameAsyncCancel (or simply CancelAsync) method. A client wishing to call the operation will define an event handler to be called when the operation completes, - - The following code snippet illustrates how to declare asynchronous operations using the event-based asynchronous pattern. - -```csharp -public class AsyncExample -{ - // Synchronous methods. - public int Method1(string param); - public void Method2(double param); - - // Asynchronous methods. - public void Method1Async(string param); - public void Method1Async(string param, object userState); - public event Method1CompletedEventHandler Method1Completed; - - public void Method2Async(double param); - public void Method2Async(double param, object userState); - public event Method2CompletedEventHandler Method2Completed; - - public void CancelAsync(object userState); - - public bool IsBusy { get; } - - // Class implementation not shown. -} -``` - - For more information about the Event-based Asynchronous Pattern, see [The Event-Based Asynchronous Pattern](../../standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-overview.md). - -#### IAsyncResult Asynchronous Pattern - - A service operation can be implemented in an asynchronous fashion using the .NET Framework asynchronous programming pattern and marking the `` method with the property set to `true`. In this case, the asynchronous operation is exposed in metadata in the same form as a synchronous operation: It is exposed as a single operation with a request message and a correlated response message. Client programming models then have a choice. They can represent this pattern as a synchronous operation or as an asynchronous one, so long as when the service is invoked a request-response message exchange takes place. - - In general, with the asynchronous nature of the systems, you should not take a dependency on the threads. The most reliable way of passing data to various stages of operation dispatch processing is to use extensions. - - For an example, see [How to: Implement an Asynchronous Service Operation](how-to-implement-an-asynchronous-service-operation.md). - - To define a contract operation `X` that is executed asynchronously regardless of how it is called in the client application: - -- Define two methods using the pattern `BeginOperation` and `EndOperation`. - -- The `BeginOperation` method includes `in` and `ref` parameters for the operation and returns an type. - -- The `EndOperation` method includes an parameter as well as the `out` and `ref` parameters and returns the operations return type. - - For example, see the following method. - -```csharp -int DoWork(string data, ref string inout, out string outonly) -``` - -```vb -Function DoWork(ByVal data As String, ByRef inout As String, _out outonly As out) As Integer -``` - - To create an asynchronous operation, the two methods would be: - -```csharp +> When using the task-based asynchronous pattern, a T:System.AggregateException may be thrown if an exception occurs while waiting on the completion of the operation. This exception may occur on the client or services + +#### Event-Based Asynchronous Pattern + + A service that supports the Event-based Asynchronous Pattern will have one or more operations named MethodNameAsync. These methods may mirror synchronous versions, which perform the same operation on the current thread. The class may also have a MethodNameCompleted event and it may have a MethodNameAsyncCancel (or simply CancelAsync) method. A client wishing to call the operation will define an event handler to be called when the operation completes, + + The following code snippet illustrates how to declare asynchronous operations using the event-based asynchronous pattern. + +```csharp +public class AsyncExample +{ + // Synchronous methods. + public int Method1(string param); + public void Method2(double param); + + // Asynchronous methods. + public void Method1Async(string param); + public void Method1Async(string param, object userState); + public event Method1CompletedEventHandler Method1Completed; + + public void Method2Async(double param); + public void Method2Async(double param, object userState); + public event Method2CompletedEventHandler Method2Completed; + + public void CancelAsync(object userState); + + public bool IsBusy { get; } + + // Class implementation not shown. +} +``` + + For more information about the Event-based Asynchronous Pattern, see [The Event-Based Asynchronous Pattern](../../standard/asynchronous-programming-patterns/event-based-asynchronous-pattern-overview.md). + +#### IAsyncResult Asynchronous Pattern + + A service operation can be implemented in an asynchronous fashion using the .NET Framework asynchronous programming pattern and marking the `` method with the property set to `true`. In this case, the asynchronous operation is exposed in metadata in the same form as a synchronous operation: It is exposed as a single operation with a request message and a correlated response message. Client programming models then have a choice. They can represent this pattern as a synchronous operation or as an asynchronous one, so long as when the service is invoked a request-response message exchange takes place. + + In general, with the asynchronous nature of the systems, you should not take a dependency on the threads. The most reliable way of passing data to various stages of operation dispatch processing is to use extensions. + + For an example, see [How to: Implement an Asynchronous Service Operation](how-to-implement-an-asynchronous-service-operation.md). + + To define a contract operation `X` that is executed asynchronously regardless of how it is called in the client application: + +- Define two methods using the pattern `BeginOperation` and `EndOperation`. + +- The `BeginOperation` method includes `in` and `ref` parameters for the operation and returns an type. + +- The `EndOperation` method includes an parameter as well as the `out` and `ref` parameters and returns the operations return type. + + For example, see the following method. + +```csharp +int DoWork(string data, ref string inout, out string outonly) +``` + +```vb +Function DoWork(ByVal data As String, ByRef inout As String, _out outonly As out) As Integer +``` + + To create an asynchronous operation, the two methods would be: + +```csharp [OperationContract(AsyncPattern=true)] IAsyncResult BeginDoWork(string data, ref string inout, AsyncCallback callback, object state); -int EndDoWork(ref string inout, out string outonly, IAsyncResult result); -``` - -```vb +int EndDoWork(ref string inout, out string outonly, IAsyncResult result); +``` + +```vb Function BeginDoWork(ByVal data As String, _ ByRef inout As String, _ ByVal callback As AsyncCallback, _ ByVal state As Object) As IAsyncResult -Function EndDoWork(ByRef inout As String, ByRef outonly As String, ByVal result As IAsyncResult) As Integer -``` - +Function EndDoWork(ByRef inout As String, ByRef outonly As String, ByVal result As IAsyncResult) As Integer +``` + > [!NOTE] -> The attribute is applied only to the `BeginDoWork` method. The resulting contract has one WSDL operation named `DoWork`. - -### Client-Side Asynchronous Invocations - - A WCF client application can use any of three asynchronous calling models described previously - - When using the task-based model, simply call the operation using the await keyword as shown in the following code snippet. - -```csharp -await simpleServiceClient.SampleMethodTaskAsync("hello, world"); -``` - - Using the event-based asynchronous pattern only requires adding an event handler to receive a notification of the response -- and the resulting event is raised on the user interface thread automatically. To use this approach, specify both the **/async** and **/tcv:Version35** command options with the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md), as in the following example. - -```console -svcutil http://localhost:8000/servicemodelsamples/service/mex /async /tcv:Version35 -``` - - When this is done, Svcutil.exe generates a WCF client class with the event infrastructure that enables the calling application to implement and assign an event handler to receive the response and take the appropriate action. For a complete example, see [How to: Call Service Operations Asynchronously](./feature-details/how-to-call-wcf-service-operations-asynchronously.md). - - The event-based asynchronous model, however, is only available in .NET Framework 3.5. In addition, it is not supported even in .NET Framework 3.5 when a WCF client channel is created by using a . With WCF client channel objects, you must use objects to invoke your operations asynchronously. To use this approach, specify the **/async** command option with the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md), as in the following example. - -```console +> The attribute is applied only to the `BeginDoWork` method. The resulting contract has one WSDL operation named `DoWork`. + +### Client-Side Asynchronous Invocations + + A WCF client application can use any of three asynchronous calling models described previously + + When using the task-based model, simply call the operation using the await keyword as shown in the following code snippet. + +```csharp +await simpleServiceClient.SampleMethodTaskAsync("hello, world"); +``` + + Using the event-based asynchronous pattern only requires adding an event handler to receive a notification of the response -- and the resulting event is raised on the user interface thread automatically. To use this approach, specify both the **/async** and **/tcv:Version35** command options with the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md), as in the following example. + +```console +svcutil http://localhost:8000/servicemodelsamples/service/mex /async /tcv:Version35 +``` + + When this is done, Svcutil.exe generates a WCF client class with the event infrastructure that enables the calling application to implement and assign an event handler to receive the response and take the appropriate action. For a complete example, see [How to: Call Service Operations Asynchronously](./feature-details/how-to-call-wcf-service-operations-asynchronously.md). + + The event-based asynchronous model, however, is only available in .NET Framework 3.5. In addition, it is not supported even in .NET Framework 3.5 when a WCF client channel is created by using a . With WCF client channel objects, you must use objects to invoke your operations asynchronously. To use this approach, specify the **/async** command option with the [ServiceModel Metadata Utility Tool (Svcutil.exe)](servicemodel-metadata-utility-tool-svcutil-exe.md), as in the following example. + +```console svcutil http://localhost:8000/servicemodelsamples/service/mex /async -``` - - This generates a service contract in which each operation is modeled as a `` method with the property set to `true` and a corresponding `` method. For a complete example using a , see [How to: Call Operations Asynchronously Using a Channel Factory](./feature-details/how-to-call-operations-asynchronously-using-a-channel-factory.md). - - In either case, applications can invoke an operation asynchronously even if the service is implemented synchronously, in the same way that an application can use the same pattern to invoke asynchronously a local synchronous method. How the operation is implemented is not significant to the client; when the response message arrives, its content is dispatched to the client's asynchronous <`End`> method and the client retrieves the information. - -### One-Way Message Exchange Patterns - - You can also create an asynchronous message exchange pattern in which one-way operations (operations for which the is `true` have no correlated response) can be sent in either direction by the client or service independently of the other side. (This uses the duplex message exchange pattern with one-way messages.) In this case, the service contract specifies a one-way message exchange that either side can implement as asynchronous calls or implementations, or not, as appropriate. Generally, when the contract is an exchange of one-way messages, the implementations can largely be asynchronous because once a message is sent the application does not wait for a reply and can continue doing other work. - -### Event-based Asynchronous Clients and Message Contracts - - The design guidelines for the event-based asynchronous model state that if more than one value is returned, one value is returned as the `Result` property and the others are returned as properties on the object. One result of this is that if a client imports metadata using the event-based asynchronous command options and the operation returns more than one value, the default object returns one value as the `Result` property and the remainder are properties of the object. - - If you want to receive the message object as the `Result` property and have the returned values as properties on that object, use the **/messageContract** command option. This generates a signature that returns the response message as the `Result` property on the object. All internal return values are then properties of the response message object. - +``` + + This generates a service contract in which each operation is modeled as a `` method with the property set to `true` and a corresponding `` method. For a complete example using a , see [How to: Call Operations Asynchronously Using a Channel Factory](./feature-details/how-to-call-operations-asynchronously-using-a-channel-factory.md). + + In either case, applications can invoke an operation asynchronously even if the service is implemented synchronously, in the same way that an application can use the same pattern to invoke asynchronously a local synchronous method. How the operation is implemented is not significant to the client; when the response message arrives, its content is dispatched to the client's asynchronous `` method and the client retrieves the information. + +### One-Way Message Exchange Patterns + + You can also create an asynchronous message exchange pattern in which one-way operations (operations for which the is `true` have no correlated response) can be sent in either direction by the client or service independently of the other side. (This uses the duplex message exchange pattern with one-way messages.) In this case, the service contract specifies a one-way message exchange that either side can implement as asynchronous calls or implementations, or not, as appropriate. Generally, when the contract is an exchange of one-way messages, the implementations can largely be asynchronous because once a message is sent the application does not wait for a reply and can continue doing other work. + +### Event-based Asynchronous Clients and Message Contracts + + The design guidelines for the event-based asynchronous model state that if more than one value is returned, one value is returned as the `Result` property and the others are returned as properties on the object. One result of this is that if a client imports metadata using the event-based asynchronous command options and the operation returns more than one value, the default object returns one value as the `Result` property and the remainder are properties of the object. + + If you want to receive the message object as the `Result` property and have the returned values as properties on that object, use the **/messageContract** command option. This generates a signature that returns the response message as the `Result` property on the object. All internal return values are then properties of the response message object. + ## See also -