Configuring WCF Services and Getting Them Ready to Ship

ervices built on the Windows Communication Foundation (WCF) platform provide a lot of flexibility to the developer. The premise of WCF is that a developer can build a service once and then deploy it as different endpoints simply by changing the configuration files. In essence, WCF is all about how you configure your services, but manipulating a configuration file involves a lot of details that developers can easily overlook. Whenever developers in large teams change configuration files, for example, unexpected errors surface. The teams get better as they learn the patterns in the configuration files, but that takes a while.

This article will save you some pain in deploying WCF services. Based on experience with a number of real projects that use WCF, this article walks you through the most essential elements of a WCF configuration?elements that you need to understand to make a stable release. A TCP endpoint is used to illustrate the WCF configuration concepts, but these concepts can apply to most other endpoints.

Reading this article and working with its sample configuration entries will give you a good understanding of all the necessary configurable entities that make a WCF service rock solid and ready to ship. The accompanying code sample shows both a bare-bones version and a ready-to-ship version.

You will need to be familiar with WCF to follow along. For an introduction to WCF, please refer to the DevX article “The Windows Communication Foundation: A Primer.”

Basic, Bare-Bones Configuration
When you create a WCF library in Visual Studio, Visual Studio tries to help you create the App Config file by anticipating and providing everything you need (see Sidebar 1. Differences in Config Files Created by Dynamic Proxy and by Static Proxy). But not all the sections created by Visual Studio are required to launch a bare-bones configuration (See the downloadable code for a bare bones example).

Let’s start at the very top of the config file:

               

This article uses the example of an order-processing service (IOrderService) that supports two methods (ProcessOrder(); and GetAllOrdersForUser();) . Here is the contract for OrderService:

