Hurry! 20% Off Ends SoonRegister Now

WCF Interview Questions

WCF(Windows Communication Foundation) is a technology or framework designed by Microsoft to develop SOAs(Service-Oriented Applications). It is used by every individual who uses the Windows Operating System. This blog discusses the most important and frequently asked WCF interview questions that an interviewer expects you to answer.

WCF is the unified programming model of Microsoft that we use to build service-oriented applications. It allows the .NET developers to develop reliable, secure, and transacted solutions that we can integrate throughout different platforms and collaborate with the existing ones. It allows us to communicate with Services, MS Messaging queues, and remoting in different ways.

WCF is a part of the .NET framework lifecycle, and the .NET framework is part of the lifecycle of the Microsoft Windows Operating System.  So, as long as the Windows Operating System continues to function, the .NET framework and WCF will continue to function. Since Microsoft Windows is the most popular and widely used operating system, the demand for WCF Developers is massive. This blog includes all the WCF interview questions that help crack your WCF job interviews.

Top 10 WCF Interview Questions and Answers 

1. Define WCF?

2. Describe WCF Architecture and its basics?

3. Why must we utilize WCF?

4. Differentiate WCF and Web Services?

5. What are the Advantages and Features of WCF?

6. Explain SOA? Is web services SOA?

7. Explain the Service Contract?

8. Explain Contracts?

9. Explain the Data Contract?

10. Explain the Fault Contract?

WCF Interview Questions for Beginners

1. Define WCF?

Ans: WCF is the platform to develop distributed enterprises and deploy the services amid different endpoints in Windows. Initially, WCF was known as “Indigo”, and we offer interoperability and develop service-oriented applications. Windows Communication Foundation(WCF) is the programming model for creating service-oriented applications. We use WCF for deploying and creating that can be accessible to different clients. 

It offers the environment where we can create the service accessible to windows clients and Linux clients or all the others. It offers more features in comparison to the web series.

If you want to enrich your career and become a professional in .Net, then enroll in ".Net Online Training" - This course will help you to achieve excellence in this domain.

2. Describe WCF Architecture and its basics?

Ans: Windows Communication Foundation is the framework to build the service-oriented applications through which we transmit the asynchronous data/message from the óne service endpoint to another service endpoint. WCF is the runtime and group of APIs to create the systems that transmit messages between clients and services. 

We use similar APIs and Infrastructure to create applications that interact with another application on a similar computer system or on the system that dwells in other companies and is retrieved over the internet. Following are some of the basics of WCF:

  • Unification
    1. Web Services
    2. Microsoft Message Queueing
    3. COM+ Services
    4. .NET Remoting
  • Service Orientation
  • Interoperability

Architecture

WCF contains four main layers that offer developers the latest service-oriented programming model. Following are the layers of WCF architecture:

WCF Architecture

3. Why must we utilize WCF?

Ans: The Windows Communication Foundation is the framework for developing service-oriented applications. The majority of the WCF functionalities are covered in the Single assembly known as System.ServiceModel.dll, placed in System.ServiceModel namespace.

Utilise WCF

Need of WCF

  1. The web service for exchanging messages in the XML format through HTTP protocol for compatibility.
  2. The remoting service for exchanging the messages in the binary format through TCP protocol for performance.
    • The secure service for processing business transactions.
    • The service that provisions the present data to others, like traffic reports or monitoring services.
    • The chat service enables two people for communicating or exchanging real-time data.
    • The dashboard applications vote multiple services for the data and display it in the logical presentation.
    • The sliver application for voting for new data feeds.

MindMajix Youtube Channel

4. Differentiate WCF and Web Services?

Ans:

WCF: Through WCF, we can transmit the data as asynchronous messages from one service endpoint to another endpoint.

Web Services: The web service is the programmable application logic available through the standard web protocols. One of these web protocols is SOAP(Simple Object Access Protocol). SOAP is the W3C presented a note that utilizes standard-based technologies(HTTP for transport and XML for data description) for encoding and transmitting the application data.

Comparison BasisWeb Service WCF
HostIIS can host the web service.Windows Activation Service, IIS, Windows Service, and Self Hosting can host it.
ModelThe WebMethod attribute represents the method uncovered by the client. The OperationContract attribute depicts the method revealed to the client.
ProgrammingWe should add the WebService attribute to the class.We must add the ServiceContract attribute to the class. 
XMLWe use System.Xml.Serialization namespace for serialization. We use System.Runtime.Serialization namespace for serialization.
OperationWeb Service supports different operations like Request-Response and  One-way. WCF supports operations like Duplex, One-way, and Request-Response.
TransportsWe can access Web Services using TCP, Custom, and HTTP. We can access WCF using TCP, HTTP, MSMQ, pipes, Custom, and P2P.
EncodingMTOM(Message Transmission Optimization Mechanism), XML 1.0, Custom, and DIME.Custom, XML 1. O, Binary, and MTOM.
ProtocolsSecurityReliable Messaging, Transactions, and Security.

5. What are the Advantages and Features of WCF?

Ans: WCF(Windows Communication Foundation) is the reliable, scalable, and secure messaging platform for the .NET platform 3.0,

  • Interoperability
  • Service Orientation
  • Multiple Message Patterns
  • Service Metadata
  • Security
  • Data Contracts
  • Multiple Encodings and Transports
  • Durable Messages
  • Queued and Reliable Messages
  • Transactions
  • Extensibility
  • AJAX and REST support
Related Article: Learn .Net Libraries

Following are the Advantages of WCF:

  • Location Independent
  • Language-Independent
  • Service-oriented
  • Support Multiple Operations
  • WCF Maintains the transactions like COM+
  • It maintains the State
  • It controls the Concurrency
  • We can Host on WAS, IIS, Windows Services, and Self Hosting

It includes JSON and AJAX Integration support:

  • We can configure WCF to work in isolation from the SOAP and instead use RSS.
  • WCF is the most rapid communication technology and provides excellent performance in comparison to other Microsoft specifications.
  • For improving transmission, communication speed requires to be maximized. We do this by sending the binary-coded XML data rather than plain text to decrease the hierarchy.
  • Distributed transaction management and object life-cycle management are useful to all the applications built through WCF.

