Sunday, 24 June 2012

WCF


Web Service in ASP.NET

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.
Consumers of a Web Service do not need to know anything about the platform, object model, or programming language used to implement the service; they only need to understand how to send and receive SOAP messages (HTTP and XML).

WCF Service

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. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.
In what scenarios must WCF be used
  • A secure service to process business transactions.
  • A service that supplies current data to others, such as a traffic report or other monitoring service.
  • A chat service that allows two people to communicate or exchange data in real time.
  • A dashboard application that polls one or more services for data and presents it in a logical presentation.
  • Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
  • A Silverlight application to poll a service for the latest data feeds.

Features of WCF

  • 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

Difference between Web Service in ASP.NET & WCF Service

WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot more than what is traditionally considered as "web services".
WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. Common scenarios for hosting WCF services are IIS, WAS, Self-hosting, Managed Windows Service.
The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer.

Key issues with XmlSerializer to serialize .NET types to XML

  • Only Public fields or Properties of .NET types can be translated into XML
  • Only the classes which implement IEnumerable interface
  • Classes that implement the IDictionary interface, such as Hash table cannot be serialized

Important difference between DataContractSerializer and XmlSerializer

  • A practical benefit of the design of the DataContractSerializer is better performance over XmlSerializer.
  • XML Serialization does not indicate which fields or properties of the type are serialized into XML whereas DataCotractSerializer
  • Explicitly shows the which fields or properties are serialized into XML
  • The DataContractSerializer can translate the HashTable into XML

Using the Code

The development of web service with ASP.NET relies on defining data and relies on the XmlSerializer to transform data to or from a service.

Key issues with XmlSerializer to serialize .NET types to XML

  • Only Public fields or Properties of .NET types can be translated into XML
  • Only the classes which implement IEnumerable interface
  • Classes that implement the IDictionary interface, such as Hash table cannot be serialized
The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW types into XML.
 [DataContract] 
public class Item 
{ 
    [DataMember] 
    public string ItemID; 
    [DataMember] 
    public decimal ItemQuantity; 
    [DataMember] 
    public decimal ItemPrice;
}
The DataContractAttribute can be applied to the class or a strcture. DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private.
Important difference between DataContractSerializer and XMLSerializer.
  • A practical benefit of the design of the DataContractSerializer is better performance over XML serialization.
  • XML Serialization does not indicate which fields or properties of the type are serialized into XML whereas DataContractSerializer explicitly shows which fields or properties are serialized into XML.
  • The DataContractSerializer can translate the HashTable into XML.

Developing Service

To develop a service using ASP.NET, we must add the WebService attribute to the class and WebMethodAttribute to any of the class methods.
Example
 [WebService] 
public class Service : System.Web.Services.WebService 
{ 
      [WebMethod] 
      public string Test(string strMsg) 
      { 
          return strMsg; 
      } 
}
To develop a service in WCF, we will write the following code:
 [ServiceContract] 
public interface ITest 
{ 
       [OperationContract] 
       string ShowMessage(string strMsg); 
} 
public class Service : ITest 
{ 
       public string ShowMessage(string strMsg) 
       { 
          return strMsg; 
       } 
}
The ServiceContractAttribute specifies that an interface defines a WCF service contract,
OperationContract attribute indicates which of the methods of the interface defines the operations of the service contract.
A class that implements the service contract is referred to as a service type in WCF.

Hosting the Service

ASP.NET web services are compiled into a class library assembly and a service file with an extension .asmx will have the code for the service. The service file is copied into the root of the ASP.NET application and Assembly will be copied to the bin directory. The application is accessible using URL of the service file.
WCF Service can be hosted within IIS or WindowsActivationService.
  • Compile the service type into a class library
  • Copy the service file with an extension .SVC into a virtual directory and assembly into bin sub directory of the virtual directory.
  • Copy the web.config file into the virtual directory.

Client Development

Clients for the ASP.NET Web services are generated using the command-line tool WSDL.EXE.
WCF uses the ServiceMetadata tool (svcutil.exe) to generate the client for the service.

Message Representation

The Header of the SOAP Message can be customized in ASP.NET Web service.
WCF provides attributes MessageContractAttribute, MessageHeaderAttribute and MessageBodyMemberAttribute to describe the structure of the SOAP Message.

Service Description

Issuing a HTTP GET Request with query WSDL causes ASP.NET to generate WSDL to describe the service. It returns the WSDL as a response to the request.
The generated WSDL can be customized by deriving the class of ServiceDescriptionFormatExtension.
Issuing a Request with the query WSDL for the .svc file generates the WSDL. The WSDL that generated by WCF can be customized by using ServiceMetadataBehavior class.

