Sunday, 4 September 2016

WCF Part 2

What is service?
A service is a unit of functionality exposed to the world. Service orientation (SO) is an abstract set of principles and best practices for building service-oriented applications.
What do you mean by client?
The client of a service is the program unit consuming its functionality. The client can
be literally anything—for instance, Console application, Windows Forms, WPF, or Silverlight class, anASP.NET page, or another service.
What is WCF?
·         Stands for Windows Communication Foundation.
·         Its code name is “Indigo”.
·         It is a framework for building, configuring and deploying interoperable distributed services.
·         It enables you to write more secure flexible services without any code change (using configuration).
·         It also provide built-in support for logging. You can enable/disable logging using configuration.
WCF = Web Service + Remoting + MSMQ + COM+
or
WCF = ASMX + .Net Remoting + WSE + Messaging + Enterprise Services
What are the transport schemes supported by WCF? Give example of address for each scheme.
Following are the transport schemes supported by WCF:
·         HTTP/HTTPS - http://localhost:8001/MyService
·         TCP - net.tcp://localhost:8002/MyService
·         IPC - net.pipe://localhost/MyPipe
·         Peer network
·         MSMQ - net.msmq://localhost/private/MyQueue
·         Service bus - sb://MyNamespace.servicebus.windows.net/
What is Contract? What are the types of Contract?
It is the agreement between client and service which specifies:
·         [ServiceContract] - which services are exposed to the client.
·         [OperationContract] - which operations the client can perform on the service.
·         [DataContract] – which data types are passed to and from the service.
·         [MessageContract] - allow the service to interact directly with messages. Message contracts can be typed or untyped and are useful in interoperability cases when another party has alreadydictated some explicit (typically proprietary) message format.
·         [FaultContract] -which errors are raised by the service and how the service handles andpropagates errors to its clients.
What is the difference between Web Service and WCF Service?
Features
Web Service
WCF
Hosting
It can be hosted in IIS.
It can be hosted in IIS, WAS (windows activation service), Self-hosting or Windows service
Programming
Apply [WebService] attribute to the class to be exposed as a service.
Apply [ServiceContract] attribute to the class to be exposed as a service.
Model
Apply [WebMethod] attribute to the method exposed to client.
Apply [OperationContract] attribute to the method exposed to client.
Supported Operations
One-way and Request- Response.
One-Way, Request-Response and Duplex.
Logging
Needs custom implementation.
No custom implementation needed. Can be configured in service config file.
Serialization
System.Xml.serialization namespace is used.
System.Runtime.Serialization namespace is used.
Supported Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom.
XML 1.0, MTOM, Binary, Custom.
Supported Transports
Can be accessed through HTTP, TCP and Custom.
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P(Peer to Peer) and Custom.
Service Types
ASMX, .Net Remoting
.ASMX, .Net Remoting, WSE(WS* Protocols), MSMQ and Enterprise Services
Supported Protocols
Security
Security, Reliable messaging, Transactions
How can we host WCF service?
Every WCF service needs to be hosted in a windows process called the host process. A single host process can host multiple services, and the same service type can be hosted in multiple host processes.
WCF services can be hosted in many ways:
IIS 5/6 Hosting
WCF services can be hosted in IIS. It is similar to hosting a ASMX web service. To host a WCF service, you need to create a .svc file similar to this example and put it in virtual directory of IIS:
Hide   Copy Code
<%@ ServiceHost Language = "C#" Debug = "true" CodeBehind = "&tilde;/App_Code/MyService.cs" Service = "MyService" %>
Instead of defining a .svc file, you can create and host the service in .config file as below:
Hide   Copy Code
<system.serviceModel>
  <serviceHostingEnvironment>
    <serviceActivations>
      <add relativeAddress = "MyService.svc" service = "WcfService.MyService"/>
      <add relativeAddress = "MyOtherService.svc" service = "MyOtherService"/>
    </serviceActivations>
  </serviceHostingEnvironment>
  <services>
    <service name = "WcfService.MyService">
      ...
    </service>
    <service name = "MyOtherService">
      ...
    </service>
  </services>
