WCF - Windows Communication Foundation




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.
WsHttpBinding 
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.
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.
WsFederationHttpBinding
Is a specialized form of WS Binding that offers support for federated security
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
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.
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
NetPeerTcpBinding
Supports features as that of netTcpBinding but it provides secure binding for peer-to-peer environment with WCF Services
NetMsmqBinding
Is required in a cross machine environment with secure and reliable queued communication. This uses MSMQ as transport
Concurrency Mode
Single Concurrency Mode
When the service is set to Single Concurrency Mode, each instance context is allowed to have a maximum of one thread processing messages at the same time. In other words, WCF will provide synchronization with the service instance and not allow concurrent calls with a synchronization lock. In short only one request will proceed at any time and the next request must wait until the first request does not proceed.
Every incoming request must try to acquire the sync lock; if no lock is found then it allows access to the service and this request makes a sync   lock. When finished operations, WCF will unlock the sync lock and allow other requests to come in.
Multiple Concurrency Mode
When the service is set to Multiple Concurrency Mode, the service allows multiple accesses at the same time. Simply service instance is not associated with any sync lock. So that concurrent calls are allowed on the service instance. WCF does not create any queue for client messages and replays them as soon as they arrive. Each service has multiple threads processing messages concurrently. The service implementation must be thread-safe to use this concurrency mode.

With Concurrency Mode Multiple, threads can call an operation at any time. It is our responsibility to guard our state with locks.
Reentrant Concurrency Mode
The Reentrant concurrency mode is nothing but a modified version of the single concurrency mode. Similar to single concurrency, reentrant concurrency is associated with a service instance and also sync lock. So that a concurrent call on the same instance is never called. In other words multiple calls on the same instance is not allowed
Instance Context Mode
PerCall
When a service is configured PerCall, every client gets a new service instance
1. Client calls the proxy and proxy forwards the call to service
2. WCF creates an instance and calls the method call.
3. When method call returns, WCF calls IDisponsible if implemented.
Benefits :
• Less Memory consumption
• Increased throughput
• Concurrency is not an issue
PerSession
WCF maintains a logical session between client and service in Persession instance mode. A new instance of the service class is created for each client
Benefits of PerSession: The state is maintained by a service instance.
Drawbacks of PerSession
1. Less throughput, greater memory consumption
2. Concurrency issues for multithreaded clients
Single (SingleTon)
When we configure a service as a singleton, all clients are connected to a single instance context. We configure a singleton service by setting the InstanceContextMode property as single. Only one instance is created upon creation of a service host. This instance is forever for the service. Another service instance is created only when we reset the IIS or when the service host is shut down


WEB API using WCF

IProductService

using CompanyModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace CompanyService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IProductService
    {
        // WebGet attribute is used to make GET request in WCF REST service
        [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetAllProducts")]
        IEnumerable<ProductModel> GetAllProducts();

        // WebInvoke attribute is used to make POST, DELETE and PUT request in WCF REST service
        [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "POST", UriTemplate = "AddProduct")]
        void AddProduct(ProductModel product);

        [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "DELETE", UriTemplate = "DeleteProduct")]
        void DeleteProduct(int id);

        [WebInvoke(ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "PUT", UriTemplate = "EditProduct")]
        void EditProduct(ProductModel product);

        [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetProductCount")]
        int GetProductCount();
    }
}

Web.config

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <!--<protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>-->
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service name="CompanyService.ProductService">
        <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="CompanyService.IProductService">
          <!--<identity>
            <dns value="localhost" />
          </identity>-->
        </endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:57694/ProductService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>


Message Contract


using System.ServiceModel;

namespace CompanyModel.Services
{
    [ServiceContract]
    public interface IBCRoutingService
    {
        [OperationContract]
        BCRoutingResponseMessage StartBCRouting(BCRoutingRequestMessage request);

        [OperationContract]
        BCRoutingResponseMessage ApprovedBCRouting(BCRoutingRequestMessage request);

        [OperationContract]
        BCRoutingResponseMessage DeniedBCRouting(BCRoutingRequestMessage request);

        [OperationContract]
        BCRoutingResponseMessage CanceledBCRouting(BCRoutingRequestMessage request);

        [OperationContract]
        BCRoutingResponseMessage ReSendBCRouting(BCRoutingRequestMessage request);

        [OperationContract]
        BCRoutingResponseMessage FetchBCReviewDetails(BCRoutingRequestMessage request);

    }

