Hosting WCF Service in Local IIS Using Visual Studio 2013 | WCF Programmer Guide | WCF Tutorial

Hosting WCF service in local IIS using Visual Studio 2013 is surprisingly easy. Let us assume you have created a WCF Service. Now to publish it in local IIS right click on project and from context menu select Properties. In Properties select Web tab. In Web tab from Servers drop down select local IIS.
clip_image002
Next click on Package/Publish Web tab and from Items to deploy drop down select Only Files Needed to run this application.
clip_image004
Now when you press F5 and run application WCF Service will be hosted in local IIS.
clip_image006

What is a fault contract in WCF? | WCF Interview Question

, ,
Normally, by default, when some exception occurs at a WCF service level, it will not expose as it is to client. Reason is that WCF exception is a CLR exception and it doesn’t make sense to expose it outside CLR because it contains internal details of service code like stack trace. So, WCF handles and returns error details to client using Fault Contract.“So, fault contract is a contract that contains the details of possible exception(s) that might occur in a service code.”
 [ServiceContract]
 public interface IService1
 {
        [OperationContract]
        [FaultContract(typeof(MyFaultDetails))]
        int MyOperation1();
 }
 [DataContract]
  public class MyFaultDetails
  {
        [DataMember]
        public string ErrorDetails { get; set; }
  }
In implementing service…..
  public int MyOperation1()
  {
       Try{               //Do something……       }catch()
       {
                  MyFaultDetails ex = new MyFaultDetails();
                  ex.ErrorDetails = “Specific error details here.“;
                  throw new FaultException(ex,“Reason: Testing…..“);
       }
  }

What are the different ways to generate proxy in WCF? | WCF Interview Question

, ,
Generating proxy using Visual Studio is simple and straight forward.
  • Right click References and choose “Add Service Reference”.
  • Provide base address of the service on “Add Service Reference” dialog box and click “Go” button. Service will be listed below.
  • Provide namespace and click OK.
Visual studio will generate a proxy automatically.
We can generate proxy using svcutil.exe utility using command line. This utility requires few parameters like HTTP-GET address or the metadata exchange endpoint address and a proxy filename i.e. optional.
svcutil http://localhost/MyService/Service1.svc /out:MyServiceProxy.cs
If we are hosting the service at a different port(other than default for IIS which is 80), we need to provide port number in base address.
svcutil http://localhost:8080/MyService/Service1.svc /out:MyServiceProxy.cs

What is a Service Proxy in Windows Communication Foundation? | WCF Interview Question

, ,
A service proxy or simply proxy in WCF enables application(s) to interact with WCF Service by sending and receiving messages. It’s basically a class that encapsulates service details i.e. service path, service implementation technology, platform and communication protocol etc. It contains all the methods of service contract (signature only, not the implementation). So, when the application interact the service through proxy, it gives the impression that it’s communicating a local object.

We can create proxy for a service by using Visual Studio or SvcUtil.exe.

What is mexHttpBinding in WCF? | WCF Interview Question

, ,
In order to generate proxy, we need service metadata and mexHttpBinding returns service metadata.
If we look into our configuration file, service will have an endpoint with mexHttpBinding as follows:
<endpoint address=”mex” binding=”mexHttpBinding”   contract=”IMetadataExchange”/>
and service metadata behavior will be configured as follows:
<serviceMetadata httpGetEnabled=”true”/>
Before deployment of application to production machine, it should be disabled.
In order to support other protocols, related bindings are mexHttpBinding, mexHttpsBinding, mexTcpBinding.

What are the different ways to expose WCF Metadata? | WCF Interview Question

, ,
By default, WCF doesn’t expose metadata. We can expose it by choosing one of the following ways:
1.    In configuration file, by enabling metadata exchange as follows:
  <system.serviceModel>
    <services>
           <service name=”MyService.Service1″
                                              behaviorConfiguration=”MyService.Service1″>
                      <endpoint address=””
                                            binding=”wsHttpBinding”
                                            contract=”MyService.IService1″>
                          <identity>
                              <dns value=”localhost”/>
                          </identity>
                      </endpoint>
                     <endpoint address=”mex” binding=”mexHttpBinding”
                                            contract=”IMetadataExchange”/>
            </service>
    </services>
    <behaviors>
            <serviceBehaviors>
                        <behavior name=”MyService.Service1″>
                                    <serviceMetadata httpGetEnabled=”true”/>
                                    <serviceDebug includeExceptionDetailInFaults=”false”/>
                       </behavior>
             </serviceBehaviors>
     </behaviors>
</system.serviceModel>
2.  ServiceHost can expose a metadata exchange endpoint to access metadata at runtime.
   using (ServiceHost host = new ServiceHost(typeof(MyService)))
   {
              ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
              behavior.HttpGetEnabled = true;
              host.Description.Behaviors.Add(behavior);
              host.Open();
              Console.WriteLine(“My Service here……….”);              Console.ReadLine();
              host.Close();
   }

What Message Exchange Patterns supported by WCF? | WCF Interview Question

, ,
  •  Request/Response
  •  One Way
  •  Duplex
Request/Response
It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body.
One Way
In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. OneWay MEP will work in such scenarios.If we want queued message delivery, OneWay is the only available option.
Duplex
The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed.

What are Contracts in WCF? | WCF Interview Question

, ,
A Contract is basically an agreement between the two parties i.e. Service and Client. In WCF, Contracts can be categorized as behavioral or structural.
  1. Behavioral Contracts define that what operations client can perform on a service.
    • ServiceContract attribute is used to mark a type as Service contract that contains operations.
    • OperationContract attributes is used to mark the operations that will be exposed.
    • Fault Contract defines what errors are raised by the service being exposed.
  2. Structural Contracts
    • DataContract  attribute define types that will be moved between the parties.
    • MessageContract attribute define the structure of SOAP message.

What are the hosting options for WCF Services? | WCF Interview Question

, ,
For a service to host, we need at least a managed process, a ServiceHost instance and an Endpoint configured. Possible approaches for hosting a service are:
1.    Hosting in a Managed Application/ Self Hosting
a.    Console Application
b.    Windows Application
c.    Windows Service
2.    Hosting on Web Server
a.    IIS 6.0 (ASP.NET Application supports only HTTP)
b.    Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP,
NamedPipes, MSMQ.

What is the difference between WCF and ASMX Web services? | WCF Interview Question

, ,
The basic difference is that ASMX web service is designed to send and receive messages using SOAP over HTTP only. While WCF service can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, Named Pipes etc).

What are the core components of WCF Service? | WCF Interview Question

, ,
A WCF service has the following core components.
  • Service Class:  A service class implementing in any CLR-based language and expose at least one method.
  • Hosting Environment: a managed process for running service.
  • Endpoint: a client uses it to communicate with service.

What is WCF throttling? | WCF Interview Question

, ,
WCF throttling enables us to regulate the maximum number of WCF instances, concurrent calls and concurrent sessions. Basic purpose is to control our WCF service performance by using Service throttling behavior.
In configuration file we can set this behavior as follows:
   <serviceBehavior>
        <behavior name=”MyServiceBehavior”>
                    <serviceThrottling
                                     maxConcurrentInstances=”2147483647”
                                     maxConcurrentCalls=”16″
                                     maxConcurrentSessions=”10″
         </behavior>
   </serviceBehavior>
Above given values are the default ones, but we can update it after looking into the requirements of our application.

What are the different ways to handle concurrency in WCF? | WCF Interview Question

, ,
There are three different ways to handle concurrency in WCF that are:
a)    Single
b)    Multiple
c)    Reentrant
Single: means at a given time, only a single request can be processed by WCF service instance. Other requests will be waiting until the first one is fully served.
Multiple: means multiple requests can be served by multiple threads of a single WCF service instance.
Reentrant: means a single WCF service instance can process one request at a given time but the thread can exit the service to call another service.
We can apply these concurrency settings by putting ConcurrencyMode property in ServiceBehavior as follows:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple]
public class MyService : IMyService
{
}

What are the different WCF Instance Activation Methods available? | WCF Interview Question

, ,
WCF supports three different types of Instance Activation methods:
a)    Per Call
b)    Per Session
c)    Singleton

Breifly explain Automatic Activation in WCF? | WCF Interview Question

, ,
Automatic activation means service starts and serves the request when a message request is received, but service doesn’t need to be running in advance.
There are few scenarios in which service needs to be running in advance, For example, in case of Self-Hosting

How to create proxy for Non-WCF Services? | WCF Interview Question

, ,
In case of Non-WCF Services, we can create proxy by either using Visual Studio or svcUtil.exe tool by pointing to WSDL of the non-WCF service. In this scenario, we can’t create proxy through ChannelFactory or manually developing proxy class because we don’t have local interfaces i.e. service contract.

Difference between using ChannelFactory and Proxies in WCF? | WCF Interview Question

, ,
A ChannelFactory creates a kind of Channel used by clients to communicate with service endpoints.
If we have control over Server and Client, then ChannelFactory is a good option because it relies on having local interfaces that actually describes the service i.e. service contract.
On the other hand, If we don’t have control over server and only have WSDL/URL, then it’s better to generate proxy using Visual Studio or SvcUtil.
SvcUtil is better option as compared to Visual Studio because we have more control in case of SvcUtil.

Creating WCF RESTful Service | WCF RESTful Guide | WCF Tutorial


A definition from Wikipedia, "Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web".

As we know that WCF allows us to make calls and exchange messages using SOAP over a variety of protocols i.e. HTTP, TCP, Named Pipes and MSMQ etc. In a scenario, if we are using SOAP over HTTP, we are just utilizing HTTP as a transport. But HTTP is much more than just a transport.

RESTful architecture use HTTP for all CRUD operations like (Read/Create/Update/Delete) using simple HTTP verbs like (GET, POST, PUT, and DELETE).It’s simple as well as lightweight. For the sake of simplicity, I am going to implement only a GET request for which service will return certain types of data (i.e. Product data) in XML format.

1. Create a WCF Service Project
  •  Open Visual Studio.
  •  From File -> New Project.  Select WCF from left and create a new WCF Service Application.
2. Preparing the data to return
  • Now add a class to newly created project. Name it to Products.cs.
Now this Products.cs file will contain two things.First one is Data Contract
[DataContract]
public class Product
{
                 [DataMember]
                 public int ProductId { get; set; }
                 [DataMember]
                 public string Name { get; set; }
                 [DataMember]
                 public string CategoryName { get; set; }
                 [DataMember]
                 public int Price { get; set; }
}
Second one is a singleton implemented class that gets products data from a database and return list of products. In order to make it simple, we are preparing data inside this class instead of fetching from the database as follows:
public partial class Products
{
        private static readonly Products _instance = new Products();
        private Products() { } 
       public static Products Instance 
      { 
                get { return _instance; } 
       } 
        public List ProductList 
        { 
               get { return products; } 
         } 
          private List<Product> products = new List<Product>() 
         { 
                 new Product() { ProductId = 1, Name = “Product 1″, CategoryName = “Category 1″, Price=10}, 
                new Product() { ProductId = 1, Name = “Product 2″, CategoryName = “Category 2″, Price=5}, 
                new Product() { ProductId = 1, Name = “Product 3″, CategoryName = “Category 3″, Price=15}, 
                new Product() { ProductId = 1, Name = “Product 4″, CategoryName = “Category 1″, Price=9} 
         }; 
 }

3. Creating Service Contract
Now add a new WCF Service to this project as follows:

It will add contract as well as service file to project. Following is the code for service contract i.e. IProductRESTService.cs.
[ServiceContract]
public interface IProductRESTService
{
           [OperationContract]
           [WebInvoke(Method = "GET",
                                    ResponseFormat = WebMessageFormat.Xml,
                                   BodyStyle = WebMessageBodyStyle.Bare,
                                   UriTemplate = "GetProductList/")]
           List GetProductList();
}
IProductRESTService contains only one method i.e. GetProductList. Important points to understand about this method is WebInvoke attribute parameters.
  • Method = “GET”, represents an HTTP GET request.
  • ResponseFormat = WebMessageFormat.Xml, response format will be XML here but we can return JSON as well by changing its value to WebMessageFormat.json.
  • BodyStyle = WebMessageBodyStyle.Wrapped, indicates both the request and response are wrapped.
  • UriTemplate = “GetProductList/”, it has two parts, URL path and query.
Don’t forget to add using System.ServiceModel.Web at top.
4. Implementing RESTful Service
In this step we are going to implement the service. Only one method GetProductList is defined in the contract, so implementing service class will be as follows:
public class ProductRESTService : IProductRESTService
{
         public List GetProductList()
         {
                      return Products.Instance.ProductList;
          }
}

5. Configure Service and Behavior
The last step is to configure the service and its behaviors using the configuration file. Following is the complete ServiceModel configuration settings.
<system.serviceModel>
   <services>
        <service name=”MyRESTService.ProductRESTService” behaviorConfiguration=”serviceBehavior”>
                <endpoint address=””
                                       binding=”webHttpBinding”
                                       contract=”MyRESTService.IProductRESTService”
                                      behaviorConfiguration=”web”></endpoint>
          </service>
   </services>
   <behaviors>
          <serviceBehaviors>
              <behavior name=”serviceBehavior”>
                  <serviceMetadata httpGetEnabled=”true”/>
                       <serviceDebug includeExceptionDetailInFaults=”false”/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
              <behavior name=”web”>
                    <webHttp/>
               </behavior>
          </endpointBehaviors>
  </behaviors>
   <serviceHostingEnvironment multipleSiteBindingsEnabled=”true” />
</system.serviceModel>
 webHTTPBinding is the binding used for RESTful services.
Now, everything about creating RESTful service is done. Let us run and see it in action.
 
Right click ProductRESTService.svc file and click “View in Browser“. You will see the following screen, that means service is fine.
Just modify the URL in browser and add “GetProductList/” to it. So, this is the UriTemplete we defined as service contract method.


Brief about WCF Callback Service Operation? | WCF Interview Question | WCF Tutorial | WCF Programmer Guide

,
WCF also provides the service to call the client. In which, service will act as client and client will act as service.
  • HTTP protocols are connectionless nature, so it is not supported for callback operation. So BasicHttpBinding and WSHttpBinding cannot be used for this operation.
  • WCF support WSDualHttpBinding for call back operation.
  • All TCP and IPC protocols support Duplex communication. So all these binding will be used for callback operation.

Defining and configuring a callback contract

Callback service can be enabled by using CallbackContract property in the ServiceContract attribute. In the below example you can find the decalration of the callback contract and it is configured in the ServiceContract attribute.
    public interface IMyContractCallback
    {
        [OperationContract]
        void OnCallback();
    }
    [ServiceContract(CallbackContract = typeof(IMyContractCallback))]
    public interface IMyContract
    {
        [OperationContract()]
        void MyMethod();
    }

Client Callback Setup

As I said earlier, in callback operation client will act as service and service will act as client. So client has to expose a callback endpoint to the service to call. In the earlier part of the tutorial I have mention that InstanceContext is the execution scope of inner most service instance. It provides a constructor that takes the service instance to the host.
 IMyContractCallback callback=new MyCallback();
        InstanceContext cntx=new InstanceContext(callback);

        MyServiceClient proxy = new MyServiceClient(cntx);
        proxy.MyMethod();   
