1. Open the WCF service application that you created earlier or download start file here.
In Service Project
2. Update the OperationContract to include a TransactionFlow attribute. This ensure a transaction is required to invoke the SubmitReview method.
[TransactionFlow(TransactionFlowOption.Mandatory)]
[OperationContract]
void SubmitReview (ProductReview pr);
3. In the service implementation for SubmitReview, modify OperationBehavior attribute as shown below:
[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
void IProductService.SubmitReview(ProductReview pr)
4. Add reference to System.Messaging and add using System.Messaging;
5. In addition to writing to an XML file, lets also write to a transactional queue. First we need to create a queue.
6. Open Computer Management, expand Services and Applications, Expand Message Queuing > right click on Private Queues > select New > Private Queue > type productreview > check Transactional > click OK.
7. To write to the productreview message queue, update the submit review method as shown below:
[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
void IProductService.SubmitReview(ProductReview pr)
{
MessageQueue queue = new MessageQueue(@".\Private$\productreview");
queue.Send(pr, MessageQueueTransactionType.Automatic);
...
In Service Host Project
8. Go to App.config of the Service Host and change the basicHttpBinding endpoint to use WsHttpBinidng and WsHttpBinding configuration should be updated as given below, to allows the transaction flow to the service.
<bindings>
<wsHttpBinding>
<binding name ="WsHttpBindingConfig" transactionFlow="true">
<reliableSession enabled="true" />
</binding>
</wsHttpBinding>
</bindings>
9. Set the service Host as start up project and test the Service Host.
In Client Project
10. Update Service Reference of the client11. In the client, update main() to uses the WSHttpBinding instead of BasicHttpBinding
12. Add reference to System.Transactions and add using System.Transactions;
13. In the main method of client wrap the method invocation using TransactionScope as shown below this makes the transaction to be flowed to service.
using (TransactionScope trans = new TransactionScope())
{
client.SubmitReview(pr);
trans.Complete();
}
Test
14. Run both Host and Client15. Check the queue to see if the message is queued. Open the queue and examine the body of the queue.
16. Now comment the trans.Complete(); and then run host and client. Add a product review and close both client and host. Now check the message queue. The new product review should not be in the queue since the transaction was not completed and this means transaction has failed and all that is executed within the transaction is rolled back.
Links and References
Transactions in WCF Services https://msdn.microsoft.com/en-us/library/ff384250.aspx
Comments
Post a Comment