</system.serviceModel>
Self Hosting
Self-hosting is the technique in which the developer is responsible for providing and
managing the lifecycle of the host process. You can host WCF service inside any Windows process, such as a Windows Forms application, a WPF application, a Console application, or a Windows NT Service.
You can also host your WCF service as in-proc. In-process (or in-proc) hosting is the hosting technique where the service resides in the same process as the client. By definition, the developer provides the host for the in-proc hosting.
Hide   Copy Code
var host = new ServiceHost(typeof(MyService));
host.Open();
Console.WriteLine("Press any key to stop service");
Console.ReadKey();
host.Close();
WAS (Windows Activation Service) Hosting
Microsoft provides a generalpurpose hosting engine called the Windows Activation Service (WAS). WAS is a system service available with Windows Vista, Windows Server 2008, and Windows 7 (or later). The WAS is a true general-purpose hosting engine. It can host websites (in fact, IIS 7 will host its websites in the WAS by default), but it can just as easily host your services, allowing you to use any transport, such as TCP, IPC, or MSMQ. You can install and configure the WAS separately from IIS 7. Hosting a WCF service in the WAS is designed to look just like hosting in IIS 5/6. You need to either supply an .svc file, just as with IIS 5/6, or provide the equivalent information in the config file.
Custom Hosting in IIS/WAS
When using IIS 5/6 or WAS, you have no direct access to the host. To overcome this hurdle, WCF provides a hook called a host factory. Using the Factory tag in the .svc file, you can specify a class you provide that creates the host instance.
Hide   Copy Code
<%@ ServiceHost Language = "C#" Debug = "true" CodeBehind = "&tilde;/App_Code/MyService.cs" Service = "MyService" Factory = "MyServiceFactory" %>
You can also specify the host factory in the config file when not using an .svc file explicitly:
Hide   Copy Code
<serviceActivations>
    <add relativeAddress = "MyService.svc" service = "MyService" factory = "MyServiceFactory" />
</serviceActivations>
Note: The host factory class must derive from the ServiceHostFactory class and override the CreateServiceHost() virtual method.
Windows Server AppFabric
AppFabric is an extension to the WAS. It is geared more toward WF services, which require support for persistence and state management correlation. Windows Server AppFabric adds items for managing and monitoring the services, as well as WCF and WF configuration items, to the IIS 7 management console. Windows Server AppFabric provides a dashboard for monitoring the running instances of WCF or WF services, and is reminiscent of the MTS or COM+ Component Services Explorer of old. Windows Server AppFabric provides health monitoring and custom diagnostics, as well as some troubleshooting features for analyzing why a service call has failed.
Windows Server AppFabric also supports scripting of all the options available in the user interface. Windows Server AppFabric offers its own events collecting system service, which stores the events in a SQL Server database. You can provide Windows Server AppFabric with tracing and tracking profiles at various verbosity levels.
How do you choose the hosting for WCF internet service?
HowToChooseHost
What are the protocols supported by WCF hosting environment? What are their advantages and disadvantages?
WCF support multiple ways in which you can host your WCF service.
Hosting Environment
Supported protocol
IIS6
http, wshttps
IIS7 – WAS (Windows Process Activation Service)
http,net.tcp,net.pipe,net.msmq
Windows console and form application
http,net.tcp,net.pipe,net.msmq
Windows service application (formerly known as NT services)
http,net.tcp,net.pipe,net.msmq
Below is the feature summary of hosting environments:
Feature
Self-Hosting
IIS Hosting
WAS Hosting
Executable Process/ App Domain
Yes
Yes
Yes
Configuration
App.config
Web.config
Web.config
Activation
Manual at startup
Message-based
Message-based
Idle-Time Management
No
Yes
Yes
Health Monitoring
No
Yes
Yes
Process Recycling
No
Yes
Yes
Management Tools
No
Yes
Yes
What is binding?
A binding is the set of configurations regarding the transport protocol, message encoding, communication pattern, reliability, security, transaction propagation, and interoperability.
What are the types of bindings supported by WCF? What are their advantages and disadvantages?
Binding
Feature
Suitable For
Transport
Message encoding
Security Mode
Resource Manager
Transaction Flow
BasicHttpBinding
Not secure by default.
Communication with WS-Basic Profile conformant Web Services like ASMX.
HTTP
Text
None
X
X
WSHttpBinding
Secure, Interoperable.
Non-duplex service contracts.
HTTP
Text
Message
Disabled
WS-Atomic
WSDualHttpBinding
Secure, Interoperable.
Duplex service contracts or communication through SOAP intermediaries.
HTTP
Text
Message
Enabled
WS-Atomic transaction
WSFederationHttpBinding
Secure, Interoperable.
Supports the WS-Federation protocol, enabling organizations that are in a federation to efficiently authenticate and authorize users.
HTTP
Text
Message
Disabled
WS-Atomic transaction
NetTcpBinding
Secure, Optimized.
Cross-machine communication between WCF applications.
TCP
Binary
Transport
Disabled
Ole transaction.
NetPeerTcpBinding
Secure.
Multi-machine communication.
P2P
Binary
Transport
X
X
NetNamedPipesBinding
Secure, Reliable, Optimized.
On-machine communication between WCF applications.
Named Pipes
Binary
Transport
X
Ole transaction.
NetMsmqBinding

