Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Windows Communication Foundation FAQ quick starter Part 2

4.67/5 (60 votes)
24 Jun 2010CPOL15 min read 1  
Windows Communication Foundation FAQ quick starter Part 2

Updated with links of WCF-Part1, WPF, WWF, WCF Tracing FAQ,  8 steps to enable Windows authentication on WCF BasicHttpBinding , Difference between BasicHttpBinding and WsHttpBinding & WCF FAQ Part 3 – 10 security related FAQ, SilverLight FAQ Part 1 & Part 2, LINQ Part1, Part2 & Part3 and One-Many and One-One relationship using LINQ to SQL.

 

Windows Communication Foundation FAQ quick starter - Part 2

 

Introduction

Can you explain duplex contracts in WCF?

How can we host a service on two different protocols on a single server?

How can we use MSMQ bindings in WCF?

Can you explain transactions in WCF?

What different transaction isolation levels provided in WCF?

Can we do transactions using MSMQ?

Can we have two-way communications in MSMQ?

What are Volatile queues?

What are Dead letter queues?
This 10 minutes small video explains how transport security can be implemented using SSL in WCF services.
Image 1


Introduction


In this section we will run through a quick FAQ for WCF. I am sure after reading this you will get a good understanding of the fundamentals of WCF.

Click here to see Windows Communication Framework (WCF) - Part 1

Click here to see Windows Presentation Foundation (WPF)

Click here to see Windows Workflow Foundation (WWF)

Click here to see WCF Tracing FAQ

Click here to see 8 steps to enable Windows authentication on WCF BasicHttpBinding

Click here to see Difference between BasicHttpBinding and WsHttpBinding

Click here to see WCF FAQ Part 3 – 10 security related FAQ

Click here to see 21 Important FAQ SilverLight - Part 1

Click here to see (Animations and Transformations) FAQ SilverLight - Part 2

Click here to see One-Many and One-One relationship using LINQ to SQL

LINQ FAQ Part 1:- LINQNewbie.aspx

LINQ FAQ Part 2:- LINQFAQPart2

LINQ FAQ Part 3:- LINQ FAQ Part 3


Can you explain duplex contracts in WCF?


In duplex contracts when client initiates an operation the server service provides a reference call back Uri back to the client. So the client initiates a call using the proxy class and when server finishes its work it notifies the client using the callback channel. This is called as duplex messaging in WCF. If you remember in the previous question, we had no way to know when the server finished its task.
 

Image 2

 Figure 18:- Duplex Service code


Let us try to understand the duplex concept by doing a small sample. The code snippet is as shown in the above figure. We will extend the previous sample, which was shown in the first question only that now we will provide the notification to the client once the doHugeTask is completed.
The first step is to change the service class. Above is the code snippet of the service class. Again, we have numbered them so that we can understand how to implement it practically line by line. So below is the explanation number by number:-
1 - In the service contract attribute we need to specify the callback contract attribute. This Callback Contract attribute will have the interface, which will define the callback.
2 - This is the interface which client will call. In order that it should be asynchronous, we have defined the one-way attribute on the doHugeTask method.
3 -This is the most important interface. As it forms the bridge of communication between server and client. The server will call the client using Completed method. Client needs to provide implementation for the completed method at the client side and server will call that method once it completes the doHugeTask method.
4 and 5 - In this we implement the Interface Duplex interface and provide implementation for doHugeTask () method.
6 - This is an important step. The OperationContext.Current.GetCallBackChannel will be used to make callback to the client.
7 - We will expose the service using HTTP protocol. In this sample, because we want to do duplex communication we need to use wsDualHttpBinding rather than just using simple Http Binding. This new binding configuration is then assigned to the end on which the service is hosted.
This completes the server side explanation for duplex.

Image 3
Figure: - 19 Duplex Client side code


Above is the code snippet for client side. So let us explain the above code with numbers.
1- We implement the completed method. This is the callback method, which the server will call when doHugeTask is completed.
2- In this step we create object of the Instance Context class. Instance Context represents context information of a service. The main use of Instance Context is to handle incoming messages. In short, proxy is used to send messages to server and Instance Context is used to accept incoming messages.
3 -In this step we pass the Instance Context object to the constructor of the proxy. This is needed, as the server will use the same channel to communicate to the client.
4 - In this section two windows are shown. The top windows is the servers output and the below windows is of the client. You can see in the below window that server as made a callback to the client.

Note: - You can get source code for the same in WCFDuplex folder. Feel Free to experiment with it. Try making one simple project of client to client chat using WCF duplex fundamentals I am sure your doubts will be cleared in and out.
 

How can we host a service on two different protocols on a single server?