6. Explain SOA? Is web services SOA?

Ans: SOA refers to service-oriented architecture. The service-oriented architecture is the architectural methodology in software development where we organize the application as services.

SOA

The services are the set of methods that include business logic for connecting the DB to other services. For example, if we go to the hotel and order the food, first our order goes to the counter, and next it will go to the kitchen where food is prepared, and lastly, the waiter serves food.

Following are some essential characteristics of service-oriented architecture:

  • SOA Services must be unattached from other services. Modifying the service must not impact the client calling service.
  • Services must be self-contained.
  • Services can specify themselves in WSDL(Web Service Description Language). Services can explain what they can do. It can tell the client what all the operations do and what all data types it utilises, and what type of value it will return. 

SOA Introduction: The Service-Oriented Architecture relies on the four crucial abstractions:

  • A Service
  • An Application Front End
  • The Service Bus
  • The Service Repository

Application Front End: Application Front End is disconnected from services. Every service has a contract that specifies what it can do and multiple interfaces for implementing the contract. 

Service Repository: Service Repository offers the home for services, and the service bus offers the mechanism to connect and interact with services.

A Service: It contains the methods with the specified contracts and business logic implementation for connecting DB to other services.

Is all web-services SOA?

SOA is the architectural idea, and web services are the technical approach for completing it. Web Services are the favoured standards for achieving SOA.

  • In the SOA, we require services that have to be liberally coupled. The web service interacts through SOAP protocol that is XML oriented and very liberally coupled. The SOA services can explain themselves. WSDL explains how we can access the service.
  • SOA Services are placed in the directory. UDDI explains where we can fetch web services. This is the implementation of the SOA Registry.

7. Explain the Service Contract?

Ans: A service contract indicates the collective mechanism through which the service requirements and capabilities are defined for its customers.  It specifies operations that the service performs when implemented. It tells the things about the service like operation locations, message data types, protocols, and clients we require for interacting with the service.

Service Contract

For creating the service contract, we define the interface with the associated methods, delegate the collection of the service operations, and next ádorn the class or interface with the “ServiceContract” attribute for indicating that it is the service contract. The methods in the interface that must be covered in the service contract are adorned with the “OperationContract” attribute.

Service Contract Attribute: We use it for declaring the type as the service contract. We can declare it without any parameters, yet it can take the named parameters.

Service Contract Attribute

8. Explain Contracts?

Ans: The primary purpose of Contracts is to enable the services and client to agree to the kinds of structures and operations they will utilize in the transmission process. It displays the conventional agreements between service and client for specifying the Platform-neutral and typical to explain what the service performs. Following are the kinds of contracts:

Contracts

1. Service Contract

It specifies the operations that the service reveals to the world outside. The service contract is defined as the interface of WCF service and tells the world outside what a service can perform. It can have service-level settings like service name and service namespace. 

2. Operation Contract

The operation contract specifies the method revealed to a client for exchanging information between the client and server. The operation contract explains what utility is provided to the client, like addition, subtraction, etc.

Operation Contract

3. Data Contract

Data Contract specifies the data types and variables similar to set and gets parameters. Yet, the variance is that the Data Contract in the WCF is utilized for serializing and deserializing the data. It specifies how we serialize and deserialize the data types. We can transform the object into a series of bytes that we can send over the network through the serialization process. We can reassemble the object from the sequence of bytes we receive from the calling application through de-serialization.

Data Contract

4. Message Contract

When the operation contract has to transmit the message as the parameter or the return values as the message, the type of this message can be defined as the message contract. The message contract specifies the message elements(Message Body, Message Header) and the message-relevant settings like message security level. The message contracts offer you full control of SOAP header content and SOAP body structure.

5. Fault Contract

The Fault Contract Specifies the errors generated by the service and how the service propagates and handles faults to its clients. The operation contract may have multiple contracts related to it.

Fault Contract

9. Explain the Data Contract?

Ans: The data contract is the official deal between a client and a service that abstractly explains the data to be interchanged. The data contract may be implicit or explicit. Simple data types like string, int have the implicit data type. User-defined objects are a complex or explicit type for which we have to specify the data contract through [DataMember] and [DataContract] attributes.

WCF Data Contract

We can define the data contract in the following way:

  • It explains the explicit format of the data transmitted to and from the service operations.
  • It explains the structure and kinds of data interchanged in the service messages.
  • Data Contract maps the CLR types to the XML schema.
  • It specifies how the data types are deserialized and serialized. Using Serialization, we can transform the object into a sequence of bytes that we can transmit over the network. Using deserialization, we can match the object from the series of bytes that we receive from the invoking application.
  • The versioning system enables us to handle the modifications to the structured data.

10. Explain the Fault Contract?

Ans: Fault Contract offers the documented view of the error granted in our service to the client. This allows us to identify what error has happened and where quickly. When we throw the exception from the service, the error will not go to the client side.

The lesser the client knows what occurred on the client side, the greater unrelated the transmission will be; this is called error masking. Generally, all the exceptions are thrown onto the service side always go to the client as the FaultException. By having all the service exceptions interchangeable, WCF outcouples the client from the service.

WCF Fault Contract

11. Explain the Endpoint and how many kinds of Endpoints?

Ans: Endpoints offer the configuration needed for the interaction and generate the entire WCF service application. The endpoint is the part of the information that teaches WCF to develop runtime communication channels for sending and receiving messages. The endpoint contains three things like address, contract, and binding.

WCF End Points

All the interactions with the WCF(Windows Communication Foundation) service happen using service endpoints. Endpoint offers clients access to functionality provided by the WCF service. Every Endpoint contains four properties:

  • The address is the location where we can discover the endpoint. 
  • The binding defines how the client can interact with the endpoint.
  • The contract finds the existing operations.

Structure of Endpoint

