WCF interview question and answer

1. What is the difference between WCF and ASMX Web Services?
Simple and basic difference is that ASMX or ASP.NET web service is designed to send and receive messages using SOAP over HTTP only. While WCF can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, NamedPipes etc).
2. What are WCF Service Endpoints? Explain.
For Windows Communication Foundation services to be consumed, it’s necessary that it must be exposed; Clients need information about service to communicate with it. This is where service endpoints play their role.
A WCF service endpoint has three basic elements i.e. Address, Binding and Contract.
  • Address: It defines "WHERE". Address is the URL that identifies the location of the service.
  • Binding: It defines "HOW". Binding defines how the service can be accessed.
  • Contract: It defines "WHAT". Contract identifies what is exposed by the service.
3. What are the possible ways of hosting a WCF service? Explain.
For a Windows Communication Foundation service to host, we need at least a managed process, a ServiceHost instance and an Endpoint configured. Possible approaches for hosting a service are:
  1. Hosting in a Managed Application/ Self Hosting
    1. Console Application
    2. Windows Application
    3. Windows Service
  2. Hosting on Web Server
    1. IIS 6.0 (ASP.NET Application supports only HTTP)
    2. Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP, NamedPipes, MSMQ.
4. How we can achieve Operation Overloading while exposing WCF Services?
By default, WSDL doesn’t support operation overloading. Overloading behavior can be achieved by using "Name" property of OperationContract attribute.
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
[ServiceContract]
interface IMyCalculator
{
   [OperationContract(Name = "SumInt")]
   int Sum(int arg1,int arg2);

   [OperationContract(Name = "SumDouble")]
   double Sum(double arg1,double arg2);
}
When the proxy will be generated for these operations, it will have 2 methods with different names i.e. SumInt and SumDouble.
5. What Message Exchange Patterns (MEPs) supported by WCF? Explain each of them briefly.
1. Request/Response 2. One Way 3. Duplex
Request/Response: It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body.
One Way: In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. OneWay MEP will work in such scenarios. If we want queued message delivery, OneWay is the only available option.
Duplex: The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed.
6. What is DataContractSerializer and How its different from XmlSerializer?
Serialization is the process of converting an object instance to a portable and transferable format. So, whenever we are talking about web services, serialization is very important.
Windows Communication Foundation has DataContractSerializer that is new in .NET 3.0 and uses opt-in approach as compared to XmlSerializer that uses opt-out. Opt-in means specify whatever we want to serialize while Opt-out means you don’t have to specify each and every property to serialize, specify only those you don’t want to serialize. DataContractSerializer is about 10% faster than XmlSerializer but it has almost no control over how the object will be serialized. If we wanted to have more control over how object should be serialized that XmlSerializer is a better choice.
7. How we can use MessageContract partially with DataContract for a service operation in WCF?
MessageContract must be used all or none. If we are using MessageContract into an operation signature, then we must use MessageContract as the only parameter type and as the return type of the operation.
8. Which standard binding could be used for a service that was designed to replace an existing ASMX web service?
The basicHttpBinding standard binding is designed to expose a service as if it is an ASMX/ASP.NET web service. This will enable us to support existing clients as applications are upgrade to WCF.
9. Please explain briefly different Instance Modes in WCF?
WCF will bind an incoming message request to a particular service instance, so the available modes are:
  • Per Call: instance created for each call, most efficient in term of memory but need to maintain session.
  • Per Session: Instance created for a complete session of a user. Session is maintained.
  • Single: Only one instance created for all clients/users and shared among all.Least efficient in terms of memory.
10. Please explain different modes of security in WCF? Or Explain the difference between Transport and Message Level Security.
In Windows Communication Foundation, we can configure to use security at different levels
a. Transport Level security means providing security at the transport layer itself. When dealing with security at Transport level, we are concerned about integrity, privacy and authentication of message as it travels along the physical wire. It depends on the binding being used that how WCF makes it secure because most of the bindings have built-in security.
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
            <netTcpBinding>
            <binding name="netTcpTransportBinding">
               <security mode="Transport">
                          <Transport clientCredentialType="Windows" />
               </security>
            </binding>
            </netTcpBinding>
b. Message Level Security For Tranport level security, we actually ensure the transport that is being used should be secured but in message level security, we actually secure the message. We encrypt the message before transporting it.
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
             <wsHttpBinding>
             <binding name="wsHttpMessageBinding">
               <security mode="Message">
                           <Message clientCredentialType="UserName" />
               </security>
              </binding>
             </wsHttpBinding>
It totally depends upon the requirements but we can use a mixed security mode also as follows:
http://www.codeproject.com/images/minus.gifCollapse | Copy Code
             <basicHttpBinding>
             <binding name="basicHttp">
               <security mode="TransportWithMessageCredential">
                          <Transport />
                               <Message clientCredentialType="UserName" />
               </security>
             </binding>
             </basicHttpBinding>