Cross-machine communication between WCF applications.
MSMQ
Binary
Message
X
X
MsmqIntegrationBinding
Does not use a WCF message encoding – instead it lets you choose a pre-WCF serialization format.
Cross-machine communication between a WCF application and existing MSMQ applications.
MSMQ
Pre-WCF format
Transport
X
X
What is Endpoint in WCF?
or
What is ABC in WCF?
Endpoint = Address (A) + Binding (B) + Contract (C)
Address specifies where the services is hosted.
Binding specifies how to access the hosted service. It specifies the transport, encoding, protocol etc.
Contract specifies what type of data can be sent to or received from the service.
Eg:
Hide   Copy Code
<endpoint name="BasicHttpGreetingService" address="http://localhost:5487/MyService/GreetingService.svc" binding="basicHttpBinding" contract="MyNamespace.MyService.IGreetingService" />
Can you explain Address in detail?
It is the url which specifies the location of the service. Client can use this url to connect to the service and invoke the service methods.
Eg: http://localhost:5487/MyService/GreetingService.svc
Can you explain Binding in detail?
It specifies how to access the hosted service. There are following characteristics of binding:
Transport defines the communication protocol to be used to communicate between service and client. It may be HTTP, TCP, MSMQ, NamedPipes etc. It is mandatory to define transport.
Encoding defines the technique used to encode the data before communicating it from one end to the other.
Protocol defines the configurations like reliability, security, transaction, timouts, message size etc.
What is binding configuration?
You can customize the binding used by endpoint using config file. For example, you can enable/disable transaction for the binding used by endpoint. All you need is to configure binding element in config file similar as below:
Hide   Copy Code
<bindings>
  <netTcpBinding>
    <binding name = "TransactionalTCP" transactionFlow = "true" />
  </netTcpBinding>
</bindings>
What is default endpoints?
If the service host does not define any endpoints (neither in config nor programmatically) but does provide at least one base address, WCF will by default add endpoints to the service. These are called the default endpoints. WCF will add an endpoint per base address per contract, using the base address as the endpoint’s address. WCF will infer the binding from the scheme of the base address. For HTTP, WCF will use the basic binding. Note that the default bindings will affect the default endpoints. WCF will also name the endpoint by concatenating the binding name and the contract name.
How can we enable/disable metadata publishing of our WCF service?
You can enable enable meta data publishing for a WCF service two ways:
·         Configure metadata publishing for a service that uses default endpoints. Specify the ServiceMetadataBehavior in the configuration file but do not specify any endpoints.
Hide   Copy Code
<configuration>
 <system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="CustomServiceBehavior">
         <serviceMetadata httpGetEnabled="True" />
         <serviceDebug includeExceptionDetailInFaults="False" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>
</configuration>
·         Configure metadata publishing for a service that uses explicit endpoints. Specify the ServiceMetadataBehavior in the configuration file and a mex endpoint.
Hide   Copy Code
<configuration>
 <system.serviceModel>
   <services>
     <service name="MyNamespace.MyService.GreetingService" behaviorConfiguration="CustomServiceBehavior">
       <endpoint address="" binding="wsHttpBinding" contract="MyNamespace.MyService.IGreetingService" />
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
     </service>
   </services>
   <behaviors>
     <serviceBehaviors>
       <behavior name="CustomServiceBehavior">
         <serviceMetadata httpGetEnabled="True" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>
</configuration>
Supported bindings for mex endpoint are mexHttpBindingmexHttpsBindingmexNamedPipeBinding andmexTcpBinding.
How can you generate proxy class and configuration file for WCF service?
WCF provides an utility svcutil.exe which can be used to generate proxy class and configuration file. Eg:
SvcUtil http://localhost:8002/MyService/ /out:Proxy.cs /noconfig
Is there any tool provided by Microsoft for editing configuration file?
Yes. Microsoft provides an utility “SvcConfigEditor.exe” that can edit any configuration file.
How can you test your new WCF service without writing any client application?
Microsoft provides a tool which can be used to test any WCF service. To use this tool, open visual studio command prompt and execute the command “wcftestclient.exe“. It will open a window where you can add many WCF services and test. You can also provide values for input parameters of WCF methods.
Which bindings support reliability and message ordering?
Binding name
Supports
reliability
Default
reliability
Supports ordered
delivery
Default Ordered
delivery
BasicHttpBinding
No
N/A
No
N/A
NetTcpBinding
Yes
Off
Yes
On
NetNamedPipeBinding
No
N/A(On)
Yes
N/A(On)
WSHttpBinding
Yes
Off
Yes
On
NetMsmqBinding
No
N/A
No
N/A
How can you configure reliability using .config file?
Hide   Copy Code
<bindings>
  <netTcpBinding>
    <binding name = "ReliableTCP">
      <reliableSession enabled = "true"/>
    </binding>
  </netTcpBinding>
</bindings>
How can you implement operation overloading in WCF service?
We can implement operation overloading using “Name” property of OperationContract attribute. For eg:
Hide   Copy Code
[ServiceContract]
interface ICalculator
{
    [OperationContract(Name = "AddInt")]
    int Add(int arg1,int arg2);
    [OperationContract(Name = "AddDouble")]
    double Add(double arg1,double arg2);
}
What is Known Types?
By default, you can not use a subclass of a data contract class instead of its base class. You need to explicitly tell WCF about the subclass using the KnownTypeAttribute. For eg
Hide   Copy Code
[DataContract]
[KnownType(typeof(SubClass))]
class BaseClass
{...}

[DataContract]
class SubClass : BaseClass
{...}
What is ServiceKnownType?
Instead of using the KnownType attribute on the base data contract, you can apply the
ServiceKnownType attribute on a specific operation on the service side. Then, only that
operation (across all supporting services) can accept the known subclass.
Hide   Copy Code
[OperationContract]
[ServiceKnownType(typeof(SubClass))]
void AddContact(BaseClass baseObject);
How can we create and host a WCF service in IIS?
How to create a service contract and operation contract? Can you give an example?
We can create a contract using an interface by applying [ServiceContract] and [OperationContract] attributes on Interface and Methods respectively.
Hide   Copy Code
[ServiceContract]
public interface IGreetingService
{
    [OperationContract]
    string GreetMe(string userName);
}

public class GreetingService : IGreetingService
{
    public string GreetMe(string userName)
    {
        return string.Format("Welcome {0}", userName);
    }
}
If we do not want to create interface then we can apply the attributes on a class itself.
Hide   Copy Code
[ServiceContract]
public class GreetingService
{
    [OperationContract]
    public string GreetMe(string userName)
    {
        return string.Format("Welcome {0}", userName);
    }
}
Can you give an example of DataContract?
Hide   Copy Code
[DataContract]
public enum Color
{
  [EnumMember]
  Red,

  [EnumMember]
  Green,

  [EnumMember]
  Blue
}
[DataContract]
public class Shape
{
  [DataMember]
  public string Name { get; set; }

  [DataMember]
  public Color FillColor { get; set; }

  [DataMember]
  public double Area { get; set; }
}
What is MessageContract? Can you give an example?
WCF uses SOAP messages to transfer information from client to server and vice-versa. It converts data contract to SOAP messages. SOAP message contains Envelope, Header and Body. SOAP envelope contains name, namespace, header and body element. SOAP Header contains important information which are related to communication but not directly related to message. SOAP body contains information which is used by the target.
Hide   Copy Code
SOAP Envelope = Name + Namespace  + Header + Body
However there are some cases when you want to have control over the SOAP messages. You can achieve this using MessageContract.
Hide   Copy Code
[MessageContract]
public class Shape
{
    [MessageHeader]
    public string ID;
    [MessageBodyMember]
    public string Name;
    [MessageBodyMember]
    public double Area;
}
In above example, ID will be added as header, Name and Area as body in SOAP envelope.
When you use MessageContract then you have control over the SOAP message. However some restrictions are imposed as below:
·         You can have only one parameter for a service operation if you are using MessageContract.
·         You can return either void or MessageContract type from service operation. Service operation can not return DataContract type.
·         Service operation can accept and return only MessageContract type.
Some important points about MessageContract:
·         You can mention the MessageHeader or MessageBodyMember to be signed or Encrypted using ProtectionLevel property.
·         The order of the body elements are alphabetical by default. But you can control the order, using Order property in the MessageBody attribute.
What is FaultContract?
In most of the cases you would like to convey the details about any error which occurred at service end. By default, WCF exceptions do not reach client. However you can use FaultContract to send the exception details to client.
Hide   Shrink http://www.codeproject.com/images/arrow-up-16.png   Copy Code
[DataContract()]
public class CustomError
{
  [DataMember()]
  public string ErrorCode;
  [DataMember()]
  public string Title;
  [DataMember()]
  public string ErrorDetail;
}

[ServiceContract()]
public interface IGreetingService
{
  [OperationContract()]
  [FaultContract(typeof(CustomError))]
  string Greet(string userName);
}

