Friday 30 September 2011

Abstract vs Interface

Abstract Class

These classes are either partially implemented, or not at all implemented.
  • This class can contain declarations and also implementations. 
  • We cannot make instance of Abstract class. We must inherit to use this class.
  • A non-abstract class derived from an Abstract class must include implementations for all inherited abstractmethods.
  • Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).

Interface

Interface is a pure abstract entity:
  • It contains only the declaration.
  • We cannot make instance of an Interface. We must inherit to use Interface.
  • A class which implements the interface should implement all the members of an Interface.
  • Members of an Interface are always public.

Few Advantages

An advantage of Abstract class over Interface

If you want to have additional functionalities for the interface, you must implement the new ones in all of the classesthat implement the changed interface. The code will not work until you make the change. But if you want to have additional functions to the Abstract class, you can have default implementation. Your code still might work without many changes.

An advantage of Interface over Abstract class

A class can inherit multiple interfaces but can inherit only one class.
Now let us discuss the most important part - when to use Abstract and when to use Interface.

When to Use Abstract and When to Use Interface

Let me explain it with reference to the scenario.
Let us take a classification called Human. As it is a very general classification, I can put all the Human related common data in Abstract class. These common data could be First Name, Last Name, Gender, Education, Occupation, Residence, etc. with some functions as virtual (or overridable), e.g., an occupation which differs from human to human.
Aim of Interface: We want the implementing object to acquire this ability.
Aim of Abstraction: We want the derived object to belong to some group. Abstraction gives the Identity to the derived object.
The sentence "Object A is a Human" is more meaningful than the sentence "Object A is an object which has the ability to walk." (Human can walk, an animal, a bird, a machine - consider it is a robot ... that can also walk.)

Why I chose interfaces IEat, IWalk, IDance and ISing

I may want Object A to walk in the morning, to eat in the afternoon or to dance in the evening, or I may not be aware at a particular time what these objects should be doing. The capability of Object A at a particular time is unknown to me. Also every derived object may need not posses the quality of walking, or dancing, or singing. An infant cannot walk, as you know everybody cannot dance and sing. So I created these interfaces so that I can define the combination of these capabilities for different objects explicitly.
Refer to the image below for a more clearer view.

Take an example of .NET interfaces IDisposable or IComparable. We implement these interfaces only if necessary. We implement IDisposable mostly when we want to handle COM components and IComparable to compare and sort the objects in an Array.
If you want your class to have an Identity of Form, you must inherit Form class and you can add the ability to dispose, by implementing IDisposable, only if you want to dispose it manually.

Polymorphic Behavior

As I told you, interface adds to the capability of an Object, this means I can have an Object which eats while walking, and the same Object which can dance, and also sing well. This gives polymorphic behavior (single object –multiple capabilities) to the object.
Let me explain this with the help of code.
namespace TestAbstractVsInterface
{
    //Abstract class

    abstract class AbstractHuman
    {
        public abstract string name { get; set;}
        public abstract string qualification { get; set;}
        
        //Remaining code goes here
        //.
        //.
        //.
        //.
    }

    //Interfaces

    interface IEat
    {
        void eat();
    }

    interface ISing
    {
        void sing();
    }

    interface IWalk
    {
        void walk();
    }

    interface IDance
    {
        void dance();
    }

    //Class which inherits abstract class and implements interfaces

    class MyClass : AbstractHuman, IEat, ISing, IWalk, IDance
    {      
        private string strName = "Arati Kadi";
        private string strQualification = "";
        
        public override string name
        {
            get { return strName; }
            set { name = value; }
        }

        public override string qualification
        {
            get { return strQualification; }
            set { name = value; }
        }

        public void eat()
        { 
            //Related code
        }

        public void sing()
        { 
            //Related code
        }

        public void walk()
        { 
            //Related code
        }

        public void dance()
        { 
            //Related code
        }

//The code snippet below checks by what type class could be //accessed as.

        public void getAbilities()
        {
            if (this is IEat)
                Console.WriteLine("MyClass can eat");                
            if (this is IWalk)
                Console.WriteLine("MyClass can walk");                
            if (this is ISing)
                Console.WriteLine("MyClass can sing");              
            if (this is IDance)
                Console.WriteLine("MyClass can dance");               
        }        
    }  

    //Test Myclass

    class testClass
    {
        MyClass objMyClass = new MyClass();

        public void test()
        {
            objMyClass.getAbilities();
        }
    }

 }

Output

MyClass can eat                  
MyClass can walk                
MyClass can sing
MyClass can dance
Technically speaking, here the class is used as more than one type. It is used as four Interface Types. It can also be used as its own type and also the type of its base class.

Reusability

Let us consider the same abstract Human class which has the virtual function Eat instead of an Interface IEat.
Now I want to create a class called Bird. As a Bird can also eat, I want to reuse the function which is already there in Human class. Suppose, just because abstract Human class has the function to eat, I cannot derive a Birdclass from that. I will tend to change the Bird's identity by doing so, or I may load unnecessary properties to theBird that could be an education, or employment, or may be the last name. Even worse I may need to change theabstract Human class so as to include the common behaviors of Bird category. This is totally senseless and messes up the class and objects. Instead, I can have another Abstract class for Birds and choose to have an interface called IEat, which could be implemented by an object of Human and also an object of Bird.

Again I want to mention .NET interfaces IDisposable, IComparable (and many). These are available in Systemnamespace and you are reusing to implement with required classes.

Conclusion

  • Abstract class gives an Identity to the derived object.
  • Interface extends the ability of an object.
  • Interfaces give polymorphic behavior.
  • Abstract class also gives polymorphic behavior. But it is more meaningful to say that Abstract class simplifies versioning, as the base class is flexible and inheriting class can create many versions of it by additional functions and also by implementing Interfaces.
  • Interfaces and Abstract Classes both promote reusability.

Removing Duplicates from List

Although there are many different ways you can remove duplicate elements from aList collection in the C# language, some are easier to implement than others. One approach, which involves using the Distinct extension method, is the easiest to add but has less predictable performance. Here, we look at how you can remove duplicate elements from a List using the Distinct method.

Example

First, this program requires a newer installation of the .NET Framework, because it uses the System.Linq namespace. In the Main method, a List with seven integer elements is created. However, the list contains duplicate elements for the values 3 and 4. By using the Distinct parameterless extension method on the List type, we can remove those duplicate elements. Then, we can optionally invoke the ToList extension to get an actual List with the duplicates removed.
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
 // List with duplicate elements.
 List<int> list = new List<int>();
 list.Add(1);
 list.Add(2);
 list.Add(3);
 list.Add(3);
 list.Add(4);
 list.Add(4);
 list.Add(4);

 foreach (int value in list)
 {
     Console.WriteLine("Before: {0}", value);
 }

 // Get distinct elements and convert into a list again.
 List<int> distinct = list.Distinct().ToList();

 foreach (int value in distinct)
 {
     Console.WriteLine("After: {0}", value);
 }
    }
}

Output

Before: 1
Before: 2
Before: 3
Before: 3
Before: 4
Before: 4
Before: 4
After: 1
After: 2
After: 3
After: 4

Thursday 29 September 2011

WCF Interview Questions

What are the types of binding available in WCF?
A binding is identified by the transport it supports and the encoding it uses. Transport may be HTTP,TCP etc and encoding may be text,binary etc. The popular types of binding may be as below:
a)BasicHttpBinding
b)NetTcpBinding
c)WSHttpBinding
d)NetMsmqBinding

What are the types of contract available in WCF?
The main contracts are:
a)Service Contract:Describes what operations the client can perform.
b)Operation Contract : defines the method inside Interface of Service.
c)Data Contract:Defines what data types are passed
d)Message Contract:Defines wheather a service can interact directly with messages
What are the various ways of hosting a WCF Service?
a)IIS b)Self Hosting c)WAS (Windows Activation Service)

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
 How can we create Proxy for the WCF Service?
We can create proxy using the tool svcutil.exe after creating the service.
We can use the following command at command line.
svcutil.exe *.wsdl *.xsd /language:C# /out:SampleProxy.cs /config:app.config
What is the difference between WCF Service and Web Service?
a)WCF Service supports both http and tcp protocol while webservice supports only http protocol.
b)WCF Service is more flexible than web service.

Which specifications does WCF follow?WCF supports specifications defined by WS-* specifications. WS-* specifications are defined
together by Microsoft, IBM, SUN and many other big companies so that they can expose there
service through a common protocol. WCF supports all specifications defined we will understand
them one by one.
• Messaging (WS-Addressing):- SOAP is the fundamental protocol for web services. WS
Addressing defines some extra additions to SOAP headers, which makes SOAP free from
underlying transport protocol. One of the good things about Message transmission is MTOM,
also termed as Message Transmission Optimization Mechanism. They optimize transmission
format for SOAP messages in XML-Binary formant using XML optimized packaging (XOP).
Because the data will sent in binary and optimized format, it will give us huge performance
gain.
• Security (WS-Security, WS-Trust, and WS-Secure Conversation): All the three WSdefine
authentication, security, data integrity and privacy features for a service.
• Reliability (WS-Reliable Messaging): This specification ensures end-to-end
communication when we want SOAP messages to be traversed back and forth many times.
• Transactions (WS-Coordination and WS-Atomic Transaction): These two specifications
enable transaction with SOAP messages.
• Metadata (WS-Policy and WS-Metadata exchange): WSDL is a implementation of WSMetadata
Exchange protocol. WS-Policy defines more dynamic features of a service, which
cannot be expressed by WSDL.
WCF follows WS-* specifications other
languages like JAVA , C++ can also exploit features like Messaging , Security , Reliability and
transactions written in C# or VB.NET. This is the biggest achievement of WCF to integrate the
above features with other languages.

What is the difference WCF and Web services?
Web services can only be invoked by HTTP. While Service or a WCF component can be invoked
by any protocol and any transport type. Second web services are not flexible. However, Services
are flexible. If you make a new version of the service then you need to just expose a new end.
Therefore, services are agile and which is a very practical approach looking at the current
business trends.

what are the advantages of hosting WCF Services in IIS as compared to self-hosting?There are two main advantages of using IIS over self-hosting:-
Automatic activation
IIS provides automatic activation that means 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.
Process recyclingIf IIS finds that a service is not healthy that means if it has memory leaks etc, IIS recycles the
process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, process stops and you loose all information. IIS also restarts the worker process. By default, the worker process is recycled at around 120 minutes. So why does IIS recycle. By restarting the worker process it ensures any bad code or memory leak do not cause issue to the whole system.
In case of self-hosting both the above features, you will need to code yourself. Lot of work
right!!.

what are the various ways of hosting a WCF service?
There are three major ways to host 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 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.

Which are the various programming approaches for WCF?/ What is one-way operation?IsOneWay equal to true ensures that the client does not have to wait for the response. So methods
marked by IsOneWay to true should always return void. In this, the caller does not get anything
in return so it is called as one-way communication

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.

This binding is used when we need to use SOAP over HTTP. This binding
can also be configured to be used as HTTPS. It can be also configured to send data in plain text or
in optimized form like MTOM.

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.
This binding sends binary-encoded SOAP, including support for reliable
message transfer, security, and transactions, directly over TCP. The biggest disadvantage of
NetTcpBinding is that both server and client should be also made in .NET language.

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.

It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with
it also supports reliable message transfer, security and transaction. WS-Reliable Messaging,
security with WS-Security, and transactions with WS-Atomic Transaction supports reliable
message.

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.

This binding sends binary-encoded SOAP over MSMQ. This binding can
only be used for WCF-to-WCF communication


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



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

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




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)


