Export (0) Print
Expand All
27 out of 27 rated this helpful - Rate this topic

Consuming and Hosting WCF Services with Custom Bindings in BizTalk Server

Dd203050.note(en-US,BTS.10).gifNote
To download a copy of this document, go to http://go.microsoft.com/fwlink/?LinkID=131765.

With the realization of the benefits of developing and orchestrating unified business solutions, today’s business organizations adopt the paradigm of Service Oriented Architecture (SOA)-based solution development for the execution of dynamically composed business processes. However, due to the disparate nature of the diverse business applications that exist in an enterprise, many organizations experience daunting challenges in integrating these business applications and services.

This paper discusses the use of Microsoft® BizTalk® Server 2006 R2 and its WCF adapters as a platform for service orientation that alleviates the aforementioned integration challenges. The paper emphasizes the configuration and integration of custom WCF bindings with BizTalk solutions, through the use of the above adapter platform. Furthermore, the paper provides concrete solutions for the identified integration concerns that apply to the orchestration of services through the use of custom WCF bindings.

Purpose of the BizTalk WCF Adapters

Microsoft BizTalk Server 2006 R2, provides a series of WCF adapters that allow BizTalk Server to communicate with WCF-based applications. The BizTalk WCF adapters include five concrete adapters for WCF predefined bindings such as BasicHttpBinding, WsHttpBinding, NetTcpBinding, NetNamedPipeBinding, and NetMsmqBinding to facilitate common WCF interaction scenarios.. Furthermore, two custom adapters are provided to extend the communication capabilities and behaviors of BizTalk through WCF extensibility points such as custom bindings and behaviors.

Primarily, the BizTalk WCF adapters provide the following core capabilities:

  • Receiving messages: Adapters can be configured with a BizTalk receive location to expose a WCF service contract. With this mechanism, ports of an orchestration or schemas can be exposed as WCF services. WCF clients can then use the above published service contract to transmit messages to an orchestration. For more information, see the Hosting a WCF Service Through a BizTalk Server Receive Port section.
  • Sending messages: BizTalk send ports can be configured with WCF adapters to invoke an external WCF service. In this scenario, the adapter acts as a WCF client for the invocation of an external WCF contract. Orchestrations use this mechanism to transmit messages to external services. For more information, see the Consuming a WCF Service Through a BizTalk Server Send Port section.

With both the above scenarios, a custom WCF binding can be configured with an adapter to send or receive messages. Through the following sections, this paper addresses the configuration and use of a custom WCF binding for receiving and sending WCF messages through BizTalk receive locations and send ports.

With the use of receive locations and send ports, clean integration contracts are exposed to the BizTalk developers to host / call WCF services. The adapters complement the orchestrations by completely abstracting the underlying integration complexities such as conversion of protocols, transaction management, and security from the core logic of the solution.

Architecture of the BizTalk WCF Adapters

The BizTalk WCF adapters provide a WS-* compatible platform for the transport types of WCF to be seamlessly integrated with the architecture of BizTalk Server 2006 R2. As mentioned in the previous section, orchestration send ports and receive locations provide the base for the integration of these two technologies.

Figure 1: The Architecture of the Adapters

The Architecture of the Adapters

As depicted in the above diagram, WCF services are hosted through a BizTalk Server receive location. The BizTalk Server runtime manages the instancing of the services that are hosted. When a hosted service is instantiated by the BizTalk Server runtime, the WCF runtime initializes the channel stack of the service and starts the appropriate service listeners to receive WCF messages. After a message is received, the WCF runtime processes it through the configured WCF channel stack and dispatches the message to an instance of the service. After the message is dispatched to the service, it is subsequently processed through the pipeline components that are configured for the receive port. Finally, the message is stored in the BizTalk MessageBox database and the subscriptions for the message are fired to complete the delivery of the message.

When a message is received by a send port, it is processed through the pipeline components of the send port to the WCF adapter. After a message is received, the WCF runtime instantiates a channel stack for the invocation of the external WCF service. The runtime also creates the required WCF messages as per the operation contract of the consumed service. Finally, WCF messages are transmitted through the instantiated channel stack to call the external service and to complete the invocation of the service method.

The architecture of the BizTalk-WCF adapters completely abstracts the logic of the orchestrations from the physical transport types that are used to receive and transmit messages.

For more information about the architecture of these adapters, see http://go.microsoft.com/fwlink/?LinkId=119789.

Important Integration Concerns

The following important integration concerns are addressed through this paper with concrete examples of using and configuring custom WCF bindings to overcome the identified integration challenges:

  • WCF-BizTalk message mapping: Covers message mapping in the context of converting messages between WCF and BizTalk Server. This forms an integral part of service integration. The “WCF Message Mapping Modes” sections in both the Hosting a WCF Service Through a BizTalk Server Receive Port and Consuming a WCF Service Through a BizTalk Server Send Port sections address message mapping.
  • Transaction management: Transactions can be propagated between WCF and BizTalk Server for effective management of transactions. The Enabling Transactions section addresses the implementation of transactions between WCF custom bindings and BizTalk Server.
  • Security: Securing of the information that is exchanged between BizTalk Server and WCF services is viewed as a pivotal integration concern. The Enabling Security section explains the configuration and use of certificate-based message / transport authentication.
  • Other integration concerns: Other integration concerns, such as enabling custom behaviors and asynchronous method invocation, are discussed in the Integration Considerations section.

BizTalk Server receive locations are used for exposing WCF services to receive incoming messages. With this option, a WCF contract is exposed for clients to invoke and deliver messages. The BizTalk Server runtime binds and hosts a WCF service as per the address, binding, and contract information that is specified on the receive location to receive incoming WCF messages. This section elaborates on advanced configuration options of a BizTalk Server receive location that uses a custom WCF binding and the msmqTransport to receive WCF messages.