WCF Vs ASMX Web Services
First of all, it needs to understand that WCF Service provides all the capabilities of .NET web servies and further extends it.
·         Simple and basic difference is that ASMX web service is designed to send and receive messages using SOAP over HTTP only. While WCF service can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, NamedPipes etc).
·         ASMX is simple but limited in many ways as compared to WCF.
·         ASMX web services can be hosted only in IIS while WCF service has all the following hosting options:
1.    IIS
2.    WAS (Windows Process Activation Services)
3.    Console Application
4.    Windows NT Services
5.    WCF provided Host
·         ASMX web services support is limited to HTTP while WCF supports HTTP, TCP, MSMQ, NamedPipes.
·         ASMX Security is limited. Normally authentication and authorization is done using IIS and ASP.NET security configuration and transport layer security. For message layer security, WSE can be used.
·         WCF provides a consistent security programming model for any protocol and it supports many of the same capabilities as IIS and WS-* security protocols, additionally, it provides support for claim-based authorization that provides finer-grained control over resources than role-based security.WCF security is consistent regardless of the host that is used to implement WCF service.
·         Another major difference is that ASMX web services uses XmlSerializer for serialization while WCF uses DataContractSerializer which is far better in performance than XmlSerializer.
·         Key Issues with XmlSerializer in serializing .NET types to xml are:
1.          Only public fields or properties of the .NET types can be translated to Xml.
2.          Only the classes that implement IEnumerable can be translated.
3.          Classes that implement IDictionary, such as Hashtable cannot be serialized.

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.

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.
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
·         HTTP
·         TCP
·         Peer network
·         IPC (Inter-Process Communication over named pipes)
·         MSMQ

The sample address for above transport schema may look like

http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService

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.
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";


   }


}

Data contract: 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.
Fault contracts: Define which errors are raised by the service, and how the service handles and opagates errors to its clients.
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

1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)

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.

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.

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.

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.

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.

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.

Federated WS binding : Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

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.

MSMQ binding:  Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

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.

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:

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

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
·         NetTcpBinding
·         WSHttpBinding
·         WSFederationHttpBinding
·         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:-

NET remoting
MSMQ
Web services
COM+

What are the main components of WCF?

The main components of WCF are

1. Service class
2. Hosting environment
3. End point

What are various ways of hosting WCF Services?

There are three major ways of hosting a WCF services
• 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. .
• Host in application domain or process provided by IIS Server.
• 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 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.
Be interview ready, test your skills in Virtual Interview

Difference between WCF and Web services?

Web Services
1.It Can be accessed only over HTTP
2.It works in stateless environment
WCF

WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services:
IIS
WAS
Self-hosting
Managed Windows Service

Which namespace is used to access WCF service?

NOTE: This is objective type question, Please click question title for correct answer.

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

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)

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?


NOTE: This is objective type question, Please click question title for correct answer.

Difference between Web Services and WCF


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 can not 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.

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.

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

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:

a. FaultException : to send untyped fault back to consumer
b. 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.

Which protocol is used for platform-independent communication?

SOAP (Simple Object Access Protocol), which is directly supported from WCF (Windows Communication Foundation).

What is ABC of WCF?

ABC is the three building blocks of WCF and they are known as
A - Address (Where): Address tells us where to find the services, like url
B - Bindings (How) : Bindings tells us how to find the services or using which protocols finds the services (SOAP, HTTP, TCT etc.)
C - Contacts (What): Contracts are an agreement between the consumer and the service providers that explains what parameters the service expects and what return values it gives.
Hope this will be very helpful to understand three building blocks of WCF, a very frequently asked interview questions.

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.
Ex.

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single)]
Public class ServiceClass : IServiceInterface{
//Implementation Code
}

Which are the 3 types of transactions manager WCF supports?

WCF supports following 3 types of transactions managers:

a. LightWeight
b. OLE Transactions
c. WS-Atomic Transactions

Which bindings in WCF support the message streaming?

1. basicHttpBinding
2. netTcpBinding
3. netNamedPipeBinding

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 advantages of hosting WCF service in WAS?

WAS (Windows Activation Service) is a component of IIS 7.0. Following are few advantages :

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?

1. Service host factory is the mechanism by which we can create the instances of service host dynamically as the request comes in.
2. This is useful when we need to implement the event handlers for opening and closing the service.
3. WCF provides ServiceFactory class for this purpose.

What are the different platforms where we can host WCF service ?

WCF Services can be hosted on following platforms
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

1. Provides process activation and recycling ability thereby increasing reliability
2. It is a simplified way of deployment and development of hosted services.
3. 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; }


NOTE: This is objective type question, Please click question title for correct answer.

What happens if we apply DataMember attributes to Static Fields?

NOTE: This is objective type question, Please click question title for correct answer.

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.

Ex:

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; }



NOTE: This is objective type question, Please click question title for correct answer.

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 ?


NOTE: This is objective type question, Please click question title for correct answer.

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 ?

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. 

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 ?

NOTE: This is objective type question, Please click question title for correct answer.

Which transferMode is the default transferMode in WCF ?

NOTE: This is objective type question, Please click question title for correct answer.

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>




Thanks and Regards
Akiii

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


    }


}


Thanks and Regards
Akiii

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.

Explain briefly the three way of communication between source and destination in WCF ?

Simplex - Also known as one way communication. Source will send a message to the target, but target will not respond to the message.

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.

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 ?


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 ?

NOTE: This is objective type question, Please click question title for correct answer.

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.



Thanks and Regards

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;


}



Thanks and Regards
Akiii

In WCF, does BasicHttpBinding supports HTTPS ?

NOTE: This is objective type question, Please click question title for correct answer.

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 ?



NOTE: This is objective type question, Please click question title for correct answer.

In WCF, which is/are used for representing content in WebHttpBinding ?



NOTE: This is objective type question, Please click question title for correct answer.

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" 


-pe means provider encryption of configuration section.
-app means your application's virtual path.
-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

Can we use both WCF Services and WCF Data Services in a single service ?

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.



Thanks and Regards
Akiii

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.
For example :-
[ServiceContract]


interface IMyContract


{


   [OperationContract(IsOneWay = true)]


   void MyMethod( );


}

In WCF, what is the default value of IsOneWay property ?



NOTE: This is objective type question, Please click question title for correct answer.

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 !




Thanks and Regards
Akiii

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.


Thansks and Regards
Akiii
http://www.feedburner.com/fb/images/pub/feed-icon16x16.pnghttp://feeds2.feedburner.com/%7Efc/DotnetfundaInterviewQuestions?bg=EB7F30&fg=000000&anim=0

WCF Interview Questions and Answers (175) - Page 6

Now you don't need go anywhere to get the best interview questions on Microsoft technology. We are trying to gather all real interview questions asked from MNCs and put them here. You can also assist us in doing so by submitting .net interview questions. These questions are generally different from certification questions however it may help you in that too.

Get 500+ .NET Interview preparation videos at discounted price

 
175 records found.


Be interview ready, test your skills in
Virtual Interview.

Can we use both WCF Services and WCF Data Services in a single service ?



NOTE: This is objective type question, Please click question title for correct answer.

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.



Thanks and Regards
Akiii

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.



Thanks and Regards
Akiii

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.




Thanks and Regards
Akiii

How is WCF One Way Contract is implemented ?



WCF one way contract is implemented via "IsOneWay = true/false" attribute.
For example :-
[ServiceContract]


interface IMyContract


{


   [OperationContract(IsOneWay = true)]


   void MyMethod( );


}




Thanks and Regards
Akiii

In WCF, what is the default value of IsOneWay property ?



NOTE: This is objective type question, Please click question title for correct answer.

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 !




Thanks and Regards
Akiii

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 !



Thanks and Regards
Akiii

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.


Thansks and Regards
Akiii

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.


Thanks and Regards
Akiii

What are the 3 message patterns available in WCF ?



Three message patterns available in WCF are :-

(1) One Way Contract
(2) Duplex Contract
(3) Request-Reply Contract



Thanks and Regards
Akiii

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.



Thanks and Regards
Akiii

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.



Thanks and Regards
Akiii

In WCF, can data contract classes inherit from one another?



[DataContract]
public class A
{
[DataMember]
public MyCustomType AValue1{ get; set; }

[DataMember]
public MyCustomType AValue2 { get; set; }
}

[DataContract]
public class B: A
{
[DataMember]
public double BValue1{ get; set; }

[DataMember]
public double BValue2 { get; set; }
}

the metadata fails to load when testing the services.
What needs to be done to load both super and sub class.
We must add KnownType Attribute.

[DataContract]
[KnownType(typeof(B))]
public class A
{
[DataMember]
public string Value { get; set; }
}

[DataContract]
public class B : A
{
[DataMember]
public string OtherValue { get; set; }
}

In what are the different ways a WCF Metadata can be accessed ?



WCF Metadata can be accessed in two ways :-

(1) WSDL document can be generated which represents the endpoints and protocols

(2) Or the ServiceHost can expose a metadata exchange endpoint to access metadata at runtime

Difference between reliable messaging and reliable sessions in WCF ?



Reliable messaging is concerned with ensuring that messages are delivered exactly once.

Reliable session provides a context for sending and receiving a series of reliable messages. reliable sessions have a dependency on reliable messaging.

You have to use reliable messaging to provide an end-to-end reliable session between a client application and a service.

So finally, both are different but related concepts

What is Windows Server AppFabric?



It is a set of extensions to the Windows OS aimed at making it easier for developers to build faster, scalable, and more-easily managed services.

It provides a distributed in-memory caching service and replication technology that helps developers improve the speed and availability of .NET Web applications and WCF services.

If you are hosting WCF services by using IIS or WAS in a production environment, you might want to consider implementing Windows Server AppFabric.

You can use use AppFabric in place of Memcached because AppFabric provides more feature than Memcached

What is the difference between RIA and WCF services?



Some points are as under

1) WCF is concerned with technical aspects of communication between servers across tiers and message data management whereas RIA Web Services delegates this
functionality to WCF.

2) WCF is a generic service that could be used in Windows Forms for example whereas RIA Web Services is focused on Silverlight and ASP.NET clients

3) WCF does not generate source code to address class business logic such as validation that may need to be shared across tiers like RIA Web Services does.

4) The RIA Services can either exist on top of WCF or replace the WCF layer with RIA Services using alternatice data source e.g. an ORM layer(EF/NHibernate etc.)

5) RIA Services allow serializing LINQ queries between the client and server.

How many different types of authorization supported by WCF ?



Role-based : Map users to roles and check whether a role can perform the requested operation.
• Identity-based : Authorize users based on their identity.
• Claims-based : Grant or deny access to the operation or resources based on the client’s claims.
• Resource-based : Protect resources using access control lists (ACLs)

What is WCF.



WCF is Windows Communication Foundation that uses message based communication. Messages will be sent between endpoints generated by Client or Service.
It ia an advanced version of the below technologies as these require
specialized knowledge and service to implement.

1. ASP .NET Web services(.asmx)
2. Remoting
3. MSMQ (Microsoft Message Queue)
4. Enterprise Services

WCF simplifies developer's task by unifying the strength of each .NET technology for network distributed services and applications
Be interview ready, test your skills in Virtual Interview.

What are the benefits of WCF?



The benefits include the following

1. Transactional support
2. Asynchronous one-way messaging
3. Interoperability
4. Independent versioning
5. Platform Consolidation

What are the principles WCF implement?



WCF services effectively communicates with the clients through these principles.

1. Explicit boundaries
WCF services function using the defined interfaces to identify the communications between server and client that flow outside the boundaries of the service

2. Independent services
WCF services are deployed and managed independently and each service interaction is independent of other interactions. They are independent of deployment, installation and version issues.

3. Schema and contract based communication
WCF services communicate with clients by providing only the schema of the message and not its implementation classes. The service implementation can be changed if required without impacting the clients

4. Policy based compatibility
Compatibility between WCF services and clients at runtime is determined using published policies. Policies help separate the description of the service fro its implementation details.

What are the four layers in WCF architecture?



SOA based WCF architecture has four layers.

1. Contracts
It describe the WCF message system. This is achieved by three contracts with policies and bindings.
1. Service Contract - Describes the method signature of the service using C# or VB
2. Data Contract - Enables .NET types to be in XML
3. Message Contract - Defines the structure os the SOAP message exchanged between the service and client
4. Policies and Bindings - Defines the security level required by the clients

2. Service Runtime
This includes the behaviors that occur when service is running.

3. Messaging
This layer contains the channels that process messages and operate on messages and message headers

4. Hosting
Describes the ways in which WCF service can be hosted.

List the behaviors included in Service Runtime of the WCF layer?



The following behaviors are included in the WCF Service Runtime layer..

1. Throttling behavior
Throttling behavior provides the options to limit how many instances or sessions are created at the application level.

2. Error behavior
By implementing IErrorHandler interface WCF allows an implementer to control the fault message returned to the caller and also it performs custom error processing such as logging

3. Metadata behavior
Through the metadata behavior we can publish metadata of the service by configuring an endpoint to expose the IMetadataExchange contract as an implementation of a WS-MetadataExchange (MEX) protocol. By default it is disabled.

4. Instance behavior
This behavior specifies how many instance of the service has to be created while running WCF.

5. Transaction behavior
This is used to enables the rollback of transacted operations if a failure occurs.

6. Dispatch behavior
This behavior controls how a message is processed by the WCF Infrastructure.

7. Concurrency behavior
Concurrency behavior measures how many tasks can be performed simultaneously

9. Parameter Filtering
This demonstrates how to validate the parameters passed to a method before it is invoked.

What is a duplex WCF service?



A duplex service contract refers to exchange of messages in which both server or client endpoints can send messages to the other independently.

A duplex service can send message back to the client endpoint providing event like behavior.

How can you specify a duplex service?



A pair of interfaces is required to create a duplex contract.

1. Service Contract interface - Describes the operations that a client can invoke.
2. Callback Contract interface - Describes the operations that service can call on client.

The service contract should specify a callback contract in the System.ServiceModel.ServiceContractAttribute.CallbackContract property.