Exception Handling

In ASP.NET Web services, unhandled exceptions are returned to the client as SOAP faults.
In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to clients for the purpose of debugging.
-----------------------------------------------------------------------------------------------------------------------------------

What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.
What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.The client of a service is merely the party consuming the service.
What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.
WCF supports following transport schemas
1.       HTTP
2.       TCP
3.       Peer network
4.       IPC (Inter-Process Communication over named pipes)
5.       MSMQ
The sample address for above transport schema may look like
1.       http://localhost:81
2.       http://localhost:81/MyService
3.       net.tcp://localhost:82/MyService
4.       net.pipe://localhost/MyPipeService
5.       net.msmq://localhost/private/MyMsMqService
6.       net.msmq://localhost/MyMsMqService
What are contracts in WCF?
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.
WCF defines four types of contracts.
1.       Service contracts
Describe which operations the client can perform on the service.
There are two types of Service Contracts.
·         ServiceContract - This attribute is used to define the Interface.
·         OperationContract - This attribute is used to define the method inside Interface.

[ServiceContract]
interface IMyContract
{
   [OperationContract]
   string MyMethod( );
}
class MyService : IMyContract
{
      public string MyMethod( )
      {
              return "Hello World";
      }
}
2.       Data contracts
Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.
There are two types of Data Contracts.
·         DataContract - attribute used to define the class
·         DataMember - attribute used to define the properties.
[DataContract]
class Contact
{
   [DataMember]
   public string FirstName;

   [DataMember]
   public string LastName;
}
If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.
3.       Fault contracts
Define which errors are raised by the service, and how the service handles and propagates errors to its clients.


4.       Message contracts
Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.
Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.
They are:-
IIS
Self Hosting
WAS (Windows Activation Service)
For more details see http://msdn.microsoft.com/en-us/library/bb332338.aspx

What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. 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.
WCF supports nine types of bindings.
1.       Basic binding
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.
2.       TCP binding
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.
3.       Peer network binding
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.
4.       IPC binding
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.


5.       Web Service (WS) binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.
6.       Federated WS binding
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.
7.       Duplex WS binding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.
8.       MSMQ binding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.
9.       MSMQ integration binding
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.
For WCF binding comparison, see http://www.pluralsight.com/community/blogs/aaron/archive/2007/03/22/46560.aspx
What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint. The Endpoint is the fusion of Address, Contract and Binding.
How to define a service as REST based service in WCF?
WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.
The below code shows how to expose a Restful service
[ServiceContract]
interface IStock
{
    [OperationContract]
   [WebGet]
   int GetStock(string StockId);
}
By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.


What is the address formats of the WCF transport schemas?
Address format of WCF transport schema always follow
[transport]://[machine or domain][:optional port] format.
for example:
1.       HTTP Address Format
http://localhost:8888
the way to read the above url is
"Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting"
When the port number is not specified, the default port is 80.
2.       TCP Address Format
net.tcp://localhost:8888/MyService
When a port number is not specified, the default port is 808:
net.tcp://localhost/MyService
NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.
3.       IPC Address Format
net.pipe://localhost/MyPipe
We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine.
4.       MSMQ Address Format
net.msmq://localhost/private/MyService
net.msmq://localhost/MyService
What is Proxy and how to generate proxy for WCF Services?
The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.
The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.
SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs
When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:  SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs

What are different elements of WCF Srevices Client configuration file?
WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like
<system.serviceModel>
   <client>
      <endpoint name = "MyEndpoint"   address  = http://localhost:8000/MyService/
         binding  = "wsHttpBinding"  contract = "IMyContract"  />
   </client>
</system.serviceModel>
What is Transport and Message Reliability?
Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.
Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.
How to configure Reliability while communicating with WCF Services?
Reliability can be configured in the client config file by adding reliableSession under binding tag.
<system.serviceModel>
   <services>
      <service name = "MyService">
         <endpoint
            address  = "net.tcp://localhost:8888/MyService"   binding  = "netTcpBinding"
              bindingConfiguration = "ReliableCommunication"   contract = "IMyContract"  />
      </service>
   </services>
   <bindings>
      <netTcpBinding>
         <binding name = "ReliableCommunication">
            <reliableSession enabled = "true"/>
         </binding>
     </netTcpBinding>
   </bindings>
</system.serviceModel>
Reliability is supported by following bindings only
1. NetTcpBinding
2. WSHttpBinding
3. WSFederationHttpBinding
4. WSDualHttpBinding.