Every Endpoint includes the following:

  • A group of behaviors that define the local deployment details of an endpoint.
  • Address: Address distinctively recognizes endpoint and informs prospective customers where it is situated. It is depicted in the WCF object model by the “EndpointAddress”  class. The “EndPointAddress” class includes:
  1. A Uri property representing the service address.
  2. The identity property depicts the security identity of the service and the collection of the optional message headers. We use the elective message headers for providing additional and detailed address information for identifying and interacting with an endpoint.
  • Binding: Binding defines how to interact with an endpoint. This contains:
  1. Transport Protocol for using(for instance, HTTP or TCP)
  2. Encoding to utilize the messages.
  3. Essential security requirements(for instance, SOAP or SSL message security).
  • Contracts: Contracts summarise what utility the endpoint reveals to the client. The contract defines
  1. What activities can a client invoke.                                                                                                                                                                                                                                                                                    
  2. The kind of data needed or input parameters for calling operation.
  3. What kind of processing or response message does the client anticipate.
WCF Endpoints Structure

12. What is Binding? What are the kinds of Binding?

Ans: Binding explains how the client will interact with the service. We have various protocols for WCF for communicating with clients. We can cite the type of protocol as per our requirements. Binding has various characteristics, containing the following:

  • Transport: Specifies the primary protocol to be utilized like Named Pipes, HTTP, MSMQ, and TCP.
  • Encoding: Three kinds of encrypting are accessible - Binary, Message Transformation Optimization Mechanism(MTOM), or Text. MTOM is a compatible message type that enables the efficient transmission of large messages or attachments.
  • Protocol: Specifies the details for binding like transaction, security, and trusty messaging capability.

Following are some of the protocols of WCF binding:

BindingDescription
BasicHttpBindingIt is a fundamental Web service communication. By default, No security.
WSHttpBindingWeb services with the WS-* support. It supports transactions.
WSDualHttpBindingWeb Services with transaction support and duplex contract.
WSFederationHttpBindingWeb Services along with the federated security. It supports transactions.
MSMQIntegrationBindingCommunication directly with the MSMQ applications. It supports transactions.

13. Describe Transactions?

Ans: The transaction is the rational unit of work containing different activities that should either fail or succeed together. For instance, if we attempt to make the online purchase for the mobile, your amount will be drawn from the bank, yet your ordered mobile was not sent to you. So what did you understand from the prior sample?

Bank operations are done in individual services, and online purchase service is swarmed as another service. The online purchase did not do well as anticipated for the earlier sample because of a database query error. Without realizing it, the bank activities were accomplished successfully. We require transactions to assure that any operations must fail or succeed. Following are the kinds of Transactions:

  1. Long-Running
  2. Atomic
WCF Transactions

WCF Transaction Phases

WCF Transactions have two phases:

  1. Commit Phase: In the Commit Phase, the entities' commitment is initiated in reality.
  2. Prepare Phase: In the Prepare Phase, the transaction manager verifies whether every entity is about to commit the transaction or not.
Related Article: .Net Interview Questions and Answers for Beginners

14. Explain the Address?

Ans: The Address is the Uniform Resource Locator(URL) that recognizes the location of the service. It specifies the network address to send and receive the messages. It is divided into four parts:

WCF Address

In WCF, each service is related to a unique address. The address offered two external elements like the location of the services and transport service that will help us interact with services. WCF supports the below transport schemas. WCF supports the following transport protocols:

  • TCP
  • HTTP/HTTPS
  • Peer Network
  • MSMQ
  • IPC
  • Service Bus

An address will have the below format:

[transport]://[domain or machine][: optional port]

Example:

http://localhost:82/MyService

15. What are the ways of hosting the WCF Service?

Ans: The WCF service may be self-hosting through the Windows Forms applications or console applications. Hosting the application in any .NET application is known as self-hosting. Follow the below procedure to create a WCF service and host it in the console application. Requirements of Hosting Environment:

  1. Availability: When you can reach the service?
  2. Manageability: Do we require access to the details regarding what is happening in the host where WCF services exist?
  3. Reliability: What happens when our service breaks? How does this influence, other consumers?
  4. Deployment: What is the deployment model? Are you installing using the Microsoft installer process and visual studio deployment packages, or is xcopy enough?
  5. Versioning: Do you require support for the earlier service versions? Do we know who is utilizing your services?
  6. State: Are the services stateless? Do you require sessions?

We have the following options to host a WCF service:

  1. Windows Service
  2. Self-Hosting
  3. Internet Information Services(IIS)
  4. Windows Activation Services(WAS)

16. What are the crucial components of the WCF Service?

Ans: A Service is defined as the application or program that other applications use. In simple words, the service utilized by end-users for doing their work is something they ask for and recognize. 

WCF(Windows Communication Foundation) is introduced in .NET 3.0. This is a good network distributed system designed by Microsoft for interaction between the applications. WCF is suitable for developing and deploying the distributed applications below the Service-Oriented Architecture Implementation.

From the WSDN, WCF is the component of the .NET framework that offers the unified programming model for quickly developing service-oriented applications that interact throughout an enterprise and the web. WCF is the integrated feature of the web service, MSMQ, COM+, and Remoting.

Following are the three main elements of the WCF application:

  1. WCF Service Endpoints: All the communication with the Windows Communication Foundation(WCF) service happens using the service endpoints. Generally, we will define the interface in a contract; thus the client application will be knowledgeable about the operations revealed to the client.
  2. WCF Service class: The WCF Service class implements services as a group of methods.
  3. WCF Service host: WCF supports different kinds of IIS, hosting, self-hosting, Windows Activation Services(WAS), and Windows Services. 

Every endpoint includes:

  • Binding: Binding defines how the client can interact with the service.
  • Address: An Address indicates where to discover the service.
  • Contract: The contract specifies what the service can do.

WCF Interview Questions for Intermediate

17. Explain Self Hosting?

