Questions in WCF - Part #1


This article presents the answers to the most commonly faced questions or clarifications.

Introduction 
This article presents the answers to the most commonly faced questions or clarifications.

What is an Endpoint? How to configure an end point in WCF Application? Is it possible to create an end point dynamically?

An Endpoint is the interface through which the Business Services are exposed to external world. Each Endpoint in a WCF application consists of following things:
(a)    Address – An address is the URL through which the client applications interact with the services. The Address can be configured in the Configuration file of the Service application.
(b)   Binding – A Binding is the one that decides how client applications can interact with the Services. This is used to specify transport, encoding and protocol details required for client applications and services to communicate each other.
(c)    Contract – A Contract is the service which is supposed to be exposed to the external world that client applications consume.
Configuring Endpoint in the Configuration File:
     <endpoint address="http://localhost/SampleServices/Service"
                  binding="basicHttpBinding"
                  contract="SampleService.IService" />
Creating an Endpoint Programmatically:
Sometimes we might have to create the Endpoints through the program based on business requirements. An equivalent C# code which would create the end point from the code looks like below:
      string serviceAddress = "http://localhost/SampleServices/Service";
         BasicHttpBinding basicHBinding = new BasicHttpBinding();
         using (ServiceHost hostService = new ServiceHost(typeof(Service1)))
         {
            hostService.AddServiceEndpoint(typeof(IService1), basicHBinding, serviceAddress);
         }

Note that the above code snippet needs to be placed in the Host Application which hosts the WCF services.


What are bindings in a Service? How many types of bindings are available?

A Binding is the one that decides how client applications can interact with the Services. This is used to specify transport, encoding and protocol details required for client applications and services to communicate each other.
All the binding configurations should be set in a separate section with the name “bindings” in the configuration file. This section is under the main section:

     <system.serviceModel>

<bindings>

</bindings>

</system.serviceModel>

You can define more than one binding configuration inside the “bindings” section.


There are many types of bindings available by default in WCF framework. Out of these, primarily four bindings are very commonly used. They are:
(a)    BasicHTTPBinding – This binding is used for basic web service communication. This is mainly used for interoperability. No security is available with this binding. The medium of communication is through web (HTTP protocol). The typical configuration settings for this binding looks like below:
    <bindings>
      <basicHttpBinding>
        <binding name="sampleBasicHttpBinding">          
        </binding>
      </basicHttpBinding>    
    </bindings>

The above section gives the flexibility to give name to your configuration settings. You could reuse this configuration setting in one or more endpoint (use the name of the binding on the “binding” attribute in your end point).

(b)   WsHTTPBinding – This binding is used for secure, reliable, interoperable binding. This binding is used for a web service with WS-* support like WS-Reliable Messaging for reliability, and WS-Security for message security and authentication. To simplify, this web service is used whenever you need some kind of security to you basic web service. The medium of communication is through web (HTTP protocol). The configuration for this type of binding starts like this:
    <bindings>      

      <wsHttpBinding>
        <binding name="sampleWsHBinding">
          
        </binding>
      </wsHttpBinding>
    </bindings>

(c)    MsmqIntegrationBinding – This binding is used when the WCF Service needs to interact with the MSMQ. The service with this binding can listen to the MSMQ and read or insert messages into the queue. The client applications insert the messages into a queue and the service can read the message from the queue. The medium of communication is through MSMQ in this case. The configuration for this type of binding starts like this:

    <bindings>      
      <msmqIntegrationBinding>
        <binding name="sampleMsmqBinding">
       </binding>
      </msmqIntegrationBinding>
    </bindings>

(d)   NetTcpBinding – This binding is used when the communication between two applications on two computers which are directly connected. This binding uses TCP protocol for communication. The configuration for this type of binding starts like this:

    <bindings>      
      <netTcpBinding>
        <binding name="sampleNetTcpBinding">          

        </binding>
      </netTcpBinding>
    </bindings>

Along with the already built-in bindings, the WCF framework also allows the developers to create custom bindings.

What is the difference between BasicHttpBinding and WsHttpBinding? When do you use what?

Following are the differences between BasicHttpBinding and WsHttpBinding. They are:
(a)    BasicHttpBinding supports wide variety of clients (like clients built on .NET, PHP, RUBY etc) whereas WsHttpBinding has limited compatibility to client applications that were built on various technologies
(b)    BasicHttpBinding sends the messages in plain text by default over the network where as WsHttpBinding sends them in an encrypted format by default over the network
(c)    BasicHttpBinding cannot send reliable messaging whereas WsHttpBiding does it.
(d)    BasicHttpBiding cannot support PerSession Instance Context mode where WsHttpBinding does.

Why an interface is required to define the Service Contract and Operation Contract?

It is always a best practice to program to an interface rather than programming to an implementation. As WCF service is invoked by wide variety of clients, it is always better to expose the Interface rather than the implementation. This give you the flexibility to change the implementation as per your business node without any impact on the client applications since the client applications are aware of the interface only and does not the implementation class (neither its name or namespace).
What is Service Behavior? What role does it play? How to configure the behavior of a Service?
Service Behavior is the configuration setting that decides the execution behavior of the Service. For example, if you would like the Service to use the single instance of its implementation all the time, this can be achieved by configuring the service behavior accordingly.
The behavior of the service can be controlled by placing a ServiceBehavior attribute on top of the Service implementation. For example, below code shows how the ServiveBehavior attribute can be placed on top of a Service implementation.
[ServiceBehavior()]

public class Service1 : IService1
{

   [OperationContract]        

   public string GetData(int value)
   {
            return string.Format("You entered: {0}", value);
   }
}

If you notice the ServiceBehavior attribute in the above code snippet, it is a blank attribute. There are many properties that can be defined within this ServiceBehavior attribute. Few of the important properties are:
(a)    ConcurrencyMode
(b)   IncludeExceptionDetailInFaults
(c)    InstanceContextMode
(d)   Name
(e)   Namespace
Service Behavior can also be configured from the Configuration file. The below sample configuration gives an idea of how it can be done:
  <behaviors>

      <serviceBehaviors>        
        <behavior name="sampleBehavior">
          
        </behavior>
      </serviceBehaviors>
  </behaviors>

The configured behavior can be attached to the end point in the below fashion:

     <endpoint address="http://localhost/SampleServices/Service"
                        binding="basicHttpBinding"
                       contract="SampleService.IService"
        behaviorConfiguration=" sampleBehavior"/>

What are different Instance Context Modes available in WCF and when do you use what? How to configure them in the code?

Instance Context Mode settings control the services instances created for the client requests. There are three Instance Context modes that can be set. They are:
(a)    PerCall
(b)   PerSession
(c)    Single
When the service is configured to run on PerCall instance context mode, the below program returns the output as “1” always.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class Service1 : IService1
    {
        int counter = 0;
        [OperationContract]        
        public string GetData(int value)
        {
            counter ;
            return counter.ToString();
        }
    }

When the service is configured to run on PerSession instance context mode, the below program holds the value of “counter” variable as long as the client proxy object is live and increments it in each call. For example, if you call GetData method 10 times using the same Client Object, the value returned will be 10 on tenth call.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]

    public class Service1 : IService1
    {
        int counter = 0;
        [OperationContract]
        public string GetData(int value)
        {
            counter ;
            return string.Format("You entered: {0}", counter.ToString());
        }
    }

When the service is configured to run on Single Instance Context mode, the below program holds the value of “counter” variable forever irrespective of the client application that is calling it. For example, Client A calls the below program 10 times and Client B calls the below service 10 times. The value that is returned to Client B on its 10th call will be 20 and not 10 or 1.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

    public class Service1 : IService1
    {
        int counter = 0;
        [OperationContract]
        public string GetData(int value)
        {
            counter ;
            return string.Format("You entered: {0}", counter.ToString());
        }
    }

What is Concurrency Mode and how does that impact the Service behavior?

Concurrency Mode settings control whether an instance of a Service Application processes messages sequentially or concurrently.
There are three modes available. They are:
(a)    Single – each service processes one message at a time
(b)   Multiple – each service processes multiple messages concurrently
(c)    Reentrant – each service instance processes one message at a time, but accepts the calls concurrently when the current message call is calling out.
The Concurrency Mode can be set using the ServiceBehavior attribute. The below code snippet shows an example.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
    public class Service1 : IService1
    {
        int counter = 0;
        [OperationContract]
        public string GetData(int value)
        {
            counter ;
            return string.Format("You entered: {0}", counter.ToString());
        }
    }

