Share via


Adapter Connection Management

One of the key features of WCF LOB Adapter SDK is target system’s Connection Management. This posts talk about how connection management is accomplished within an adapter.

Contents

· Connection Lifecycle

· Connection Pool Settings

· Extracting Client Credentials

· Implementing Connection

· Implementing Connection Uri

There are three major pieces an Adapter Developer has to implement when creating an adapter using WCF LOB Adapter SDK as shown in the following diagram:

The key aspects of Connectivity Bucket are:

· Open, close and maintain the connections with the target applications for metadata and message exchange

· Leverage Connection Pooling features provided by the framework

· Adapter Wizard generates AdapterConnectionFactory, AdapterConnection and AdapterConnectionUri

o AdapterConnectionFactory class follows the factory pattern to create a new Adapter object

o Adapter Developer implements Open(), Close(), IsValid(), ClearContext() and Abort() methods in the AdapterConnection class

o Adapter Developer implements BuildUri() and ParseUri() in the AdapterConnectionUri to represent a connection string as URI

Connection Lifecycle

An adapter connection object represents a physical connection from adapter to the target system such as a packaged application or a database. Connections are expensive to create and open, hence one of the performance best practices is to reuse and share the connection whenever possible. This is where Connection Pooling comes in and allows the users to share a connection from the pool of connections. When the request message is processed and the response is returned to the user, the connection is returned back to the pool. There can also be a limit to how many connections can be opened simultaneously due to licensing and resource limitations. WCF LOB Adapter SDK supports connection pooling by default. A connection pool in the adapter is associated per channel and is obtained based on each unique combination of the Connection Uri and the Client Credentials. When an adapter connection object is requested, it is retrieved from the pool if a usable connection is available. To be usable, the connection must currently be unused and have a valid link to the target application/system.

· On Channel Create

o Get a connection pool based on the URI and WCF Client Credentials

It may :

§ Build adapter connection factory

§ Create a new connection pool based on the adapter connection factory

· On Channel Open

o Get a connection handler

§ Use the same used connection / or get a new connection from the pool (depends on the settings)

It may:

1. Create a connection

2. Open a connection

§ Create a handler from connection

· On Channel Close

o Dispose all connection handlers used by the channel

o Clears Context on the connection

o Connection goes back to the pool

 

Note   Do not call Close or Dispose on the adapter connection object or any other managed object in the Finalize method of your class. In a finalizer, only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition. For more information, see Programming for Garbage Collection.

Connection Pool Settings

The Connection Pool settings are defined within the WCF LOB Adapter SDK class Microsoft.ServiceModel.Channels.Common.ConnectionPoolSettings.

Property Name

Default

Description

EnablePooling

True

Turn connection pooling on or off for the adapter. If the connection pooling is not available, a new instance of the connection is created every time a request comes in. The setting can be turned off in the scenarios where the target system may have its own connection pooling mechanism.

HandlersShareSameConnection

True

Adapter can support Metadata Handlers and Message Exchange Handlers. As the name implies, this setting enables these handlers to share the same connection for a particular user.

IdleTimeSpan

15 Minutes

Regardless of the maximum available connections, the connections can stay idle for specific time span. This setting is used by the WCF LOB Adapter SDK to close the idle connections when idle time span elapses.

IdleVerificationInterval

30 Seconds

This setting relates to the cleaning thread that performs checks on connections.

IdleVerificationTimeout

15 Seconds

When the cleaning thread in the WCF LOB Adapter SDK is trying to close the idle connections, the close method on the connection may take a long time due to some external factors. This timeout is used to generate a timeout if the

MaxAvailableConnections

5

This setting specifies the maximum number of available open connections in the Connection Pool at any point of time. The WCF LOB Adapter SDK cleaning thread will close the connections, if the number of open connections in the pool exceeds the MaxAvailableConnections.

MaxConnectionsPerSystem

100

This specifies the maximum number of connections the adapter will attempt to open with the target application. This number cannot be greater than the max # of connections supported by the target system.

 

For example, let’s say there are 100 connections already open. Another request comes in and asks for a connection # 101. Since the number exceeds what the system can support, channel.open() is blocked and will timeout because of connection not available.

 

An adapter developer may choose to expose some of these settings as adapter binding properties, so that adapter consumer can set them during design-time and run-time experience.

Class Diagram

The following diagram shows the relationship between key connectivity related classes in the adapter. The Adapter Developer needs to implement only AdapterConnection and AdapterConnectionUri. Rest is provided by either WCF or WCF LOB Adapter SDK.

