Google News
logo
WCF Interview Questions
WCF stands for Windows Communication Foundation. It is a framework which is used for building, configuring and basically a Microsoft technology deploying interoperable distributed services. Using WCF, you can send data as asynchronous messages from one service endpoint to another. The program gives you the opportunity to do correspondence via different methods, including MS informing queuing, services, and remote access. It also enables you to communicate with non-Microsoft applications or .NET programs. Formerly known as Indigo, it also provides hosting services across all operating systems. WCF services can be hosted in IIS, self-hosted, or through the Windows Activation Service.
WCF follows the “Software as a Service” model, where all units of functionality are defined as services.  For communication, each point is a portal or connection either with the client or other services. It is a program that exposes a collection of endpoints.
WCF service endpoint has three basic elements: address, binding, and contract.
 
Address : It defines the address of the URL that identifies the location of the service and specifies the location where messages are received. It is specified as a Uniform Resource Identifier (URI). The URI schema part names the transport mechanism to use to reach the address, such as HTTP and TCP. The hierarchical part of the URI contains a unique location whose format is dependent on the transport mechanism.
 
The endpoint address enables you to create unique endpoint addresses for each endpoint in service or, under certain conditions, to share an address across endpoints.

Binding : It defines how the service can be accessed, how an endpoint communicates to the world. It is constructed of a set of components called binding elements that "stack" one on top of the other to create the communication infrastructure. At the very least, a binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages or the message pattern used by an endpoint.
 
Contract : It defines what is exposed by the service. Ties together multiple related operations into a single functional unit. The contract can define service-level settings, such as the namespace of the service, a corresponding callback contract, and other such settings. In most cases, the contract is defined by creating an interface in the programming language of your choice and applying the ServiceContractAttribute attribute to the interface. The actual service code results by implementing the interface.

WCF Service End Points

Operation contract : An operation contract defines the parameters and returns type of operation. When creating an interface that defines the service contract, you signify an operation contract by applying the OperationContractAttribute attribute to each method definition that is part of the contract. The operations can be modeled as taking a single message and returning a single message, or as taking a set of types and returning a type. In the latter case, the system will determine the format for the messages that need to be exchanged for that operation.
 
Message contract : Describes the format of a message. For example, it declares whether message elements should go in headers versus the body, what level of security should be applied to what elements of the message, and so on.
 
Fault contract : Can be associated with a service operation to denote errors that can be returned to the caller. An operation can have zero or more faults associated with it. These errors are SOAP faults that are modeled as exceptions in the programming model.
 
Data contract : The descriptions in metadata of the data type that a service uses. This enables others to interoperate with the service. The data types can be used in any part of a message, for example, as parameters or return types. If the service is using only simple types, there is no need to use data contracts explicitly.
Here are some reasons to use WCF services :
WCF
* Easy to use, and is flexible as well.  
* Windows activation service, IIS, and self-hosting options are available. 
* Provides support for multiple protocols including HTTP, WS-HTTP, TCP, P2P, MSMQ, and named pipes.   
* Use remote service to exchange messages in binary format using TCP protocol for maximizing the performance.  
* Uses chat to communicate with people or to exchange data. 
* To monitor the service, it provides data such as a traffic report.   
* Security services that process the transaction.   
* Used to exchange messages in XML format via an HTTP protocol in order to maintain interoperability.  
* Real-time data exchange using secure networks.
WCF has the following benefits : 
 
* Performs better than other Microsoft specifications.   
* Secure communication, data transmission, or even speed optimization can be achieved. 
* Decrease the latency by exchanging data in binary format.  
* Comparatively more reliable and secure than ASMX Web services.  
* Using the security model and altering the binding does not require a lot of coding changes.  
* A few changes to the configuration file will meet your needs.   
* Ensures interoperability between services.   
* Multiple hosting options are available such as IIS, WAS, self-Hosting.
Windows Communication Foundation (WCF) is a framework for building service-oriented applications by which we can send asynchronous message/data from one service endpoint to another service endpoint.
 
