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.


It is a Software development kit for developing services on Windows. WCF is introduced in .NET 3.0. In the  System. Service Model namespace. WCF is based on basic concepts of Service oriented architecture (SOA)

1.What is the diff between WCF and ASMX?
Simple and basic difference is that ASMX or ASP.NET web service is designed to send and receive messages using SOAP over HTTP only. While WCF can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, NamedPipes etc).

2.What are the WCF Service endpoints?
For Windows Communication Foundation services to be consumed, it’s necessary that it must be exposed; Clients need information about service to communicate with it. This is where service endpoints play their role.
WCF service endpoint has three basic elements i.e. Address, Binding and Contract.
  • Address: It defines "WHERE". Address is the URL that identifies the location of the service.
  • Binding: It defines "HOW". Binding defines how the service can be accessed.
  • Contract: It defines "WHAT". Contract identifies what is exposed by the service.
3.What are the possible ways of hosting wcf?
For a Windows Communication Foundation service to host, we need at least a managed process, a ServiceHost instance and an Endpoint configured. Possible approaches for hosting a service are:
  1. Hosting in a Managed Application/ Self Hosting
    1. Console Application
    2. Windows Application
    3. Windows Service
  2. Hosting on Web Server
    1. IIS 6.0 (ASP.NET Application supports only HTTP)
    2. Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP, NamedPipes, MSMQ.
4.How we can achieve operation over loading?
By default, WSDL doesn’t support operation overloading. Overloading behavior can be achieved by using "Name" property of OperationContract attribute
[ServiceContract]
    public interface IService1
    {
        [OperationContract(Name = "SumInt")]
        int Sum(int arg1, int arg2);

        [OperationContract(Name = "SumDouble")]
        double Sum(double arg1, double arg2);
    }
When the proxy will be generated for these operations, it will have 2 methods with different names i.e. SumInt and SumDouble.

5.What Message patterns(MEP's) supported by wcf?
       1. Request/Response 2. One Way 3. Duplex

Request/Response

It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body.

One Way

In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. OneWay MEP will work in such scenarios. If we want queued message delivery, OneWay is the only available option.

Duplex

The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed.

6.What is DataContract Serializer,and how it's diff from xml serializer?
Serialization is the process of converting an object instance to a portable and transferable format. So, whenever we are talking about web services, serialization is very important.
Windows Communication Foundation has DataContractSerializer that is new in .NET 3.0 and uses opt-in approach as compared to XmlSerializer that uses opt-out. Opt-in means specify whatever we want to serialize while Opt-out means you don’t have to specify each and every property to serialize, specify only those you don’t want to serialize. DataContractSerializer is about 10% faster than XmlSerializer but it has almost no control over how the object will be serialized. If we wanted to have more control over how object should be serialized that XmlSerializer is a better choice.

7.How we can use messageContract partially,with a datacontract for a service operation in wcf?
MessageContract must be used all or none. If we are using MessageContract into an operation signature, then we must use MessageContract as the only parameter type and as the return type of the operation.
8. Which standard binding could be used for a service that was designed to replace an existing ASMX web service?
The basicHttpBinding standard binding is designed to expose a service as if it is an ASMX/ASP.NET web service. This will enable us to support existing clients as applications are upgrade to WCF.

9.Explain diffarent instance modes in wcf?
WCF will bind an incoming message request to a particular service instance, so the available modes are:
  • Per Call: instance created for each call, most efficient in term of memory but need to maintain session.
  • Per Session: Instance created for a complete session of a user. Session is maintained.
  • Single: Only one instance created for all clients/users and shared among all.Least efficient in terms of memory.
10.difference between Transport and Message Level Security.?
In Windows Communication Foundation, we can configure to use security at different levels
a. Transport Level security means providing security at the transport layer itself. When dealing with security at Transport level, we are concerned about integrity, privacy and authentication of message as it travels along the physical wire. It depends on the binding being used that how WCF makes it secure because most of the bindings have built-in security.
<netTcpBinding>
            <binding name="netTcpTransportBinding">
               <security mode="Transport">
                          <Transport clientCredentialType="Windows" />
               </security>
            </binding>
       </netTcpBinding>
b. Message Level Security For Tranport level security, we actually ensure the transport that is being used should be secured but in message level security, we actually secure the message. We encrypt the message before transporting it.
          <wsHttpBinding>
             <binding name="wsHttpMessageBinding">
               <security mode="Message">
                    <Message clientCredentialType="UserName" />
               </security>
              </binding>
          </wsHttpBinding>
It totally depends upon the requirements but we can use a mixed security mode also as follows:
          <basicHttpBinding>
             <binding name="basicHttp">
               <security mode="TransportWithMessageCredential">
                          <Transport />
                               <Message clientCredentialType="UserName" />
               </security>
             </binding>
           </basicHttpBinding>

Diff between WebService,WCF,WCF Rest and WebApi

WebService
·         It is based on SOAP and return data in XML form.
·         It support only HTTP protocol.
·         It is not open source but can be consumed by any client that understands xml.
·         It can be hosted only on IIS.

WCF
·         It is also based on SOAP and return data in XML form.
·         It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
·         The main issue with WCF is, its tedious and extensive configuration.
·         It is not open source but can be consumed by any client that understands xml.
·         It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest
·         To use WCF as WCF Rest service you have to enable webHttpBindings.
·         It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
·         To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
·         Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
·         It support XML, JSON and ATOM data format.

 WebApi
·         This is the new framework for building HTTP services with easy and simple way.
·         Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
·         Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
·         It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
·         It can be hosted with in the application or on IIS.
·         It is light weight architecture and good for devices which have limited bandwidth like smart phones.

·         Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

Simple WCF Restfull Service code with endpoints


IService1

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetAllEmployeeDetails")]
List<Employee> GetAllEmployeeDetails();

Service1.Svc.Cs
public List<Employee> GetAllEmployeeDetails()
{
   List<Employee> objList = new List<Employee>();
   string conStr = string.Empty;
   conStr = "Data Source=INHYDSPARSHIMON\\SQL2012;Initial Catalog=SMPL;User ID=sa;Password=p@ssw0rd";
   using (SqlConnection con = new SqlConnection(conStr))
   {
     using (SqlDataAdapter cmd = new SqlDataAdapter("Select * from tbl_Customer", con))
      {
         DataSet ds = new DataSet();
         cmd.Fill(ds, "tbl");
         for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
         {
              Employee obj = new Employee();
              obj.Id = Convert.ToInt32(ds.Tables[0].Rows[i]["Id"].ToString());
              obj.Customer = ds.Tables[0].Rows[i]["Customer"].ToString();
              obj.CompanyName = ds.Tables[0].Rows[i]["CompanyName"].ToString();
              obj.ContactTitle = ds.Tables[0].Rows[i]["ContactTitle"].ToString();
              obj.Address = ds.Tables[0].Rows[i]["Address"].ToString();
              objList.Add(obj);
         }
       }
     }
     return objList;
   }

Endpoints Setting
<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service behaviorConfiguration="Default" name="AES.Service1">
        <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="AES.IService1"/>
        <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="Default">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
        </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
</system.serviceModel>

Output
[{"Address":"Hyderguda,Attapur,Hyderabad","CompanyName":"Shapar Technologies","ContactTitle":"SHPR","Customer":"Shankar","Id":1},{"Address":"Indranagar,Hyderabad","CompanyName":"Marri IT","ContactTitle":"MR","Customer":"Karthik","Id":2}]

Types Of Contracts
[ServiceContract]
A service contract defines the operations which are exposed by the service to the outside world. A service contract is the interface of the WCF service and it tells the outside world what the service can do. It may have service-level settings, such as the name of the service and namespace for the service.
[ServiceContract]
    public interface IService1
    {     
        [OperationContract]
        string GetData(int value);
     }


[OperationContract] An operation contract is defined within a service contract. It defines the parameters and return type of an operation. An operation contract can also defines operation-level settings, like as the transaction flow of the op-eration, the directions of the operation (one-way, two-way, or both ways), and fault contract of the operation.
  [FaultContract(typeof(MyFaultContract))]
  [OperationContract]
  string MyMethod();

[DataContract]
A data contract defines the data type of the information that will be exchange be-tween the client and the service. A data contract can be used by an operation contract as a parameter or return type, or it can be used by a message contract to define elements.
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;        
        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }
    }