How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag.
<client>
   <endpoint
      ...
      binding = "wsHttpBinding" 
     bindingConfiguration = "LongTimeout"
      ...   />
</client>
<bindings>
   <wsHttpBinding>
      <binding name = "LongTimeout" sendTimeout = "00:04:00"/>
   </wsHttpBinding>
</bindings>
If no timeout has been specified, the default is considered as 1 minute.

How to deal with operation overloading while exposing the WCF services?
By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.
[ServiceContract]
interface ICalculator
{
   [OperationContract(Name = "AddInt")]
   int Add(int arg1,int arg2);
   [OperationContract(Name = "AddDouble")]
   double Add(double arg1,double arg2);
}
Notice that both method name in the above interface is same (Add), however the Name property of the OperationContract is different. In this case client proxy will have two methods with different name AddInt and AddDouble.
What was the code name for WCF?
The code name of WCF was Indigo .
WCF is a unification of .NET framework communication technologies which unites the following technologies:-
1.       NET remoting
2.       MSMQ
3.       Web services
4.       COM+

What are the main components of WCF?
The main components of WCF are
1.        Service class
2.       Hosting environment
3.       End point
For more details read http://www.dotnetfunda.com/articles/article221.aspx#WhatarethemaincomponentsofWCF
What are various ways of hosting WCF Services?
There are three major ways of hosting a WCF services
1.       Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
2.       Host in application domain or process provided by IIS Server.
3.       Host in Application domain and process provided by WAS (Windows Activation Service) Server.
More details http://www.dotnetfunda.com/articles/article221.aspx#whatarethevariouswaysofhostingaWCFservice

What is the difference WCF and Web services?
Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.
Second web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.
We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc
Major Difference is That Web Services Use XmlSerializer But WCF Uses
DataContractSerializer which is better in Performance as Compared to XmlSerializer.
Key issues with XmlSerializer to serialize .NET types to XML
* Only Public fields or Properties of .NET types can be translated into XML.
* Only the classes which implement IEnumerable interface.
* Classes that implement the IDictionary interface, such as Hash table cannot be serialized.
The DataContractAttribute can be applied to the class or a strcture. DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private.
For more details, read http://msdn.microsoft.com/en-us/library/aa738737.aspx
What is three major points in WCF?
We Should remember ABC.
Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.
Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols
Contract --- Specifies the interface between client and the server. It's a simple interface with some attribute.

What are the various ways of hosting a WCF service?
1.       Self hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of ServiceHost class and the service closes when you call the Close of the ServiceHost class.
2.       Host in application domain or process provided by IIS Server.
3.       Host in Application domain and process provided by WAS (Windows Activation Service) Server.
Which namespace is used to access WCF service?
   System.ServiceModel