Let us first understand what this question actually means. Let us say we have made a service and we want to host this service using HTTP as well as TCP. You must be wondering why to ever host services on two different types of protocol. When we host a service, multiple types of client consume it and it’s very much possible that they have there own protocol of communication. A good service has the capability to downgrade or upgrade its protocol according the client who is consuming him.
Let us do a small sample in which we will host the ServiceGetCost on TCP and HTTP protocol.
 

Note: - You can the below sample in “WCFMultipleProtocolGetHost” folder in the CD provided.


Below is the code snippet pasted from the same sample? As usual, we have numbered them and here is the explanation of the same:-
1 and 2 - As we are hosting the service on two protocols we need to create two objects if the URI. You can also give the URI through config file. Pass these two objects of the URI in the constructor parameter when creating the service host object.



Image 4
 

Figure 20:- Server side code for Multi Protocol hosting


3 – In the config file we need to define two bindings and end as we are hosting the service in multiple protocols.
Once we are done the server side coding its time to see make a client by which we can switch between the protocols and see the results. Below is the code snippet of the client side for multi-protocol hosting.
 

Image 5

Figure 21:- Multi Protocol Client code


Let us understand the code:-
1 - In the generated config file we have added two ends. When we generate the config file, it generates only for one protocol. The other end has to be manually added.
2 - To test the same we have a list box, which has the name value given in the end point.
3 - In the list box select event we have then loaded the selected protocol. The selected protocol string needs to be given in the proxy class and finally call the proxy class GetTotalCost.
 

How can we use MSMQ bindings in WCF?
 

First let us understand why MSMQ came in to picture and then rest will follow. Let us take a scenario where your client needs to upload data to a central server. If everything will works fine and the server is available 24 hours to client then there are no issues. In case the server is not available, the clients will fail and the data will not be delivered. There is where MSMQ comes in to picture. It eliminates the need of persistent connection to a server. Therefore, what you do is deploy a MSMQ server and let the clients post message to this MSMQ server. When your actual server runs, it just picks up the message from the queue. In short, neither the client nor the server needs to be up and running on the same time. In WCF we have a client and service model and in real world it is very much practical possible that both the entities will not be available at one time.
In order to use MSMQ you need to install the Message queuing by click on Install windows component and selecting MSMQ queuing. Once that done we are all set to make our sample of MSMQ using WCF

Image 6
 Figure 22:- MSMQ Installation


This sample will be simple. We send some messages from the client and keep the server down. As the server is down it will make postings to the MSMQ server. Then we will run the server service and service should pick up the message and display the same.

Image 7
Figure 23:- MSMQ Server side code walkthrough

Above snippet is the server side code. So let us understand the whole snippet:-
1 – First thing is the queue name where the messages will go if the server is not running. The server name we can get from the config file. You can see in the above snippet we have defined the Mismanage in App.config file.
2 – We first check does this queue exist if it exists then go-ahead. If not then go to create a queue. Please note you need import using System. Messaging namespace. Then we can use the Message Queue to create a queue if the queue does not exist.
3 – First thing which should surprise you is why we are creating a URI with HTTP protocol as we are going to use MSMQ. Ok! This is bit tricky but fun. As we know in order to connect to this service, we need to generate a client proxy using SVCUTIL. Therefore, this URI will help us do that. It is not actually used by the client to connect.
4 – We need our end and the MSMQ bindings.
5 and 6 – Again as usual we need is an interface and implementation for the same. In implementation we have created a method called send Message.
Once the above steps are executed, run the server and generate the client proxy using SVCUTIL utility.
Now comes the final step making a client. One change you need to make is change the address to the MSMQ server in the app.config. In this, we have just looped ten times and fired an offline message. Please note to keep your server down.

Image 8
Figure 24:- MSMQ Client side code

Now go to computer management and you can see your queue messages waiting to be picked by the server. Run the server and below should be the output. If you come back again you will see that there are no messages in the queue.

Image 9
Figure 25:- MSMQ Server side display


One of the important concepts is to understand when to use MSMQ protocol. When we expect that client and server will not be available, at one time this is the best option to opt for.


Can you explain transactions in WCF?

What different transaction isolation levels provided in WCF?
 

Transactions assure that a group of related activity occurs as a single atomic unit. In simple words, every activity in the unit must either all succeed or all should fail. WCF provides a central transaction system that can be used to handle transaction operations. One of the things WCF provides is a single unified transaction system for both database and non-database activity. For instance, BeginTrans and CommitTrans are database related syntaxes but we can not use the same for other activities like if we want to upload all message in a single transaction to a MSMQ server. One thing to note is that WCF transaction abides to WS specifications. That means any other language like JAVA can take advantage of this transaction…. I think that is the best part of WCF embracing other languages.