Give an example of a duplex service



[ServiceContract(SessionMode=SessionMode.Required,


                 CallbackContract=typeof(IRespondBackCallback))]


public interface ICalculatorDuplex


{


    [OperationContract(IsOneWay = true)]


    void FunctionClientCanCall();


}






public interface IRespondBackCallback


{
                                                      

    [OperationContract(IsOneWay = true)]


    void FunctionServiceCanCall(double result);


}

Explain the functionality of the Message layer in WCF.



The Messaging layer contains channels that process messages and operate on messages and message headers. The messaging layer has eight channels which defines the possible formats and data exchange patterns.
The eight channels are divided into two categories.

1. Transport Channels
These channels helps reads and write messages from the network.
1. WS Security Channel
2. WS Reliable MessagingChannel
3. Encoders:Binary/ MTOM/ Text/ XML

2. Protocol Channels
These channels implement message processing protocols.
1. HTTP Channel
2. TCP Channel
3. TransitionFlow Channel
4. NamedPipe Channel
5. MSMQ Channel

What is a Throttling behavior in WCF?



Throttling behavior of the WCF service holds the configuration for three limitations that control the amount of resources that your service hosting can allocate to deal with the client request. Thus it enables to
1. Manages resource Usage
2. Balances performance load

How can we specify the throttling behavior for a WCF service?



Throttling behavior is specified by the following three parameters.

1. MaxConcurrentCalls - Total no of concurrent calls service will accept
2. MaxConcurrentSessions - Total no of sessionful channels service will accept
3. MaxConcurrentInstances - Total no of service instances will be created for servicing requests.

It can be specifed either through code or configuration file. It requires the "System.SystemModel.Behavior" namespace to be included.

What is a metadata export?



Metadata Export is the process of describing the service endpoints and projecting them into a parallel, standardized representation that clients can use to understand how to use the service.

How to publish service metadata?



WCF services publish its metadata by exposing one or more metadata endpoints. Publishing service metadata makes service metadata available using standardized protocols, such as MEX and HTTP/GET requests.
Metadata endpoints are the same as other service endpoints and have an address, a binding, and a contract.
You can add metadata endpoints to a service host in configuration or in code.

In WCF, suppose you have a derived class inherited from a datacontract class, will the derived class automatically have a datacontract as well ?



The Data contract is not inherited, so any derived class, would have to be explicitly declared as having a Data contract attribute as well.


Thanks and Regards
Akiii

In WCF, if your service wants an authentication before it is used then what is the best way to handle an authentication mechanism with WCF?



The best way to handle this would be to design a Message contract that
accepts these authentication tokens in the header of the message.



Thanks and Regards
Akiii

What is meant by WS Addressing Standard in WCF ?



The address for an endpoint is a unique URL that identifies the
location of the service. The address should follow the Web Service Addressing (WS-Addressing) standard, and they are :-

(1) Scheme - This is typically “http” followed by a colon.

(2) Machine - Identifies the machine name, which can be a public URL such as “www.google.com" or a local identifier such as “localhost”.

(3) Port - The optional port number, preceded by a colon.

(4) Path - The path used to locate the service files. Typically, this is just the service name, but the path can consist of more than one level when a service resides in a directory structure.



Thanks and Regards
Akiii

Give some examples of varying address in WCF ?



An address can vary, depending on whether it is hosted by Microsoft Internet Information Services (IIS) on a public network or hosted locally on an internal network computer. It can also vary, depending on the protocol the binding uses. For example, all the following could be valid addresses:

(1) http://www.google.com/MyService/
(2) http://localhost:9800/Service1/MyService/
(3) net.tcp://localhost:9801/MyService/


Thanks and Regards
Akiii

What namespace is used by ASMX and WCF respectively for serialization ?



For serialization, WCF uses the System.Runtime.Serialization namespace for serialization.

Web service(i.e), ASMX uses System.Xml.serialization namespace.



Thanks and Regards
Akiii

ServiceContract, DataContract and MessageContract maps to which web services standard ?



(1) ServiceContracts maps to WSDL
(2) DataContracts maps to XSD
(3) MessageContracts maps to SOAP


Thanks and Regards
Akiii

What is a WCF Test Client ?



WCF Test Client is a GUI tool which enables us to enter parameters, invoke services with these parameters and view the responses returned by services.


After you create a new WCF service project and press F5 to start the debugger, the WCF Service Host begins to host the service in your project. Then, WCF Test Client opens and displays a list of service endpoints defined in the configuration file. You can test the parameters and invoke the service, and repeat this process to continuously test and validate your service.

Thanks and Regards
Akiii

In WCF, is returning a void return type returns anything ?



[ServiceContract]


    public interface IService1


    {


        [OperationContract]


        void Employee(string value);


    }