Ans: We have a project, and we have to locally host one WCF service in this solution. This kind of host is known as Self-Hosting. To implement self-hosting, we have to include the “System.Service.Model.ServiceHost” namespace to implement self-hosting. Advantages of self-hosting are

  1. Easy to use: Using only a few lines of code, we can run our service.
  2. Flexible: We can easily control the lifetime of our services using the “open()” and “close()” methods of the “ServiceHost<T>.”
  3. Easy to Deploy: Generally, deploying a windows application is as simple as xcopy. We don’t require any problematic deployment scenarios on the server farms for deploying the simple windows application that acts as a WCF ServiceHost. 
  4. Easy to Debug: Debugging WCF services that we host in a self-hosted environment offer a usual debugging method without attaching separate applications that activate the service.
  5. Supports all transports and bindings: Self-hosting will not restrict you to advanced transports and bindings. On Windows Server 2003 and Windows XP, IIS restricts you to HTTP only.

Disadvantages of Self Hosting are

  1. Limited Features: Self-hosted applications have restricted support for easy manageability, high availability, recoverability, versioning, robustness, and deployment. Anyhow, advanced WCF does not offer these; thus, in the self-hosted scenario, you need to implement these features yourself; IIS, for instance, comes with various features by default.
  2. Limited Availability: The WCF service is accessible only when the application is running.

18. How can we host the WCF service in IIS?

Ans: If we want to host the WCF service in IIS, only HTTP is available as the transport protocol. In the subsequent versions of IIS(Internet Information Services), we can utilize other protocols(MSMQ, NamedPipes, and TCP/IP) as the transport protocol.

If we host the IIS service, we include every feature of IIS like ideal shutdown, process recycling, etc. Visual Studio offers two ways to host a WCF service in the local IIS in all the usual methods with a publishing wizard. We will discuss another method of easily using Visual Studio for hosting our WCF service in the local IIS. We should follow the below steps for hosting the WCF services:

host the WCF service in IIS

19. Explain one-way operation?

Ans: When the operation contains no return value, the client ensures the failure or success of invocation. WCF provides one-way operations for supporting this kind of fire-and-forget invocation. Once the client publishes the call, no interconnected reply message will return to the client. One-way message interchange is helpful when the client has to send the information for the service but does not receive a response. We utilize the one-way design pattern:

  • When the client should invoke the call activities and is not impacted by the operation at the operation level.
  • While utilising “NetMsmqBinding” or “MsmqIntegrationBinding” class.

For creating the one-way service contract, we specify our service contract, implement the “OperationContractAttribute” class to every operation, and fix the “is one-way” property to true, as displayed in the below sample code:

WCF One Way Operation

20. Explain DataContractSerializer?

Ans: WCF offers a message-oriented programming framework. We utilize WCF for transmitting messages between the applications. Implicitly WCF depicts every message using the message class. When the WCF sends the message, it takes the logical message object and encrypts it into a series of bytes.

Then WCF studies those bytes and decrypts them in the logical object. The mechanism builds a series of bytes into the logical object; this is known as the encrypting process. When the WCF ‘gets the local message at the runtime, it converts them into the corresponding .NET objects. This mechanism is known as serialization.

WCF Data Contract Serializer

WCF has three fundamental serializers:

  • DataContractSerializer
  • NetDataContractSerializer
  • XMLSerializer

WCF deserializes the WCF messages into the .NET objects and serializes the .NET objects into the WCF messages. By default, WCF offers the “DataContractSerializer” with the service contract. We can modify this default serializer to a custom serializer like the XMLSerializer.

WCF Xmlserializer

XMLSerializerFormat attribute on “ServiceContract” indicates the serializer is all the operation contracts. We can also fix a separate contract for every operation.

XMLSerializer: We may discover the XMLSerializer in System.Xml.Serialization namespace. WCF endorses the serialization from the .NET 1.0. By default, it is utilized with ASP.NET web services.

DataContractSerializer: The DataContractSerializer is the default serializer for the WCF. We don’t need to note the “DataContractSerializer” attribute above the service contract.

NetDataContractSerializer: The NetDataContractSerializer is similar to the .NET Remoting Formatters. It applies the IFormatter, and it is coherent with the Serializable types. It is not suitable for a service-oriented design.

21. Why do we require One Way Service?

Ans: There may be requirements where the operation of the service is not returning any value. At the same time, the client does not care about the failure or success of the service. The client will call the service and operation and forget and continue with operations.

One-way operations: In WCF, this is the best way to acquire Fire and Forget Invocation of service. WCF creates the request message when the client issues a call and has no equivalent response message. No Service side-exception will choose their way to the client.

Configuring One Way operation: “ISOneWay” property of the “OperationContract” is utilized for configuring the service as a one-way service. We have to set this property to true. Setting this property to true spins the service operation as a one-way operation. The client has no connection with calling one-way operation.

Configuring One Way operation

22. Describe Transaction Propagation?

Ans: Transaction Propagation can propagate the transaction throughout the limits of a single service. In another way, the service can participate in the transaction that the client starts. In the SOA environment, transaction propagation turns into an essential requirement. WCF endorses SOA; thus, it also offers support for transaction propagation. 

To facilitate transaction propagation, we have to fix the value of the transaction property of the binding being used. We can do this programmatically as follows:

Transaction Propagation

Or we can do it elaborately by updating the configuration file as below:

Transaction Propagation

23. Explain WCF Throttling?

Ans: WCF Throttling offers a few properties that we can utilize for restricting how many sessions or instances are generated at the application level. We can improve the performance of the WCF service by creating the proper instance.

Throttling of the services is an important component of WCF performance tuning. The WCF throttling offers the prosperities maxConcurrentInstances, max concurrent sessions, and max concurrent calls, which can enable us to restrict the number of sessions or instances generated at the application level.

Property/AttributeDescription
maxConcurrentInstancesThis defines the utmost amount of instances of the context object that implements at a time with service.
maxConcurrentCallsThis defines the utmost number of messages refined throughout the service host. The default value of this property is 16. 
maxConcurrentSessionsThis defines the utmost amount of sessions at once in the service host object. 10 is the default value.

 

WCF Throttling

 24. Explain Service Proxy?

Ans: In WCF, a Simply Proxy or Service Proxy allows applications to communicate by receiving and sending messages. Basically, it is the class that binds the service details like service execution technology, service path, communication protocol, and platform. It includes every method of the service contract.