· ClientCredentials is a standard WCF class

· MyAdapterConnectionUri (inherits from Adapter SDK Microsoft.ServiceModel.Channels.Common.ConnectionUri)

· MyAdapter (inherits from Adapter SDK Microsoft.ServiceModel.Channels.Common.Adapter)

· MyAdapterConnectionFactory (inherits from Adapter SDK Microsoft.ServiceModel.Channels.Common.ConnectionFactory)

· MyAdapterConnection (implements Adapter SDK Microsoft.ServiceModel.Channels.Common.IConnection)

Only a valid connection object will be added to the pool – i.e. after it has been authenticated.

 

Extracting Credentials

In the Connection implementation, the Adapter Developer can extract the user credentials from WCF ClientCredentials class. For example the following code snippet shows getting the username and password, if the transport security mode of UserName was used. 

 The Adapter Developer can extract the credentials and pass them to the target system in the format and protocol expected by the target system application.

Transport Security

Adapter Consumer

Adapter Developer

UserName

Client Proxy Code

// create proxy

SapRfcClient sapRfcClient = new SapRfClient("mySapConfig");

// provide credentials         sapRfcClient.ClientCredentials.UserName.UserName = "xxx"; sapRfcClient.ClientCredentials.UserName.Password = "yyy";

// call method

 

Metadata Adapter Metadata Utility Tool

Click on Configure button. Select Security Tab. Choose “Username” in the Client credential type combo box. Fill in “User name” and “Password”.

 

Use the “UserName” property in the ClientCredentials object.

 

Implementing Connection

The main methods to be implemented are: Open(), Close(), IsValid(), Abort() and ClearContext(). See the following sample code snippets that use SqlConnection API to connect to a database. 

    public class SQLAdapterConnection : IConnection

    {

        private SqlConnection sqlConnection;

        /// <summary>

        /// Closes the connection to the target system

        /// </summary>

        public void Close(TimeSpan timeout)

        {

            // Note: we don't support timeout in this sample

            this.sqlConnection.Close();

        }

        /// <summary>

        /// Returns a value indicating whether the connection is still valid

        /// </summary>

        public bool IsValid(TimeSpan timeout)

        {

            return this.sqlConnection.State == System.Data.ConnectionState.Open;

        }

        /// <summary>

        /// Opens the connection to the target system.

        /// </summary>

        public void Open(TimeSpan timeout)

        {

            this.sqlConnection.Open();

            SQLAdapterUtilities.Trace.Trace(

                System.Diagnostics.TraceEventType.Information,

                "https://Microsoft.Adapters.Samples.Sql/TraceCode/SQLConnectionOpened",

                "The SQL Connection was opened",

                this,

                new SQLConnectionTraceRecord(this.SqlConnection));

        }

        /// <summary>

        /// Clears the context of the Connection. This method is called when the connection is set back to the connection pool

        /// </summary>

        public void ClearContext()

        {

           

        }

        /// <summary>

   /// Aborts the connection to the target system

        /// </summary>

        public void Abort()

        {

            try

            {

                this.sqlConnection.Close();

            }

            catch (Exception e)

            {

                SQLAdapterUtilities.Trace.Trace(

                    System.Diagnostics.TraceEventType.Error,

                    "https://Microsoft.Adapters.Samples.Sql/connection/ConnectionCloseError",

                    "An exception was thrown while trying to close the connection",

                    this,

                    e);

            }

        }

    }

 

Implementing Connection Uri

The {Adapter}ConnectionUri is a helper class used for parsing and building a standard address object that’s passed into the adapter. Since each adapter implementation can differ, Adapter SDK doesn’t have the knowledge of parsing and building adapter specific URI. This is the responsibility of the Adapter Developer.

· In Parse functionality, the adapter can then take elements out of this Uri and convert to the target system specific connection string.

· In Build functionality, the adapter takes the individual properties in the ConnectionUri class implementation and returns the Uri back to the caller. This is especially useful in Add Adapter Service Reference Visual Studio Plug-In/Consume Adapter Service BizTalk Project Add-In where the Adapter Consumer can just provide the connection properties and the Connection Uri String is constructed by the adapter.

· The Adapter Developer can also associate various UI Type Editors (see code snippet below) to ensure the consumer provides valid values for each property. See the complete list of UI Type Editors here.

[Editor(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]

        [Category("Connection Properties")]

        [Description("Select the class library you want to reflect.")]

        public string Path

        {

            get

            {

                return this.fileName;

            }

            set

            {

                this.fileName = value;

            }

        }