Category Archives: WCF


How does HTTPS works?

How does HTTPS works?

  1. Client request for secure Https  page.
  2. Web server respond by sending certificate with public key.
  3. Client checks the validity of the certificate and create a symmetric session key using the public key and sends it back to Web serer.
  4. Web server decrypt the symmetric session key using it’s private key and sends page encrypted using the symmetric session key.
  5. Secure session has now been established between Client browser & Web server.


HTTPS pages typically use one of two secure protocols to encrypt communications – SSL (Secure Sockets Layer) or TLS (Transport Layer Security). Both the TLS and SSL protocols use what is known as an ‘asymmetric’ Public Key Infrastructure (PKI) system. An asymmetric system uses two ‘keys’ to encrypt communications, a ‘public’ key and a ‘private’ key. Anything encrypted with the public key can only be decrypted by the private key and vice-versa.

The ‘private’ key should be kept strictly protected and should only be accessible the owner of the private key. In the case of a website, the private key remains securely ensconced on the web server. Conversely, the public key is intended to be distributed to anybody and everybody that needs to be able to decrypt information that was encrypted with the private key.



Leave a comment

Filed under .Net, ASP.Net, C#, WCF

When to use Channel factory in WCF

If you are using assembly-sharing (which is, let’s face it, hugely convenient if you own both ends of the pipe), then both ends already have a complete version if the interface etc. It seems redundant to run the svcutil tool (at command-prompt or via the IDE) just to get back a wrapper for what we already have. It also works very well when you want to code only to an interface, not to the wrapper class – and use some centralised code to get a channel to a particular interface at a given address. This is actually how I mainly use WCF.

The “client” approach works well for one-off services, or where it doesn’t need to go through any central tooling. It also makes for very simple demos.

How to: Use the ChannelFactory

Leave a comment

Filed under WCF

EmitDefaultValue Significance

In .Net, types have default value. Like for reference type default value is null, and for integer type default value is 0.
It is desirable to omit data member from serialized data which is set to it’s default value as a performance advantage.

To omit a member from serialised data, set the EmitDefaultValue property of the attribute to false. Default is true.

public class Employee
    public string employeeName = null;

    public int employeeID = 0;

    [DataMember(EmitDefaultValue = false)]
    public string position = null;

    [DataMember(EmitDefaultValue = false)]
    public int salary = 0;

    [DataMember(EmitDefaultValue = false)]
    public int? bonus = null;

    [DataMember(EmitDefaultValue = false)]
    public int targetSalary = 57800;

XML Representation

   <employeeName xsi:nil="true" />

Data Member Default Values

Leave a comment

Filed under WCF

Channel Factory

What is Channel Factory
There are three ways to create a WCF client:

  1. Proxy – Using VS or SvcUtil.exe
  2. WCF Channel Factory
  3. REST services, using HttpClient or WebClient

A Channel Factory enables you to create a communication channel to the service without a proxy.
A Channel Factory is implemented by the IChannelFactory Interface.
The Channel Factory class is useful when you want to share a common service contract DLL between the client and the server.

Using the ChannelFactory<T> class is an easier alternative to making calls to the WCF services to the laborious process of generating proxies via the SvcUtil.exe tool every time a service contract changes. Channel Factory is a factory for creating service communication channels at runtime.
ChannelFactory<T> takes a generic parameter of the service type (it must be a service contract interface) to create a channel.

For using channel factory, the following steps are necessary:

  • Create a binding in WCF
  • Create a ChannelFactory class
  • Create a Channel
  • Send-Receive messages over that channel
public interface IService1

    string GetData(int value);


How to Call WCF Service Use Channel Factory

//1. Create a binding  in WCF
BasicHttpBinding myBinding = new BasicHttpBinding();
EndpointAddress myEndpoint = new EndpointAddress("http://localhost:3047/Service1.svc");

//2. Create a ChannelFactory class
ChannelFactory myChannelFactory = new ChannelFactory(myBinding, myEndpoint);
//3. Create a Channel
IService1 instance = myChannelFactory.CreateChannel();

//4. Send-Receive messages over that channel