WCF is a runtime and a set of APIs for creating systems that sends messages between services and clients. The same infrastructure and APIs are used to create applications that communicate with other applications on the same computer system or on a system that resides in another company and is accessed over the Internet.
 
The WCF fundamentals are as follows :
 
* Unification
COM+ Services
Web Services
.NET Remoting
Microsoft Message Queuing
* Interoperability
* Service Orientation

WCF Architecture :

There are four major layers that provide developers with a new service-oriented programming model. The WCF architecture consists of the following layers.

WCF Architecture
Features of WCF
 
Windows Communication Foundation (WCF) is a secure, reliable, and scalable messaging platform for the .NET Framework 3.0,
 
* Service Orientation
* Interoperability
* Multiple Message Patterns
* Service Metadata
* Data Contracts
* Security
* Multiple Transports and Encodings
* Reliable and Queued Messages
* Durable Messages
* Transactions
* AJAX and REST Support
* Extensibility

Advantages of WCF
 
* Service Oriented
* Location Independent
* Language Independent
* Platform Independent
* Support Multiple operation
* WCF can maintain transaction like COM+ Does
* It can maintain state
* It can control concurrency
* It can be hosted on IIS, WAS, Self hosting, Windows services.

It has AJAX Integration and JSON (JavaScript object notation) support.
 
* WCF can be configured to work independently of SOAP and use RSS instead.
* WCF is one of the fastest communication technologies and offers excellent performance compared to other Microsoft specifications.
* To improve communication, transmission speed needs to be optimized. This is done by transmitting binary-coded XML data instead of plain text to decrease latency.
* Object life-cycle management and distributed transaction management are applicable to any application developed using WCF.
The three core components of WCF are as follows: 
 
Service class : In the runtime layer, you will find the behaviors that occur only when a service is actually running, i.e., the runtime behaviors of the service. Throttling is used to control the number of messages processed that can be altered if the service grows to a preset limit. 

Endpoint : WCF Service makes available a set of endpoints. All Endpoints are portals through which users are able to communicate with the outside world. Endpoints are composed of three components: Address, Binding, and Contract.  

Hosting Environment : It is the host application that is responsible for controlling the service's lifetime. Self-Hosting or management of services can be done by the existing hosting process.
The "Address" property is the part of endpoint defined in service level. This property is used to specify the location where the service is located.
The "Binding" property is the part of endpoint defined in service level. This property is used to specify the type protocols, encodings, and transport.
The "Contract" property is just an interface between the client and server where client and server communicate with each other. Contracts are used to specify operations available.
A service is a set of functionality exposed to the world. Service orientation (SO) is an abstract set of principles and best practices for building service-oriented applications.
WCF Proxies are used to communicate between client and server. The communication takes place by exchanging the messages in the form of requests and responses. It will have the details like Service Path, Protocol details and so on.
The Service Contracts attribute is used at the service level for WCF service. It provides the list of operations that can be performed from that service.
 
Service Contracts can be defined as :
 
[ServiceContract]
WCF proxy classes enable client applications to communicate with services by sending and receiving messages. Communication involves exchanging messages in the form of requests and responses. This will include details such as the Service Path, Protocol Details, etc.
Using WCF tracing, you can diagnose data, fault messages, and analyze them. Tracing offers better insight into the application's behavior and flows than debugging. It gives you a detailed account of all application components including faults, code exceptions, system events, and operation calls. By default, WCF tracing is not enabled, therefore it must be enabled by configuring it with the switch value and tracelistener. 

WCF Tracing basically involves the following four steps :

* Emitting Trace Information From Service
* Setting Trace Level
* Configuring The Listner
* Enabling Message Logging
Since, WCF's support various protocols, such as TCP, HTTP, and MSMQ, the user must ensure that the necessary steps are taken to safeguard messages, and also establish security policies for authenticating and authorizing calls. WCF provides an easy and rich configuration environment for secure messaging.

WCF supports the following security models :  
 
Message Security : This application uses the WS-Security specification to encrypt messages. Messages are now securely encrypted using certificates and can be sent over any port using plain HTTP.  

Transport Security : This is a protocol that implements security, so it only works point to point. Since security is protocol-dependent, security support is limited and confined to the standard protocol security limitations.

TransportWithMessageCredential : It can be referred to as a mixture of both Message and Transport security implementation. Credentials are sent with the message, and the transport layer provides message protection and server authentication.
Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another.
 
Web Services: A Web Service is programmable application logic accessible via standard web protocols. One of these web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C submitted note (as of May 2000) that uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.

Features Web Service WCF
Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions
SOA
 
SOA stands for service oriented architecture. Service Oriented Architecture is an architectural approach in software development where the application is organized as "Services". Services are a group of methods that contain the business logic to connect a DB or other services. For instance you go to a hotel and order food. Your order first goes to the counter and then it goes to the kitchen where the food is prepared and finally the waiter serves the food.

SOA
Some important characteristics of Service Oriented Architecture
 
* SOA services should be independent of other services.
Altering a service should not affect the client calling the service.
 
* Services should be self-contained.
 
• Services should be able to define themselves (in the Web Service Description Language (WSDL)). Services should be able to describe what they do. It should be able to tell the client what all of the operations it does, what are all the data types it uses and what kind of value it will return.

SOA Overview : A Service Oriented Architecture is based on four key abstractions.
 
* An Application Front End
* A Service
* A Service Repository
* A Service Bus

Application Front End : The application front end is decoupled from the services. Each service has a contract that defines what it will do and one or more interfaces to implement the contract.
 
A Service : It has the methods with the defined contracts and the implementation of the business logic to connect the DB or other service.
 
A Service Repository : The service repository provides a home for the services and the service bus provides an industry-standard mechanism for connecting to and interacting with the services.
 
Are web-services SOA ?
 
SOA is thinking, it's an architectural concept and web service is one of the technical approach to complete it. Web services are the preferred standards to achieve SOA.
 
* In SOA we need the services to be loosely coupled. A web service communicates using SOAP protocol which is XML based which is very loosely coupled. SOA services should be able to describe themselves. WSDL describes how we can access the service.
* SOA services are located in a directory. UDDI describes where we can get the web service. This nothing but implementation of SOA registry.
Three different types of transaction managers supported by WCF include : 
 
* Light Weight 
* WS- Atomic Transaction 
* OLE Transaction
The main use of contracts is to allow the client and services agree as to the types of operations and structures they will use during the communication process. It also shows the formal agreements between client and service to define a platform-neutral and standard for describing that what the service does.
 
Service Contract : A service contract defines the operations which are exposed by the service to the outside world. A service contract is the interface of the WCF service and it tells the outside world what the service can do. It may have service-level settings, such as the name of the service and namespace for the service.
[ServiceContract]
interface IMyContract
{
[OperationContract]
string MyMethod();
}

class MyService : IMyContract
{
public string MyMethod()
{
return "Namaste";
}​

Operation Contract :
An Operation Contract defines the method exposed to the client to exchange the information between the client and server. An Operation Contract describes what functionality is to be given to the client, such as addition, subtraction and so on.
 
It can be defined as in the following :
public interface IService1
{
    [OperationContract]
    string GetData(int value);
    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);
}
 

Data Contract :
Data Contracts define the data type for variables that are the same as get and set properties but the difference is that a Data Contract in WCF is used to serialize and deserialize the complex data. It defines how data types are serialized and deserialized. Using serialization, you can convert an object into a sequence of bytes that can be transmitted over a network. Using de-serialization, you reassemble an object from a sequence of bytes that you receive from a calling application.
 
Example :
public class Student
{
    private string _Name;
    private string _City;
    [DataMember]
    public string Name
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
        }
    }
}

Message Contract :
When an operation contract required to pass a message as a parameter or return value as a message, the type of this message will be defined as message contract. A message contract defines the elements of the message (like as Message Header, Message Body), as well as the message-related settings, such as the level of message security.

The SOAP header is implemented in the namespace system.web.services.protocol.  
[MessageContract]
public class AutherRequest
{
   public string AutherId;
}
Message Header : A Message Header is applied to a member of a message contract to declare the member within the message header.
[MessageContract]
public class AutherRequest
{
   [MessageHeader]
   public string AutherId;
}

 

Message Body Member :  A Message Body Member is applied to the member of a message contract to declare the members within the message body.
[MessageContract]
public class AuthorResponse
{
    [MessageBodyMember]
    public Auther Obj;
}

Fault Contract :
A fault contract defines errors raised by the service, and how the service handles and propagates errors to its clients. An operation contract can have zero or more fault contracts associated with it.
 
The following is the syntax to raise the custom error in WCF :
[ServiceContract]
public interface IGetDetailsService
{
    [OperationContract]
    [FaultContract(typeof (Student))]
    Student GetDetails(string Name);
}
[DataContract]
public class Student
{
    private string _Name;
    private string _City;
    [DataMember]
    public string Name
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
        }
    }
    [DataMember]
    public string City
    {
        get
        {
            return _City;
        }
        set
        {
            _City = value;
        }
    }
}
You need at least a managed process, a ServiceHost instance and an Endpoint configured for hosting a WCF service.
 
Following are the possible approaches for hosting a service :
 
Hosting in a Managed Application/ Self Hosting :

* Console Application
* Windows Application
* Windows Service
* Hosting on Web Server
* IIS 6.0 (ASP.NET Application supports only HTTP)
* Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP, NamedPipes, MSMQ.
Following is a list of different isolation levels in WCF :
 
Read Uncommitted : Also known as dirty isolation level. It makes sure that corrupt Data cannot be read. This is the lowest isolation level.

Read Committed : It ensures not to read the data that has been changed by any other application and is not yet committed. It is the default level.

Repeatable Read : It stops the usage of dirt read and non-repeatable read. It states that data fetched through a query will be locked and will not be updated by any other transaction.

Serializable : It does not allow any modification and addition of new data till the transaction is completed. This is considered to be a very restrictive level.

Snapshot : It raises an error on modifying a data that has already been changed by any transaction.
A list of address formats and their respective bindings :
 
TCF Address Format : net.tcp://local host:portnumber
 
HTTP Address Format : http://local host:portnumber
 
MSMQ Address Format : net.msmq://local host:portnumber
WCF supports the following types of built-in bindings :
 
* Basic binding
* Web binding
* Web Service (WS) binding
* WS Dual binding
* TCP binding
* IPC binding
* MSMQ binding
* Federated WS binding
* Peer Network binding
* MSMQ integration binding
There are two ways to create a WCF Client or calling a WCF Service as :
 
* WCF Proxy
* Channel factory
WCF manages the session by creating the instance of the service class. This created instance(s) handle the incoming service request. In WCF, the session is the way of managing the services instance(s) so that the server can use these instances in an optimized way. At the server side, the InstanceContext class is used to manage service class instance.

There are following instance management ways :
 
Per Call : A new instance will be created for each request from the same client or a new one, which means that every request will be a new request. Although this mode is most efficient in terms of memory, a session still needs to be maintained.  

Per Session : A new instance would be created for each new client session, and the scope of that object would correspond to the scope of that session. 
 
Single Instance : For each service object, only one instance will be created for all requests, regardless of whether they are coming from the same client or not. This is the least efficient instance mode in terms of memory usage.
Concurrency management is closely related to the Instance management in WCF but both are two different things. Instance management specifies how the service instances are created while Concurrency management specifies how many concurrent requests are handled by the service instances.

By using concurrency, you can make your service instance thread-safe. By default, a per-call service instance is thread-safe since each request is served by a new service instance. A per-session service instance is not thread-safe since multiple requests of a client are served by a single service instance.

Hence, it’s required concurrency management. A single service instance is not thread-safe since multiple requests of all clients are served by a single service instance. Hence, it’s required concurrency management.
WCF Data Services uses OData (Open Data Protocol) protocol for querying or manipulating the data. WCF Data Services is built on top of WCF REST Services. It is a RESTful service to support CRUD operations on the database using the HTTP protocol. It supports all database operations using URI. DATA protocol can expose data from the relational database, File systems, Web sites, services etc. It supports XML or JSON format for exposing the data.
After the initial deployment of the WCF service, you may need to change the service for a variety of reasons like as changing business needs or fixing others issues. Each change in your existing service introduces a new version of the service. Service versioning is helpful in backward compatibility with your existing clients.
Impersonation is a way to authorize a caller (client) identity to access the service domain’s resources. The service resources may be local files or database tables and should be on the same machine on which service is hosted. By default, impersonation is disabled and resources are accessed by using the WCF service's process identity.
WCF RIA is the framework for developing the n-tier application for RIA (Rich Internet App). It is used in Rich Internet Apps like Silverlight, AJAX etc. WCF RIA is used to solve the major problems like Tight Coupling.
You can generate proxy by using the following steps :
 
* Using Visual Studio
* Using SvcUtil
There are three modes of communication in WCF :
 
One-Way : In the One-Way operation mode, the 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.
 
Request-Reply : When as client makes a request to the WCF service and client will wait to get a response from service (till receiveTimeout). After getting the response it will start executing the rest of the statement.
 
Callback : It is the service to call the client. In which, service will act as client and client will act as service.
When a client made a request to a service, it will wait until it gets the response back.
 
* If the response is not received until the given time, it will show an error.
 
* If the client gets the response then next instructions will be executed.
A transaction is a logical unit of work consisting of multiple activities that must either succeed or fail together. For example, you are trying to make an online purchase for a dress; your amount is debited from the bank, but your ordered dress was not delivered to you. So what did you get from the preceding example? Bank operations hosted in a separate service and the online purchase service (Ordering the goods) hosted as another separate service. For the preceding example the online purchase service did not work well as expected due to the database query error, without knowing it the Bank operations were completed perfectly. For this we really need transactions to ensure that either of the operations should succeed or fail. Before we go to the WCF transactions, let us discuss what exactly are the basics behind the transactions.
 
The following are the types of the Transactions :
 
* Atomic
* Long Running

Phases of WCF Transaction
 
There are two phases in a WCF transaction :
 
Prepare Phase - In this phase, the transaction manager checks whether all the entities are ready to commit for the transaction or not.
Commit Phase - In this phase, the commitment of entities get started in reality.
A WCF service can be self-hosting using a console application or Windows Forms applications. Hosting a WCF service in any managed .Net application is called self-hosting. Now the following is the procedure for creating a WCF service and hosting it in a console application. Hosting Environment Requirements :
 
Availability : When do you want to be able to reach your service?
Reliability : What happens when your service somehow breaks? How does this affect other consumers?
Manageability : Do you need easy access to information about what is happening on the host where WCF services live?
Versioning : Do you need to support older versions of the service? Do you know who is consuming your services?
Deployment : What is your deployment model? Are you installing through the Microsoft Installer process and Visual Studio deployment packages, or is xcopy sufficient?
State : Are your services stateless? Do you need sessions?

The following are the various options available for hosting a WCF Service :
 
* Self-Hosting
* Windows Service
* Internet Information Services (IIS)
* Windows Activation Services (WAS)
We have our project (it may be Windows or a web application or something else) and we want to host one WCF service within this solution locally. This type of hosting is called Self-Hosting. To implement self-hosting we need to include System.Service.Model.ServiceHost namespace.
 
The following are the advantages of self-hosting :
 
Is easy to use : With only a few lines of code you have your service running.
 
