Configuring WCF Services and Getting Them Ready to Ship

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.

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists