SYNTAX HIGHLIGHTER

Tuesday, August 25, 2015

WCF self host application with MSMQ


Windows Communication Foundation (WCF) is a framework for building service-oriented applications, it is a unified component for work with existing technologies like Web service, Remorting, MSMQ act. This article I am going work with with WCF with MSMQ (Microsoft Messaging Queue). Which enable application to running at different times to across the network and system that be temporarily offline. When we compare MSMQ with web service MSMQ work without running server application at server. It just queue message and process later when server come up online.

before start  you should have basic knowledge of

1. Windows Communication Foundation (WCF) for more details click here.

2. Microsoft Messaging Queue for more details click here

3. Visual Studio (2012/2013)

1. Create a blank Solution name it as RetailsStore

2. Add new Class library project called "RetailStore.Services"

3. Add System.ServiceModel Reference to newly created project



3. Add new interface called "ITradeService" and below code

using System.ServiceModel;

namespace RetailStore.Services
{
    [ServiceContract]
    public interface ITradeService
    {
        [OperationContract(IsOneWay = true)]
        void DoTrade(string buystock, string sellStock, int amount);
    }
}

4. Add new class called "TradeService" and paste below code

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace RetailStore.Services
{
    public class TradeService : ITradeService
    {
        [OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
        public void DoTrade(string buystock, string sellStock, int amount)
        {
            ReceiveContext receiveContext;

            if (!ReceiveContext.TryGet(OperationContext.Current.IncomingMessageProperties, out receiveContext))
            {
                Console.WriteLine("Recieve context is not available for the message");
                return;
            }
            Console.WriteLine("Received Reauest to Sell Stock {0} with the quantity of {1} from and buy {2}", sellStock,
                amount, buystock);
            if (amount == 50)
            {
                receiveContext.Complete(TimeSpan.MaxValue);
                Console.WriteLine("Amount is more than 50");
            }
            else
            {
                receiveContext.Abandon(TimeSpan.MaxValue);
            }

            Console.WriteLine();
        }
    }
}

5. Now your service library ready to host. here i have used Command line hosting.to do that Add new     Console project called "HostApp"  6. Add Reference "RetailStore.Services" to HostApp

7. Add System.ServiceModel Reference to  HostApp

8. Paste below code to main method
 
using System;
using System.ServiceModel;
using RetailStore.Services;

namespace HostApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            const string baseAddress = "net.msmq://localhost/private/TradeQueue";
            using (var servicehost = new ServiceHost(typeof (TradeService), new Uri(baseAddress)))
            {
                servicehost.Open();
                Console.WriteLine("The Trade Service is online");
                Console.WriteLine("Press Enter to terminate service.");
                Console.WriteLine();
                Console.ReadLine();
                servicehost.Close();
            }
        }
    }
}

9. Add below configuration setting to HostApp App.config
 

    
      
        
          
            
          
        
        
      
    
    
      
        
          
            
          
        
      
    
    
      
        
          
        
      
    
  
10. Set HostApp as start project and run. copy "http://localhost:5051/TradeService" above line (07) address and paste it browser you can get below screen. now we are ready to access service form client.




11. Create new Console Application called it as "ClientApp"

12. To add service reference run host app in release mode to do that make sure Host app as start up           project and Press (Ctrl+F5). Then select ClientApp project and select service reference using               above Url and name Namespace as "TradeServiceRef"



12. Add System.Transaction Reference to ClientApp to available transaction

13. Paste below code to Client App

 
using System;
using System.Transactions;
using ClientApp.TradeServiceRef;

namespace ClientApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            using (var proxy = new TradeServiceClient())
            {
                using (var scope = new TransactionScope(TransactionScopeOption.Required))
                {
                    proxy.DoTrade("MSFT", "IBM", 60);
                    Console.WriteLine("Selling 60 stocks of IBM and Buying MSFT");
                    proxy.DoTrade("ACN", "ABN", 100);
                    Console.WriteLine("Selling 100 stocks of ABN and Buying ACN");
                    scope.Complete();
                }
            }

            Console.ReadLine();
        }
    }
}

14. now you are complete all the coding. before run application please make sure MSMQ is installed in Dev box. if not use this link to configure MSMQ link

15. Create transaction Queue called "TradeQueue"

16. Stop the HostApp and run the ClientApp. you can see your message queuen in internal MSMQ

Running Client

Messages queue on private Queue




17. To process message stop the Client App and run HostApp you can see all the queue massages have been processed

note. As a series of this articles, next article we will look how to enable dependency injection for this application.

Download source code from here.Click
Coding Hunt!:)