What is a SOA Service?
SOA is Service Oriented Architecture. SOA service is the encapsulation of a high level business concept. A SOA service is composed of three parts.
1.       A service class implementing the service to be provided.
2.       An environment to host the service.
3.       One or more endpoints to which clients will connect.
What is the use of ServiceBehavior attribute in WCF?
ServiceBehaviour attribute is used to specify the InstanceContextMode for the WCF Service class (This can be used to maintained a state of the service or a client too)
There are three instance Context Mode in the WFC
1.       PerSession : This is used to create a new instance for a service and the same instance is used for all method for a particular client. (eg: State can be maintained per session by declaring a variable)
2.       PerCall : This is used to create a new instance for every call from the client whether same client or different. (eg: No state can be maintained as every time a new instance of the service is created)
3.       Single : This is used to create only one instance of the service and the same instance is used for all the client request. (eg: Global state can be maintained but this will be applicable for all clients)
Which namespace is required in a class to use DataContract or DataMember attribute for a class or properties?
using System.Runtime.Serialization;
Important difference between DataContractSerializer and XMLSerializer.
* A practical benefit of the design of the DataContractSerializer is better performance over Xmlserializer.
* XML Serialization does not indicate the which fields or properties of the type are serialized into XML   where as DataCotratSerializer Explicitly shows the which fields or properties are serialized into XML.
* The DataContractSerializer can translate the HashTable into XML.
in WCF, Which contract is used to document the errors occurred in the service to client?
Fault Contract is used to document the errors occurred in the service to client.
Which is the default Message Exchange Pattern (MEP) ?
Request/Response
What is the Messaging Pattern? Which Messaging Pattern WCF supports?
Messaging Pattern : Messaging patterns describes how client and server should exchange the message. There is a protocol between client and server for sending and receiving the message. These are also called Message Exchange Pattern.
WCF supports following 3 types of Message Exchange Patterns
1.       request - reply (default message exchange pattern)
2.       OneWay (Simplex / datagram)
3.       Duplex(CallBack)
What is .svc file in WCF?
.svc file is a text file. This file is similar to our .asmx file in web services.
This file contains the details required for WCF service to run it successfully.
This file contains following details :
1.       Language (C# / VB)
2.       Name of the service
3.       Where the service code resides
Example of .svc file
<%@ ServiceHost Language="C#/VB" Debug="true/false" CodeBehind="Service code files path" Service="ServiceName"
We can also write our service code inside but this is not the best practice.



What is XML Infoset?
The XML Information Set defines a data model for XML. It is an abstract set of concepts such as attributes and entities that can be used to describe a valid XML document. According to the specification, "An XML document's information set consists of a number of information items; the information set for any well-formed XML document will contain at least a document information item and several others."
What is DataContractSerializer in WCF?
DataContractSerializer is new WCF serializer.
This is serialization engine in WCF. DataContractSerializer translate the .NET framework objects into XML and vice-versa. By default WCF uses DataContractSeriazer.
What is Message Contract in WCF?
Message Contract :Message Contract is the way to control the SOAP messages, sent and received by the client and server.
Message Contract can be used to add and to get the custom headers in SOAP message
Because of Message Contract we can customize the parameters sent using SOAP message between the server and client.
What is Fault Contracts in WCF?
Fault Contracts is the way to handle exceptions in WCF. The problem with exceptions is that those are technology specific and therefore cannot be passed to other end because of interoperability issue. (Means either from Client to Server or vice-versa). There must be another way representing the exception to support the interoperability. And here the SOAP Faults comes into the picture.
Soap faults are not specific to any particular technology and they are based on industry standards.
To support SOAP Faults WCF provides FaultException class. This class has two forms:
1.        FaultException : to send untyped fault back to consumer
2.       FaultException<T>: to send typed fault data to the client
WCF service also provides FaultContract attribute so that developer can specify which fault can be sent by the operation (method). This attribute can be applied to operations only.
What is the difference between XMLSerializer and the DataContractSerializer?
a.       DataContractSerializer is the default serializer fot the WCF
b.      DataContractSerializer is very fast.
c.       DataContractSerializer is basically for very small, simple subset of the XML infoset.
d.      XMLSerializer is used for complex schemas.

What is the purpose of base address in WCF service? How it is specified?
When multiple endpoints are associated with WCF service, base address (one primary address) is assigned to the service, and relative addresses are assigned to each endpoint. Base address is specified in <host> element for each service.
E.g.
<configuration>
    <system.servicemodel>
      <Services>
<service name=”MyService>
  <host>
  <baseAddresses>
 <add baseAddress =”http://localhost:6070/MyService”>
</baseAddresses>
</host>
</service>
<services>
</system.servicemodel>
</configuration>
Which protocol is used for platform-independent communication?
SOAP (Simple Object Access Protocol), which is directly supported from WCF (Windows Communication Foundation).
How the concurrency mode is specified in WCF service?
The concurrency mode is specified using the ServiceBehavior attribute on the class that implements the service.
[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single)]
Public class ServiceClass : IServiceInterface
{
//Implementation Code
}
There are 3 possible values of ConcurrencyMode enumeration
1.       Single
2.       Reentrant
3.       Multiple
Which are the 3 types of transactions manager WCF supports?
WCF supports following 3 types of transactions managers:
1.       LightWeight
2.       b. OLE Transactions
3.       c. WS-Atomic Transactions
Which bindings in WCF support the message streaming?
Following bindings supports the streaming in WCF:
1.       basicHttpBinding
2.       netTcpBinding
3.       netNamedPipeBinding
Which is the default mode for Instancing in WCF?
PerCall
How to set the instancing mode in WCF service?
In WCF, instancing mode is set at service level. For ex.
//Setting PerSession instance mode
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class MyService : IMyService
{
//Implementation goes there
}

What is Address Header in WCF?
Address Header contains the information which is sent with every request, it can be used by either end point service or any intermediate device for determining any routing logic or processing logic.
WCF provides AddressHeader class for this purpose.
Example :
AddressHeader addressHeader= AddressHeader.CreateAddressHeader("Name of the header", "Information included in header ");
Once the AddressHeader instance is created, it can be associated with end point instance as follows :
EndpointAddress endpoint = new EndpointAddress(new Uri("http://myserver/myservice"), addressHeader);
In WCF which bindings supports the reliable session?
In WCF, following bindings supports the reliable session
1.       wsHttpBinding
2.       wsDualHttpBinding
3.       wsFederationHttpBinding
4.       netTcpBinding