[MessageContract]
When an operation contract required to pass a message as a parameter or return value as a message, the type of this message will be defined as message contract. A message contract defines the elements of the message (like as Message Header, Message Body), as well as the message-related settings, such as the level of message security. Message contracts give you complete control over the content of the SOAP header, as well as the structure of the SOAP body.
[OperationContract]
        double CalPrice(PriceCalculate request);
[MessageContract]
    public class PriceCalculate
    {
        [MessageHeader]
        public string SoapHeader { get; set; }
        [MessageBodyMember]
        public string PriceCalculation { get; set; }
    }

[FaultContract]
A fault contract defines errors raised by the service, and how the service handles and propagates errors to its clients. An operation contract can have zero or more fault contracts associated with it.
      [FaultContract(typeof(MyFaultContract1))]
        [FaultContract(typeof(MyFaultContract2))]
        [OperationContract]
        string MyMethod();

List of WCF Bindings
1.BasicHttpBinding 
is designed to replace ASMX Web services. It supports both HTTP and Secure HTTP. As far as encoding is concerned, it provides support for Text as well as MTOM encoding methods. BasicHttpBinding doesn’t support WS-* standards like WS-Addressing, WS-Security and WS-ReliableMessaging.

2.WsHttpBinding 
also supports interoperability. With this binding, the SOAP message is, by default, encrypted. It supports HTTP and HTTPS. In terms of encoding, it provides support for Text as well as MTOM encoding methods. It supports WS-* standards like WS-Addressing, WS-Security and WS-ReliableMessaging. By default, reliable sessions are disabled because it can cause a bit of performance overhead.
3.WsDualHttpBinding 
has all features of WsHttpBinding with addition that it supports Duplex MEP (Message Exchange Pattern). In this MEP, service can communicate with client via callback. Its basically a two way communication.
4.WsFederationHttpBinding
is a specialized form of WS Binding that offers support for federated security.
                                              Single Computer Scenario
If our WCF service resides on a single computer, then netNamedPipeBinding will be the best choice.
5.NetNamedPipeBinding
is secure and reliable binding on a single WCF computer across process communication. It provides support for binary encoding which is the best choice in this scenario and uses named pipes as transport for SOAP messages.
                   Intranet/Cross Computers .NET Communication Scenario
If we need to communicate across computers with same .NET technology on intranet, then netTcpBinding or netPeerTcpBinding options are available. It’s basically the replacement or enhancement of earlier .NET Remoting technology.
6.NetTcpBinding 
supports reliability, transactions and security. It also supports TCP protocol and binary as encoding method. We can say that it’s the most optimized or fastest binding because both client and service are on the same WCF technology.
7.NetPeerTcpBinding 
upports features as that of netTcpBinding but it provides secure binding for peer-to-peer environment with WCF Services.
8.NetMsmqBinding 
is required in a cross machine environment with secure and reliable queued communication. This uses MSMQ as transport.

No comments: