How to: Configure a Service Bus Client Using Code
Updated: June 18, 2014
Once you have defined the Microsoft Azure Service Bus interface (as described in Designing a WCF Contract for Service Bus) in your code, you can continue configuring the client application. Configuring a Service Bus client application programmatically is very similar to configuring any other Windows Communication Foundation (WCF) application, which is described in detail in the Configuring Services topic in the WCF documentation. The following topic describes how to programmatically create and configure a simple client that uses the NetTcpRelayBinding binding, and also a discussion of issues specific to Service Bus.
The main difference between configuring a service and a client is that clients must know some of the configuration settings that are used by the service, and comply with them. These settings include the type of binding to use, and also what security options you must have to access the service (that is, authentication and transport-level security.) For more information about setting security, see Securing and Authenticating a Service Bus Connection.
Define the endpoint using the service namespace name and schema type.
string serviceNamespace = "ServiceBusTutorial"; Uri uri = ServiceBusEnvironemnt.CreateServiceUri("sb", serviceNamespace, "sample/EchoService/";
In this context, the schema type is “sb”, indicating Service Bus, and the service namespace is “ServiceBusTutorial”.
Create a TransportClientEndpointBehavior using your credentials.
TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior(); sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider("your issuer name", "your issuer secret");
In your code, substitute “YOUR ISSUER NAME” and “YOUR ISSUER SECRET” with the issuer name and secret you want to use when you connect to the service endpoint.
Create and initialize the channel factory with the endpoint, binding type, and contract type:
ChannelFactory<IEchoChannel> channelFactory = new ChannelFactory<IEchoChannel>(); channelFactory.Endpoint.Address = new EndpointAddress(uri); channelFactory.Endpoint.Binding = new NetTcpRelayBinding(); channelFactory.Endpoint.Contract.ContractType = typeof(IEchoChannel);
Apply the Service Bus credentials:
You have now configured the client application. You can move on to implementing the rest of the client application, in Building a Service Bus Client Application. Note that this tutorial does use an App.config file; however, it is only to store name and password information in a string, and is easily replaced by the code used in this procedure.