Difference between proxy and channel factory

PROXY Channel Factory
1 Only require URL where the service resides You must have direct access to the assembly that contains that service contract T for
2 Very Simpler Not easier
3 Easy to Understand channels are complex, network-related
4 There is Visual Studio gives you add the reference When you share a common service contract dll between the client and the server, you’ll be using the ChannelFactory class
5 Proxies have several restrictions like:

  1. Properties need to have gets and sets
  2. Contructors can’t be exposed
  3. Methods other than the service contract cannot be exposed
If you know that your entities will not change much and the client code is less, then a DLL would work better than a proxy
6 By using SVCutil.exe you will create PRoxy When you are using DLL that refers Service contract interface then use the channel factory class

When to use a ChannelFactory i.e. a shared DLL?

A DLL is helpful if the client code is under you control and you’d like to: share more than just the service contract with the client — such as some utility methods associated with entities and make the client & the service code more tightly bound. If you know that your entities will not change much and the client code is less, then a DLL would work better than a proxy. Proxies have several restrictions like:

  1. Properties need to have gets and sets
  2. Contructors can’t be exposed
  3. Methods other than the service contract cannot be exposed

What all to package in the DLL?

You’ll need to package the following:

  1. Entities
  2. Service contract — the interface
  3. RequestMsg classes (if any)
  4. ResponseMsg classes (if any)

So if you are designing a connected system and using WCF for that, then you can use a shared dll instead of a proxy, to avoid code repetition and be more effective in the use of the service entities.


Leave a comment

Filed under WCF

Transaction in WCF

Leave a comment

Filed under WCF

Differences Article

Response.Redirect vs Server.transfer


wcf service over web services.

Leave a comment

Filed under ASP.Net, C#, WCF

Wcf Duplex Contract – Subscriber-Publisher usng wsDualHttpBinding

Any real time Application (like score-card etc) that involves update are follow either of two process i.e Pulling or Pushing.

Pulling– client constantly sending request to server for updates. This implementation works fine when there are frequent updates but pulling can be an overhead when updates are very less.

Pushing– Server sends update to client when available. This is the best approach over pulling where we have very less updates from server.

wsDualHttpBinding is used Pushing implementation.
In .net netTcp & namedPipe binding support bi-directional binding but http not, so in WCF they introduced a new binding wsHttpBinding().
It has two channels, one is client to server & other is server to client.
Here we basically have two contracts,
->one contract which is used by service.
->other is used by Client which is a Callback contract.

[ServiceContract(CallbackContract = typeof(IMessageCallback))]
public interface IMessage

interface IMessageCallback
      [OperationContract(IsOneWay = true)]
      void OnMessageAdded(string message, DateTime timestamp);

Leave a comment

Filed under WCF

WCF Concurrency and Throttling

WCF concurrency tells how it can serve multiple requests at same time.

WCF instance dictates how objects are created.

WCF concurrency dictates how many requests can be handled by WCF objects.

The reasons why we need concurrency are Increase throughput and Integration with a legacy system.

There are three types of WCF Concurrency:

  • Single

Only one request will be processed at any given moment of time. The other request have to wait until the request processed by WCF service is completed.

  • Multiple

Multiple requests can be handled by WCF service object. Requests are handled at the same time by multiple threads on WCF service object but we need to take care of concurrency issues.

  • Reentrant

A single request thread has access to the WCF service object, but the thread can exit the WCF service to call another WCF service or can also call a WCF client through callback and reenter without deadlock.

Below is the example:































Leave a comment

Filed under WCF

WCF Instance Management

WCF can control how WCF service objects are created on WCF server using Wcf Instance. There are three ways of WCF instance creation InstanceContextMode.

  • PerCall (default)
  • PerSession
  • Single


Create a new WCF instance on every WCF client call

public class MyService : IMyService

Ony one WCF instance is created for all the call from a WCF client session.

public class MyService : IMyService

NOTE:- If you doesn’t create Sessionful binding then PerSession will act as PerCall. As a result every request to the service creates a new instance of the service class.


Only one global WCF intance should be created for all WCF clients.