The client application utilizes a WCF client proxy for communicating with the service. Generally, client applications import the service metadata for creating the WCF client program that we can use for invoking service.

The fundamental steps to creating the WCF client: Compile the service code. Proxy offers similar operations as the service contract, yet also offers other methods to manage the proxy life cycle and connection to service. Proxy includes the data of service like Binding, Configuration, and address such that the client can communicate with the service. What security policies do we have to obey and whatever is prescribed by the service for working correctly?

25. Describe WCF Concurrency? What are the modes of Concurrency?

Ans: WCF Concurrency indicates, “Various calculations are executing concurrently.”

WCF Concurrency allows us to configure how the WCF service instances may assist multiple requests simultaneously. We will require WCF concurrency due to the following reasons; there can be reasons, yet these are considered the important reasons:

We can utilize the parallel feature in the below three ways:

1. Single: The Single thread processes a single request on the server at any moment. The client proxy transmits the request to the server; it processes that request and takes another request. Concurrency. Single declaration:

Concurrency Single Mode

2. Multiple: Multiple threads will process more than one request on the server at any moment. The client proxy transmits the request to the server. The server will process those requests by generating multiple threads on the server object.

3. Reentrant: Reentrant concurrency mode is similar to the single concurrency mode. It is the single-threaded service instance that accepts requests from the client proxy, and it releases the thread once the reentrant object invokes another service or invokes the WCF client using a callback.

WCF Concurrency Reentrant mode
Related Article: Introduction to .Net FrameWork?

26. Describe Exception Handling? What are the ways to handle the exceptions in WCF?

Ans: Exception handling is essential for all applications to troubleshoot unusual problems in the applications. The Windows Communication Foundation(WCF) offers various options to handle the exceptions in the WCF services. Following are the options to handle the exceptions: 

  1. Through FaultException: Good Option
  2. Through returnUnknownExceptionsAsFaults: Debugging Mode
  3. Through IErrorHandler: Only when the Fault cannot manage the exception.
Exception Handling

Exception in a WCF

Exception in a WCF

Example:

Exception in a WCF Example

27. Define REST? How do we create a RESTful Service in WCF?

Ans: Representational State Transfer(REST) is a protocol to exchange data in a distributed environment. The fundamental idea behind the REST is that you must handle your distributed services as the resource, and you must utilize HTTP protocols for performing different operations on that resource. 

JSON

JSON(JavaScript Object Notation) originated from Javascript programming language characters. It allows us to exchange and display the data independently, self-descriptive, and easy way. The data can be utilized and converted into javascript objects.

In almost every web-based application, we can consume WCF through Javascript, AngularJS, jQuery, etc. When the client invokes WCF, XML or JSON is utilized in communication. WCF contains the options for sending responses in the JSON object. We can configure it with WebInvoke or WebGet attribute and WebHttpBinding. This enables us to reveal the Service Contract as the REST service that we can invoke through either XML or JSON.

  • PUT: It displaces the complete collection with another collection.
  • GET: It fetches the Information.
  • DELETE: It deletes the complete information.
  • POST: It creates the latest entry in the collection.

28. Explain Tracing?

Ans: In WCF, the tracing process is on the basis of the classes that exist in the “System.Diagnostic” namespace. The elementary classes are called Trace, TraceListener, and TraceSource. We have the below options for configuring the WCF to eject the tracing information or Define the Trace Source:

  • System.ServiceModel
  • System.ServiceModel.IdentityModel
  • System.ServiceModel.MessageLogging
  • System.Runtime.Serialization
  • System.ServiceModel.Activation
  • Cardspace
  • System.IO.Log
WCF Tracing

Following are the essential steps of WCF Tracing:

WCF Tracing Steps

Set Trace Level:

WCF Set Trace Level

29. Explain KnownType Attribute?

Ans: The KnownType Attribute class enables us to define the types that must be covered for attention in the deserialization. Generally, WCF service receives and returns a base type; if we anticipate the service for receiving and returning the inherited type next, we utilize the known type attribute.

When sending the parameters and returning the values between a service and a client, both endpoints, if we anticipate the service to receive and return the inherent type, we utilize the known type attribute.

While sending parameters and returning the values between the client and the service, both endpoints share every data contract of data to be sent.

WCF KnownType Attribute

30. What are the different kinds of Bindings?

Ans: Binding explains how the client will interact with the WCF service. We will use the binding according to the client's requirements. It endorses different protocols for communicating with the client and various encryption protocols for transferring the data on the internet. Thus, fundamentally binding is an approach of interaction between service and client according to the client’s requirements.

Basic Binding: Basic Binding is offered by BasicHttpBinding class. Basic Binding is developed for revealing the WCF service as the ASMX web service, such that the earlier clients can utilize the new service. Generally, it utilizes the HTTP protocol for transport and encrypts the message in the UTF-8 text format. We can also utilize HTTPS using the basic binding.

Web Service Binding: Web Service Binding is offered by the WSHttpBindingClass. It is similar to the fundamental binding and utilizes HTTPS or HTTP protocols for transport. Yet this is developed to provide different WS - * specifications like WS - Transactions, WS - Reliable Messaging, and WS - Security, which are not endorsed by the basic binding.

wsHttpBinding = basicHttpBinding + WS-*specification

Web Binding: Web Binding is offered by WebHttpBinding class. Web Binding is developed to reveal the WCF services as the HTTP requests through HTTP-POST and HTTP-GET. We use it with REST-based services that can offer an output in the JSON or XML format. This is very much required with social networks to implement a syndication feed.

TCP Binding: TCP Binding is offered by NetTcpBindingClass. It utilizes the TCO protocol for interaction across two machines in the Intranet. It encrypts the message in binary format. It is a more rapid and reliable binding in comparison to HTTP protocol bindings. TCP Binding is utilized only when the interaction is a WCF-to-WCF which indicates both service and client must have WCF.

The “NetMsmqBinding” class offers MSMQ Binding. It utilizes the MSMQ for transport and supports the disconnected message queued. It gives solutions for the disconnected use cases in which the service handles the message other than the client.

IPC Binding: IPC Binding is offered by NetNamedPipeBinding class. It utilizes the named pipe for interaction between two services on a similar machine. This is the most rapid and secure binding among all the bindings.

31. How do we create Basic HTTP Binding?

Ans: The “basicHttpBinding” is utilized to offer support for the older clients that anticipate an inherent ASMX web service. The “TransportCredentialOnly” security mode option sends the user credentials without signing or encrypting the messages.

BasicHttpBinding is ideal for interaction with the ASP.NET Web Service(ASMX) based services affirming the WS-Basic profile that affirms the web services.

  • This binding utilizes HTTP as transport and the text or XML as default message encoding.
  • Security is deactivated by default.
  • The Basic HTTP Binding does not support WS-*  functionalities like WS-Security, WS-Addressing, and WS-ReliableMessaging.
  • It is quite weak in interoperability.

Use the below procedure:

  • Create the WCF  basicHttpBinding project.
  • Start the Visual Studio and choose “New Project” from the Start Page or from file menu; choose “New” and next “project.”
  • After choosing, a dialog will appear displaying every template given by Visual Studio.
  • From installed templates, choose C# then in that, you will choose WCF service application.

32. Explain Instance Context Mode?

Ans: The Instance Context specifies how long the service instance resides on the server.

Request-Response Cycle

Every time the client transmits the request to the WCF service, what takes place backstage? Generally, after the client request, the WCF service creates the service class instance at the service that makes the operations engaged and next, it will return a response to the client. The process service instance object has been generated in this response and request. 

WCF Framework defines the below Instance Context Modes:

PerCall: The latest instance of the service can be generated for a request from a different client or the same client, indicating all requests are the latest requests. In the PerCall mode, no state is retained. In the per-call service, all the client requests acquire the latest committed service instance, and the memory utilization is less in comparison to other kinds of instance activation. 

Per-Session Service: We create the new instance for every new session, and that object scope will be that session scope.

Singleton Service: We create a single instance for a service object that looks after every request from the same client or a different client.

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]

WCF Interview Questions for Advanced Professionals

33. Describe Security Implementation in WCF?

Ans: WCF supports various protocols like MSMQ, HTTP, and TCP; the user should take the required steps to secure our messages and define security policies to protect messages for authorising and authenticating the calls. WCF offers a vibrant and simple configurable environment to implement security. WCF supports the below securities:

  • Message Security: Message security utilizes WC-Security specification for securing the messages. The message is encoded through the certificate and can securely travel on any port through plain http. It offers end-to-end security.
  • Transport Security: Transport Security is the protocol implemented security; thus, it works only point-to-point. Since the security relies on the protocol, it has restricted security support and is confined to protocol security restrictions.
  • TransportWithMessageCredential: This is the combination of both transport and message security implementation.

34. What are the differences between WsHttpBinding and BasicHttpBinding?

Ans:

Comparison BasisWsHttpBindingBasicHttpBinding
CompatibilityThis is reckoned on the clients who do not install the .NET 3.0, and it endorses a broader range of clients. Most clients, such as Windows 2000, do not execute the .NET 3.0. Thus, the earlier version of the .NET can utilize this service. Since it is developed through WS-* specifications, it will not support the broader range of clients, and the former .NET versions that may not utilize it less than the 3rd version. 
Security SupportThis reveals the web services through WS-* specifications.This supports the old ASMX style, WS-BasicProfile 1.1. 
Reliable MessagingSupported since it supports the WS-* specifications. Not Endorsed. In other terms, if the client discharges two or three calls
SOAP VersionSOAP 1.2SOAP 1.1
Default Security OptionsSince the WsHttpBinding WS-*, it includes the WS-Security activated by default. Thus, the data is not transmitted as plain text. By default, messages do not have security when the client calls. Conversely, data is not transmitted as plain text.  
Security Options
  • None
  • Message
  • Transport
  • Transport with the message credentials
  • None
  • Basic
  • Windows - default authentication
  • Certificate

The most significant difference is the security aspect. By default, BasicHttpBinding transmits the data in plain text, while WsHttpBinding transmits it in a secured and encoded manner.

35. Describe Streaming?

Ans: In the WCF, any message ís transmitted only after the entire message is transmitted. It indicates that the first message is buffered at the recipient side, and after it is wholly obtained, it gets transmitted to the receiving end.

The primary difficulty with this process is that the recipient end is unresponsive while buffering the message. Thus, the default method of binding message handling is suitable for the small messages, but for the big messages, this process is suitable. Therefore, to suppress this difficulty, Streaming is introduced.

Configuring the Streaming in the Config file:

WCF Streaming Configuring file

Streaming and Binding

  1. HTTP, TCP, and IPC bindings support the streaming.
  2. By default, the Binding Streaming is deactivated.
  3. TransferMode property must be set as per the required streaming mode in bindings.
  4. We must enable the message streaming in binding for overriding buffering and enabling the streaming.
  5. The kind of TransferMode property is the enum TransferMode.

36. Describe Transport Level Security?

Ans: The objective of Transport Level Security is to provide privacy, authentication, and integrity. Following are the Advantages of Transport Level Security:

  • Less Probability of Phishing Network.
  • Fewer chances of Sniffing Network.
  • Fewer chances for message alteration.
  • Fewer chances of a replay of the message attack.

Transport Level Security Offers:

  1. Authentication of the service and sender.
  2. Message Confidentiality
  3. Message Integrity
  4. Replay the message detection.

37. Explain Messages and SOA?

Ans:

Message Pattern: The message in the WCF is the same as the messages in real time.

It explains how the programs to interchange with each other. It has three methods of communication between destination and source. We don’t need to invoke a Java class from the C# class. When the programs have to communicate with each other, they send messages to each other.

Although it is acceptable to communicate through messages, we must normalize those messages. Next, when people want to exchange the data between the two programs, they receive the normalized message to accomplish it.