In the above case, the response message is still being sent back to the client. The difference is it sends an empty SOAP body.
So, returning void doesn't mean it will not return anything to the Client !


Thanks and Regards
Akiii

Why it is dangerous to send a oneway message in WCF ?



It is dangerous to send a oneway message since there is no assurance that the operation is processed or not.


Thanks and Regards
Akiii

State 3 Duplex contract problems in WCF ?



(1) Threading problems can occur if either of the Callback channels are not empty.

(2) If the client and service has a long running work then this pattern doesn't scale very well. It can block the client or the service until the process is completes !

(3) It requires a connection back to the client. And there may be a chance to not connect back due to firewall and Network Address Translation problems.


Note :- It is always better to use Request / Response MEP rather than using Duplex method.

Thanks and Regards
Akiii

Which command is used to convert WSDL to a proxy



svcutil.exe command will convert the WSDL to a proxy class for our client

Open visual studio command prompt window
click on visual studio command prompt,set the current folder to the location where you want the generated proxy and configuration files to be created.

Run SvcUtil.exe to generate the output files.

Which type of securities are available in WCF?



NOTE: This is objective type question, Please click question title for correct answer.

Which are the available types of transport schemas in WCF?



NOTE: This is objective type question, Please click question title for correct answer.

Which is/are the possible value/s of ConcurrencyMode enumeration in WCF?



NOTE: This is objective type question, Please click question title for correct answer.

What is/are the type/s of Messaging pattern/s in WCF?



NOTE: This is objective type question, Please click question title for correct answer.

You are developing data access service that access by several types of clients (non-.net or .net) to access a back-end database server running Microsoft SQL Server. Which approach should you use?



NOTE: This is objective type question, Please click question title for correct answer.

You are developing a web service that will be accessed by Clients might be running JavaScript or the .NET Framework. you need to Create the data access layer with the least amount of development effort.



NOTE: This is objective type question, Please click question title for correct answer.

Which is/are available Instance Mode/s in WCF?



NOTE: This is objective type question, Please click question title for correct answer.

Which message encoding format/s is/are available in WCF?



NOTE: This is objective type question, Please click question title for correct answer.

What is MTOM?



MTOM stands for Message Transmission Optimization Mechanism and is an Interoperable standard that reduces the overhead for transfer large binary data in WCF. Its a mechanism for transmitting large binary attachments with SOAP messages as raw bytes.

What is the purpose of ExtensionDataObject in WCF? or How to make DataContract forward compatible?



A .NET serialization system supports backward-compatibility on custom data types naturally. However, sometimes we also need forward-compatibility for data types used in a WCF service.ExtensionDataObject property is used to achieve the Forward compatible in WCF.

Suppose that you have a service that exchanges some custom data types between clients. If one side updates the custom data type (adds some fields or properties) or uses a newer version, it is important to make sure that the other side can still work correctly with the updated data type instances without using the updated version of data.

Let see how can we achieve this in WCF.

1.First we need to make our Custom Data type to implement the IExtensibleDataObject interface.

[DataContract]

public class Employee: IExtensibleDataObject

{

[DataMember]

public string Name{ get; set; } [DataMember]

public string Address{ get; set; }

public ExtensionDataObject ExtensionData

{

get;

set;

}

}


2. Next we need to make sure that we haven't enabled the IgnoreExtensionDataObject property on ServiceBehaviorAttribute applied on your WCF service .This property is disabled by default.

What is the difference between a standard void operation and a one-way operation?



Suppose you have the following ServiceContract implemented:

[ServiceContract]
public interface IMyTask
{
[OperationContract(IsOneWay=false)]
void MyTask();
[OperationContract(IsOneWay = true)]
void MyTaskOneWay();
}

By invoking the two operations from the client side and capturing the HTTP message, we can get different response messages.

The normal void operation will return HTTP 200 status code and the complete SOAP Response in the body and the one-way operation will only return a HTTP 202 Accepted status header. This indicates that the one-way operation call gets finished as long as the
server side received the request, while the normal void operation will wait for the server side to execute and return the response data.

Which of the following represent the .net attribute from System.Servicemodel namespace that you will use while define a new Service Contract ?



NOTE: This is objective type question, Please click question title for correct answer.

Which of the following properties you should enable, so can your service will expose its metadata through HTTP-GET



NOTE: This is objective type question, Please click question title for correct answer.

Which standard binding you would be use if your service will hosted on the same computer as the client ?



NOTE: This is objective type question, Please click question title for correct answer.

What is RoundTripping ?



A client with an older version (v1.0) of a data contract can communicate with a service with a newer version(v2.0) of the same data contract, or a client with a newer version of a data contract can communicate with an older version of the same data contract. this new-to-old-to-new interaction is called versioning roundtrip.

Round-tripping guarantees that no data is lost. WCF does have some built-in support it (IExtensibleDataObject interface).