What are the benefit of hosting WCF service in Windows Activation Service is a component of IIS 7.0?
1.       We are not only limited to HTTP protocol. We can also use supported protocols like TCP, named pipes and MSMQ
2.       No need to completely install IIS. We can only install WAS component and keep away the WebServer.
What is service host factory in WCF?
        Service host factory is the mechanism by which we can create the instances of service host dynamically as the request comes in.
        This is useful when we need to implement the event handlers for opening and closing the service.
        WCF provides ServiceFactory class for this purpose.
What are the different platforms where we can host WCF service ?
1.       WAS(Windows Activation Service)
2.       Self Hosting
3.       IIS
What are the different WCF binding available?
        BasicHttpBinding
        WSHttpBinding
        WSDualHttpBinding
        WSFederationHttpBinding
        NetTcpBinding
        NetNamedPipeBinding
        NetMsmqBinding
        NetPeerTcpBinding
        MsmqIntegrationBinding
Advantages of Hosting WCF in IIS
        Provides process activation and recycling ability thereby increasing reliability
        It is a simplified way of deployment and development of hosted services.
        Hosting WCF services in IIS can take advantage of scalability and density features of ASP.NET



Can we overload methods in WCF Service or Web Service?
Yes for a WCF Service use the Name property of OperationContractAttribute class
example:
[ServiceContract]
interface ddd
{
    [OperationContract(Name = "one")]
    int calc(int a,int b);
    [OperationContract(Name = "two")]
    double calc(double a,double b);
}
1.       For a Web Service use the MessageName property of WebMethodAttribute class
2.       Please comment the following line in the .cs file of the Web Service
//[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[WebMethod]
public string HelloWorld(string a) {
return "Hello"+" "+a;
}
[WebMethod(MessageName="second")]
public string HelloWorld()
{
return "Hello second";
}
What does a Windows Communication Foundation, or WCF, service application use to present exception information to clients by default?
However, the service cannot return a .NET exception to the client. The WCF service and the client communicate by passing SOAP messages. If an exception occurs, the WCF runtime serializes the exception into XML and passes that to the client.
What is the use of Is Required Property in Data Contracts?
Data Contracts, is used to define Required or NonRequired data members. It can be done with a property named IsRequired on DataMember attribute.
[DataContract]
public class test
{
      [DataMember(IsRequired=true)]
      public string NameIsMust;
      [DataMember(IsRequired=false)]
      public string Phone;          
}
Which of the following members of the class are serialized? [DataContract] public class Person { [DataMember] internal string Name; [DataMember] private int Age; private string Address; }
Name and Age
What happens if we apply DataMember attributes to Static Fields?
Ignored
What is data contract equivalence?
Two data contracts are said to be equivalent, if they satisfy the following conditions.
- Both the datacontracts must have same namespace
- Both the datacontracts must have same name
- The data member on data contract must have an equivalent data member on the other.
- The members in the datacontract must appear in the same order in both datacontracts.
The following two data contracts are equal.
[DataContract]
public class Person
{
    [DataMember]
    public string Name;
    [DataMember]
    public string Email_ID;
}

[DataContract(Name = "Person")]
public class Employee
{
    [DataMember(Name = "Name")]
    private string EmpName;
    private string address;

    [DataMember(Name = "Email_ID")]
    private string EmpEmailId;
}



How do we customize Data Contract Names for Generics types?
We can customize the generic datacontract names by allowing parameters. Find the Example below
[DataContract(Name = "Shape_{1}_brush_and_{0}_shape")]
public class Shape< Square,RedBrush>
{
// Code not shown.
}
Here, the Data Contract Name is "Shape_RedBrush_brush_and_Square_shape”
{0} – First Parameter in the generic type.
{1}- Second Parameter in the generic type.
The following Two data contracts are equal. [DataContract(Name = "Maruthi")] public class Car { [DataMember] public int Cost; [DataMember] public int Bhp; } [DataContract(Name = "Maruthi")] public class Car2 { [DataMember(Order = 2)] public int Bhp; [DataMember(Order = 1)] public int Cost; }
False bcoz:-
The data contracts are said to be equal if they have
- Same Namespaces
- Same Names
- Same Data Member Names
- Same Order of the Member Names
Snippet-1 :
As order not specified, The default Order is alphabetical (Bhp,Cost).
Snippet-2 :
Here the Order is based on the order attribute..which is (Cost,Bhp).
As the order of the data member names differs, the above statement is false.
What is the address formats of the WCF transport schemas?
Address format of WCF transport schema always follow
[transport]://[machine or domain][:optional port] format.
For example: HTTP Address Format :
http://localhost:8888
The way to read the above url is "Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting" When the port number is not specified, the default port is 80.
TCP Address Format net.tcp://localhost:8888/MyService When a port number is not specified, the default port is 808: net.tcp://localhost/MyService NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.
IPC Address Format net.pipe://localhost/MyPipe We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine. MSMQ Address Format net.msmq://localhost/private/MyService net.msmq://localhost/MyService