SOA is an architectural approach where two non-compliant applications can interact through a general language, and WCF is an example of  SOA(Service-Oriented Architecture). Following are the SOA characteristics:

  • In the SOA, we must detach the services from other services. Modifying the service must not impact the calling service.
  • Services can define themselves. The Services can answer the question of what it does. It can tell the client what operations it performs. And what data types does it utilize? And what type of responses will it give?
  • Services must support “secure communication.”
  • Services must endorse “reliable messaging.” Indicates that there must be an assurance that the request will have arrived at the proper destination and we can achieve a proper response.
WCF Messages and SOA

38. Describe Message Exchange Patterns?

Ans: MEP refers to Message Exchange Patterns. In the WCF, we will create the services. What will the service do for us? Service does specific tasks to support us or transmit the response from the request. All those communications are carried out through messages. We transmit some messages as requests and get the message in the form of a response from the service. WCF has three kinds of Message Exchange Patterns(MEPs):

  • One-Way
  • Request / Response
  • Duplex

One-Way: Fix the IsOneWay property of the OperationContractAttribute to true for the OneWay message exchange pattern. We use the One-Way message exchange pattern when the service performs certain operations, and we do not need a response back. For instance, if we have to modify the transaction status from pending to finished and we do not need to obtain validation from service, that status is modified. We can utilise the OneWay pattern.

Message Exchange Patterns One-Way

 

Message Exchange Patterns One-Way

Request / Response: Request / Response is a quite common MEP. For setting this pattern, we have to set the IsOneWay property of the OperationContractAttribute as false. The default value of the IsOneWay property is false. Thus eventually, we do not have to set this property. By default, it is set. For this reason, it is effortless to implement.

Message Exchange Patterns Request / Response

 

Message Exchange Patterns Request / Response

Duplex: Duplex is the two-way message medium. When the client transmits the message to the service to demonstrate long-run processing and needs notification from the service, the duplex MEP is suitable.

We have two kinds of contracts, CallbackContract and ServiceContract, needed to implement the duplex MEP. The MEP is specified by relating a CallbackContract to ServiceContract. It is performed using the CallbackContract attribute of the ServiceContract.

Message Exchange Patterns Duplex

 

Message Exchange Patterns Duplex

39. What are the different kinds of Instance Modes?

Ans: The Instance mode is the service side execution. It must not display on the client side. The WCF specifies behaviors. Behaviour is the local property of the client or service that will not impact the interaction. The client hardly knows about service behavior and will not display service binding and published metadata. Following are the different Instance modes of WCF:

1. PerCall

When a service installs PerCall, each client obtains the latest service instance.  The following diagram tells how the PerCall instance works:

  • The client invokes the proxy, and the proxy sends the invocation to the service.
  • WCF generates the instance and invokes the method call.
  • When the method call returns, WCF invokes ÏDisponsible if executed.
WCF Parcell

2. PerSession Service

WCF supports the logical session between the service and client in the Precession instance mode. We create a new instance for every client. The below diagram depicts the request from client through Persession service instance mode:

WCF PerSession Service

Single Instance Service

When we set the service as a singleton, every client is linked to the single instance context. We install the singleton service by setting the InstanceContextMode property to single. This instance belongs to the service. We create another instance only by resetting IIS or when the service host is turned off.

WCF Single Instance Service

When you must use per session, single-mode, and per call?

Per Session

  • We have to maintain the states between the WCF calls.
  • We have a scaled-up architecture.
  • Light Resource References.

Single Mode

  • We have to share the global data using our WCF service.
  • Scalability is not essential.

Per Call

  • We need a stateless service.
  • Our Service stores intensive resources like vast memory objects and connection objects.
  • Scalability is the primary requirement. We want a scaled architecture.
  • Our WCF functions are invoked in the single-threaded model.

40. Explain MSMQ?

Ans: MSMQ(Microsoft Messaging Queue) is utilised for asynchronous interaction through messages. We can consider MSMQ as an inter-process communication capability. Whenever two processes need to interact with each other in the “Fire and Forget”, MSMQ is helpful for that.

Example: For instance, if the billing software requires executing more than 1000 bills at midnight and should send mail to all those users. When the operator uses the software, he requires immediate notification. The operator cannot wait for every bill to be processed and gets mail.

MSMQ plays an essential role in interaction by the billing software for sending those 1000s of the customer email information into the queue, and the Queue event handler handles the requests. The operator obtains immediate notification of processes rather than learning the “Behind the Scene” process.

41. Describe Method Overloading?

Ans: Method Overloading is the feature that enables the generation of multiple ways with similar names. Yet, every method must vary from another in the output and input of the functions. All the methods should have different data types of parameters, whether they should vary in the amount of the parameters or the kind of parameters.

We can also consider Method Overloading as the run-time polymorphism as the invoking method knows the address of the called method, and the method addresses are fixed at run time. This is also called Early Binding.

Method Overloading

42. Describe Duplex and Message Exchange Pattern?

Ans: Duplex is defined as a two-way communication mechanism. In Duplex, the consumer sends the message to the service, and the service transmits the notification that request Processing is performed. It is the same as that we pass the command to print the papers in the printer machine. The printer machine begins the communication by building the link with the machine and begins printing the printer.

  1. Duplex service enables the calling back of some operations on clients.
  2. Duplex service is also called Call Backs.
  3. All Binding will not support the duplex service.
  4. Duplex communication is not conventional. They are out-and-out Microsoft features.
  5. Duplex interaction is feasible on the netNamedPipeBinding and netTCPBinding.
  6. wsDualHttpBinding supports the duplex communication on the HTTP Binding.
Duplex and Message Exchange Pattern

We require the Message Exchange Pattern when:

  • We need to invoke the function not to take a longer time.
  • We are only required to invoke the function and do not want to wait for a response.
  • We require a two-way communication mechanism.
  • When we know that the function call is not stopping and simultaneously requires advanced functionality for the application.

43. Explain WCF Messaging Layer?