Is flexible : You can easily control the lifetime of your services through the Open() and Close() methods of ServiceHost<T>.
 
Is easy to debug : Debugging WCF services that are hosted in a self-hosted environment provides a familiar way of debugging, without having to attach to separate applications that activate your service.
 
Is easy to deploy : In general, deploying simple Windows applications is as easy as xcopy. You don't need any complex deployment scenarios on server farms, and the like, to deploy a simple Windows application that serves as a WCF ServiceHost.
 
Supports all bindings and transports : Self-hosting doesn't limit you to out-of-the-box bindings and transports whatsoever. On Windows XP and Windows Server 2003, IIS limits you to HTTP only.

The following are the disadvantages of self-hosting :
 
Limited availability : The service is reachable only when the application is running.
 
Limited features : Self-hosted applications have limited support for high availability, easy manageability, robustness, recoverability, versioning, and deployment scenarios. At least, out-of-the-box WCF doesn't provide these, so in a self-hosted scenario you have to implement these features yourself; IIS, for example, comes with several of these features by default.
WCF uses the DataContractSerializer class as its default serializer. Other serialization purposes can be served by this serializer. Using the DataContractAttribute and DataMemberAttribute attributes, we can also explicitly create a data contract.
DATA Serializer
Example : 
DataContractSerializer dataContractSerializer = new  DataContractSerializer(typeof(MyTestClassType));
Throttling is derived from the keyword throughput, which means work that is performed at specific intervals of time. We can limit the number of instances or sessions created at the application level using the properties like maxConcurrentCalls, maxConcurrentInstances, and maxConcurrentSessions provided by WCF throttling. Performance is boosted by using it.
MEP (Message Exchange Pattern) is a way of communicating between clients and servers in WCF. MEP is one of the greatest features of WCF. The three types of MEPs supported by WCF are as follows:  
 
Request-Reply : Request-Reply is WCF's default communication pattern. 

One-way : Using this pattern means you don't expect to receive a response back from the service after it performs a certain operation.  

Duplex : Duplex is a two-way communication way. The duplex MEP is applicable when the client initiates a long-running process with the service and the service requires notification. 
In essence, MSMQ (Microsoft Messaging Queue) is a technology used for asynchronous communications. MSMQ is also capable of inter-process communication. MSMQ is very useful when two processes wish to communicate in a "Fire and Forget" manner.  MSMQ is basically developed by Microsoft and is deployed in the Windows operating system. It facilitates communication across heterogeneous networks and systems that might be a bit offline from time to time.
For troubleshooting unexpected problems in applications, exception handling is essential. Exception handling is a feature of object programming languages and it is an error that occurs during execution. In WCF, there are three ways to handle exceptions:  
 
returnUnknownExceptionsAsFaults : Debugging Mode  

FaultException : Best Option 

IErrorHandler : Only when Fault cannot handle the exception
WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the application level. Performance of the WCF service can be improved by creating proper instance.
 
The throttling of services is another key element for WCF performance tuning. WCF throttling provides the prosperities maxConcurrentCalls, maxConcurrentInstances, and maxConcurrentSessions, that can help us to limit the number of instances or sessions are created at the application level.

Attribute / Property Description
maxConcurrentCalls This specifies the maximum number of messages processed across the service host. The default value for this property is 16 (WCF 4.0 is improved to default is 16 * Processor Count).
maxConcurrentInstances This specifies the maximum number of instances of a context object that executes at one time with the service. The default is Int32.MaxValue.
maxConcurrentSessions This specifies the maximum number of sessions at one time within the service host object. The default value is 10 (WCF 4.0 increases that to 100 * Processor Count).
 
<configuration>
    <system.serviceModel>
        <services>
            <service .... .... .... </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="ServiceBehavior">
                    <serviceThrottling maxConcurrentCalls="16" maxConcurrentSessions="100" maxConcurrentInstances="10" />
                    <serviceMetadata httpGetEnabled="true" /> </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>
REST : 
Representational State Transfer (REST) is a protocol for exchanging data over a distributed environment. The main idea behind REST is that we should treat our distributed services as a resource and we should be able to use simple HTTP protocols to perform various operations on that resource.
 
JSON :
The JavaScript Object Notation (JSON) data format, or JSON for short, is derived from the literals of the JavaScript programming language. JSON helps us to present and exchange data in a self-descriptive, independent and light way. This data can then be easily consumed and transformed into JavaScript objects.
 
In most browser-based applications, WCF can be consumed using JavaScript, jQuery, AngularJS and so on. When a client makes a call to WCF, JSON or XML is used as the format of the communication. WCF has the option to send the response in JSON object. This can be configured with the WebGet orWebInvoke attribute and the WebHttpBinding. This allows you to expose a ServiceContract as a REST service that can be invoked using either JSON or plain XML.
 
* GET : Retrieves the information.
* PUT : Replaces the entire collection with another collection.
* POST : Creates a new entry in the collection.
* DELETE : Deletes the entire collection.
DataContractSerializer XMLSerializer
For WCF, DataContractSerializer is the default serializer XMLSerializer is not a default serializer
Compare to XMLSerializer it is faster XMLSerializer is slower
It is used for simple schemes It is used for complex schemes
Following are two ways to enable the metadata for WCF :
 
For Default Endpoint : <serviceMetadata> tag is used in web.config file without specifying the endpoint.
 
For Custom Endpoint : <serviceMetadata> tag is used in web.config file with specifying the defined endpoint.
A list of bindings that are used for metadata :
 
* mexHttpBinding
* mexNamedPipeBinding
* mexHttpsBinding
* mexTcpBinding
Exception handling is critical to all applications for troubleshooting the unexpected problems in applications. The Windows Communication Framework (WCF) provides several options for handling exceptions in WCF services. This article discusses these approaches and describes the advantages and disadvantages of each. The following options are provided to handle exceptions in WCF:
 
* Using returnUnknownExceptionsAsFaults : Debugging Mode
* Using FaultException : Best Option.
* Using IErrorHandler : Only when the exception can't be handled by Fault

Exception handling in WCF
Exception Handling
Exceptions inside a WCF Service
 
Before describing the details of exception handling in WCF, let's explore what happens if we do not handle an exception inside the service. Consider a service with the CreateUser method as shown in the following:  
public void CreateUser(User user)
{
    if(user.isValid())
    {
        //Create User
    }
    else
    {
        throw new ApplicationException(“User Inavalid.”);
    }
}
 
Example : 
public class DBManagerService: IDBManagerService

void Save(Employee emp)
{
    try
    {
        //Code to store an employee object to the database
    }
    catch (Exception ex
        {
            throw new Exception(“Error occurred
                while saving data…”);
        }
    }
}
Below is a detailed comparison table between both the entities from security, compatibility, reliability, and SOAP version perspectives.
Criteria BasicHttpBinding WsHttpBinding
Security support This supports the old ASMX style, i.e., WS-BasicProfile 1.1. This exposes web services using WS-* specifications.
Compatibility This is aimed for clients who do not have .NET 3.0 installed and it supports wider ranges of clients. Many of the clients like Windows 2000 still do not run .NET 3.0. So an older version of .NET can consume this service. As it is built using WS-* specifications, it does not support wider ranges of clients and it cannot be consumed by older .NET versions less than 3 version.
SOAP version SOAP 1.1 SOAP 1.2 and WS-Addressing specification.
Reliable messaging Not supported. In other words, if a client fires two or three calls you really do not know if they will return back in the same order. Supported as it supports WS-* specifications.
Default security options By default, there is no security provided for messages when the client calls happen. In other words, data is sent as plain text. As WsHttBinding supports WS-*, it has WS-Security enabled by default. So the data is not sent in plain text.
Security options • None
• Windows – default authentication
• Basic
• Certificate
• None
• Transport
• Message
• Transport with message credentials