WCF - Interview Questions with Answers

Windows Communication Foundation :Interview Questions with Answers
What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it. WCF is Microsoft's unified programming model for building service-oriented applications with managed code. It extends the .NET Framework to enable developers to build secure and reliable transacted Web services that integrate across platforms and interoperate with existing investments.

Windows Communication Foundation combines and extends the capabilities of existing Microsoft distributed systems technologies, including Enterprise Services, System.Messaging, Microsoft .NET Remoting, ASMX, and WSE to deliver a unified development experience across multiple axes, including distance (cross-process, cross-machine, cross-subnet, cross-intranet, cross-Internet), topologies (farms, fire-walled, content-routed, dynamic), hosts (ASP.NET, EXE, Windows Presentation Foundation, Windows Forms, NT Service, COM+), protocols (TCP, HTTP, cross-process, custom), and security models (SAML, Kerberos, X509, username/password, custom).

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

What is endpoint in WCF? or What is three major points in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service.

In WCF the relationship between Address, Contract and Binding is called Endpoint. The Endpoint is the fusion of Address, Contract and Binding.


1. Address : Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.

2. Contract : Specifies the interface between client and the server.It's a simple interface with some attribute.

3. Binding : Specifies how the two paries will communicate in term of transport and encoding and protocols.

What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary).

A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.

1. Basic binding :
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.


2. TCP binding :
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

3. Peer network binding :
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.

4. IPC binding :
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.

5. Web Service (WS) binding :
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

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

7. Duplex WS binding :
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

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

9. MSMQ integration binding :
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

What is contracts in WCF?
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.

1. Service contracts : Describe which operations the client can perform on the service.

2. Data contracts : Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

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

4. Message contracts : Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.


What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas. WCF supports following transport schemas

1. HTTP
2. TCP
3. Peer network
4. IPC (Inter-Process Communication over named pipes)
5. MSMQ

The sample address for above transport schema may look like

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

What is the difference WCF and Web services?
1. Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type.

2. Second web services are not flexible. But Services are flexible. If you make a new version of the service then you need to just expose a new end point. So services are agile and which is a very practical approach looking at the current business trends.

How can we host a service on two different protocols on a single server?
Let’s first understand what this question actually means. Let’s say we have made a service and we want to host this service using HTTP as well as TCP.

You must be wondering why to ever host services on two different types of protocol. When we host a service it’s consumed by multiple types of client and it’s very much possible that they have there own protocol of communication. A good service has the capability to downgrade or upgrade its protocol according the client who is consuming him.

Let’s do a small sample in which we will host the ServiceGetCost on TCP and HTTP protocol.

Once we are done the server side coding its time to see make a client by which we can switch between the protocols and see the results. Below is the code snippet of the client side for multi-protocol hosting

How does WCF work?
Follows the 'software as a service' model, where all units of functionality are defined as services.

A WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal (connection) for communication with either clients (applications) or other services.

Enables greater design flexibility and extensibility of distributed systems architectures.

A WCF application is represented as a collection of services with multiple entry points for communications.

What are the main components of WCF?

1.Service: The working logic or offering, implemented using any .Net Language(C).

2.Host: The environment where the service is parked. E.g. exe, process, windows service

3.Endpoints: The way a service is exposed to outside world.

Explain transactions in WCF.
Transactions in WCF allow several components to concurrently participate in an operation. Transactions are a group of operations that are atomic, consistent, isolated and durable. WCF has features that allow distributed transactions. Application config file can be used for setting transaction timeouts.


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)

Thanks
Prasham
.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.
The XML Information Set defines a data model for XML. It is an abstract set of concepts such as attributes and entities that can be used to describe a valid XML document. According to the specification, "An XML document's information set consists of a number of information items; the information set for any well-formed XML document will contain at least a document information item and several others."
1.IIS
2.Self Hosting
3.WAS (Windows Activation Service)
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.
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.

Thanks
Prasham
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.
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.

Thanks
Prasham
When multiple endpoints are associated with WCF service, base address (one primary address) is assigned to the service, and relative addresses are assigned to each endpoint. Base address is specified in <host> element for each service.
E.g.
<configuration>
    <system.servicemodel>
      <Services>
<service name=”MyService>
  <host>
  <baseAddresses>
 <add baseAddress =”http://localhost:6070/MyService”>
</baseAddresses>
</host>
</service>
<services>
</system.servicemodel>
</configuration>


Thanks
Prasham
SOAP (Simple Object Access Protocol), which is directly supported from WCF (Windows Communication Foundation).
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.
Hello,

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
}

There are 3 possible values of ConcurrencyMode enumeration
Single
Reentrant
Multiple

Thanks
Prasham
Hello,

WCF supports following 3 types of transactions managers:

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

Thanks
Prasham
Hello,

Following bindings supports the streaming in WCF:

1. basicHttpBinding
2. netTcpBinding
3. netNamedPipeBinding
 

WCF Interview Questions

What is WCF?
WCF stands for Windows Communication Foundation (WCF) and is considered as the Microsoft Service-Oriented Architecture (SOA) platform for building distributed and interoperable applications. WCF unifies ASMX, Remoting, and Enterprise Services stacks and provides a single programming model. WCF services are interoperable and supports all the core Web services standards. WCF services also provide extension points to quickly adapt to new protocols and updates and integrates very easily with the earlier microsoft technologies like Enterprise Services, COM and MSMQ.
What is the version of the .NET framework in which WCF is released?
WCF - Windows Communication Foundation is released as part of .NET Framework 3.0. WPF (Windows Presentation Foundation), WF (Workflow Foundation) and Card Space are also part of .NET Framework 3.0.

What is the advantage of using WCF over other distributed programming models like Web Services(ASMX), .NET Remoting, Enterprise Services stack etc.?
To understand the advantage of using WCF over other distributed programming models like Web Services(ASMX), .NET Remoting, Enterprise Services stack etc, let's consider the following scenario. We have developed an application using web services. As we know web services use HTTP protocl and XML SOAP formatted messages, they are good for developing interoperable applications in a heterogeniuos environment. We have a new client. Our new client is using .NET and he wants binary formmatted messages over TCP protocol, because interoperability is not a concern and binary formmatted messages over TCP protocol are much faster than XML SOAP formmatted messages over HTTP. To satisfy the requirement of this client, now we cannot use our existing web service. So, we have to develop a brand new remoting application from the scratch. The business functionality is the same in web services and remoting application. Since our different clients have different requirements, we ended up creating the same business application using web services and remoting technologies. This approach has several disadvantages as listed below.
1. Developers have to be familiar with two different technologies (Web Services and Remoting).
2. We end up creating duplicate business applications with different technologies which also leads to maintainance overhead.
On the other hand WCF unifies Web Services, .NET Remoting, and Enterprise Services stacks under one roof. For the same requirement that we have seen untill now, we just create one application and expose multiple end points to satisfy the requirements of multiple clients. In WCF configuration drives protocol choices, messaging formats, process allocation, etc. WCF services are loosely coupled, meaning that a WCF service is not bound to a particular protocol, encoding format, or hosting environment. Everything is configurable.

Why are WCF Services are considered as loosely coupled?
WCF Services are considered as loosely coupled because WCF services are not tightly bound to a particular protocol, encoding format, or hosting environment. All of these are configurable. At the time of designing WCF services, we donot have to worry about what protocol, encoding format, or hosting environment to use to expose the service. We can worry about all these at the time of deployment.

What are the 3 things that a WCF Services end point must have?
                        OR
What are the ABC of a WCF service?
Address - The address where the WCF Service is hosted.
Binding - The binding that decides the protocol, message encoding and security to use. Binding also decides whether to use reliable messaging and transaction support.
Contract - The service contract defines what service operations are available to the client for consumption.
So the Address(A), Binding(B) and Contract(C) are called as the ABC of the service end point.
What is the role of WSDL in WCF?
           OR