public class GreetingService : IGreetingService
{
  public string Greet(string userName)
  {
    if (string.IsNullOrWhiteSpace(userName))
    {
        var exception = new CustomError()
        {
            ErrorCode = "401",
            Title = "Null or empty",
            ErrorDetail = "Null or empty user name has been provided"
        };
        throw new FaultException<CustomError>(exception, "Reason : Input error");
    }
    return string.Format("Welcome {0}", userName);
  }
}
How is the service instance created? How can you manage or control WCF service instance creation?
Client request can be served by using single service instance for all users, one service instance for one client, or one instance for one client request. You can control this behavior by using the technique called Instance Management in WCF.
There are three instance modes supported by WCF:
·         Per-CallService instance is created for each client request. This Service instance is disposed after response is sent back to client.
·         Per-Session (default): Service instance is created for each client. Same instance is used to serve all the requests from that client for a session. When a client creates a proxy to particular service, a service instance is created at server for that client only. When session starts, context is created and when it closes, context is terminated. This dedicated service instance will be used to serve all requests from that client for a session. This service instance is disposed when the session ends.
·         Singleton: All client requests are served by the same single instance. When the service is hosted, it creates a service instance. This service instance is disposed when host shuts down.
You can configure instance mode using [ServiceBehavior] attribute as below:
Hide   Copy Code
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class MyService:IGreetingService
Can you control when the service instance is recycled?
Yes, we can control when the service instance is recycled using the ReleaseInstanceMode property of theOperationBehavior attribute. You can control the lifespan of your WCF service. You can set the value ofReleaseInstanceMode property as one of the following:
·         RealeaseInstanceMode.None: No recycling behavior.
·         RealeaseInstanceMode.BeforeCall: Recycle a service object before an operation is called.
·         RealeaseInstanceMode.AfterCall: Recycle a service object after an operation is called.
·         RealeaseInstanceMode.BeforeAndAfterCall: Recycle a service object both before and after an operation is called.
Can you limit how many instances or sessions are created at the application level?
Yes, you can limit how many instances or sessions are created at the application level. For this, you need to configure throttling behavior for the service in its configuration file. Some of these important properties are:
·         maxConcurrentCalls limits the total number of calls that can currently be in progress across all service instances. The default is 16.
·         maxConcurrentInstances limits the number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue.
·         maxConcurrentSessions limits the number of sessions a ServiceHost object can accept. It is a positive integer that is 10 by default.
Hide   Copy Code
<behaviors>
 <serviceBehaviors>
   <behavior name="ServiceBehavior">
     <serviceThrottling maxConcurrentCalls="500" maxConcurrentInstances ="100" maxConcurrentSessions ="200"/>
   </behavior>
What are session modes in WCF? How can you make a service as sessionful?
ServiceContract attribute offers the property SessionMode which is used to specify the session mode. There are three session modes supported by WCF:
·         Session.Allowed(default): Transport sessions are allowed, but not enforced. Service will behave as a per-session service only if the binding used maintains a transport-level session.
·         Session.Required: Mandates the use of a transport-level session, but not necessarily an application-level session.
·         Session.NotAllowed: Disallows the use of a transport-level session, which precludes an application-level session. Regardless of the service configuration, the service will always behave as a per-call service.
Hide   Copy Code
[ServiceContract(SessionMode = SessionMode.NotAllowed)]
interface IMyContract
{...}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract
{...}
What is the instance mode as a product of the binding, contract configuration, and service behavior?
Binding
Session mode
Context mode
Instance mode
Basic
Allowed/
NotAllowed
PerCall/
PerSession
PerCall
TCP, IPC
Allowed/
Required
PerCall
PerCall
TCP, IPC
Allowed/
Required
PerSession
PerSession
WS
(no Message security, no reliability)
NotAllowed/
Allowed
PerCall/
PerSession
PerCall
WS
(with Message security or reliability)
Allowed/
Required
PerSession
PerSession
WS
(with Message security or reliability)
NotAllowed
PerCall/
PerSession
PerCall
What is MEP (Message Exchange Pattern) in WCF?
MEP describes the way in which Client and Server communicates. It describes how client and server would be exchanging messages to each other. There are three types of message exchange patterns:
·         Request- Replay (default): When client makes a request to the WCF service, it waits to get response from service till receiveTimeout expires. If client does not get any response from the service before receiveTimeout expires, TimeoutException is thrown.
·         One-Way: When client makes a request to the WCF service, it does not wait for reply from the service. Service does not send any response to the sender, even if any error occurs in the communication. It does not support out or ref parameters. It does not return value to an operation. One way operation do not return values or exceptions. But while dispatching the one-way operation any error because of communication problems like host not available or address missmatch will through an exception on client side, again this depends on service instance mode and trasport session
·         Duplex/Callback: Client and service can sends messages to each other by using One-way or request-reply messaging. This MEP is supported by only bidirectional-capable bindings like as WS Dual, TCP and IPC bindings.To make a duplex contract, you must also define a callback contract and assign the typeof that callback contract to the CallbackContract property of your service contract’s ServiceContract attribute.
Hide   Copy Code
public interface IMyDuplexServiceCallback
{
[OperationContract(IsOneWay = true)]
void Progress(string status);
}

[ServiceContract(CallbackContract = typeof(IMyDuplexServiceCallback))]
public interface IMyDuplexService
{
[OperationContract(IsOneWay = true)] //One-Way
void SaveData();

[OperationContract] //Request-Reply.
string GetData();
}
For Duplex MEP, you need to specify the one of the binding which supports bi-directional like wsDualHttpBinding as in below example:
Hide   Copy Code
<services>
  <service name="MyWCFServices.DuplexService">
    <endpoint address ="" binding="wsDualHttpBinding" con-tract="MyWCFServices.IDuplexService">
    </endpoint>
You can configure MEP using IsOneWay property of OperationContract attribute as below:
Hide   Copy Code
[OperationContract(IsOneWay = true)]
What is transaction and committed transaction in WCF?
A transaction is a collection or group of one or more units of operation executed as a whole. It provides way to logically group multiple pieces of single work and execute them as a single unit. In addition, WCF allows client applications to create transactions and to propagate transactions across service boundaries.
A transaction that executes successfully and manages to transfer the system from the consistent state A to the consistent state B is called a committed transaction.
What is Two-phase commit protocol in WCF? Why is it needed?
Consider for example client calling multiple service or service itself calling another service, this type of system are called as Distributed Service-oriented application. Now the questions arise that which service will begin the transaction? Which service will take responsibility of committing the transaction? How would one service know what the rest of the service feels about the transaction? Service could also be deployed in different machine and site. Any network failure or machine crash also increases the complexity for managing the transaction. This problem is resolved by using two phase protocol.
All the transactions in WCF complete using two phase commit protocol. It is the protocol which enables transactions in a distributed environment. This protocol mainly consist of two phases:
·         Prepare phase: In this phase the client application performs the operations of a WCF service. WCF service determines whether the requested operation will be successful or not and notify the client about the same.
·         Commit Phase: In the commit phase the client checks for the responses it got from the prepare phase and if all the responses are indicating that the operation can be carried out successfully the transaction is committed. If the response from any one of the operations indicates failure then the transaction will be rolled back. The actual operation on the service end will happen in the commit phase.
WCF service will have to send the notification of whether the operation will succeed or fail to the client application. It means that the One way operations can never support transactions. The operations that support transactions have to follow the Request-Response MEP. Also the applied binding should support WS-Atomic Transaction protocol like wsHttpBinding.
What is Transaction Propagation in WCF? Explain with example.
Suppose that there are two services CreditService and DebitService. CreditService has operation Credit(int accountId, double amount) and DebitService has operation Debit(int accountId, double amount). If you want to transfer amount from one account to another account, you need to call both the services. You also need to ensure that both the services should either succeed or fail together. You can achieve this by propagating the transaction of first service call to the second service call. Transaction Propagation is supported by WCF. You can propagate transaction across the service boundaries. It enables multiple services to participate in same transaction.
You can enable/disable transaction propagation using configuration as below:
Hide   Copy Code
<bindings>
   <netTcpBinding>
     <binding transactionFlow="true"></binding>
   </netTcpBinding>