Ans: The message layer is made up of channels. The channel is an element that executes the message in a particular methodology. Channels are the essential abstraction to send messages and receive messages from the endpoint.

  • SOAP Envelope: SOAP Envelope is the repository for two significant parts of the SOAP message, the SOAP body, and the SOAP header. The SOAP Envelope includes various parts of essential information as elements.
  • Message Structure: WCF utilizes the message for passing the data or exchanging the information from one point to another point. Every message is a SOAP message. The fundamental structure of the SOAP message contains three components.
  • SOAP Body: This element includes the real SOAP message for the interaction with the SOAP receiver; a message can have multiple bodies. Any information meant to be exchanged when a message arrives at the aimed destination exists in the message body.
  • SOAP Header: Through the SOAP Header, we can send key information about services to the outer world if required. It is only for information exchange. Any child elements of the header element are known as “header blocks.”  This offers a process to group the logical data. 
 WCF Messaging Layer

44. Explain trace-level in the trace listeners?

Ans: For enabling the trace, we require to refer to the trace source in the configuration file, such as Web.config. “System.ServiceModel” is the frequently utilized trace source. For Message logging, we use the “System.ServiceModel.MessageLogging” as the trace source. WCF tracing offers the following tracing levels:

Index.noTrace Level Category of EventTracing DescriptionTraced Events
1ImportantNegative EventSudden events or error conditions. Once this happens, the application can turn off immediately or shortly. 
  1. OutOfMemoryException
  2. ThreadAbortException
  3. StackOverFlowException
  4. ConfigurationErrorsException
  5. SEHException
  6. System Hang Errors
2Off No Tracing.Tracing is Ignored.
3WarningNegative Events.It indicates the feasibility of the problems. The application stays up and persists in the processing.

Traces every problem that happened or may happen:

  1. Rejected Credentials.
  2. Timeout has surpassed.
  3. Receiving a queue is close to maximum capacity.
  4. Receiving more requests than anticipated.
4ErrorNegative EventsUnforeseen events or any error condition. When the application does not turn off, it stays up and persists in processing.Trace all the exceptions.
5VerbosePositive EventsSimilar to the “Information”, the only variance is that it enables low-level tracing. Widely utilized for debugging.
6InformationPositive EventsOnly Informative traces that says the successful landmark of application execution. It traces all the diagnostic data.
7AllNegative & PositiveIt contains all the above events.It contains all the above events.
8ActivityTracing  The traces are associated with the communication between components and activities. 

45. Describe Fault Exception in WCF?

Ans: The fault exception is a method to manage the error or exception in WCF. In the C#, we can manage the error through try and catch blocks on the client side. We use the fault exception to manage the error through the service class and present it on the client side. Whenever the client invokes a service class, a sudden exception comes like Divide by Zero, or SQL Server is not responding. In this case, the service class throws the exception to the client through fault exception. 

Generally, when we throw an exception from the service, it will not go to the client. WCF gives the option to manage and tell the error message to the client from the service through the SOAP Fault Contract. For supporting the SOAP Faults, WCF offers the FaultException class. This class includes two forms:

  1. FaultException: For sending the untyped fault back to the caller.
  2. FaultException<T>: For sending the typed fault data to the client. Fundamentally, it is a generic type.

Syntax:

[OperationContract]

[FaultContract(typeof(MyException))]

String getDetails(int value);

46. Explain Instance Management?

Ans: Instance Management is defined as the group of techniques utilized by the WCF for binding the client requests for the service instances and administering the service instance that manages the client request.

Instance Management is the technique to determine which service instance will host the client's request. It also determines when the service instance will serve the client’s request. Instance Management is an essential factor while designing the service. It impacts:

  • Service Scalability
  • The durability of the Service
  • Service Queues
  • Transactions
  • Performance of the Service

Instance Management is considered the group of techniques for determining which service instance will host the client request and when. Fundamentally, we have the following Instance Modes:

  • Per-Session Instance Mode 
  • Per-call Instance Mode
  • Singleton Instance Mode

Why do we require Instance Management?

We require Instance-Management since applications vary excessively in their requirements for scalability, throughput, performance, queued, and transaction calls. Thus, a single solution for all the applications does not suit.

Instance Management

47. Describe Information cards?

Ans: Since we are utilizing the DerivativesCalculator sample for improving the WCF application, thus we can utilize it for adding the Information Card to the WCF application. Information Cards offer more advantages than CardSpace. Advantages of adding the Information Card:

  1. Authorization
  2. Authentication
  3. Giving trust to the domains
  4. Reduce the IT Pain
  5. Assists in Maintaining the Security

The Information card is the virtual representation of the individual’s identity that is ensured by a specific party. The Information Cards are similar to real-time identity cards like credit cards, driver’s licenses, passports, and employee cards. 

WCF Information cards
  • Information Cards are more compliant than sample usernames and passwords.
  • Information Cards can possibly display any kind of identity claim that adds up to all the interacting parties and which users can release.
  • Information cards utilize strong cryptography, which makes them more secure than passwords.

48. Explain the Message Contract?

Ans: We use the Message Contract to control the message body's structure and serialization process. We also use it for sending or accessing the information in the SOAP headers. By default, WCF looks after creating SOAP messages as per the service DataContracts and operation contracts.

The MessageContract restraints the message body structure and serialization process. We can type or untype the MessageContract, and it is helpful in compatibility cases and when there is an available message format. We must obey it.

We implement the SOAP header in the namespace System.web.services.protocol

Message Contract

Message Header: The message header is applied to the member of the message contract for declaring the member in the message header.

Message Header

Message Body Member: The message body header is implemented on the member of the message contract for declaring the members in the message body.

Message Body Member

Conclusion

These WCF Interview Questions covered all the real-world scenarios and concepts of WCF. I hope these questions are sufficient to prepare for your job interviews. If you have any queries, let us know by commenting below.

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
.NET TrainingDec 24 to Jan 08View Details
.NET TrainingDec 28 to Jan 12View Details
.NET TrainingDec 31 to Jan 15View Details
.NET TrainingJan 04 to Jan 19View Details
Last updated: 07 Oct 2024
About Author

 

Madhuri is a Senior Content Creator at MindMajix. She has written about a range of different topics on various technologies, which include, Splunk, Tensorflow, Selenium, and CEH. She spends most of her time researching on technology, and startups. Connect with her via LinkedIn and Twitter .

read less