Sunday, October 2, 2011

Use of MSMQ Binding provided by WCF.For Centralized Reliable logging Mechanism.




Msmq Binding is used to communicate to the Service using Microsoft Message Queuing. I have used this binding for transferring log messages. This way we can build a centralised logging system.
For this I followed the steps mentioned below

   1.   Installed Microsoft Message Queuing
   2.   Create a message Queue with Transaction Enabled
   3.   Create a Service


    [ServiceContract]
    public interface ILogService
    {


        [OperationContract(IsOneWay =true )]
        void Log(string Message);


    } 


  Note:if we use NetMsmqBinding we have to mark all operations with in the service contract as OneWay.


  4.Define the implementation


public class MathService:ILogService
    {


        public void Log(string message)
        {


            File.AppendAllText(@"C:\logFolder\AppMessages.txt", message +      Environment.NewLine);


           
        }


    }
  5.Host the Service I have used Self Hosting.




            //Address of the message Queue in the machine -
            // use public with active directory installation
            // in case of Active directory integration . other machines can also access
            // the Queue
            Uri uri = new Uri(@"net.msmq:\\mycomputer\private\testQueue");
         
            //Create Msmq binding with impersonate
            // you may need need to do some thing more if you desire security
            NetMsmqBinding messageQueueBinding = new NetMsmqBinding(NetMsmqSecurityMode .None);


            ServiceHost host = new ServiceHost(typeof(ILogService), uri);
            host.AddServiceEndpoint(typeof(ILogService), messageQueueBinding,uri .AbsoluteUri  );


            //host the WCF Service
            host.Open();




6.Design a Logging Client Application I have used Simple Console Application to demonstrate the same.


class Program
    {
        static void Main(string[] args)
        {


            Uri uri = new Uri ("net.msmq:\\mycomputer\private\testQueue");
            EndpointAddress  address = new EndpointAddress (uri.AbsoluteUri );
            NetMsmqBinding binding =new NetMsmqBinding (NetMsmqSecurityMode.None );
            ChannelFactory <ILogService> SerChannel = new ChannelFactory<ILogService> (binding ,address );
           
            ILogService client = SerChannel.CreateChannel ();
            client.Log (" This is a log message");
            Console.ReadLine ();
        }
    }

No comments: