Wednesday, 17 June 2015

WCF security

While we talk about security following terms play important role.

Authentication : Process of validating/identifying the sender and recipient of the message.

Authorization : Process of determining the rights of authenticated user.

Confidentiality : Process of ensuring that only the intended recipient of the message can view the message.this can be achieved by encrypting the message.

Integrity : Ensuring that the message is not tampered by a malicious user as it is being transmitted from sender to receiver.we can achieve this by signing the message.

By default all the bindings provide above security features except basicHttpBinding.

Following security modes can be used with WCF service.

Transport Security : Securing the transport channel is called transport security. each of the protocol (Http,TCP, MSMQ etc.) have their own way of providing transport security.

For example, TCP provides transport security, by implementing TLS (Transport Layer Security). The TLS implementation is provided by the operating system.

HTTP provides transport security by using SSL(Secure Socket Layer) over http. 

Transport security provides only point-to-point channel security.it means if there is an intermediary (Load balancer, proxy etc.) between, then the intermediary has direct access to content of message.

Message Security : Securing the message itself by encapsulating the security credential with every SOAP message is called message security. as the message itself is protected if provides end to end security.

Mixed transfer security mode : It uses Transport security for message integrity, privacy and service authentication and it uses Message security mode for securing client credential.
One of the disadvantage of the mixed mode is that it will secure only point-to-point as nature of Transport security.

Both security modes: This mode Both transfer security mode uses both Transport security and Message security..

Default security mode in wsHttpBinding is Message Security mode.(encryption and signing of message aromatically attached)
Please refer following table for supported and default security mode of different bindings.

NameNoneTransportMessageMixedBoth
BasicHttpBindingYes(default)YesYesYesNo
NetTcpBindingYesYes(default)YesYesNo
NetNamedPipeBindingYesYes(default)NoNoNo
WsHttpBindingYesYesYes(default)YesNo
WsDualHttpBindingYesNoYes(default)NoNo
NetMsmqHttpBindingYesYesYes(default)NoYes

Following is the SOAP body if security mode is message.Message is both encrypted and signed.

<s:Body u:Id="_0">
<e:EncryptedData Id="_1" Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns:e="http://www.w3.org/2001/04/xmlenc#">
<e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"></e:EncryptionMethod>
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<o:SecurityTokenReference xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<o:Reference ValueType="http://schemas.xmlsoap.org/ws/2005/02/sc/dk" URI="#uuid-3c8a7bb8-acd0-4bbb-8abe-1ea4a214254b-96"></o:Reference>
</o:SecurityTokenReference>
</KeyInfo>
<e:CipherData>
<e:CipherValue>yAMmq3Dv28ukYopUIObISQ3YLRap/o7s77aZPA5UWGcRPmvCxEmDuApNOjPxO+7cMCh7KTYRqovSCg5XFgsnfli6zVhIRXBX76Uh7etSJqyu3M/xs6hTwKXr/W5qIvN0r491vnJnSeiSXkAWpWrJQ/hswZm46tKIVPi9/Uq4hyCnUMQ86Kzg7eP3jxu+6JLj/EPEdjutKNgsL8crv6T2dC9MZBmSo1HgfkTYq/JYBP4=</e:CipherValue>
</e:CipherData>
</e:EncryptedData>
</s:Body>

If we change security mode from default(that is message in wsHttpBinding) to None 

<wsHttpBinding>
        <binding name="wsHttp">          
          <security mode="None"></security>
        </binding>
</wsHttpBinding>

After changing security mode, SOAP body will be as follows.

<s:Body>
<HelloMessageResponse xmlns="http://tempuri.org/">
<HelloMessageResult>HelloRahul!!</HelloMessageResult>
</HelloMessageResponse>
</s:Body>

We can customize the level of protection using ProtectionLevel attribute .











None : No protection.Message is not encrypted and not signed.
Sign : No encryption but is digitally signed to ensure the integrity of message.
EncryptAndSign : Message is encrypted and then signed to ensure confidentiality and integrity of message. 

Following 6 attributes has the ProtectionLevel named parameter.They are specified in the order of precedence.

[ServiceContract]
      [OperationContract]
            [FaultContract]
            [MessageContract]
                  [MessageHeader]
                  [MessageBodyMember]


Note : If we use binding that by default does not support security like basicHttpBinding and we use Protection level other than None, at run time we will get error.




Authentication in WCF