public class MyService : IMyService

Leave a comment

Filed under WCF

Contracts in WCF

WCF Contracts
There are basically four types of contracts:-
1) Service Contracts
It define what operation the client can perform using the Service. There are two types of Service contracts
a) ServiceContract – This attribute defines Interface.
b) OperationCOntract – This attribute defines method of Interface.

2) Data Contract
It defines the data types passed to and from the service. There are two types again:
a) DataContract – This attribute defines the data class.
b) DataMembers – This attribute defines the properties.
If DataMember attributes are not specified for a properties in the class, that property can’t be passed to-from web service.

3) FaultContract
It defines which type of error will be raised by the Service.

4) Message Contract
It allows service to interact directly with Message. Message Contract can be types or untyped.

Leave a comment

Filed under WCF

WCF Security & Types

There are two types of Security implemented in WCF:
Transport Level  :- It means securing the meadiums on which data travels.
Message Level :- It means securing the actual data packets sent by WCF.

Transport median (like HTTP, TCP, MSMQ etc) itself provide security features like HTTP can have SSL security (HTTPS).

Message security is provided using WS-Securities like message encrypted using encryption algo, message encrypted using X-509 certificate, message protected using username/password.

WCF gives option to either use Message/Transport level security standalone or combination of both.

We will implement combination of both below.

Step 1:- Customize WsHttp binding with Security mode & Credential Type
Configure wsHttp binding with Security Mode & Credential Type. There are three options for security mode i.e.
Message &

Now as we are implementing dual security so we will use TransportWithMessageCredential mode where Transport level security is provided by SSL & Message security is provided by Username-Password.
Secondly CredentialType needs to be provided out of
certificate &
issued token

We will be using CredentialType as username.
Below are the changes done in web.config:

<binding name=”Binding1″>
<security mode=”TransportWithMessageCredential”>
<message clientCredentialType=”UserName” />

Step 2:- Create Custom Validator Class
After customizing wsHttp binding, we need to create custom validator class for authentications.
To create the custom validator class you need to inherit it from “UserNamePasswordValidator” class & override Validate() method.

class MyValidator : UserNamePasswordValidator
protected override void Validate(string userName, string password)
if(userName==”Dev” && password=”pass123″)
throw new FaultException(“Invalid Credentials”);

The faultException is handled by WCF client if the credentials are not valid.

Step 3:- Define Runtime behavior.
Now we need to execute MyValidator class for the Username provided inthe WCF service by WCF client. So for this we add behavior

<userNameAuthentication userNamePasswordValidationMode=”Custom”
customUserNamePasswordValidatorType=”MyValidator” />

Step-4 :- Define SSL for your WCF Service
Step 5:- Consume WCF service
Step 6:- Run WCF Service
Above three steps are explained in below link

Leave a comment

Filed under WCF

Exception Handling in WCF


Server Side Exception Handling


Exception Handling in WCF

We basically handle two types of exception in WCF service and covert them to the FaultExcetion<SomeErrorDto> to make client familiar with the exceptions. Let me explain the complete scenario with a sample application XYZ:

Catch (XYZException ex)


       //Convert Application specific (XYZException) exceptions to FaultException<XYZErrorDto>.

       throw ExceptionHelper.HandleXYZToFaultException(ex);


Catch(Exception ex)


      //Convert Generic Exception to FaultException<XYZErrorDto>.

       throw ExceptionHelper.HandleGenericToFaultException(ex);



Our XYZException Class

public class XYZException : System.Exception


    private int _errorCode;

     public int ErrorCode


        get { return _errorCode; }

        set { _errorCode = value; }



    public XYZException(string message, Exception ex)  : base(message, ex)



    public XYZException(string message, int code, Exception ex)  : base(message, ex)


        _errorCode = code;



Our ExceptionHelper class:

using System;

using System.Data.SqlClient;

using System.ServiceModel;


public class ExceptionHelper


    //Used in the BL(Business Logic) layer

    public static XYZException HandleGenericToXYZException(Exception genExcep)


        //Logging the Generic Execption here before converting it to Application specific

       // (XYZException) exception.

        if ((genExcep != null))


            return new XYZException(genExcep . Message, genExcep);




            return null;




    //Convert Application specific Exception to FaultException<XYZErrorDto>

    public static FaultException<XYZErrorDTO> HandleXYZToFaultException(XYZException xyzExcep)


        return HandleGenericToFaultException(xyzExcep);


    //Used in WCF service.

    public static FaultException<XYZErrorDTO> HandleGenericToFaultException(Exception genExcep)


        XYZErrorDTO objXYZErrDTO = new XYZErrorDTO();

        if ((genExcep != null))


            objXYZErrDTO = new XYZErrorDTO(genExcep.Message);




            objXYZErrDTO = new XYZErrorDTO(“An unexpected error has occurred in the system”);


        //Logging the Generic Execption here before converting it to FaultException.

        return new FaultException<XYZErrorDTO>(objXYZErrDTO);




UI Exception Handling


Now it is clear the UI will only receive Exceptions of type FaultException only from server, moreover we need to handle the Generic exception raised at the UI also. So if the UI code logic involve server resource usage the we have to catch both the exceptions else there will be only catching of general exception as shown below:



     //Logic involve usage of server resources 


Catch (FaultException ex)




Catch (Exception ex)




Our UIExceptionHelper class:

using System.ServiceModel;

using System.Diagnostics.EventLog;

 public class UIExceptionHelper


     public static void HandleFaultException(FaultException<XYZErrorDTO> faultExcep)




            //Logging FaultException before displaying on Screen.          

            LogManager.LogError(faultExcep, errorCode, ConfigurationManager.AppSettings(“LogCategory”));

            WebMsgBox.Show(Decl.WEB_MSG, faultExcep.Detail.Message);


        catch (Exception ex)




     public static void HandleGenericException(Exception excep)




            //Logging the Generic message before redirecting to custom error page.

            string strMsg = excep.Message.Replace(Constants.vbCrLf, ” “);

            string strTrace = excep.StackTrace.Replace(Constants.vbCrLf, ” “);

            LogManager.LogError(excep, errorCode, ConfigurationManager.AppSettings(“LogCategory”));

            //Redirecting to Custom Error Page for Generic Exceptions.

            Response.Redirect(Decl.ERROR_PAGE + “?Error=” + strMsg + “&Trace=” + strTrace);


        catch (Exception ex)






Leave a comment

Filed under C#, WCF

Explanation of WCF web.config

Explanation of WCF web.config class 

<configuration xmlns=”″&gt;



      <service behaviorConfiguration=”returnFaults”>

        <endpoint contract=”IMyService” binding=”wsHttpBinding”/>





        <behavior >

          <serviceDebug includeExceptionDetailInFaults=”true” />

<serviceMetadata httpGetEnabled=”true” />






    <compilation debug=”true”/>



Within the <system.serviceModel> we will host Serivces tag, which will has all services we will have in our project or what we want to expose. 

Within   <Services> we will host service by service

Each service tag has a name attribute “the name of the service class” and “behaviorConfiguration” that specify name of behaviour tag within serviceBehaviors tag

Each service has endpoint (“ABC”) tag with three attributes

Address(“Where”): will be “” empty if the service on the localhost.

Binding(“How”): binding=”wsHttpBinding” we will use http or https for transportation and communication

Contract(What”):the Name of the interface

Within <ServiceBehaviours> there are behaviour tag

<serviceDebug includeExceptionDetailInFaults=”true />

Each behaviour has name attribute so service can find it as mentioned before

serviceDebug includeExceptionDetailInFaults=”true” specify that occurrence of exceptions include details of the exception in the message. 

<serviceMetadata httpGetEnabled=”true” />

To enable service client to get metadata of the service project assembly to view and call service contained types


Leave a comment

Filed under WCF

WCF Transactions

 WCF Transactions

WCF provide the functionality of transactions based on WS specification which allow other language like JAVA to take advantage of this transaction that is the best part of WCF embracing other languages. Under transactions, every activity in the unit must either all succeed or all should fail.