[ServiceContract]public interface IOrderService{        [OperationContract]        bool ProcessOrder(List orderList);        [OperationContract]        List GetAllOrdersForUser(int userId);        // TODO: Add your service operations here}

The service is implemented by a class (OrderService):

public class OrderService : IOrderService{        public bool ProcessOrder(List orderList)        {            Console.WriteLine("Your order is processed");            return true;        }        public List GetAllOrdersForUser(int userId)        {             List orderList = new List();   Console.WriteLine("came to                 GetAllOrdersForUser");            return orderList;        }}

These methods are not fully implemented at this point, but this code is enough to get the service exposed and reachable.

You need to add a service section to the node in the config file. The service requires an element called name, which has to be the fully qualified class name of the class that implements the interface:

      

Instead of depending on the fully qualified name, you could specify a human-readable name and use it on the Service class, in this case OrderService:

[ServiceBehavior ( ConfigurationName = "OrderProcessingService")]

The benefit of this approach is that it explicitly maps the section to the code.

In order to reach the service from outside, you need to specify an endpoint. This endpoint will have the following address:

                contract="OrderService.IOrderService">

The endpoint requires, at the bare minium, an address, a binding, and a contract (the ABC of a service). The Address is where someone can call the service. In this case, the Net.TCP service is running in port 1973 and has a Binding, which is Net.TCP. This service is exposing a Contract called IOrderService. (See Sidebar 2. Securing Service Endpoints.)

This is all you need to make a service usable. Note that there is no metadata exchange (MEX) binding or any way to discover WSDL. All you need to do in the client is share the contract and you should be able to consume the service. The client section of the App Config file looks like this:

                 

The next section explains how to get the order service ready to ship.

Getting OrderService Ready to Ship

Figure 1. WCF Config Editor View of BareBones Configuration File: WCF Service Configuration Editor is currently the best way to modify WCF configurations.

While the configuration entries shown in BareBones are just enough to get going, they are in no way ready to ship. This section looks at some of the specific requirements of the config section.

WCF Service Configuration Editor (config editor) is a Visual Studio tool that is currently the best way to modify WCF configurations. Its one flaw is that it doesn't enable you to add comments to the configuration sections. If you add comments and then use the config editor, it overwrites everything. Nevertheless, it does provide a host of features out of the box. Figure 1 shows the BareBones configuration file in its current state as seen through the config editor.

The following are the specifics for modifying the WCF configuration.

1. Give the endpoint a valid name.
Notice that BareBones contains a service that has an endpoint called [Empty Name]. Every endpoint should have a name. Although not required, naming your endpoints makes maintenance easy. In the endpoint discussed here, the code for a name is name="OrderService".

Figure 2. OrderServiceTCPBinding: Shows a New Binding Section: Create a new binding section called OrderServiceTCPBinding to the BareBones config file.

2. Add a new binding section.
Create a new binding section called OrderServiceTCPBinding to the BareBones config file. Figure 2 shows OrderServiceTCPBinding.

3. Associate the endpoint to the binding created.
This allows you to make changes to a number of properties on the endpoint and not be limited only to the default ones. Figure 3 shows a screenshot of associating a binding with an endpoint.

4. Change the max buffer size and max received message size (if needed).
At run time you may encounter two errors related to the amount of data being served by the server:

  1. The maximum message size quota for incoming messages (65536) has been exceeded.
  2. Maximum number of items that can be serialized or deserialized in an object graph is '65536'.

WCF limits the amount of data you can send over the wire per call to 64K, which is why the first error occurs. If your endpoint has methods that return more data than that (such as a collection), you have to change the buffer size and max received size from 64K to a suitable number.

Figure 3. Associating a Binding with an Endpoint: Create a new binding section called OrderServiceTCPBinding to the BareBones config file.

If you add a service by using the add service reference option, the values added on the server won't always reflect on the client. The client always defaults to 64K, which can cause a lot of confusion if many developers are changing the client configuration. A binding value that is updated on the server will have to be changed again on the client.

To fix the second error mentioned above, you can add the following element to the client config file in the service behavior section (2147483647 is used as an example only):

 

5. Add a service behavior.
Apply a new behavior (called OrderServiceBehavior) to all the endpoints in your service. Four properties in OrderServiceBehavior (serviceDebugging, serviceMetaData, serviceThrottling, and maxConcurrentSession) are of particular interest (see Figure 4):

Figure 4. Four Must-Know Sections in serviceBehavior: Four properties in OrderServiceBehavior are of particular interest.
  • serviceDebugging: This property is essential for troubleshooting when issues arise in production. The IncludeExceptionDetailsInFaults attribute should be set to false in production. If set to true (as it might in a development or staging box), it will actually show what the exception is on the client side. This gives extremely critical details about issues happening in a service.
  • serviceMetaData: This property contains a property called HttpGetEnabled that will have to be set to HttpEndpoint to allow for discovery with the ?wsdl option. This option does not apply to this example as it uses a TCP endpoint.
  • serviceThrottling: This is a mechanism to control the resource usage in a service.
  • maxConcurrentSession: Of the four properties, this one is the most important. It controls the maximum number of simultaneous sessions accepted by the client. Each time a client opens a TCP connection to a server, it counts as one session. If the caller forgets to close a TCP connection on the client side, then the session limit can be reached very easily. The service will queue all incoming requests until the client requests that are not served time out. The service then closes the open session abruptly. As a good code review step, make sure all open connections in the client are closed, or use a using block for the client to dispose the connection as soon as it is no longer required.

    Set the maxConcurrentSession to as high as number as possible. You can adjust the serviceTimeout property to affect serviceThrottling as well.

6. Associate the endpoint with the new behavior.
After defining OrderServiceBehavior, associate the endpoint with that behavior.

Figure 5. Adding a MEX TCP Endpoint: In order for the TCP endpoint to be discoverable, you have to add a mexTcpBinding.

7. Add a metadata exchange (MEX) endpoint.
In order for the TCP endpoint to be discoverable, you have to add a mexTcpBinding (see Figure 5). This is a requirement of the WS-MetadataExchange (WS-I) specification. With this endpoint, you will be able to add a service reference or generate a client proxy.

If you are using an HTTP endpoint, a MEX endpoint is not required. Enabling HttpGetEnabled in the service behavior will suffice.

All MEX endpoints have to implement a contract called IMetadataExchange. Visual Studio is not smart enough to add this interface for you. If you make a typo, this endpoint will error out. Also, a mexTcp endpoint cannot run under the same port as the real service unless port sharing is enabled. When a service contains more than one endpoint, it is better to use a base address and a relative addressing scheme for the endpoints.

The Code for the Final Version
Listing 1 shows the final version of the application config file, and Listing 2 shows the corresponding client version of the same file (See Sidebar 3. Managing Service Config Versions). Both are ready to ship!

Configuration Key to WCF Service Deployments
This article explained the most essential elements of a WCF configuration that you need to make a stable release. Configuration management is a big part of managing WCF service deployments. Having a strategy early on in the development phase and understanding what happens with changes to the different sections in the configuration will go a long way toward successful WCF service deployments and maintenance.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a