Image 10
Figure 26:- Transactions in WCF


In order to support transaction the service should first support transactions. Above is a simple code snippet of the server service and client and explanation for the same:-

The top code snippet is of the server service and the below code snippet is of the client.

1 - At interface level the operation contract is attributed with [Transaction Flow] attribute. There are three values for it Allowed (which mean operation mar or may not be used in transaction), Not Allowed (Where it is never used in transaction) and required (Where the service can only be used in transactions). Below code snippet currently says that this service can only be used with transactions.

2 - In this section the [Service Behavior] attribute specifies the transaction isolation level property. Transaction isolation specifies the degree of isolation most compatible with other applications. So let us review what are the different levels you can provide in transaction isolation.
The data affected by a transaction is called volatile.
Chaos: - pending changes from more highly isolated transactions cannot be overridden.
Read Committed: - Volatile data can be modified but it cannot be read during the transaction.
Read Uncommitted: - Volatile data can be read as well as modified during the transaction.
Repeatable Read: - Volatile data can be read but not modified during the transaction and new data can be added.
Serializable: - Volatile data can be only read. However, no modifications and adding of new data is allowed.
Snapshot: - Volatile data can be read. However, before modifying the data it verifies if any other transaction had changed data. If yes then it raises error.
By default, the System. Transactions infrastructure creates Serializable transactions.

3 - This defines the transaction behavior with in the service. [Operation Behavior] has a property called as transaction scope. Transaction Scope setting indicates that operation must be called within a transaction scope. You can also see TransactionAutoComplete is set to true which indicates that transaction will complete by default if there are no errors. If you do not provide the TransactionAutoComplete to true then you will need to call OperationContext.Current.SetTransactionComplete() to make the transaction complete.
Now let us make a walkthrough of the client side code for the service.

4 and 5 - You can see from the client we need to define Isolation level and the scope while making the call to our Update Accounts method
 

Can we do transactions using MSMQ?

While doing MSMQ there can be scenarios in the project, where we would like all the messages are uploaded to either MSMQ or all messages read from MSMQ. After any message is read from MSMQ, it is deleted from the queue. Therefore, some times this can be critical if there are exceptions in reading or uploading messages. As said before WCF transaction can be applied to database as well as other operations like MSMQ. So let us try to understand the same by doing a small sample.
Below is a numbered code snippet of MSMQ transactions.

1 - Send message is the exposed method in the service. We have marked this method as TransactionScopeRequired=true

2 - On the client side we have use the transaction scope to say that we are starting a transaction to MSMQ server. You can see we have used the send Message to send the messages to MSMQ.

3- We can then use Complete or Dispose method to complete or rollback the transactions.
The below MSMQ transaction code ensures that either all messages are send to the server or none are sent. Thus satisfying consistency property of transactions.

Image 11
Figure 27:- Transaction snippet code


Can we have two-way communications in MSMQ?
 

Yes
 

What are Volatile queues?
 

There are scenarios in the project when you want the message to deliver in proper time. The timely delivery of message is more important than losing message. In these scenarios, Volatile queues are used.
Below is the code snippet, which shows how to configure Volatile queues. You can see the binding Configuration property set to Volatile Binding. This code will assure that message will deliver on time but there is a possibility that you can lose data.

<appSettings>
<!-- use appSetting to configure MSMQ queue name -->
<add key="queueName" value=".\private$\ServiceModelSamplesVolatile" />
</appSettings>

<system.serviceModel>
<services>
<service name="Samples.StockTickerServ"
behaviorConfiguration="CalculatorServiceBehavior">
...
<!-- Define NetMsmqEndpoint -->
<endpoint address="net.msmq://localhost/private/ServiceModelSamplesVolatile"
binding="netMsmqBinding"
bindingConfiguration="volatileBinding"
contract="Samples.InterfaceStockTicker" />
...
</service>
</services>

<bindings>
<netMsmqBinding>
<binding name="volatileBinding"
durable="false"
exactlyOnce="false"/>
</netMsmqBinding>
</bindings>
...
</system.serviceModel>
 

What are Dead letter queues?
 

The main use of queue is that you do not need the client and the server running at one time. Therefore, it is possible that a message will lie in queue for long time until the server or client picks it up. But there are scenarios where a message is of no use after a certain time. Therefore, these kinds of messages if not delivered within that time span it should not be sent to the user.
Below is the config snippet, which defines for how much time the message should be in queue.

<bindings>
<netMsmqBinding>
<binding name="MyBindings"
deadLetterQueue="Custom"
customDeadLetterQueue="net.msmq://localhost/private/ServiceModelSamples"
timeToLive="00:00:02"/>
</netMsmqBinding>
 

For further reading do watch the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)