</bindings>
Above configuration ensures that transaction can be propagated. However it does not force the transaction propagation until you specify for particular operation. You need to enable transaction flow for the operations whom you want to be part of transaction as below:
Hide   Copy Code
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Credit(int accountId, double amount);
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Debit(int accountId, double amount);
Note: You can have single operation as which can do credit and debit. However I have separated as two for illustrating about transaction.
transactionFlow and TransactionFlowOption together enables the transaction flow for particular operation. If you enable only one of these two, transaction flow can not be enabled.
There are 3 possible values for TransactionFlowOption:
·         TransactionFlowOption.Mandatory: specifies that this function can only be called within a transaction.
·         TransactionFlowOption.Allowed: specifies that this operation can be called within a transaction but its not mandatory.
·         TransactionFlowOption.NotAllowed: specifies that this operation can not be called within a transaction.
How to create WCF transaction?
There are some steps you need to follow to enable transaction for a WCF service as below:
Step 1: Decorate the operation contract with TransactionFlow attribute for enabling the transaction.
Hide   Copy Code
<code>[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Debit(int accountId, double amount);
Step 2: Create the service class which implements the service contract and set the operation behavior withTransactionScopeRequired = true. This attribute is used to enable the service transaction when the client transaction is not available.
Hide   Copy Code
<code>[OperationBehavior(TransactionScopeRequired = true)]
public bool Debit(int accountId, double amount)
{
  // Debit logic goes here
}
Step 3: Enable transaction flow in configuration file.
Hide   Copy Code
<bindings>
      <wsHttpBinding>
        <binding name="myTransactionBinding" transactionFlow="true" ></binding>
      </wsHttpBinding>
    </bindings>
What is Restful service?
·         REST stands for Representational State Transfer.
·         REST is an architectural style for building distributed applications. It involves building Resource Oriented Architecture (ROA) by definding resources that implement uniform interfaces using standard HTTP verbs (GET, POST, PUT, and DELETE), and that can be located/identified by a Uniform Resource Identifier (URI).
Any Service which follows the REST architecture style is called as RESTful service.
Characteristics of RESTful services:
·         We can load the server information using web url in the browser.
·         We can access/modify the server resource using Url.
·         It allows the client, written in different language, to access or modify the resource in the server using URL.
·         It uses the http protocol for its communication and it is stateless.
·         It can transfer the data in XML,JSON,RSS,ATOM.
How can you control if and when concurrent calls are allowed?
Or
What is concurrency modes in WCF? Why do we use it?
We can use Concurrency Modes in WCF to control if concurrent calls to the context are allowed or not and if yes then when concurrent calls to the instance/context should be allowed.
There are three possible values for Concurrency Modes:
ConcurrencyMode.Single(default)- only one caller at a time is allowed.
WCF will provide automatic synchronization to the service context and disallow concurrent calls by associating the context containing the service instance with a synchronization lock. If there are multiple concurrent callers to the same context while the lock is locked, all the callers are placed in a queue. Once the context is unlocked waiting callers are allowed to lock the context in the order of queue. If a call times out while blocked, WCF will remove the caller from the queue and the client will get a TimeoutException.
ConcurrencyMode.Multiple - multiple callers at a time are allowed.
WCF will not synchronize access to the service context. It means that the service context is not associated with any synchronization lock. In this case, you must manually synchronize access to the service instance state using .NET locks such as Monitor or a WaitHandle-derived class.
ConcurrencyMode.Reentrant - multiple callers at a time are allowed only if it is reentrant.
WCF associates the service context with a synchronization lock, so concurrent calls on the same instance are never allowed. However, if the reentrant service calls another service or a callback, and that call chain somehow winds its way back to the service instance that call is allowed to reenter the service instance. For example, suppose there are three services A, B and C. Service A calls service B, service B calls service C, and service C calls service A then service C is allowed to call service A because it is reentrant service.
You can set the concurrency mode for the service by setting the ConcurrencyMode property of ServiceBehavior attribute.
Hide   Copy Code
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]


Hope it helps you in understanding the basic concepts of WCF and answer related questions. Please comment your suggestion to make this article more useful. You can write your question, if any, as comment and I shall answer it.


No comments:

Post a Comment