What are the core security concepts supported by WCF? | WCF Interview Question

,
There are four core security Features
Confidentiality: It’s a confirmation about the recipient. Only the valid recipient can read the message when it passed between service and client.
Integrity: is to ensure that message received is not being tempered or changed during exchange.
Authentication: is a way for the parties (sender and receiver) to identify each other.
Authorization: ensures that what actions an authenticated user can perform?

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.

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( );

Brief about WCF Request-Reply Operation? | WCF Interview Question | WCF Tutorial | WCF Programmer Guide

,


By default all WCF will operated in the Request-Replay mode. It means that, when client make a request to the WCF service and client will wait to get response from service (till receiveTimeout). After getting the response it will start executing the rest of the statement. If service doesn't respond to the service within receiveTimeout, client will receive TimeOutException.

Apart from NetPeerTcpBinding and the NetMsmqBinding all other bindings will support request-reply operations.