This is achieved by using [TransactionFlow] attribute with different options like:

  • TransactionFlowOption.NotAllowed: This is a default option. Using this option no transaction is applied.
  • TransactionFlowOption.Allowed: This means client can use transaction but it is not compulsory.
  • TransactionFlowOption.Mandatory: This option specifies that client must call the WCF service in a transaction mode. If the WCF service is called without transaction, ‘FaultException’ will be raised. 

Leave a comment

Filed under WCF

SOA with WCF

SOA principle followed by WCF

 1) Boundaries are well defined

client who is consuming the service does not need to know how the implementation of the service is done. like in case of DCOM any changes at server level the client also has to change.

  2) Services Independent

In SOA, services can be versioned and you can setup new endpoint for same service with different requirement.

eg: Service like “Search Tickets (Ticket Number) “which gives details based on Ticket Number and its exposed on end point “ep1”. Tomorrow you want make your Search Tickets service more useful by also providing an extra option of allowing him to search by passenger name. Therefore, you just declare a new end “ep2” with service “Search Tickets (Ticket Number, Passenger Name)”. So the client who is consuming the service at end ep1 continues and at the other end, we have evolved our service by adding new ends ep2.

 3) Services share only schemas and contracts

Services use Schemas to represent data and contracts to understand behavior. They do not use language dependent types or classes in order to understand data and behavior. XML is used to define schemas and contracts. Due to this, there is not heavy coupling between environments. 

4) Service compatibility is policy based

Policy describes the capabilities of the system. Depending on policies, the service can degrade to match the service for the client. For instance your service needs to be hosted for two types of client one which uses Remoting as the communication methodology while other client uses DCOM. An ideal SOA service can cater to both of them according to there communication policies. 

  Note: – Many people assume Web services are the base for SOA. The answer is 50 % right. What web services lack is the policy based Service compatibility. If you host a web service it can only serve with HTTP communication channel and SOAP message. Any other type of client trying to communicate he will not degrade it self. This is what is provided by WCF. You can host the service in one or more mode. For instance you can host a WCF service using remoting and ASMX.

1 Comment

Filed under WCF



  • WCF stands for Windows Communication Foundation.
  • WCF is advanced API (Application Programming Interface) for creating distributed applications using .NET framework.
  • It is introduced in .NET 3.0.
  • WCF API is found in System.ServiceModel namespace.
  • WCF is based on basic concepts of Service oriented architecture (SOA)



They are kind of connections exposed by WCF for communicating with either client applications or other service applications.


Components of WCF application

  • a WCF service
  • a WCF service host
  • a WCF service client


“ABC” of a WCF Service

  • Addresses:   This is location of the service in the form of an URI (Uniform resource Identifier) generally mentioned In the config file.
  • Bindings: This includes the type of network protocol  used by the Service. For Example HTTP, TCP/IP or others.
  • Contracts:  This is in fact the methods exposed by the WCF service.



What are the address formats of the WCF transport schemas? 
Address format of WCF transport schema always follow

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

for example:

HTTP Address Format

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


When a port number is not specified, the default port is 808:


NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.

IPC Address Format

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

Binding Class Name Transport Message Encoding Message Version Security Mode RM Tx Flow*
BasicHttpBinding HTTP Text SOAP 1.1 None X X
WSHttpBinding HTTP Text SOAP 1.2

WS-A 1.0

Message Disabled WS-AT
WSDualHttpBinding HTTP Text SOAP 1.2

WS-A 1.0

Message Enabled WS-AT
WSFederationHttpBinding HTTP Text SOAP 1.2

WS-A 1.0

Message Disabled WS-AT
NetTcpBinding TCP Binary SOAP 1.2 Transport Disabled OleTx
NetPeerTcpBinding P2P Binary SOAP 1.2 Transport X X
NetNamedPipesBinding Named Pipes Binary SOAP 1.2 Transport X OleTx
NetMsmqBinding MSMQ Binary SOAP 1.2 Message X X
MsmqIntegrationBinding MSMQ X** X Transport X X
CustomBinding You decide You decide You decide You decide You decide You decide


For WCF binding comparison, see

1 Comment

Filed under WCF