The client must use a proxy that will set up the bidirectional communication and pass the callback endpoint reference to the service. This can be achieved by creating the proxy using DuplexClientBase
   class MyServiceClient:DuplexClientBase,IMyContract
    {
        public MyServiceClient(InstanceContext callbackCntx)
            : base(callbackCntx)
        {            
        }
        public void MyMethod()
        {
             base.Channel.MyMethod();
        }
    }

Service-Side Callback Invocation

The client-side callback endpoint reference is passed along with every call the client makes to the service, and it is part of the incoming message. The OperationContext class provides the service with easy access to the callback reference via the generic method GetCallbackChannel<T>( ). Service can call the client side callback method using reference e to the client side callback instance. The following code shows the callback method invocation.
IMyContractCallback
 callbackInstance=OperationContext.Current.GetCallbackChannel();
            callbackInstance.OnCallback();

Brief about WCF One-Way Operation | WCF Interview Question | WCF Tutorial | WCF Programmer Guide

,
In One-Way operation mode, client will send a request to the server and does not care whether it is success or failure of service execution. There is no return from the server side, it is one-way communication.
Client will be blocked only for a moment till it dispatches its call to service. If any exception thrown by service will not reach the server.
Client can continue to execute its statement, after making one-way call to server. There is no need to wait, till server execute. Sometime when one-way calls reach the service, they may not be dispatched all at once but may instead be queued up on the service side to be dispatched one at a time, according to the service's configured concurrency mode behavior. If the number of queued messages has exceeded the queue's capacity, the client will be blocked even if it's issued a one-way call. However, once the call is queued, the client will be unblocked and can continue executing, while the service processes the operation in the background.

Definition :

One-way operation can be enabled by setting IsOneWay property to true in Operation contract attribute.
[ServiceContract]
public interface IMyService
{
    [OperationContract(IsOneWay=true)]
    void MyMethod(EmployeeDetails emp);
}

One-Way Operations and Sessionful Services

Let us see the example, what will happen when you use the one-way communication with Sessionful service.
    [ServiceContract(SessionMode = SessionMode.Required)]
    interface IMyContract
    {
        [OperationContract(IsOneWay = true)]
        void MyMethod();
    }
As per above configuration, when client makes one-way call using MyMethod() operation and if it close the proxy. Client will be blocked until operation completes. It will be good practice, that one-way operation should be applied on per-call and singleton service.
Suppose If you want to make use of One-way operation in Sessionful service, use in the last operation of the service which will terminate the session. This operation should not return any value.
    [ServiceContract(SessionMode = SessionMode.Required)]
    interface IMyContract
    {
        [OperationContract]
        void MyMethod1();

        [OperationContract]
        string MyMethod2();

        [OperationContract(IsOneWay = true, IsInitiating = false,
                                           IsTerminating = true)]
        string CloseSessionService(int id);
       
    }

One-Way Operations and Exceptions

Suppose when we are using BasicHttpBinding or WSHttpBinding, i.e. no transport session is used, if any exception throw by service will not affect the client. Client can make a call to the service using same proxy
[ServiceContract]
interface IMyContract
{
   [OperationContract(IsOneWay = true)]
   void MethodWithError( );

   [OperationContract]
   void MethodWithoutError( );
}
//Client side without transport session
MyContractClient proxy = new MyContractClient( );
proxy.MethodWithError( ); //No exception is thrown from serivce
proxy.MethodWithoutError( ); //Operation will execute properly
proxy.Close( );
In the presence of transport session, any exception thrown by service will fault the client channel. Client will not be able to make new call using same proxy instance.
//Client side transport session
MyContractClient proxy = new MyContractClient( );
proxy.MethodWithError( ); 
proxy.MethodWithoutError( ); //Can not executre because channel is faulted
proxy.Close( );