Can we have a message contract as input parameter and data contract as returned parameter in a single operation contract?
No, Input and return parameter should be same as Message contract if we want to use message contract in a operation contract.

What is Asynchronous Messaging ?
Asynchronous messaging describes a way of communications that takes place between two applications or systems, where the system places a message in a message queue and does not need to wait for a reply to continue processing.

What is the key architectural principles behind Service Oriented Architecture (SOA) ?
Its the ability to re-use existing software assets whenever possible and to expose the functionality of these assets as a set of services.

Which namespace is used by WCF to define services and their operations ?
System.ServiceModel

What does the namespace "System.Runtime.Serialization" exactly do in WCF ?
WCF uses the class to convert objects into a stream of data suitable for transmitting over the network (this process is known as Serialization). It also uses them to convert a stream of data received from the network back into objects (De-Serialization).
If you define additional methods in the WCF service that are not in the service contract, will it be visible to client applications ?
No
Which file specifies the name and location of the class that implements the WCF service ?
Service.svc file
Why in WCF, the "httpGetEnabled" attribute is essential ?
The attribute "httpGetEnabled" is essential because we want other applications to be able to locate the metadata of this service that we are hosting.
<serviceMetadata httpGetEnabled="true" />
Without the metadata, client applications can't generate the proxy and thus won't be able to use the service.
In WCF, "wsHttpBinding" uses plain unencrypted texts when transmitting messages and is backward compatible with traditional ASP.NET web services (ASMX Web Services) ?
False
What is the former name of Windows Communication Foundation (or WCF) ?
Indigo
What is "Automatic activation" in WCF ?
Automatic Activation means that the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in case of self hosting the service should always be running.
WCF processes messages in buffered mode. True or False ?
True
Which transferMode is the default transferMode in WCF ?
Buffered

Can we propagate CLR Exception across service boundaries in WCF ?
No, we cannot propagate CLR Exceptions across service boundaries.
If you want to propagate exception details to the clients then it can be done through "FaultContract " attribute. This way a custom exception is being passed to the client.
In WCF, what happens if there is an unhandled exception ?
The service model returns a generic SOAP fault to the client which does not include any exception specific details by default. However, an exception details in SOAP faults can be included using IncludeExceptionDetailsInFaults attribute. If IncludeExceptionDetailsInFaults is enabled, exception details including stack trace are included in the generated SOAP fault. IncludeExceptionDetailsInFaults should be enabled for debugging purposes only. Sending stack trace details is risky.
IncludeExceptionDetailsInFaults can be enabled in the web.config file :-
<behaviors>
            <serviceBehaviors>
                <behavior name="ServiceGatewayBehavior">
                    <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                    <serviceMetadata httpGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
Are SOAP faults inter-operable ?
Yes, SOAP faults are inter-operable as they are expressed to clients in XML form.
.Net exception classes are not good to be used in SOAP faults. Instead we should define our own DataContract class and then use it in a FaultContract.

public interface ICalculator
{      
    [OperationContract]
    [FaultContract(typeof(MathFault))]
    int Divide(int n1, int n2);
}
[DataContract]
public class MathFault
{ 
    [DataMember] 
    private string operation { get; set; }
    [DataMember]   
    private string problemType { get; set; }   
}
public int Divide(int n1, int n2)
{
    try
    {
        return n1 / n2;
    }
    catch (DivideByZeroException)
    {
        MathFault objMath = new MathFault();
        objMath.operation = "division";
        objMath.problemType = "divide by zero";
        throw new FaultException<MathFault>(objMath);
    }
}
What is a proxy class for WCF Service ?
It is a class by which a service client can interact with the service. The client will make an object of the proxy class and by the help of it will call different methods exposed by the service.
State which one is the odd one out in case of SOAP(Simple Object Access Protocol) Message format.
MenuBar
Explain briefly the three way of communication between source and destination in WCF ?
1.       Simplex - Also known as one way communication. Source will send a message to the target, but target will not respond to the message.
2.       Request/Replay - It is two way communications, source send message to the target, target will resend the response message to the source. But in this scenario at a time only one can send a message (that is), either source or destination.
3.       Duplex -Also known as two way communication, both source and target can send and receive message simultaneously.
Can you show me an example in how to write a Message Contract in WCF ?
[MessageContract]
public class EmployeeDetails
{
    [MessageHeader]
    public int ID;
    [MessageBodyMember]
    public string First_Name; 
    [MessageBodyMember]
    public string Last_Name;
}
Message contract can be applied to type using MessageContract attribute as shown above. We can add custom header and custom body by using MessageHeader and MessageBodyMember attribute respectively.
When EmployeeDetails type in the service operation is used as parameter then WCF will add an extra header call 'ID' to the SOAP envelope. It also add First_Name, Last_Name as an extra member to the SOAP Body.
Why do we need MessageContract when DataContract can do the job ?
When we need a higher level of control over the message, such as sending custom SOAP header, then we can use MessageContract instead of DataContract . But in general cases, most of the messaging needs can be fulfilled by DataContracts.
State 3 primary aspects of WCF ?
1.        Inter-operability with applications built on differnet technologies.
2.       Unification of the original Dotnet Framework communication Technologies.
3.       Support for Service Oriented Architecture (SOA).
If you have a Dotnet Web Service and a Java Client Application, then which Communication technology will you use other than WCF ?
Web Service (that is), ASMX will be the most likely way to achieve cross-vender inter-operability.
If both the application are in Dotnet then which technology is used for better performance apart from WCF ?
Remoting



State the three components that a WCF service must have ?
The three components that a WCF must implement are :-
1.       Service Class = This can be implementated in any dotnet language. It implements one or more methods.
2.       Host Process = A process in which the service will run.
3.       End-Points = One or more end-points are provided that allow the clients to access the service.
In WCF, can we have multiple endpoints with the same address ?
No

Suppose you have created a WCF service. You have an interface stating your methods that must be exposed to the clients. But you have forgotten to specify "[OperationContract]" attribute in any of your method. What will happen ?
If you do not specify "[OperationContract] " in any of the methods in your interface then you will get the following error :-
IService1' has zero operations; a contract must have at least one operation
Here, Iservice is the name of my Interface. you can have your own name.
So, it is mandatory to label "[OperationContract] " attribute to at least one method while declaring your interface methods or ServiceContract.
In WCF, can a struct be used as a DataContract ?
Yes, a struct can be used as a DataContract. For example :-
[DataContract]
struct EmployeeInfo
{
[DataMember]
public int id;
[DataMember]
public string name;
[DataMember]
public DateTime joining_date;
}
In WCF, does BasicHttpBinding supports HTTPS ?
Yes, BasicHttpBinding supports Transport Security (https). However, by default it is not configured. you yourself have to configure it. For example :-
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
In WCF, is SOAP envelope created while using WebHttpBinding ?
No, SOAP envelope is not created in WebHttpBinding . The information is trasmitted through HTTP or HTTPS.
In WCF, which is the right binding for RESTful communication and other situations where SOAP isn't required ?
WebHttpBinding is the right choice for RESTful communication and other situations where
SOAP isn't required. Here, information/message is transferred directly by HTTP or HTTPS.

In WCF, which is/are used for representing content in WebHttpBinding ?
·  JavaScript Object Notation (JSON)
·  Opaque Binary Encoding
·  Text-Based XML
In WCf, which binding is used if you are using WCF-to-WCF communication between processes on the same machine ?
NetNamedPipesBinding binding is used.
How can you define an Endpoint problematically in WCF ?
ServiceHost s = new ServiceHost(typeof(EmployeeReservations));
s.AddEndpoint(typeof(EmployeeReservations), new BasicHttpBinding(),
"http://www.google.com/employee/emp.svc");
EmployeeReservations is the name of the contract.
http://www.google.com/employee/emp.svc is the address of the web service.
Defining endpoints programmatically in WCF is a good practice or not ?
Even though defining endpoints programmatically is possible, the most common approach
today is to use a configuration file associated with the service. Endpoint definitions embedded in code are difficult to change when a service is deployed, yet some endpoint characteristics, such as the address, are very likely to differ in different deployments. Defining endpoints in config files makes them easier to change, since changes don?t require modifying and recompiling the source code for the service class.
Which element is the prime element in the config file in which all WCF-based application configuration is contained ?
Configuration information for all services implemented by a WCF-based application is
contained within the system.serviceModel element. This element contains a services element that can itself contain one or more service elements.