    [MessageContract(IsWrapped = false)]
    public class BCRoutingResponseMessage
    {
        [MessageBodyMember]
        public bool IsRoutingStarted { get; set; }

        [MessageBodyMember]
        public List<BcReviewAttachment> AttachedDocList { get; set; }

        [MessageBodyMember]
        public List<BcReviewerStatus> ReviewerList { get; set; }
    }

    [MessageContract(IsWrapped = false)]
    public class BCRoutingRequestMessage
    {
        [MessageBodyMember]
        public int ModelID { get; set; }

        [MessageBodyMember]
        public int BCStatus { get; set; }

        [MessageBodyMember]
        public List<BcReviewAttachment> ReviewAttachDocList { get; set; }

        [MessageBodyMember]
        public int ModelUserID { get; set; }

        [MessageBodyMember]
        public int UserID { get; set; }

        [MessageBodyMember]
        public List<BcReviewerStatus> ReviewerList { get; set; }

        [MessageBodyMember]
        public string OneLinkNo { get; set; }

        [MessageBodyMember]
        public string StrategyNo { get; set; }

        [MessageBodyMember]
        public string TemplatePath { get; set; }

        [MessageBodyMember]
        public string IdendifiyingTemplateName { get; set; }

        [MessageBodyMember]
        public string DocumentPath { get; set; }

        [MessageBodyMember]
        public string ModelURLPath { get; set; }

        [MessageBodyMember]
        public string BCReviewStatus { get; set; }

    }

    public class BCRoutingService : IBCRoutingService
    {
        public BCRoutingResponseMessage StartBCRouting(BCRoutingRequestMessage request)
        {
            BCRoutingResponseMessage response = new BCRoutingResponseMessage();
        }
    }


}

WCF Server Web.config


<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding maxBufferPoolSize="2147483647"
          maxReceivedMessageSize="2147483647"
          maxBufferSize="2147483647" transferMode="Buffered" receiveTimeout="00:10:00" sendTimeout="00:10:00">
         <security mode="Transport"></security>
        </binding>
      </basicHttpBinding>
    </bindings>
      
       <behaviors>
      <serviceBehaviors>
       <behavior name="costmodelBehaviour">
          <!-- To avoid disclosing metadata information,
          set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
          <!-- To receive exception details in faults for debugging purposes,
          set the value below to true.  Set to false before deployment
          to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <services>
      <service name="CostModel.Services.MasterDataService" behaviorConfiguration="costmodelBehaviour">
        <endpoint address="" binding="basicHttpBinding" contract="CostModel.Services.IMasterDataService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/MasterDataService/MasterDataService/" />
          </baseAddresses>
        </host>
      </service>

      <service name="CostModel.Services.CostModelService" behaviorConfiguration="costmodelBehaviour">
        <endpoint address="" binding="basicHttpBinding" contract="CostModel.Services.ICostModelService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/MasterDataService/CostModel/" />
          </baseAddresses>
        </host>
      </service>



      <service name="CostModel.Services.DepartmentBreakDownService" behaviorConfiguration="costmodelBehaviour">
        <endpoint address="" binding="basicHttpBinding" contract="CostModel.Services.IDepartmentBreakDownService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/MasterDataService/DepartmentBreakDownService/" />
          </baseAddresses>
        </host>

      </service>

   </services>
</system.serviceModel>

WCF Client Web.config


<system.serviceModel>
  <bindings>
    <basicHttpBinding>
      <binding name="BasicHttpBinding_IDepartmentBreakDownService" maxReceivedMessageSize="1000000">
        <security mode="Transport">
        </security>
      </binding>
      <binding name="BasicHttpBinding_ICostModelService" receiveTimeout="00:10:00" sendTimeout="00:10:00">
        <security mode="Transport">
        </security>
      </binding>
    </basicHttpBinding>
  </bindings>

  <client>
    <endpoint address="https://nfscm-dev.appl.kp.org:444/Services/CostModel.Services.DepartmentBreakDownService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IDepartmentBreakDownService" contract="DepartmentBreakDownService.IDepartmentBreakDownService" name="BasicHttpBinding_IDepartmentBreakDownService" />
    <endpoint address="https://nfscm-dev.appl.kp.org:444/Services/CostModel.Services.CostModelService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ICostModelService" contract="CostModelService.ICostModelService" name="BasicHttpBinding_ICostModelService" />
  </client>

</system.serviceModel>  

Comments

Popular posts from this blog

WEB API

MVC