In WCF, which is the default place for maintain session state ?



NOTE: This is objective type question, Please click question title for correct answer.

You want to use performance monitor to track the no of rejected messages in your developed WCF application.



NOTE: This is objective type question, Please click question title for correct answer.

Which two in-built binding elements are required to use while implementing custom binding in you wcf service ?



NOTE: This is objective type question, Please click question title for correct answer.

You have a class name OrderService that include two methods to reject and process order. you need to expose the orderservice class as a wcf service and ensure it support one or more inheritance. what must you do ?



NOTE: This is objective type question, Please click question title for correct answer.

What is Binding in WCF?



Binding describes how client will communicate with services. There are different protocols available to communicate to client. Binding has several characteristics :

Transport - Define base protocol to be used like HTTP, Named Pipes, TCP and MSMQ.

Encoding(Optional) - Three types of encoding available - Text, Binary or Message Transmission Optimization Mechanism(MTOM). MTOM is interoperable message format that allows the effective transmission of attachments or large message.

Protocol(Option) - Defines information to be used in Binding such as security transaction or reliable messaging capability.

What are types of Binding available in WCF?



BasicHttpBinding – It uses SOAP over HTTP.
WsHttpBinding – It uses SOAP over HTTP, it also supports reliable message transfer.
NetTcpbinding – It uses SOAP over TCP, but server and client should be in .Net.
NetNamedPipesBinding – It uses SOAP over Named Pipes.

Explain contract and all types of contract in WCF?



Contract is platform-neutral and standard way of describing what services does. In WCF, all services are exposed as contract. There are four types of contracts :

Service Contract – It describes operation provided by service. A service should contain at least one service contract. Service Contract is defined by using [ServiceContract] attribute , it is similar to [WebMethod] of Web Services.

Data Contract – It describes data exchange between service and client. Data Contract is defined using [DataContract] and [DataMember] attribute.

Message Contract – It transfers information from service to client. WCF uses SOAP message format for communication.

Fault Contract – It handles and convey error message to the client when service get error.

Difference between WCF and Web Service?



1) Web Services support hosting in IIS whereas WCF support hosting in IIS, WAS and Self-hosting.

2) Web Services can be invoked by Http whereas WCF service can be invoked by Http, Tcp, Named Pipes, MSMQ.

3) WCF Services are more reliable and secure as compare to Web Services.

4) WCF Services are more flexible as we make a new version of service we just have to expose a new endpoint.

5) In Web Service, [WebMethod] attribute specifies the method exposed to client. In WCF [OperationContract] attribute represents the method.

What is Service Host in WCF?



Service Host object is in process of hosting the WCF service and registering endpoints. It loads the service configuration endpoints, apply the settings. System.ServiceModel.ServiceHost namespace holds this object. This object is created while self hosting the WCF service.

There is scenerio, when one client has to access service SOAP using Http and other client have to access Binary using TCP, how can you acheive?



This can be acheived by adding extra endpoint in configuration file.

<endpoint address="http://locahost:8090/Service" contact="IMathService" binding="wsHttpBinding"/>
<endpoint address="net.tcp://locahost:8080/Service" contact="IMathService" binding="netTcpBinding"/>

What are advantages of WCF?



Advantages of WCF are :
WCF is interoperable with other services but .Net Remoting requires client and service in .Net.
WCF service provides better reliability and security as compare to Web Services.
In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small change in the configuration will make your requirement.

What is WCF?



WCF is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is latest service oriented technology. Interoperability is fundamental characteristic of WCF. WCF is combined feature of Web Service, Remoting, MSMQ, and COM+. WCF provides a common platform for all .NET communication.

You are developing WCF service which read message from a system transactional dead-letter queue. which URI should you specify in the endpoint configuration settings of the service ?



NOTE: This is objective type question, Please click question title for correct answer.

In WCF, which binding is used for cross-machine communication or WCF-to-WCF communication?



NOTE: This is objective type question, Please click question title for correct answer.

What is the Extension of WCF service?



NOTE: This is objective type question, Please click question title for correct answer.

How many isolation levels are present and what are they?



1. READ UNCOMMITTED: - An uncommitted transaction can be read. This transaction can be rolled back later.
2. READ COMMITTED :- Will not read data of a transaction that has not been committed yet
3. REPEATABLE READ: - Locks placed on all data and another transaction cannot read.
4. SERIALIZABLE:- Does not allow other transactions to insert or update data until the transaction is complete.

How can we achieve overloading concept in WCF?



Yes, by using [OperationContract(Name="OverloadedName")] But, still outer world will get them with unique and different name. Overloading is a technique to write manageable/maintainable code. But in case of WCF service, uniqueness is required for generating WSDL, and that can be done either by using unique method