Most binding in WCF provide authentication without any additional configuration.

for example, both wsHttpBinding and netTcpBinding provides windows authentication.

we can check this by using following code.

ServiceSecurityContext.Current.Primaryidentity.IsAuthenticated;
ServiceSecurityContext.Current.Primaryidentity.AuthenticationType;
ServiceSecurityContext.Current.Primaryidentity.Name;

We can set the the authentication type by using clientCredentialType attribute within security tag of binding.

















Friday, 12 June 2015

Multiple Concurrency Mode in WCF

This post is continuation of post Concurrency Mode in WCF. Please visit following link before reading this post.
http://logicsmaze.blogspot.in/2015/06/concurrency-mode-in-wcf.html

Multiple Concurrency Mode in WCF :
With multiple concurrency mode an exclusive lock is not acquired by on the service instance. With multiple concurrency modem multiple threads are are allowed to access the service instance simultaneously and we get better  throughput.

Like single concurrency mode, multiple concurrency mode is not influenced by instance context mode and whether the binding supports session or not.

Concurrency mode can be set by using ConcurrencyMode attribute of [ServiceBehaviour]




Instance Context ModeConcurrency ModeIs Binding Support SessionWill Concurrency Call Processed
PerCallMultipleNoYes
PerCallMultipleYesYes
PerSessionMultipleNoYes
PerSessionMultipleYesYes
SingleMultipleNoYes
SingleMultipleYesYes

For detailed description about other concurrency mode please visit following posts.
Single-concurrency-mode-in-wcf
Multiple-concurrency-mode-in-wcf
Reentrant-concurrency-mode-in-wcf

Thanks :-)

Reentrant Concurrency Mode in WCF

This post is continuation of post Concurrency Mode in WCF. Please visit following link before reading this post.
http://logicsmaze.blogspot.in/2015/06/concurrency-mode-in-wcf.html

The Reentrant concurency mode is nothing but a modified version of a single concurrency mode.Similar to single concurrency, reentrant concurrency exclusively lock the service instance so that a concurrent call on the same instance is never called.
But apart from that, Reentrant concurrency mode allows the service to issue callbacks to the client.And this call back can be two way and re-entrant calls can be accepted by service instance.




If we implement call back scenario, set Concurrency mode Single, as we run client we will get error because call back will be two way and service reference will not serve re-entrant call.

If we set Concurrency mode Single and set IsOneWay = true within [OperationContract], in this scenario call back request go to the client but client can't send call back response to service, so everything will work fine.

   [ServiceContract]

    public interface IReportProgressCallback
    {
        [OperationContract(IsOneWay=true)]
        void ReportProgress(int percentage);
    }

If we want to use two way callback than we need to set concurrency mode reentrant.

For detailed description about other concurrency mode please visit following posts.
Single-concurrency-mode-in-wcf
Multiple-concurrency-mode-in-wcf
Reentrant-concurrency-mode-in-wcf

Thanks :-)

Thursday, 11 June 2015

Concurrency mode in WCF - Single Concurrency Mode in WCF

This post require knowledge of Instance Context Mode in WCF. Please visit following post before reading this post.
http://logicsmaze.blogspot.in/2015/06/instance-context-mode-in-wcf.html

When multiple thread executing the application code simultaneously is called as concurrency.

There are 3 types of concurrency mode in WCF.

1. Single Concurrency Mode
2. Reentrant Concurrency Mode
3. Multiple Concurrency Mode

Concurrency mode can be set by using ConcurrencyMode attribute of [ServiceBehaviour]










The default concurrency mode in WCF is Single.This means only a single thread can access the service instance at any given point of time.An exclusive lock is acquired and all the other threads will have to wait until the current request completes and the lock is released.

Single Concurrency Mode in WCF :

A single request has access to the WCF service object at a given moment of time.So only one request will be proposed at a given moment of time.The other request have to wait  until the request processed by the WCF service is completed.

Whenever a WCF service handles client requests concurrently or not, depends on 3 things.

1.Service Instance Context mode
2. Service Concurrency Mode
3. Whether binding support session or not

Example 1 : If we set ConcurrencyMode Single and InstanceContextMode to PerCall, If used binding does not support session (basicHttpBinding does not support session) then service can processed concurrent call.

Example 2 : If we set ConcurrencyMode Single and InstanceContextMode to PerCall, If used binding support session (netTcpBinding support session) then service can not processed concurrent call.

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single,InstanceContextMode=InstanceContextMode.PerCall)]
   