How can I encrypt sensitive data in the WCF configuration file?
To encrypt sensitive data in WCF configuration file, use aspnet_regiis.exe tool.
Example: If you want to encrypt Connection String section of WCF config file, use -pe that means provider encryption .
aspnet_regiis -pe "connectionStrings" -app "/MachineDPAPI"
-prov "DataProtectionConfigurationProvider"
1.       -pe means provider encryption of configuration section.
2.       -app means your application's virtual path.
3.       -prov means provider name
For more info: http://msdn.microsoft.com/en-us/library/k6h9cz8h(VS.80).aspx
In WCF, which bindings/bindings doesn't support reliable session ?
BasicHttpBinding doesn't support reliable session. All other bindings mentioned above supports reliable session.
Can we use both WCF Services and WCF Data Services in a single service ?
No - WCF Services and WCF Data Services need to be exposed as two different endpoints.
Briefly explain WCF Data Services ?
WCF Data Services are used when you want to expose your data model and associated logic through a RESTful interface. It includes a full implementation of the Open Data (OData) Protocol for .NET to make this process very easy.
WCF Data Services was originally released as ‘ADO.NET Data Services’ with the release of .NET Framework 3.5.

Explain in brief, WCF One Way Contract ?
WCF One Way Contract are methods/operations which are invoked on the service by the client or the server in which either of them do not expect a reply back. For example :-
If a client invokes a method on the service then it will not expect a reply back from the service.
What is the most primary reason to use WCF One Way Contract ?
One way contract is used to ensure that the WCF client does not go in a blocking mode . If your WCF operation contracts are returning nothing and they are doing some heavy process then it is better to use one way contract.
How is WCF One Way Contract is implemented ?
WCF one way contract is implemented via "IsOneWay = true/false" attribute.
[ServiceContract]
interface IMyContract
{
   [OperationContract(IsOneWay = true)]
   void MyMethod( );
}

In WCF, what is the default value of IsOneWay property ?
By default IsOneWay property is false. You must explicitly specify the value of the attribute property to be true if you want a one-way contract for the method.

In WCF, while using one way contract, suppose a client invokes a method and the server while executing it, encounters an error. Will the error message propagate to the client or will the client ever know that there was an error on the server side ?
No, one-way operations cannot return values and any exception thrown on the service side will not make its way to the client. The client will never know whether there was an error or not !
Is the below code correct :- [ServiceContract] interface IMyContract { [OperationContract(IsOneWay = true)] int MyMethod( ); }
No, there should be no reply associated with a one-way operation. In the above an integer value is returned even though the IsOneWay property is true !

What is Sessionful Services in WCF One Way Contract ?
[ServiceContract(SessionMode = SessionMode.Required)]
interface IService
{
   [OperationContract(IsOneWay = true)]
   void Method1();
}
If the client issues a one-way call and then closes the proxy while the method executes, the client will still be blocked until the operation completes.
Please note that the above is a bad design because clients are never meant to be blocked when using one way contract.
What is duplex contract in WCF?
In Duplex contract, clients and servers can communicate with each other independently.
Duplex contracts consists of two one-way contracts so that parallel communication is achieved.
What are the 3 message patterns available in WCF ?
1.       One Way Contract
2.       Duplex Contract
3.       Request-Reply Contract
What is the primary reason for which Duplex Contract is used in WCF ?
Duplex Contracts are needed when the service queries the client for some additional information or the service wants to explicitly raise events on the client.
Can you show a sample of Duplex Contract in WCF ?
[ServiceContract(Namespace = "http://www.Microsoft.com",
                     SessionMode = SessionMode.Required,
                     CallbackContract = typeof(IDuplexCallBack) )]  

    public interface IService1
    {
        [OperationContract(IsOneWay = true)]
        void getData();       
    }
 public interface IDuplexCallBack
   {
        [OperationContract(IsOneWay = true)]
        void filterData(DataSet Output);
    }
In the above code, getData() is a method which will be called by the client on the Service. This getdata() is implemented in the server side.
filterData() is a method which will be called by the server on the Client. This method is implemented in the client side.
CallbackContract is the name of the contract which will be called by the server on the client to raise an event or to get some information from the client.


http://msdn.microsoft.com/en-us/library/gg132851