What is WSDL?
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.
What is the tool that a client application can use to generate the proxy for a WCF service?
Service Utility (svcutil.exe) can be used by the clients to generate the proxy and configuration file. For the client to be able to generate proxies, the service should enable metadata exchange.

Define Service Contracts and Operation Contracts in WCF?1. Service Contract - An interface that exposes the service operations is usually decorated with the service contract attribute. Always provide meaningful Namespace and Name to a service contract as shown in the example below.
2. Operation Contract - All methods in a service contract should have OperationContract attribute. You can also provide explicit Name, Action and ReplyAction as shown in the example below.
Can you apply, ServiceContract attribute to a class rather than an interface in WCF?
Yes, a ServiceContract attribute can be applied either to a class or an interface, but defining service contracts using interfaces rather classes has the following benifits.

1. Defining service contracts using interfaces, removes coupling to service implementation. Later the implementation can be changed at will without affecting the clients.
2. Defining service contracts using interfaces, also allows a service to implement more than 1 contract.



What is the purpose of MessageParameter attribute in WCF?
MessageParameter attribute is used to control the parameter and returned object names from a service operation. Consider the example below. On the service side, the method parameter name in SaveCustomer([MessageParameter(Name = "Customer")] Customer cust) is cust. If we donot use MessageParameter attribute, then "cust" is what is exposed as parameter name to the client, which is not very proffesional. So we are using MessageParameter attribute to expose the method parameter name as Cutomer


 What are the different options available to serialize complex types that are sent and received betweclients and services in WCF?
The following are the different options available to serialize complex types that are exchanged between clients and services in WCF. These options have their own advantages and disadvanatages. Data contracts is the preferred way to serialize complex types in WCF.
1. Serializable types - Us the Serializable attribute on the type that you want to serialize
2. Data contracts - Use DataContract attribute on the type and DataMember attribute on every member of the type, that you want to serialize. You can apply DataMember attribute either on a filed or a property.
3. Known types - Use Known types to enable polymorphic behavior in service contracts.
4. IXmlSerializable - IXmlSerializable types provide XSD schema to Web Services Description Language (WSDL) and metadata exchange (MEX).


What is the disadvantage of using Serializable attribute to serialize a complex type that is sent and received between clients and services in WCF?
When we decorate a class with Serializable attribute, all the fields of the class are serialized regardless of the accessibility. We donot have control on what to serialize and what not to serialize. We also will not have any control over naming conventions or data types.


What is the preferred way for serializing complex types in WCF?
The preferred way for serializing complex types in WCF is to use data contracts. Using Data Contracts provides us with the following advantages.
1. Using DataMember attribute, you can control which members of the class to serialize.
2. You can also control the order in which members are serialized using Order parameter of the DataMember attribute..
3. You can also provide explicit Name to the serialized members using Name parameter of the DataMember attribute.
4. You can also specify if a member is required or optional using IsRequired parameter of the DataMember attribute.


Consider the example below which uses Name, IsRequired and Order parameters of the DataMember attribute to serialize CustomerId property. By the way DataMember attribute can be used with either fields or properties. If you donot specify the order in which members are serialized, then by default alphabetical ordering is done by the DataContractSerializer.
















What is the best way to serialize Polymorphic Types in WCF?
The best way to serialize Polymorphic Types in WCF is to use KnownType attribute on the parent type as shown in the example below. CorporateCustomer and PremiumCustomer classes inherit from Customer class, and hence we can associate CorporateCustomer and PremiumCustomer types as known types in 3 different ways depending on the project requirement.


1. Associate known types to the base types themselves.
2. Associate known types to particular operations.
3. Associate known types to the service contract as a whole.


In Example 1, we are associating known types, CorporateCustomer and PremiumCustomer to the base type, Customer.




In Example 2, we are associating known type, CorporateCustomer on SaveCorporateCustomer(Customer customer) and GetCorporateCustomer(int CustomerId) operations using ServiceKnownType attribute.