Dd203050.note(en-US,BTS.10).gifNote
For standard isolated WCF adapters such as the WCF-BasicHttp adapter, the WCF-WSHttp adapter, and the WCF-CustomIsolated adapter, the steps that are described in this section can also be accomplished by using the BizTalk WCF Service Publishing Wizard. This wizard automates most of the steps that are described in the following subsections. For more information, see http://go.microsoft.com/fwlink/?LinkID=100232.

Receive Ports and WCF ABCs

The BizTalk Server receive ports provide the infrastructure for WCF services to be hosted. Any WCF service consists of three key properties in the form of an address, a binding, and a contract, which are commonly referred to as the ABCs of a WCF service. Therefore, these properties need to be defined for a service that is hosted by a receive location. As per these three key properties and other configuration properties that are discussed in the following subsections, the BizTalk Server runtime instantiates and hosts a WCF service on a receive location.

Specifying the WCF Service Address

The address property is used by WCF clients to identify and connect to the service hosted by the BizTalk port. After the BizTalk solution is deployed, the address of the WCF service can be configured through the port configuration options in the following manner:

Figure 2 – Service Address Configuration

Service Address Configuration

The fully qualified concrete address of the service endpoint needs to be specified in the above manner. In the above example, the service runtime will listen to the private “custominqueue” MSMQ queue to receive messages.

Specifying the WCF Service Binding

Now that an address is specified, the service needs to be bound to a concrete transport to receive messages. A binding can range from a standard out-of-the-box binding such as NetTcp or NetMsmq to a custom binding. When an out-of-the box adapter is used, selection of the adapter itself determines the transport type of the service. For example, the NetMsmq adapter uses MSMQ as the concrete transport. However for custom adapters, a concrete transport needs to be specified through the Binding tab of the port in the following manner:

Figure 3 – Binding Configuration

Binding Configuration

As depicted in the above diagram, the channel stack will be displayed by default with text encoding and HTTP as the transport when a customBinding is selected. This can be configured according to the channel stack and encoding mechanism that is required for the solution. This section illustrates the configuration of a custom channel stack with the msmqTransport over the above default custom binding configuration. The following steps explain the creation of a custom channel stack through a BizTalk receive location:

  1. Create a custom binding extension class. The class needs to be derived from the BindingElementExtensionElement class.
  2. Build the above extension class as a .NET assembly and place it in the GAC folder of the BizTalk receive host.
  3. Modify and add the following configuration setting into the machine.config file of the BizTalk receive host.
    
    <system.serviceModel>
      <extensions>
        <bindingElementExtensions>
        <add name="CustomBindingElementExtension" 
             type="Virtusa.App.Services.Channel.
                 CustomBindingElementExtension,      
                 Virtusa.App.Services.Channel, Version=1.0.0.0, 
                 Culture=neutral, PublicKeyToken=70cf70c48ef4b25e"/>
        </bindingElementExtensions>
      </extensions>
    </system.serviceModel>
    
    Dd203050.note(en-US,BTS.10).gifNote
    The configuration information of the bindingElementExtension should match the assembly used for the custom binding. The SvcConfigEditor.exe utility that comes with Windows SDK can be used for editing .config files.

  4. To remove all the unwanted extensions, right-click CustomBindingElement on the Binding tab and then click Remove extension.
  5. To create the custom channel stack, add an extension element by selecting the Add extension option. The following diagram depicts the binding extension elements that are available for addition.
    Figure 4 – Binding Extensions
    Binding Extensions

    Dd203050.note(en-US,BTS.10).gifNote
    If the custom extension is not visible in the above manner, try again after restarting the BizTalk Server host instance and reopening the BizTalk Server Administration console.

  6. Select the CustomBindingElementExtension option to complete the addition of the binding element.
    Figure 5 – Channel Stack
    Channel Stack

    The above diagram depicts the configuration of the channel stack after the addition of the custom binding element (CustomBindingElementExtension) and the transport element (msmqTransport).

After the channel stack is configured in the above manner, the service is bound to the configured concrete transport by the WCF runtime to receive messages.

Specifying the WCF Service Contract

The contract specifies messages that are exchanged by the service and its clients. The contract becomes an important part of the service definition, because it describes the interface of the service operations that are exposed. The BizTalk WCF Services use untyped message contracts to receive messages. The use of untyped message contracts allows the receiving of any WCF-compliant messages from clients. Therefore, type resolution of these incoming WCF messages happens through the use of BizTalk-WCF message mapping modes to resolve the incoming messages to a type that is acceptable to BizTalk Server (see the WCF Message Mapping Modes section for more information). This allows the use of any contract as long as the incoming WCF message is mapped to its BizTalk Server equivalent through an inbound message body mapping option.

WCF Message Mapping Modes

The adapters provide three message mapping modes to map incoming WCF messages to BizTalk equivalents:

  • Envelope: With this mode, the entire <soap:Envelope> of the incoming WCF message is mapped to the body part of the BizTalk message. The elements of the SOAP header of the message are automatically placed on the context of the BizTalk message.
  • Body: This is the default mapping option. This mode maps the contents of the <soap:Body> element to the content of the BizTalk message body part.
  • Path: This mode allows the content of the incoming SOAP message to be mapped to the body part of the BizTalk message as per an XPath string. The specified XPath expression is evaluated against the SOAP Body element of the incoming message. This option also allows an encoding type to be specified for the mapping. By default, String, XML, Base64, and Hex encoding types are supported.
    Dd203050.note(en-US,BTS.10).gifNote
    For the body path expression property, only the XPath expressions suitable for forward-only processing of XML are supported. For more information, see http://go.microsoft.com/fwlink/?LinkId=119792.

    Figure 6 – Inbound Message Mapping Modes
    Inbound Message Marshalling Modes

    As seen in the above figure, the inbound BizTalk message body specifies how the incoming WCF message should be read and mapped:
    An example of an XPath expression is as follows:
    
    /*[local-name()='Message']/*[local-name()='MessageDetails']/*[local-name()='MessageDescripton']
    
    The above expression selects the highlighted section of the following incoming WCF message:
    Figure 7 – SOAP Message
    
    <?xml version="1.0" encoding="utf-8" ?>
    <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
      <s:Header>
        <a:Action s:mustUnderstand="1">http://Virtusa/MessageHandling/IMessageHandler/processMessage</a:Action>
      </s:Header>
      <s:Body>
        <Message xmlns="http://virtusa.com/service/">
          <MessageDetails>
            <MessageID>1c4047d3-84da-4630-a3a1-163c95198b2</MessageID>
            <MessageDescription>Description Here</MessageDescription>
          </MessageDetails>
        </Message>
      </s:Body>
    </s:Envelope>
    
    
    Note that if the path expression mode is selected and the body path expression block is kept empty, by default the <soap:Body> element of the message is encoded in Base64 and is mapped to the BizTalk body part element.
    As seen above, the Path expression mapping mode provides a lot of flexibility through the use of powerful XPath expressions to map a section of a custom WCF message to a BizTalk message.

Behaviors and WCF Receive Locations

Service behaviors are used to modify the functionality of a service or a client channel. For example, the <serviceThrottling> behavior governs the WCF throttling settings such as maxConcurrentSessions that the service supports. Similarly, pre-configurable behaviors exist to control settings such as security and transactions of a service. For a full list of pre-built WCF behaviors, see http://go.microsoft.com/fwlink/?LinkID=75851.

Figure 8 – Behavior Configuration

Behavior Configuration

Behaviors for WCF services that are hosted through BizTalk Server are visible through the Behaviors tab of the receive location configuration. The behavior configuration depends on the binding and the underlying transport option that are selected on the Binding tab. After the binding and underlying transport are selected, the service behavior and the endpoint behavior can be customized as per the run-time requirements of the solution.

WCF also facilitates the writing of custom behaviors to extend the functionality of a service. For more information about writing a custom behavior and configuring it on a BizTalk Server port, see the Enabling Custom Behaviors section.

Send ports provide the infrastructure to invoke external WCF services and to transmit messages to these services through a BizTalk solution. As in receive locations, send ports are configured to host a WCF adapter. The adapter abstracts the WCF communication specifics from the rest of the solution. As per the port configuration options such as the address, binding, and action, the adapter dynamically instantiates a channel stack and calls the consumed service to deliver a WCF message. This section elaborates on advanced configuration options of a BizTalk Server send port with a custom WCF binding and the msmqTransport for consuming WCF services.

Dd203050.note(en-US,BTS.10).gifNote
For standard WCF adapters such as the WCF-WsHttp adapter and the WCF-NetTcp adapter, the steps described in this section can also be accomplished using the BizTalk WCF Service Consuming Wizard. This wizard automates most of the steps of consuming an external WCF service. For more information, see http://go.microsoft.com/fwlink/?LinkId=119794.

Send Ports and WCF ABCs

Similar to receive locations, a BizTalk Server send port must be configured with the address, binding, and contract properties of the consumed service. When a message is submitted to a send port, the BizTalk Server runtime instantiates a service channel, and invokes the respective WCF service by using the service’s ABC properties and certain other configuration values that are discussed in the following subsections.

Specifying the WCF Service Address

The address property is used by the BizTalk Server runtime to establish a concrete connection to the called service. Similar to receive locations, the address of the called WCF service can be configured through the port configuration options in the following manner:

Figure 9 – Service Address Configuration

Service Address Configuration

The fully qualified concrete address and action URL of the service endpoint can be specified in the above manner. Furthermore, the WCF Action property can also be left blank and set in an orchestration or a pipeline component. As seen in the above example, the BizTalk WCF runtime will identify the targeted service action and the address URI of the targeted service, as per the values that are specified on the General tab. The action URL contains the namespace of the WCF service (for example, http://Virtusa.com/appservice) and the name of the service method (for example, “Retrieve”) that should be invoked.

Dd203050.note(en-US,BTS.10).gifNote
The WCF.Action property is automatically promoted by the WCF receive adapters. If it is not set, the WCF send adapter will use the action of the WCF message received by the receive location.

Note that the above example uses the single action format. The action value can also be specified with the action mapping format by using the BTS.Operation property. For example, if the BTS.Operation context property is set to “Retrieve1”, the following XML fragment can be specified for the mapping:


<BtsActionMapping>
    <Operation Name="Retrieve1" Action="http://Virtusa.com/appservice/Retrieve1" />
    <Operation Name="Retrieve2" Action="http://Virtusa.com/appservice/Retrieve2" />
</BtsActionMapping>

When the mapping is specified in the above manner, the adapter will construct the SOAPAction header with the value “http://Virtusa.com/appservice/Retrieve1”.

Furthermore, if the outgoing messages come from an orchestration port, orchestration instances dynamically set the BTS.Operation property to the operation name of the port. If outgoing messages are routed with content-based routing, the BTS.Operation property can be specified through pipeline components.

Specifying the WCF Client Binding

The client channel needs to be bound to a concrete transport to send messages. Again a binding can take the form of a standard out-of-the-box binding such as NetTcp or NetMsmq, a custom binding, or a separate binding such as MyBinding. The binding configuration for the consumed WCF service that uses a custom binding can be specified on the Binding tab of the port in the following manner:

Figure 10 – Binding Configuration

Binding Configuration

As depicted in the above diagram, the default channel stack will be displayed with text as the encoding type and HTTP as the default transport. This can be configured according to the channel stack and the encoding mechanism that is required for the solution. The following steps explain the configuration of a custom channel stack for a BizTalk send port:

  1. Create a custom binding extension class. The class needs to be derived from the BindingElementExtensionElement class.
  2. Build the particular extension class as a .NET assembly and GAC it to the machine where the send port is running.
  3. Modify and add the following configuration setting into the machine.config file of the machine where the send port is running:
    
    <system.serviceModel>
      <extensions>
        <bindingElementExtensions>
        <add name="CustomBindingElementExtension" 
             type="Virtusa.App.Services.Channel.
                 CustomBindingElementExtension,      
                 Virtusa.App.Services.Channel, Version=1.0.0.0, 
                 Culture=neutral, PublicKeyToken=70cf70c48ef4b25e"/>
        </bindingElementExtensions>
      </extensions>
    </system.serviceModel>
    
    Dd203050.note(en-US,BTS.10).gifNote
    The configuration information of the bindingElementExtension should match the assembly used for the custom binding. The SvcConfigEditor.exe utility that comes with Windows SDK can be used for editing .config files.

  4. To remove all the unwanted extensions, right-click CustomBindingElement on the Binding tab, and then click Remove extension.
  5. To create the custom channel stack, add an extension element by selecting the Add extension option. The following diagram depicts the binding extension elements that are available for addition.
    Figure 11 – Binding Extensions
    Binding Extensions

  6. Select the CustomBindingElementExtension option to complete the addition of the binding element.
    Figure 12 – Channel stack
    Channel stack

After the binding is configured in the above manner, all calls that go through the send port will be bound to the configured transport type by the WCF runtime.

Specifying the WCF Client Contract

Similar to receive locations, the WCF send ports use untyped message contracts to send out messages. Therefore, an explicit mapping is required to map the BizTalk message to a WCF message. A WCF action can be specified for the send port or the WCF Action property can be left blank, and set in an orchestration or a pipeline component. The action element determines the service action that is invoked by the port. See Figure 9 for a depiction of the action configuration.

After the configuration of the action in the above manner, the contents of the BizTalk messages need to be mapped to the WCF message structure. This mapping is configured through the WCF message mapping options of the send port. For more information about the above mapping, see the WCF Message Mapping Modes section.

WCF Message Mapping Modes

The message mapping modes of the send port determine the mapping of BizTalk messages to WCF messages. SOAP messages are created by the WCF adapters as per the outbound WCF message body options that are specified for the port.

Two mapping options are provided:

  • Body: With this option the body of the BizTalk message is mapped to the <soap:Body> of the WCF message. This is a straightforward mapping that allows the creation of the SOAP envelope body with the body of the BizTalk message.
  • Template: Similar to the Path message mapping option of receive locations, the template message mapping mode provides flexibility in creating the outgoing WCF message. With this approach an explicit XML template can be specified to map the BizTalk message to a WCF message.

Figure 13 – WCF Outbound Message Mapping

WCF Outbound Message Mapping

For example, if the body element of the outgoing BizTalk message contains <Message>…</Message> as defined by Figure 7, and if this message needs to be wrapped with a <MessageBody> tag before it is inserted into the <soap:Body> section, the following template can be used to complete the mapping:


<MessageBody xmlns="http://virtusa.com/service">
    <bts-msg-body xmlns="http://www.microsoft.com/schemas/bts2007" 
encoding="xml"/>
</MessageBody>

The above option provides the flexibility of placing the content of the <bts-msg-body> element within an XML message schema that the service clients understand. Also note the use of the encoding attribute. As in receive locations, by default, String, XML, Base64, and Hex encoding types are supported.

Although the above Body mapping mode only allows standard XML encoding, as a result of the above encoding options, the template mode facilitates the use of non-XML encoding options. For example, if the BizTalk message body contains binary information, this mode can be used to encode and embed the <bts-msg-body> in a format such as base64.

For more information about the mapping modes and configuration options, see http://go.microsoft.com/fwlink/?LinkId=119796.

Behaviors and WCF Send Ports

Optionally, endpoint behaviors can be configured for WCF send ports. The endpoint behaviors that are specified for the send port affect how the consumed service is called by the WCF adapter.

The endpoint behavior configuration depends on the binding and the underlying transport that are selected on the Binding tab. After the binding and underlying transport are selected, the endpoint behavior can be customized as per the run-time requirements of the solution. After a behavior is configured, the WCF adapter uses the configured behavior to execute the outgoing service calls. The channel stack that is initiated by the adapter will hold the code that needs to be executed for the configured behavior.

WCF also facilitates the writing of custom behaviors to extend the functionality of a service. For more information about writing a custom behavior and configuring it on a BizTalk Server port, see the Enabling Custom Behaviors section.

Dynamic Send Ports

Dynamic send ports facilitate the sending of messages to multiple WCF services. With this mechanism the properties of the send port, such as the address of the service and the binding, are all initialized dynamically. Dynamic send ports are used in situations where the targeted WCF adapter is selected dynamically through the logic of the BizTalk solution. The properties for a dynamic send port can be specified through an orchestration or a pipeline component. The following code fragment demonstrates the creation of a dynamic send port through an orchestration expression block:

Figure 14 – Dynamic Send Port Configuration


OutMessage = InMessage;

OutMessage(WCF.BindingType) = "customBinding";
OutMessage(WCF.Action) = @"http://virtusa.com/appservice/Retrieve";
OutMessage(WCF.BindingConfiguration) = 
    @"<binding name=""CustomBinding"" closeTimeout=""00:10:00"" 
       sendTimeout=""00:10:00"" openTimeout=""00:09:00"">
   <CustomBindingElementExtension/>
   <msmqTransport durable=""true"" useActiveDirectory=""false""/>
     </binding>";
OutMessage(WCF.EndpointBehaviorConfiguration) = 
    @"<behavior name=""CustomBindingBehavior"">
         <CustomBehaviorExtension appliesTo=""InMessage""/>
         <synchronousReceive/>
     </behavior>";
OutMessage(WCF.OutboundBodyLocation) = "UseTemplate";
OutMessage(WCF.OutboundXmlTemplate) = 
    @"<MessageBody xmlns=@"http://virtusa.com/service/">
           <bts-msg-body xmlns="http://www.microsoft.com/schemas/bts2007" 
    encoding="xml"/>
     </MessageBody>";

DynamicSendPort(Microsoft.XLANGs.BaseTypes.Address) = 
  "net.msmq://remotehost/private/custoninqueue";
DynamicSendPort(Microsoft.XLANGs.BaseTypes.TransportType) = 
  "WCF-Custom";

As seen in the code, an outbound message is created with properties such as the action, binding, and behavior configuration. All the properties that need to be configured through the static port dialog box of the send port are configured through code in the above manner. After the properties are configured, a dynamic port is created with the address and the transport type to dispatch the message. A full list of configurable properties for a send port is available at http://go.microsoft.com/fwlink/?LinkID=92956.

Configuring a Static Port to Behave as a Dynamic Port

In cases where the same static port is required to invoke different instances of the same WCF service on a per-message basis, a static send port can be configured to behave as a dynamic port. This configuration is done through a custom pipeline component. With the above scenario, it is assumed that most configuration options of the port remain the same, and only a few options such as the OutboundTransportLocation property change between the different outbound service calls.

Figure 15 – Dynamic Send Port Pipeline Configuration


pInMsg.Context.Write("OutboundCustomHeaders", 
 "http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties", 
 "<headers>
    <FromName xmlns="http://virtusa.com/service/schema">Name</FromName>
 </headers>");

pInMsg.Context.Write("IsDynamicSend", 
 "http://schemas.microsoft.com/BizTalk/2003/system-properties", true);

pInMsg.Context.Write("OutboundTransportLocation",  
 "http://schemas.microsoft.com/BizTalk/2003/system-properties",  
 "net.msmq://remotehost/private/custoninqueue");

The IsDynamicSend property disables the caching of the binding, address, and channel information of the channel factory of the WCF send adapter, causing the address to be changed on a per-message basis.

The above option provides great flexibility in changing a property such as the service address on a per-message basis, where the rest of the properties of the send port remain the same between service invocations. Note that, in addition to service properties, the above mechanism can be used to set additional information on the SOAP header element.

BizTalk WCF receive locations and send ports support the use of transactions based on the transaction capabilities of the underlying WCF binding that is used. In a transacted receive operation, the receive location allows a transaction to be flowed in. When a transaction is flowed in, until the transaction is committed, the subscriptions for the incoming message will not be fired. Similarly, on a transacted send operation, the send port allows a transaction to be propagated to an external WCF service. If the transaction is aborted, the message will continue to reside in the MessageBox database in its last consistent state.

Note that certain standard bindings such as WCF-WsHttp and WCF-NetTcp support the specification of transactional properties as a port configuration option (applies to both send ports and receive locations). With these standard bindings, a transaction can be enabled by selecting the Enable Transactions option, of the binding tab of the adapter.

This section elaborates the enabling of transactions on receive locations and send ports that use a WCF custom binding.

When a custom binding element extension is used, two models are available for transactions:

  1. Channel Initiated Transactions: In this model, the client initiates a transaction, and then the transaction is sent to the server. The Server/Dispatcher does not create the transaction or commit the transaction. Transactions of this nature can be enabled through adding a transactionFlow element to the custom binding configuration.
  2. Dispatcher Initiated Transactions: The ITransactedBindingElement needs to be implemented to enable a dispatcher initiated transaction. The remainder of the section describes the enabling of dispatcher initiated transactions in custom binding extension elements.

Implementing the ITransactedBindingElement

The ITransactedBindingElement interface represents an interface that should be implemented by custom binding elements that require the WCF dispatcher to instantiate a transaction, before the incoming message is dispatched to the service operation.

This interface should be implemented by any custom binding that requires transaction support. It is required that the custom binding implements the above interface and returns true to its TransactedReceiveEnabled property:

Figure 16 – Dynamic Send Port Pipeline Configuration


public class CustomBindingElement : BindingElement, ITransactedBindingElement
{
    // Other Implementations . . . . 

    // Enable the transaction in binding level.
    public bool  TransactedReceiveEnabled
    {
    get 
 { 
          return true; 
       }
    }
}

The above Boolean value specifies whether a transaction is enabled for a receive operation.

Receive Transactions for Custom Bindings

When a transaction flows into a receive location, the receive location joins the incoming transaction. This implies that the incoming message will not be committed to the MessageBox database until the distributed transaction is completed.

When transactions are enabled on a one-way receive location, a different generic service contract is used by the BizTalk Server runtime. This contract is named ITwoWayAsyncVoidTxn and it takes the following form:

Figure 17 – ITwoWayAsyncVoidTxn Contract


    [ServiceContract(
    Namespace="http://www.microsoft.com/biztalk/2006/r2/wcf-adapter")]
    public interface ITwoWayAsyncVoidTxn
    {
        [TransactionFlow(TransactionFlowOption.Mandatory)] 
        [OperationContract(AsyncPattern=true, IsOneWay=false, 
        Action="*", ReplyAction="*")]
        IAsyncResult BeginTwoWayMethod(Message message, AsyncCallback 
        callback, object state);
        void EndTwoWayMethod(IAsyncResult result);
        ...
    }

Dd203050.note(en-US,BTS.10).gifNote
The above code is included for reference purposes to illustrate the use of a transactional contract. It is not required to implement the above contract through custom code.

In cases where the one-way receive location uses the NetMsmqBinding, the runtime enables a different variation named IOneWayAsyncTxn.

As mentioned in the Implementing the ITransactedBindingElement section, the ITransactedBindingElement interface needs to be implemented by the binding element, to enable dispatcher initiated transactions on a receive operation that uses a custom binding. The ITransactedBindingElement notifies the WCF runtime to enable a dispatcher initiated transaction.

Dd203050.note(en-US,BTS.10).gifNote
Refer to the Specifying the WCF Service Binding section of the receive location for the deployment steps of the custom binding. After the custom binding is deployed in the above manner, the dispatcher will initiate transactions for the receive location.

Send Transactions for Custom Bindings

As described above in the “Channel Initiated Transactions” definition, WCF send ports can be configured to flow transactions to external services. After a send port transaction is enabled, the send port propagates the transaction to the WCF service that is consumed. When a send transaction is enabled, the BizTalk send host evaluates the outcome of the transaction that was flowed out to commit the send operation.

In cases where a custom binding is used, the WCF runtime inspects the transaction behavior of the binding element to decide whether a transaction needs to be flowed with the external service call.

WCF provides a variety of security implementations. However, these options depend on the capabilities of the underlying binding of the adapter. For a majority of the WCF adapters, security is configured through the Security tab of the receive location or the send port. However, WCF-custom adapters do not provide this setting by default, because the security options that are available vary depending on the binding and transport that are used. This section illustrates the configuration of certificate-based security on WCF receive locations and send ports that use custom bindings.

Security and WCF

As mentioned before, configuration of the security mode is done according to the binding that is used by the adapter. Furthermore, both the client and the service are required to use the same transfer security mode. As shown in Table 1, all WCF bindings do not support all the security modes that are available.

Table 1 – Binding and Transfer Security Modes

(*) – Default security mode of the bindings.

D.O.B. = Depends on the binding.

Name None Transport Message Both TransportWithMessageCredential TransportCredentialOnly

WCF-BasicHttp

Yes (*)

Yes

Yes

N\A

Yes

Yes

WCF-NetTcp

Yes

Yes (*)

Yes

N\A

Yes

N\A

WCF-NetMsmq

Yes

Yes (*)

Yes

Yes

N\A

N\A

WCF-NetNamedPipe

Yes

Yes (*)

N\A

N\A

N\A

N\A

WCF-WSHttp

Yes

Yes

Yes (*)

N\A

Yes

N\A

WCF-Custom

D.O.B.

D.O.B.

D.O.B.

D.O.B.

D.O.B.

D.O.B.

When the security mode is selected as message or transport, additional information about the credentials that should be used for the message or transport security mode should also be specified.

Message security:

  • Message client credential type (None, Windows, UserName, or Certificate)
  • Algorithm suite (Basic256, TripleDes, etc.)

Transport security:

  • Transport client credential type (None, Windows, or Certificate)
  • Transport protection levels (for example, for NetMsmq and NetTcp bindings, None, Sign, or EncryptAndSign can be specified for the protection level)

Configuring Certificate-Based Security on Receive Locations with Custom Bindings

Certificate-based security can be used to authenticate WCF messages that are received by a receive location. To configure certificate-based security on a receive location that uses a custom WCF adapter, the binding type and the underlying transport of the adapter need to be configured for certificate authentication. Note that the following steps are required to configure certificate-based authentication through the use of custom bindings. The security configuration for the custom binding can be specified on the Binding tab of the receive location in the following manner:

Figure 18 – Define authentication mechanism

Define authentication mechanism

The above example uses MSMQ as the transport of the adapter. As depicted on the above figure, the certificate AuthenticationMode and the signature ProtectionLevel should be selected for the binding configuration. After the completion of the above, certificate-based authentication should be configured on the Behavior tab of the receive location through the following steps:

  1. Right-click ServerBehavior and then click Add extension to select the serviceCredentials item from the following window.
    Figure 19 – Service Credential Extension
    Service Credential Extension

  2. After adding the extension, expand the ServiceCertificate and ClientCertificate sections to add the certificate and store configuration information that is relevant for the solution.
    Figure 20 – Service Certificate Authentication Details
    Service Certificate Authentication Details

  3. At a minimum, values for fields such as findValue, storeLocation, and storeName need to be provided. For a list of configurable service credentials, see http://go.microsoft.com/fwlink/?LinkId=129656.
    After the completion of the binding element and the behavior configuration in the above manner, the receive location will use the certificate and store information to authenticate all incoming WCF messages.

Configuring Certificate-Based Security on Send Ports

Certificate-based security can be used to add appropriate credentials to the outgoing WCF messages of a BizTalk send port. Similar to the receive locations, certificate-based authentication needs to be configured on the binding element and the behavior configuration of a send port that uses a custom WCF adapter. The following steps provide the required steps to complete the configuration:

  1. Configure certificate-based authentication on the binding element of the send port in the same manner as the receive locations. See the previous section for more information. After the completion of the above, the following steps need to be followed to complete the behavior configuration:
  2. Right-click EndPointBehavior and then click Add extension to select the clientCredentials item from the following window.
    Figure 21 – Client Credential Extension
    Client Credential Extension

  3. After adding the extension, expand the ServiceCertificate and ClientCertificate sections and add the certificate and store configuration information that is relevant for the solution.
    Figure 22 – Client Certificate Authentication Details
    Client Certificate Authentication Details

  4. At a minimum, values for fields such as findValue, storeLocation, and storeName need to be provided. For a list of configurable client credentials, see http://go.microsoft.com/fwlink/?LinkId=129656.
    After the completion of the binding element and the behavior configuration in the above manner, the send port will use the certificate and store information to add the relevant security credentials for the consumed service to authenticate the outgoing WCF messages.

This section covers a few other integration considerations that are important in using the rich feature set of the BizTalk WCF adapters. These considerations, such as custom behaviors and SOAP headers, extend the functionality of the adapters to facilitate powerful integration capabilities.

Enabling Custom Behaviors

Custom behaviors enable the customization of WCF receive locations and send ports to handle specific integration requirements such as security and auditing. Custom behaviors play a significant role in the integration of services through allowing the capabilities of the underlying communication channel to be enhanced. Typically, custom behaviors are specified in WCF Service Contracts in the following manner:


[OperationContract(Action = "*", IsOneWay = true)]
[CustomBehavior(CustomBehaviorApplies.InMessage)]
[TransactionFlow(TransactionFlowOption.Allowed)]
void Retrieve(Message inMessage);

In cases where advanced custom behavior extensions need to be enabled, the IEndpointBehavior interface needs to be implemented for the custom behavior class. The IEndpointBehavior adds the binding parameters that are required by the WCF runtime to apply the custom behavior. The following code fragment illustrates the implementation of a custom endpoint behavior:

Figure 23 – Implementing IEndpointBehavior


public class CustomEndpointBehavior : IEndpointBehavior
   {
     public void AddBindingParameters(ServiceEndpoint endpoint,
               BindingParameterCollection bindingParameters)
      {
         foreach (OperationDescription operation in
               endpoint.Contract.Operations)
         {
               // Add your implementation. 
      }
  }

  public void ApplyClientBehavior(ServiceEndpoint endpoint,
           ClientRuntime clientRuntime)
  {
   // Nothing to implement.
  }

  public void ApplyDispatchBehavior(ServiceEndpoint endpoint, 
           EndpointDispatcher endpointDispatcher)
  {
   // Nothing to implement.
  }

  public void Validate(ServiceEndpoint endpoint)
  {
   // Nothing to implement.
  }
}

As illustrated in the above code fragment, the parameters of the custom behavior need to be added to all the operations of your endpoint. This enables the WCF runtime to build the channel stack of the service with the custom behavior. For more information about implementing an IEndpointBehavior, see http://go.microsoft.com/fwlink/?LinkId=119800.

After the implementation of the IEndpointBehavior, for BizTalk Server to recognize the custom behavior as a configuration option, a BehaviorExtensionElement needs to be defined. Note that this is only required when a custom behavior extension element needs to be enabled.

The BehaviorExtensionElement can be implemented in the following manner:

Figure 24 – Implementing a Behavior Extension Element


public sealed class CustomBehaviorExtension : 
               BehaviorExtensionElement
{
        public override Type BehaviorType
        {
            get 
      { 
        return typeof(CustomEndpointBehavior); 
      }
        }

        protected override object CreateBehavior()
        {
            return new CustomEndpointBehavior
                       (this.CustomBehaviorAppliesTo);
        }

        [ConfigurationProperty("customBehaviorAppliesTo", 
         DefaultValue = CustomBehaviorApplies.Both)]        
           public CustomBehaviorApplies CustomBehaviorAppliesTo
        {
            get
            { 
                return (CustomBehaviorApplies)  
                       this["customBehaviorAppliesTo"];
            }
            Set                  
            {
                this["customBehaviorAppliesTo"] = value;
            }
        }
          }

As illustrated by the above code fragment, a custom behavior extension needs to be defined. The BehaviorType property needs to be overridden to return the endpoint behavior that implements the IEndpointBehavior interface. Furthermore, the CreateBehavior method needs to be overridden to return the configuration property of the custom behavior. This will allow the custom endpoint behavior to be recognized by BizTalk Server as a configuration option.

Configuring a Custom Behavior

After the IEndpointBehavior and the BehaviorExtensionElement are implemented in the above manner, the custom behavior of the solution needs to be configured with a receive location or a send port.

Figure 25 – WCF Send Port Behaviors

WCF Send Port Behaviors

As depicted on the above diagram, the behavior elements of the custom binding will not be configured by default. This can be configured according to the behavior requirements of the solution. The following steps explain the configuration of a custom behavior in a BizTalk send port or a receive location:

  1. Build the BehaviorExtensionElement class as an assembly and GAC it to machine where the send port is running (note that the IEndpointBehavior should already be in the GAC).
  2. Add the following configuration setting into the machine.config file of the host.
    
    <system.serviceModel>
      <extensions>
        <behaviorExtensions>
       <add name="CustomBehaviorExtension"        
       type="Virtusa.App.Services.Channel.CustomBehaviorExtension,      
                 Virtusa.App.Services.Channel, Version=1.0.0.0, 
                 Culture=neutral, PublicKeyToken=70cf70c48ef4b25e"/>
        </behaviorExtensions>
      </extensions>
    </system.serviceModel>
    
    
    Dd203050.note(en-US,BTS.10).gifNote
    The configuration information of the behaviorExtensions should match the assembly that is used for the custom behavior. The SvcConfigEditor.exe utility that comes with Windows SDK can be used for editing .config files.

  3. Restart the BizTalk Host and the BizTalk Server Administration console.
  4. To complete the creation of the custom behavior, add extension elements by clicking the Add extension menu option. The following diagram depicts a default list of extension elements that are available for addition through the Add extension menu option.
    Figure 26 – Behavior Extensions
    Behavior Extensions

After a behavior is configured in the above manner, the WCF adapter uses the configured behavior to handle an incoming service call or to execute an outgoing service call. The channel stack that is initiated by the adapter will hold the code that needs to be executed for the configured behavior.

Propagating Namespaces

The current implementation of BizTalk Server 2006 R2 has an issue in propagating the namespaces that are required for external service calls that use a custom binding. Therefore, when an external WCF service is consumed by a send port, the relevant namespaces that are required for the service call are not transferred with the service call.

This is categorized as a known issue in the KB article http://support.microsoft.com/default.aspx?scid=kb;EN-US;942612.

The above update resolves this issue. Therefore, in instances where a custom binding is used, it is important that this update is applied to the relevant BizTalk Hosts.

Note that this update also resolves a transaction time-out issue and a template / encoding issue. See the KB article for more information.

Synchronous vs. Asynchronous Methods on a Custom Binding

For a variety of reasons including performance, the BizTalk WCF adapters only support the invocation of asynchronous methods of a WCF channel stack. However, in cases where a synchronous custom binding needs to be integrated with the adapters, asynchronous methods can be implemented to call the relevant synchronous implementation:


protected override IAsyncResult OnBeginSend(Message message
    TimeSpan timeout, AsyncCallback callback, object state)
{
   // Call the sync version of OnBeginSend.
Send(message, timeout); 
            return new AsyncResult(callback, state);

}

As seen in the above example, asynchronous methods need to be overridden to call the synchronous implementation. Therefore, when the WCF runtime calls the asynchronous method, in turn the synchronous method is called by the channel. Note that the AsynResult class in the above example is a wrapper class that implements the IAsyncResult interface.

Through the above mechanism, a custom binding with synchronous methods can be successfully integrated with the asynchronous channel invocation model of the adapters.

Accessing SOAP Headers Through Pipeline Components

Accessing SOAP headers through pipeline components can be considered as a useful feature to facilitate WCF contracts that use the SOAP header to transfer message context information. BizTalk Server provides APIs to access SOAP header context properties through custom pipeline components. The context properties are accessed by using the context property name and its target namespace. The following examples illustrate the reading and writing of context properties through a custom pipeline component.

Reading from the SOAP header


public IBaseMessage Execute(IPipelineContext pContext, 
   IBaseMessage pInMsg)
{
  object readValue = pInMsg.Context.Read ("InboundHeaders",   
"http://schemas.microsoft.com/BizTalk/2006/01/Adapters/WCF-properties").ToString();

  return pInMsg;
}

Writing to the SOAP header


public IBaseMessage Execute(IPipelineContext pContext, 
   IBaseMessage pInMsg)
{  
  string writingValue = "<?xml version=\"1.0\"?>
  <OrigDest xmlns=\"http://SOAPHeaderSchemas.OrigDestSOAPHeader\">
     <Origination>Home</Origination>
     <Destination>Work</Destination>
  </OrigDest>";

  pInMsg.Context.Write("OrigDest",
       "http://schemas.microsoft.com/BizTalk/2003/SOAPHeader", 
       writingValue);
  return pInMsg;
}

As illustrated in the above examples, the SOAP header can be accessed to read and write message context properties.

Note that a complete set of BizTalk message context properties that are accessible through pipeline components are available at http://go.microsoft.com/fwlink/?LinkId=119803.

As illustrated throughout this paper, WCF provides a powerful communication platform to enhance the capabilities of the BizTalk messaging infrastructure. The BizTalk WCF adapters enable WCF services to be seamlessly hosted through standard receive locations and facilitate the consumption of external WCF services through send ports of a BizTalk solution.

In addition to the out-of-the-box bindings that are provided, WCF enhances communication flexibility through enabling the development of custom bindings. The BizTalk WCF adapters provide a variety of implementation and configuration options for the integration of a custom WCF binding with a BizTalk solution. These bindings significantly enhance the capabilities of integrating disparate services by abstracting the service-specific communication complexities from the rest of the solution.

As discussed in the above sections, key integration concerns such as transaction management and security play a vital part in service-enabling of solutions through the SOA paradigm. Therefore, it is essential that a communication infrastructure fully addresses these concerns in a standard manner.

With the above capabilities, the BizTalk WCF adapters provide a powerful platform for the development of service-oriented solutions in realizing the full potential of executing dynamically composed business processes.

Thilina Gunasinghe is a Software Architect for Virtusa Corporation, a global software services company. Thilina specializes in SOA-based solution development and orchestration of services. Thilina holds a Masters in Software Engineering from the University of York, UK and has over 8 years of SOA-based solution architecting experience and over 5 years of BizTalk solution development experience. He is also the principal author of “Establishing a Standard Business Process Execution Architecture for Integrating Web Services”, an IEEE publication. Thilina can be contacted at tgunasinghe@virtusa.com.

Chelliah Montford Anslum works for Virtusa Corporation as a Senior Technical Lead. Anslum specializes in WCF development and BizTalk Server integration. Anslum holds a Masters from the University of Colombo, Sri Lanka and has over 7 years of software development experience. He also has over 6 years of solution designing and development experience on the .NET platform. Anslum can be contacted at canslum@virtusa.com.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.