What is WCF Throttling? How do you configure the code to throttle based on the need?

Throttling provides an ability to control the number of calls that the WCF service can handle. Throttling Settings limits the number of concurrent calls that can be made to the service and concurrent instances created at the service end and this provides an ability to configure the service to make use of resource effectively.
The below configuration settings control the number of calls, instances and sessions that can be made to the Service.

      <serviceBehaviors>        
        <behavior name="sampleBehavior">
          <serviceThrottling maxConcurrentCalls="10" 

                   maxConcurrentInstances="10" 

                   maxConcurrentSessions="10"/>

       </behavior>
      </serviceBehaviors>

To look in more detail into this setting, “maxConcurrentCalls = 10” setting allows only maximum of 10 concurrent calls to be made to the Service method. Any other call that is coming to the service needs to wait until, at least one of the call in the above 10 calls is complete.

               
How does tracing and logging of WCF service can be configured?
All you need to do is make some configuration settings to enable tracing and logging in WCF. The service logging and tracing can be easily configured using the inbuilt tool – (svcConfigEditor.exe). Open the WCF Application configuration file from this tool and configure the settings.

How to make WCF Services operate on multiple threaded?

This can be achieved by using WCF Throttling. Refer to Question #8.

How to define the behavior of a WCF service based on the load?

This can be achieved by using WCF Throttling. Refer to Question #8.
How to increase the response message size in a WCF Service?
When you have a large amount of data that needs to be returned from the Service application to the client application, at times the service throws an exception stating that the message not former properly. This is because of the message size settings configured in the configuration file. Below configuration setting provides an idea on where to change the configuration settings:

<bindings>
      <netTcpBinding>
        <binding name="sampleNetTcpBinding" maxReceivedMessageSize="" >
 
        </binding>
      </netTcpBinding>
</bindings>

Under the binding node, the “maxReceivedMessageSize” attribute needs to be configured properly.


How to increase the request time out in WCF Service?
If the service application takes long time to respond a request, the request might timeout on the client side before the service application returns the response. This can be handled by configuring the receiveTimeout attribute properly. Below configuration settings show how:

<bindings>
      <netTcpBinding>
        <binding name="sampleNetTcpBinding" receiveTimeout="">
 
        </binding>
      </netTcpBinding>
</bindings>

How to hide a property defined inside a DataContract class?

DataContract is the attribute placed on top of the customer data objects (composite data types) to make them serializeable. As you know, the response from the service is always serialized and sent back to the client. Below code snippet shows how to do this:

[DataContract]
    public class CompositeType
    {
    }

When this attribute is placed on top of the object CompositeType, the object can be recognized at the client application end.

Now come to the properties inside the CompositeType, every property inside this class needs to be decorated with the attribute “DataMember”, to have the property recognized at the client end. If no “DataMember” attribute is placed, the propertly is not visible at client application end. Following code snippet shows how to do this.

 [DataContract]
    public class CompositeType
    {    
        bool boolValue = true;
        string stringValue = "Hello ";
 
        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }
 
        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }

How to enable Sessions usage in WCF Service?

Session based call can be achieved using PerSession Instance Context mode. But please note that PerSession Instance Context mode is not supported by the BasicHttpBinding. If there is a specific need for running the service on BasicHttpBinding for better interoperability, then there is an alternative to enable sessions at the level of BasicHttpBinding by enabling ASP.NET Sessions at Service level. The ASP.NET Compatibility can be set by placing the attribute “AspNetCompatibilityRequirements” on top of the Service Implementation. Below code snippet explains how to do this:

[AspNetCompatibilityRequirements(RequirementsMode =
                       AspNetCompatibilityRequirementsMode.Required)]
    public class Service1 : IService1
    {
        int counter = 0;
        [OperationContract]
        public string GetData(int value)
        {
            counter ;
            return string.Format("You entered: {0}", counter.ToString());
        }
    }


Conclusion 
The basic questions related to WCF are addressed in this article and advanced questions will be presented in the next article.

Related tags

Questions in WCF, WCF Basics, WCF Interview Questions