In Example 3, we are associating known types, CorporateCustomer and PremiumCustomer to the service contract ICustomerService as a whole.




It is also possible to specify known types in a configuration file rather than in code. Example 4 shows how to specify known types in configuration.file.




Explain the significane of MessageContract attribute?
                                            OR
Why and When do you use MessageContract attribute?


There are several advantages of using MessageContract attribute in WCF. MessageContract attribute can be used for
1. Adding custom headers to the message.
2. Controling message wrapping.
3. Controling signing and encryption of messages.


MessageContract attribute provides us with greater control over message headers and body elements. MessageContract attribute converts a type to a SOAP message. The example below shows how to use IsWrapped and ProtectionLevel parameters of MessageContract attribute. You may also set an explicit Name and Namespace.




MessageContract attribute is supported by MessageHeader attribute and MessageBodyMember attribute. You can apply MessageHeader attribute to fields or properties of message contract. This is a simple technique for creating custom headers.You can provide Name, Namespace and ProtectionLevel. You may also set SOAP protocol settings like Relay, Actor, MustUnderstand.


MessageBodyMember attribute can also be Applied to fields or properties of message contract.Can have several body elements. This is equivalent to multiple parameters in operation and this is the only way to return multiple complex types. It is suggested as a good practice to always supply Order. You can also set Name, Namespace, ProtectionLevel. The example below shows how to use MessageHeader and MessageBodyMember attributes.



What is WS-Policy?
             OR
What is Web Services Policy?
Web Services Policy or WS-Policy is an interoperable standard for describing policies that influence communication with the clients. Usually WS-Policy is included in the WSDL contract exposed by the WCF service, although it is optional.


What is the use of WS-Policy?
WS-Policy is generally used for
1. Describing protocols for accessing operations
2. Security
3. Reliable messaging
4. Transactions
5. Message encoding (Message Transmission Optimization Mechanism [MTOM])
6. Other protocols


You can specify the above settings in WSDL directly without a policy section, but the disadvantage is that, once published, the WSDL contract is final. If the clients has to communicate with a WCF service that has changed the settings in the WSDL, the clients need to rebuild the proxy and configuration or atleast the changes to the WSDL contract must support backward compatibility.


The advantage of using WS-Policy is that it can change over time, and the clients can discover the changed policy to communicate via metadata exchange. But keep in mind that, you can only change the policy safely if clients are positioned to handle dynamic changes.
Are WCF Contracts version tolerant?
Yes, WCF contracts are version tolerant by default. Service contracts, data contracts, and message contracts forgive missing and non required data. They also Ignore any superfluous or additional data sent by the client to the service. The DataContractSerializer provides tolerance. Reasonable changes can be made without impacting existing clients.


The following table summarizes the changes to a service contract and impact on existing clients.


What are bindings in WCF?
Bindings in WCF define the configuration of communication channel between clients and services. Binding specifies
1. Transport Protocol
2. Message encoding
3. Security Mechanism
4. Reliable Messaging
5. Transactions Support

What are different Transport protocols available in WCF?
1. TCP
2. HTTP
3. Named Pipes
4. MSMQ

What message encoding formats are available in WCF?
1. Text - For interoperability
2. MTOM (Transmission Optimization Mechanism) - For transfering large objects
3. Binary - For speed

What are the 2 ways available for configuring bindings in WCF?
1. Declaratively using a configuration file
2. Programatically in the code.

Using configuration file has several advantages.

List a few standard bindings available in WCF?
1. BasicHttpBinding
2. NetPeerTcpBinding
3. WSFederationHttpBinding
4. NetNamedPipeBinding
5. WSHttpBinding
6. WSDualHttpBinding
7. NetTcpBinding
8. NetMsmqBinding
9. MsmqIntegrationBinding

Can you create a customized binding in WCF?
Yes, bindings in WCF are completely extensible and we can create a customized one