==================================================================
Choosing the right WCF binding
enter image description here
  1. BasicHttpBinding: Basic web service communication. Exposes WCF services as legacy ASMX web services. Used for interoperability. No security by default.
  2. WSHttpBinding: Web services with WS-* support. Supports transactions and reliable messaging.
  3. WSDualHttpBinding: Web services with duplex contract and transaction support.
  4. WSFederationHttpBinding: Web services with federated security. Supports transactions.
  5. MsmqIntegrationBinding: Communication directly with MSMQ applications. Supports transactions.
  6. NetMsmqBinding: Communication between WCF applications by using queuing. Supports transactions.
  7. NetNamedPipeBinding: Communication between WCF applications on same computer. Supports duplex contracts and transactions.
  8. NetPeerTcpBinding: Communication between computers across peer-to-peer services. Supports duplex contracts.
  9. NetTcpBinding: Communication between WCF applications across computers. Supports duplex contracts and transactions.
 name or unique OperationContract's name attribute value. Interfaces plays an important role and provides much flexibility for this. We can write many implementations of an interface, and it gives more flexibility plus concise. So why to think on overloading for WCF service methods?

Different types of WCF bindings

WCF has a couple of built in bindings which are designed to fulfill some specific need. You can also define your own custom binding in WCF to fulfill your need. All built in bindings are defined in the System.ServiceModel Namespace. Here is the list of 10 built in bindings in WCF which we commonly used:

1.     Basic binding

This binding is provided by the BasicHttpBinding class. It is designed to expose a WCF service as an ASMX web service, so that old clients (which are still using ASMX web service) can consume new service. By default, it uses Http protocol for transport and encodes the message in UTF - 8 text for-mat. You can also use Https with this binding.

2.     Web binding

This binding is provided by the WebHttpBinding class. It is designed to expose WCF services as Http requests by using HTTP-GET, HTTP-POST. It is used with REST based services which may give output as an XML or JSON format. This is very much used with social networks for implementing a syndication feed.

3.     Web Service (WS) binding

This binding is provided by the WSHttpBinding class. It is like as Basic binding and uses Http or Https protocols for transport. But this is designed to offer various WS - * specifications such as WS – Reliable Messaging, WS - Transactions, WS - Security and so on which are not supported by Basic binding.
   wsHttpBinding= basicHttpBinding + WS-* specification

4.     WS Dual binding

This binding is provided by the WsDualHttpBinding class. It is like as wsHttpBinding except it sup-ports bi-directional communication means both clients and services can send and receive messages.

5.     TCP binding

This binding is provided by the NetTcpBinding class. It uses TCP protocol for communication be-tween two machines with in intranet (means same network). It encodes the message in binary format. This is faster and more reliable binding as compared to the Http protocol bindings. It is only used when communication is WCF - to – WCF means both client and service should have WCF.

6.     IPC binding

This binding is provided by the NetNamedPipeBinding class. It uses named pipe for Communication between two services on the same machine. This is the most secure and fastest binding among all the bindings.

7.     MSMQ binding

This binding is provided by the NetMsmqBinding class. It uses MSMQ for transport and offers sup-port to disconnected message queued. It provides solutions for disconnected scenarios in which service processes the message at a different time than the client send the messages.

8.     Federated WS binding

This binding is provided by the WSFederationHttpBinding class. It is a specialized form of WS binding and provides support to federated security.

9.     Peer Network binding

This binding is provided by the NetPeerTcpBinding class. It uses TCP protocol but uses peer net-working as transport. In this networking each machine (node) acts as a client and a server to the other nodes. This is used in the file sharing systems like torrent.

10.MSMQ Integration binding

This binding is provided by the MsmqIntegrationBinding class. This binding offers support to communicate with existing systems that communicate via MSMQ.

Choosing an Appropriate WCF binding

. Depending upon your requirements, you can choose a binding for your service as shown below in the diagram:
http://www.dotnet-tricks.com/Content/images/wcf/choosebindings.png

WCF bindings comparison

Binding
Configuration
Protocol/Transport
Security
Default Session
Transaction
Duplex
BasicHttpBinding
Basic Profile 1.1
Http, Https
None
No
-
-
WSHttpBinding
WS
Http, Https, TCP
Message
Optional
Yes
-
WSDualHttpBinding
WS
Http, Https
Message
Yes
Yes
Yes
NetTcpBinding
.Net
Named Pipe
Transport
Optional
Yes
Yes
NetNamedPipeBinding
.Net
Named Pipe
Transport
Yes
Yes
Yes
NetMsmqBinding
.Net
MSMQ
Transport
Yes
Yes
No
WSFederationHttpBinding
WS-federation
Http, Https
Message
Yes
Yes
No
NetPeerTcpBinding
Peer
TCP
Transport
-
-
Yes
MsmqIntegrationBinding
MSMQ
MSMQ
Transport
Yes
Yes


No comments:

Post a Comment