Following table shows all the combination with Single concurrency mode to show when will concurrency call will processed and not.

Instance Context Mode Concurrency Mode Is Binding Support Session Will Concurrency Call Processed
PerCall Single No Yes
PerCall Single Yes No
PerSession Single No Yes
PerSession Single Yes Yes- Between different client
No-Requests from the same client
Single Single No No
Single Single Yes No
Code Implementation : following are the code implementation for example 1.

// Service Contract
[ServiceContract]
 public interface IService1
    {
        [OperationContract]
        List<int> GetEvenNumber();
        [OperationContract]
        List<int> GetOddNumber();

    }

//Service Implementation

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single,InstanceContextMode=InstanceContextMode.PerCall)]
    public class Service1 : IService1
    {

        public List<int> GetEvenNumber()
        {
            Console.WriteLine("Thread {0} Started GetEvenNumber at {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, DateTime.Now);
            List<int> lstEvenNo = new List<int>();
            lstEvenNo.Add(2);
            lstEvenNo.Add(4);
            lstEvenNo.Add(6);
            lstEvenNo.Add(8);
            lstEvenNo.Add(10);
            Thread.Sleep(1000);
            Console.WriteLine("Thread {0} Completed GetEvenNumber at {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, DateTime.Now);
            return lstEvenNo;
        }

        public List<int> GetOddNumber()
        {
            Console.WriteLine("Thread {0} started GetOddNumber at {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, DateTime.Now);
            List<int> lstOddNo = new List<int>();
            lstOddNo.Add(1);
            lstOddNo.Add(3);
            lstOddNo.Add(5);
            lstOddNo.Add(7);
            lstOddNo.Add(9);
            Thread.Sleep(1000);
            Console.WriteLine("Thread {0} Completed GetOddNumber at {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, DateTime.Now);
            return lstOddNo;
        }
}

Config File :

<services>
      <service name="HelloWCFService.Service1" behaviorConfiguration="mexBehaviour">
        <endpoint address="HelloWCFService" binding="basicHttpBinding" contract="HelloWCFService.IService1"></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:49416/"/>
            <!--<add baseAddress="net.tcp://localhost:9210/"/>-->
          </baseAddresses>
        </host>
      </service>
    </services>

Client Code : Client code is implemented using Windows Form Application.
In following code Background worker is used to send asynchronous request. 

public partial class Concurrency : Form
    {
        SimpleService.Service1Client simpleServiceClient;
        public Concurrency()
        {
            InitializeComponent();
            simpleServiceClient = new SimpleService.Service1Client();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();  
        }

        private void button2_Click(object sender, EventArgs e)
        {
            backgroundWorker2.RunWorkerAsync();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            lstEvenNo.DataSource = null;
            lstOddNo.DataSource = null;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = simpleServiceClient.GetEvenNumber();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lstEvenNo.DataSource = (int[])e.Result;
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = simpleServiceClient.GetOddNumber();
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            lstOddNo.DataSource = (int[])e.Result;
        }
    }

Client/Service Output :
In the below image, when we click EvenNumber and OddNumber button at a time.
See the red highlighted service log, both thread start executing code without waiting to complete other thread.


























For detailed description about other concurrency mode please visit following posts.
Single-concurrency-mode-in-wcf
Multiple-concurrency-mode-in-wcf
Reentrant-concurrency-mode-in-wcf

Thanks :-)

Session Mode in WCF

This post is continuation of post Instance Context Mode in WCF. Please visit following post before reading this post.
http://logicsmaze.blogspot.in/2015/06/instance-context-mode-in-wcf.html

Code to retrieve session ID from the WCF service :
string sessionID = OperationContext.Current.SessionId;

Code to retrieve session ID from the client application :
string sessionID = ocjClient.InnerChannel.SessionId;

Client side and server side session id's are co-related using the reliable session id.

 <binding name="netTCP" receiveTimeout="00:00:20">
          <reliableSession enabled="true"/>
  </binding>

If TCP binding is being used with reliable session is disabled, then the client and server session id's will be different. if reliable session are enabled ,the session id's will be same.

With wsHttpbinding, the session id's are same whether reliable session are  enabled or not.

Session Mode in WCF :

There are three type of session mode enumerator in WCF that we can use with [ServiceContract].













Allowed : This is a default session mode if we does not specified explicitly.In this mode service contract support session if binding supports them.

NotAllowed : If we use this enumerator of session mode, service contract does not support binding that initiate sessions( TCP binding support session so we can't use netTcpBinding binding with this mode of session).

Required : service contract requires a binding that support session.If we use binding that does not support session like basicHttpBinding with session mode Required, following exception will throw.
System.InvalidOperationException : Contract requires session, but binding "BasicHttpBinding" does't support it.

Following are some example with combination of InstanceContextMode, SessionMode and bindings.

Example 1 : Set service InstanceContextMode to Single and SessionMode to Allowed

If we use basicHttpBinding that does not support sessions, the service still works as a singleton service but without session( Without session means if we try to get value of session it will be blank in both slient side and service side).

On the other hand if we use netTcpBinding that support sessions, the service gets a session and continue to work as a singleton service.

Example 2 : Now set SessionMode to Required

If we use netTcpBinding, that support sessions, the service gets a session and continue to work as a singleton service.

On the other hand, if we use basicHttpBinding that does not support sessions, the following exception is throws.
System.InvalidOperationException : Contract requires session, but binding "BasicHttpBinding" does't support it.

You can try more example by changing combination of values of InstanceContextModeSessionMode and bindings.

Related Post : 

Message-exchange-pattern-in-wcf
Different-option-of-hosting-wcf-service
Binding-in-wcf-choosing-right-wcf-service
Hosting WCF with Non-Http protocol
Exchanging-metadata-in-wcf
Some-interesting-facts-about-data-contract
Knowntype-attribute-in-wcf
Associating-knowntype-in-wcf
Message-contract-in-wcf
Exception-handling-in-wcf


Instance-context-mode-in-wcf


Tuesday, 9 June 2015

Instance Context mode in WCF

What does Instance mode means in WCF ?

Whenever a request come to the service, a object of service class is created and this object invoke the respective operations.
"Instance Context mode decide how long the service instance remains on the server."

Now the question is that after returning the response to client what happened with that service object.

Is this destroyed after the response?
Is this remain in server memory forever?
Is this remain on server for session duration of a client.?

There are 3 types of instancing mode.

1. PerCall : Whenever a request comes from client a new object of service class is created every time whether it is a new request or request is coming from same client session.

2. PerSession : A new instance of a service object is created for each new client session and maintained for the duration of the session.If the request again come from same client existing object of service class will serve the request.Data is also persist between service call from same client until session is expired.

3. Single : Only a single object of service class is created and this object is responsible to handle all requests for the lifetime of application whether the request come from same client or different client.


To specify the instancing mode you have to set InstanceContextMode attribute of [ServiceBehavior]









Visit following post for detailed implementation of PerCall , PerSession  and Single instance context mode.

Instance-context-mode-in-wcf
PerCall-instance-context-mode-in-wcf
PerSession-instance-context-mode-in-wcf
Single-instance-context-mode-in-wcf.html

Related Post :

Message-exchange-pattern-in-wcf
Different-option-of-hosting-wcf-service
Binding-in-wcf-choosing-right-wcf-service
Hosting WCF with Non-Http protocol
Exchanging-metadata-in-wcf
Some-interesting-facts-about-data-contract
Knowntype-attribute-in-wcf
Associating-knowntype-in-wcf
Message-contract-in-wcf
Exception-handling-in-wcf
Exception Handling in WCF - SOAP Fault in WCF
Exception Handling in WCF - Unhandled Exception in WCF
Exception Handling in WCF - Creating and Throwing Strongly Typed SOAP Fault


PerCall Instance Context Mode in WCF

This post is continuation of post Instance Context Mode in WCF. Please visit following post before reading this post.
http://logicsmaze.blogspot.in/2015/06/instance-context-mode-in-wcf.html


Whenever the instance context mode for WCF service is set to PerCall, a new instance of the WCF service object is created for every request whether the request come from same client or a different client.

To specify the PerCall instancing mode you have to set InstanceContextMode attribute of [ServiceBehavior] with PerCall enumeration.










Implications of PerCall WCF Service :


  1. Better memory usage as service object freed immediately after the method call returns.
  2. Concurrency not an issue
  3. Application scalability is batter
  4. State not maintained between calls
  5. Performance could be an issue as there as overhead involved in reconstructing the service instance state on each and every memory call.


Detail Code Implementation :

In following code value of variable [i] will be 1 for each call.

[ServiceContract]
    public interface IService1
    {
        [OperationContract]
        int IncrementNumber();
     
    }

 [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
    public class Service1 : IService1
    {
        private int _Number;
        public int IncrementNumber()
        {
            _Number = _Number + 1;
             return _Number;
        }
}

Client Code :

protected void Page_Load(object sender, EventArgs e)
    {
         int i;
         ServiceReference1.Service1Client ocjClient = new ServiceReference1.Service1Client();
         i = ocjClient.IncrementNumber();
         Response.Write("Number After first call :" + i.ToString());
         i = ocjClient.IncrementNumber();
         Response.Write("Number After Second call :" + i.ToString());
         i = ocjClient.IncrementNumber();
         Response.Write("Number After Thisrd call :" + i.ToString());
    }

Output :

Number After first call : 1
Number After first call : 1
Number After first call : 1

Visit following post for detailed implementation of PerCall , PerSession  and Single instance context mode.

Instance-context-mode-in-wcf
PerCall-instance-context-mode-in-wcf
PerSession-instance-context-mode-in-wcf
Single-instance-context-mode-in-wcf.html

Related Post : 

Message-exchange-pattern-in-wcf
Different-option-of-hosting-wcf-service
Binding-in-wcf-choosing-right-wcf-service
Hosting WCF with Non-Http protocol
Exchanging-metadata-in-wcf
Some-interesting-facts-about-data-contract
Knowntype-attribute-in-wcf
Associating-knowntype-in-wcf
Message-contract-in-wcf
Exception-handling-in-wcf


Instance-context-mode-in-wcf





PerSession instance context mode in WCF

This post is continuation of post Instance Context Mode in WCF. Please visit following post before reading this post.
http://logicsmaze.blogspot.in/2015/06/instance-context-mode-in-wcf.html

If the instance context mode in WCF is set to PerSesion, a new instance of the service object is created for each new client session and maintained for the duration of the session.

To specify the PerSession instancing mode you have to set InstanceContextMode attribute of [ServiceBehavior] with PerSession enumeration.









Default session time out is 10 minute.

If you want to Increase/decrease session time out, make following changes in config file.






Note : Once the session is time out, connection of service is closed.As a result, communication channel gets faulted and the client can no longer use the same proxy to communicate with service.

Note : If binding does not support session then the service behave as a PerCall service.
If you are using bascHttpBinding, basicHttpBinding does not support session so client call will be same as PerCall service and state of service object will not be persist.

Implications of PerSession WCF Service :

  1. State maintain between call.
  2. Greater memory consumption as service objects remains in memory until the client session times out.
  3. Concurrency is an issue for multi-threaded clients

Detail Code Implementation :

In following code value of variable [i] will increase in each call.

If you make call from other browser, new session will be created for that client and value of variable [i] will start from 1 and increase in each call.

[ServiceContract]
    public interface IService1
    {
        [OperationContract]
        int IncrementNumber();
     
    }

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
    public class Service1 : IService1
    {
        private int _Number;
        public int IncrementNumber()
        {
            _Number = _Number + 1;
             return _Number;
        }
}

Client Code :

protected void Page_Load(object sender, EventArgs e)
    {
         int i;
         ServiceReference1.Service1Client ocjClient = new ServiceReference1.Service1Client();

         i = ocjClient.IncrementNumber();
         Response.Write("Number After first call :" + i.ToString());

         i = ocjClient.IncrementNumber();
         Response.Write("Number After Second call :" + i.ToString());

         i = ocjClient.IncrementNumber();
         Response.Write("Number After Thisrd call :" + i.ToString());
    }

Output :

Number After first call : 1
Number After first call : 2
Number After first call : 3

Visit following post for detailed implementation of PerCall , PerSession  and Single instance context mode.

Instance-context-mode-in-wcf
PerCall-instance-context-mode-in-wcf
PerSession-instance-context-mode-in-wcf
Single-instance-context-mode-in-wcf.html

Related Topics :

Message-exchange-pattern-in-wcf
Different-option-of-hosting-wcf-service
Binding-in-wcf-choosing-right-wcf-service
Hosting WCF with Non-Http protocol
Exchanging-metadata-in-wcf
Some-interesting-facts-about-data-contract
Knowntype-attribute-in-wcf
Associating-knowntype-in-wcf
Message-contract-in-wcf
Exception-handling-in-wcf
Exception Handling in WCF - SOAP Fault in WCF
Exception Handling in WCF - Unhandled Exception in WCF
Exception Handling in WCF - Creating and Throwing Strongly Typed SOAP Fault

Single instance context mode in WCF

This post is continuation of post Instance Context Mode in WCF. Please visit following post before reading this post.
http://logicsmaze.blogspot.in/2015/06/instance-context-mode-in-wcf.html

If the instance context mode in WCF is set to Single, only a single object of service class is created and this object is responsible to handle all requests for the lifetime of application whether the request come from same client or different client.

To specify the Single instancing mode you have to set InstanceContextMode attribute of [ServiceBehavior] with Single enumeration.









Detail Code Implementation :

In following code value of variable [i] will increase in each call whether call is made from same client or other client.

If you make call from multiple browser, value of [i] will start from last set value of [i].

[ServiceContract]
    public interface IService1
    {
        [OperationContract]
        int IncrementNumber();
     
    }

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class Service1 : IService1
    {
        private int _Number;
        public int IncrementNumber()
        {
            _Number = _Number + 1;
             return _Number;
        }
}

Client Code :

protected void Page_Load(object sender, EventArgs e)
    {
         int i;
         ServiceReference1.Service1Client ocjClient = new ServiceReference1.Service1Client();

         i = ocjClient.IncrementNumber();
         Response.Write("Number After first call :" + i.ToString());

         i = ocjClient.IncrementNumber();
         Response.Write("Number After Second call :" + i.ToString());

         i = ocjClient.IncrementNumber();
         Response.Write("Number After Thisrd call :" + i.ToString());
    }

Output From First browser :

Number After first call : 1
Number After first call : 2
Number After first call : 3

Output From Second browser :

Number After first call : 4
Number After first call : 5
Number After first call : 6



Which design is better PerCall service or PerSession service ?


  1. If you prefer using object orientated programming style, then PerSession should be choice. on the other hand if you prefer SOA style, then PerCall should be your choice.
  2. Decision can also be depends on the application architecture, performance and scalability needs.
  3. PerSession service perform better because the service object does not have to be instantiated on subsequent request whereas PerCall service scale better because the service object destroyed immediately after the method call returns.
Visit following post for detailed implementation of PerCall , PerSession  and Single instance context mode.

Instance-context-mode-in-wcf
PerCall-instance-context-mode-in-wcf
PerSession-instance-context-mode-in-wcf
Single-instance-context-mode-in-wcf.html

Related Post : 

Message-exchange-pattern-in-wcf
Different-option-of-hosting-wcf-service
Binding-in-wcf-choosing-right-wcf-service
Hosting WCF with Non-Http protocol
Exchanging-metadata-in-wcf
Some-interesting-facts-about-data-contract
Knowntype-attribute-in-wcf
Associating-knowntype-in-wcf
Message-contract-in-wcf
Exception-handling-in-wcf
Exception Handling in WCF - SOAP Fault in WCF
Exception Handling in WCF - Unhandled Exception in WCF
Exception Handling in WCF - Creating and Throwing Strongly Typed SOAP Fault

Monday, 8 June 2015

MTOM in WCF - Sending large data in WCF


Let's discuss a scenario,suppose  you want to transfer a large amount of data like .doc file using WCF.

If size of data/file is more than 65546, you will get following error.
"The maximum message size quota for incoming messages(65536) has been exceeded".

Now the solution is to set maxReceivedMessageSize attribute in binding tag to resolve this.



The default message encoding in wcf is Text, which is base64 encodes data. this has the following 2 disadvantages.


  1. Base64 encoding increases the message size by approximately 33%.
  2. Involves additional processing overhead to base64 encode and decode.


To overcome with these disadvantages we have another approach to send large data using WCF.

The preferred approach to send large binary messages in WCF is to use MTOM message encoding.

Following configuration is needed in config file to implement MTOM.



MTOM is an interoperable standard and stand for "Message Transmission Optimization Mechanism".

MTOM does not use base64 encode data.This also means, the additional processing overhead to base64 encode and decode data is removed.hence, MTOM can significantly improve the overall message transfer performance.

With Text message encoding, the binary data is base64 encoded and it is embedded in SOAP envelop.
With MTOM, data is in binary form and this binary data is included as MIME attachment.

Related Topics : 
Message-exchange-pattern-in-wcf
Different-option-of-hosting-wcf-service
Binding-in-wcf-choosing-right-wcf-service
Hosting WCF with Non-Http protocol
Exchanging-metadata-in-wcf
Some-interesting-facts-about-data-contract
Knowntype-attribute-in-wcf
Associating-knowntype-in-wcf
Message-contract-in-wcf
Exception-handling-in-wcf
Exception Handling in WCF - SOAP Fault in WCF
Exception Handling in WCF - Unhandled Exception in WCF
Exception Handling in WCF - Creating and Throwing Strongly Typed SOAP Fault
Instance-context-mode-in-wcf




Friday, 5 June 2015

Message Exchange pattern in WCF - Duplex Pattern

This post is continuation of post "Messasge Exchange pattern in WCF". Please read following post before proceeding this post.
http://logicsmaze.blogspot.co.uk/2015/06/message-exchange-pattern-in-wcf.html 

Duplex message Exchange Pattern :

When client send request to service and request is time consuming like fetching report.While service is executing the request client have to wait for completion of request.But with duplex message exchange pattern, within the execution period of request service can also send messages to client back, like progress percentage of request or which steps is currently executing etc. and client can utilize this data within waiting period.

Duplex message exchange pattern is not supported by basicHttpBinding and wsHttpBinding as well so implementing this you have to use netTcpBinding.

Note : Visit following like to know hou to use netTcpbinding in wcf.

Steps to Implement Duplex message exchanging pattern.

Step 1 : Add new WCF service.      

   [ServiceContract(CallbackContract = typeof(IReportProgressCallback))]  
    public interface IReportService
    {    

        [OperationContract]
        void ProcessReport();      
     
    }
    [ServiceContract]
    public interface IReportProgressCallback
    {
        [OperationContract]
        void ReportProgress(int percentage);
    }

In above code a new service contract for callback should be declared.To link this callback contract with IReportService contract you have to use Callbackcontract attribute of [ServiceContract] (refer highlighted line in above code)

Step 2 : Implement these Interfaces :

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Reentrant)]
public class Service1 : IReportService
    {
 public void ProcessReport()
        {
            for (int i = 1; i < 100; i++)
            {
                Thread.Sleep(100);
                OperationContext.Current.GetCallbackChannel<IReportProgressCallback>().ReportProgress(i);
            }
        }
    }

Note : If you don't use green highlighted lines of code, while using service you will get following error.


Step 3 : Create new client Windows form project.

 [CallbackBehavior(UseSynchronizationContext=false)]
    public partial class Form1 : Form, ReportService.IReportServiceCallback
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Process_Click(object sender, EventArgs e)
        {
            InstanceContext instanceContext=new InstanceContext(this);
            ReportService.Service1Client client = new ReportService.Service1Client(instanceContext);
            client.ProcessReport();
        }

        public void ReportProgress(int percentage)
        {
            TextBox.CheckForIllegalCrossThreadCalls = false;
            textBox1.Text = percentage.ToString() + "% completed";
        }
     
    }

When you run windows application client, output will be like follows:
On clicking Process button, client can display callback messages on text-box and label to show progress report.


















If you want to implement same with One-Way pattern than remove following highlighted lines from existing code and add IsOneWay attribute of [OperationContract] true.

[CallbackBehavior(UseSynchronizationContext=false)]
    public partial class Form1 : Form, ReportService.IService1Callback
{

and


[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Reentrant)]
public class Service1 : IReportService
    {


And use

 [OperationContract(IsOneWay = true)]
        void ProcessReport();

 [OperationContract(IsOneWay=true)]
        void ReportProgress(int percentage);


Now run client with One-Way message exchange pattern.

Related Topics : 
Message-exchange-pattern-in-wcf
Different-option-of-hosting-wcf-service
Binding-in-wcf-choosing-right-wcf-service
Hosting WCF with Non-Http protocol
Exchanging-metadata-in-wcf
Some-interesting-facts-about-data-contract
Knowntype-attribute-in-wcf
Associating-knowntype-in-wcf
Message-contract-in-wcf
Exception-handling-in-wcf
Exception Handling in WCF - SOAP Fault in WCF
Exception Handling in WCF - Unhandled Exception in WCF
Exception Handling in WCF - Creating and Throwing Strongly Typed SOAP Fault
Instance-context-mode-in-wcf