Monday, 17 March 2014

Interview Q & A on WCF Services in Asp.Net(Part 1)

1.WCF Service?
Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.

2.In what scenarios must WCF be used?
A secure service to process business transactions.
A service that supplies current data to others, such as a traffic report or other monitoring service.
A chat service that allows two people to communicate or exchange data in real time.
A dashboard application that polls one or more services for data and presents it in a logical presentation.
Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
A Silverlight application to poll a service for the latest data feeds.

3.Features of WCF?
Service Orientation
Interoperability
Multiple Message Patterns
Service Metadata
Data Contracts
Security
Multiple Transports and Encodings
Reliable and Queued Messages
Durable Messages
Transactions
AJAX and REST Support
Extensibility

4.Difference between Web Service in ASP.NET & WCF Service?
WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot more than what is traditionally considered as "web services".

WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.

ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.

Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. Common scenarios for hosting WCF services are IIS,WAS, Self-hosting, Managed Windows Service.

The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer.

4(i).Key issues with XmlSerializer to serialize .NET types to XML
Only Public fields or Properties of .NET types can be translated into XML.
Only the classes which implement IEnumerable interface.
Classes that implement the IDictionary interface, such as Hash table cannot be serialized.
The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW types into XML.

 Example:
[DataContract]
public class Item
{
    [DataMember]
    public string ItemID;
    [DataMember]
    public decimal ItemQuantity;
    [DataMember]
    public decimal ItemPrice;
}
The DataContractAttribute can be applied to the class or a strcture. DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private.

4(ii).Important difference between DataContractSerializer and XMLSerializer?
A practical benefit of the design of the DataContractSerializer is better performance over XML serialization.
XML Serialization does not indicate which fields or properties of the type are serialized into XML whereas DataContractSerializer explicitly shows which fields or properties are serialized into XML.
The DataContractSerializer can translate the HashTable into XML.

4(iii).Developing Service
To develop a service using ASP.NET, we must add the WebService attribute to the class and WebMethodAttribute to any of the class methods.

Example:
 [WebService]
public class Service : System.Web.Services.WebService
{
      [WebMethod]
      public string Test(string strMsg)
      {
          return strMsg;
      }
}

4(iv).To develop a service in WCF, we will write the following code:
[ServiceContract]
public interface ITest
{
       [OperationContract]
       string ShowMessage(string strMsg);
}
public class Service : ITest
{
       public string ShowMessage(string strMsg)
       {
          return strMsg;
       }
}
The ServiceContractAttribute specifies that an interface defines a WCF service contract, OperationContract attribute indicates which of the methods of the interface defines the operations of the service contract.
4(v).A class that implements the service contract is referred to as a service type in WCF:

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

4(vi).Client Development

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

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

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

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

5.What is the difference between basicHttpBinding and wsHttpBinding?
BasicHttpBinding is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. BasicHttpBinding is a WS-I Basic Profile [1] binding; it does not implement any advanced WS-* specs and sticks with SOAP over HTTP(S). Due to the binding's simplicity it enables a higher level of interoperability with existing web service client and services.
wsHttpBinding uses message security by default, with WS-Security and WS-SecureConversation. In Additions, it supports reliable messaging, atomic and distributed transactions.

6.What is EndPoint?
The Endpoint's Address is a network address where the Endpoint resides. It's nothing but the combination of an Address, a Binding, and a Contract. In simple terms, it's a URL on which clients can communicate to the service.

7.What are the different types of contract we have in WCF?
Contracts will describe what the service is offering. There are 4 types of contracts in WCF.

Service Contract
Indicates that an interface or a class defines a service contract in a application.
[ServiceContract]
public interface IService
{
                [OperationContract]
                string GetData(int value);
}

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.
[DataContract]
public class CompositeType
{
                bool boolValue = true;

                [DataMember]
                public bool BoolValue
                {
                                get { return boolValue; }
                                set { boolValue = value; }
                }
}

Fault contracts
Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

Message contracts
Message Contracts are used for SOAP formats to provide additional information as part of message header.

8.How do you communicate with a WCF service from your application?
We can communicate to WCF service using a proxy. Proxy represents the service contract. Proxy will encapsulates every aspect of the service: its location, implementation technology, runtime platform, and the communication transport.

Proxy classes can be created either while adding service reference to the client application from Visual Studio IDE or we can create it by using svcutil.exe.

9.How do you implement 2 or more web methods (method overloading) with same name in WCF?
Method overloading is not supported directly as per the WSDL rules. We need to set an additional property in association to OperationContract attribute as shown below:

Here GetData is specified twice but OperationContract is specified with an additional parameter Name with value of GetSum.

[ServiceContract]
public interface IService
{
                [OperationContract]
                string GetData(int value);

        [OperationContract(Name="GetSum")]
        string GetData(int value1, int value2);
}

10.Explain briefly about WCF architecture.
WCF consists of three main components: Address, Binding and Contract (We can remember it as ABC).

Address
Address indicates the location of the service where it is hosted. Clients need this address in order to contact the service. This is nothing but the URL of service.

Binding
Binding tells the way of communication which means the type of data transfer and the communication potocal. E.g. SOAP over HTTP, Binary over TCP etc.

Contract
Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method. This is nothing but the web methods that are being distributed to clients.

11.What is the difference between WCF and Web services?
WCF is completely a new for implementing service oriented applications. So it has lot of new features compared to ASP.Net web services. Such as

WCF can be hosted in different types of applications like IIS, Windows Activation Services, Self Hosting and Managed Windows Service with difference protocals such as HTTP, TCP, NamedPipes, MSMQ where as web services can be hosted only on IIS over HTTP.

WCF services can be accessed over many protocals like HTTP, TCP, NamedPipes, MSMQ etc where as web services can be hosted and access using only HTTP.

12.Which name space is requried to implement WCF service and client applications?
System.ServiceModel

13.What is WCF?
Windows Communication Foundation or just WCF is a programming framework used to build applications that communicate with each other. It is a part of the .NET Framework dedicated to communications.

14.What are the different WCF binding available?
• BasicHttpBinding
• WSHttpBinding
• WSDualHttpBinding
• WSFederationHttpBinding
• NetTcpBinding
• NetNamedPipeBinding
• NetMsmqBinding
• NetPeerTcpBinding
• MsmqIntegrationBinding

15.What is the proxy for WCF Service?
A proxy is a class by which a service client can Interact with the service. By the use of proxy in the client application we are able to call the different methods exposed by the service.

16.What is the difference between XMLSerializer and the DataContractSerializer?
1. DataContractSerializer is the default serializer fot the WCF
2. DataContractSerializer is very fast.
3. DataContractSerializer is basically for very small, simple subset of the XML infoset.
4. XMLSerializer is used for complex schemas.

17.What is endpoint in WCF service?
The endpoint is an Interface which defines how a client will communicate with the service. It consists of three main points: Address,Binding and Contract.

18.What is the difference between WCF Service and Web Service?
1) WCF Service supports both http and tcp protocol while webservice supports only http protocol.
2) WCF Service is more flexible than web service.
3) WCF is combination of WebService, Remoting, MSMQ.

19.What are the various ways of hosting a WCF service?
Self hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of ServiceHost class and the service closes when you call the Close of the ServiceHost class. Host in application domain or process provided by IIS Server. Host in Application domain and process provided by WAS (Windows Activation Service) Server.

20.What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.

21.List the behaviors that WCF service uses during its execution?
A WCF service uses the following list of behaviors during its execution.
1. Throttling
2. Security
3. Instancing
- PerCall
- PerSession
- Single
4. Error handling
5. Concurrency
- Multiple
- Single
- Reentrant
6. Transactions

22.What is WCF?
Unified programming model, provided by WCF, helps in building Service Oriented Application (SOA) through some simple implementation. WCF Service features for usage in SOA implementation.

23.Uses of WCF services:
• Expose functionality using contracts to clients
• Can be deployed over various protocols to satisfy various distributed and interoperable scenarios
• Execute autonomously and do not impact another service in case of failure
• Design and implementation are separate from business logic, which eases migration to SOA design.

24.What is the programming life cycle of WCF?
Windows Communication Foundation (WCF) enables applications to communicate whether they are on the same computer, across the Internet, or on different application platforms. This topic outlines the tasks that are required to build a WCF application. The basic tasks to perform, are, in order to:
1. Define the Service Contract
2. Implement the Service Contract
3. Configure the Service by specifying endpoint information and other behavior information
4. Host the service in an application
5. Build the client application

25.Define WCF data contract?
- A data contract is defined by using a Data Contract Attribute on a class or structure.
- Members of the data structure which will be used by the service need to be marked with the Data Member Attribute.
- Only those members will be transferred between the service and its client. In the same way that different classes can implement the same interface, different classes can implement the same Data Contract, and can serialize and deserialize the same data.

26.What is the advantage and disadvantage of implementing IExtensibleDataObject?
WCF guidelines recommend enhancing all data contracts with support of IExtensibleDataObject interface, to preserve unexpected data from clients. During deserialization, superfluous data is placed in a dictionary on the service side and during serialization, the same data is written as XML as it was originally provided by the client. This is very useful to preserve data from version 2.0 services at a version 1.0 client. It is also useful in case where downstream calls from version 2.0 services go to other services handling version 1.0.
However, there is also a disadvantage of implementing IExtensibleDataObject. It carries risks of denial of service (DoS) and unnecessary use of server resources.

27.What is the role of WSDL in WCF?
WSDL stands for Web Service Description Language. The WCF service exposes the WSDL document for the clients, to generate proxies and the configuration file. The WSDL file provides the following information for the consumers of the WCF service.
1. Provides the information about the service contract and operations available.
2. Provides the information about all the end points exposed by the WCF service.
3. Provides the information about the messages and types that can be exchanged between the client and the WCF service.
4. WSDL also provides any information about the policies used.

28.What are the different types of bindings available in WCF?
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.
29.What are Various Ways of Hosting WCF Services?

Three ways of hosting WCF Services:
1. Self-hosting the service in its own application domain. The service comes into existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.
2. Host in application domain or process provided by IIS Server.

3. Host in application domain and process provided by WAS (Windows Activation Service) Server.

No comments:

Post a Comment