MessageQueue Class - Queuing Messages in .NET

Discussion in 'C#' started by MinalS, Apr 16, 2015.

  1. MinalS

    MinalS New Member

    Joined:
    Jul 8, 2014
    Messages:
    138
    Likes Received:
    32
    Trophy Points:
    0
    In synchronous programming, the user needs to wait for the method completion. In asynchronous programming, the calling thread starts the method and executes concurrently. The message queuing operates asynchronously. The client does not wait for the server to read the data.

    Message queuing provides various features like guaranteed delivery, confirmations, transactions, confirmations. User can send, receive messages to and from the queue.

    Use of Message Queuing



    The message queuing is useful when the client application is disconnected from the network. Consider an example of when user visits a site. The user enters the order data into the site. The application sends the message for each order to the message queue located on the client side. The order is automatically transferred to the client system from the message queue to the target system message queue.

    Features of Message Queuing



    Some of the features of the message queuing is mentioned below:
    1. User can send and receive messages in a disconnected environment.
    2. The messages can be sent quickly using the express mode. The messages are stored in the memory.
    3. The messages can be sent using guaranteed delivery. The recoverable messages are stored in files and can be delivered when the server reboots.
    4. User can sent multicast messages using the message queuing
    5. The messages are secured using the access control list for defining the users for sending and receiving messages.
    6. It supports algorithms that can handle large number of queues

    Message Queuing Components



    Message queuing 5.0 is present in Windows. Initial versions of message queuing did not support HTTP protocol and multicast messages. The different components of message queuing is as mentioned below:
    1. MSMQ HTTP Support: It helps user to send and receive messages using the HTTP protocol
    2. MSMQ Server Core: It is required for the base functionality along with the message queue
    3. Triggers: The applications are instantiated on the arrival of a new message
    4. MSMQ DCOM Proxy: The system connects to the remote server using the DCOM API
    5. Multicast support: It is a message that can be sent to the server groups
    6. Active Directory Domain Services Integration: It is the message queue names written to the Active directory. The windows users and groups can be secured.

    Message Queuing Architecture



    The message queuing is used to read and write messages from the queue. The different attributes are as mentioned below:

    1. Messages

    A message is sent to the queue. It contains a body that contains a data sent and a label as the message title. User can add any information to the message body. There are several formats used for the data conversion to be added to the body. The message also contains information about sender, timeout configuration, transaction ID.

    There are different messages that can be used.
    1. A normal message is sent by the application
    2. Response message are sent by receiving the applications when the sender needs special response
    3. Acknowledgment message provides status of a normal message. They are sent to the administration queues and reports the success or failure of the messages
    4. The report message is generated using the Message Queuing System
    The messages in a queue are sorted in the priority; the highest priority message is processed first. The message has two delivery modes as express and recoverable. The express messages are fast delivers as they are used only for storing messages. Recoverable messages are stored in the files. They contain the message route till the message is delivered.

    2. Message Queue

    The message queue acts as a bin for messages. Private and public queues are used for sending messages. There are several queue types present for message storage. They are as listed below:
    1. A public queue is published in the Active Directory. The data of the queues is replicated in the directory domains. The queue can be easily accessed without knowing the computer name.
    2. Private queues do not appear in the Active Directory. The queues are accesses when the complete path name is known.
    3. Journal queues are used for copying messages once they are received or sent. The journal queue contains two types of queues as source journaling and target journaling. Source journaling is used with the message properties. Target journaling is turned on and the messages are stored in the journal queue of the target system.
    4. Dead letter queues store messages if the message does not come at the target system before timeout is reached. The queue is checked for the messages that did not come.
    5. Report queue is used for the test messages. The queue is created by changing the type of the private or public queue.
    6. Response queue is used when more than simple acknowledgement is needed for the answer from the receiving side.

    Message Queue Programming



    Learn how to create queues, send and receive messages in a queue.

    Create Message Queue

    The Create method is used to create message queues programmatically. The path of the queue is passed in the create method. It contains host name for the queue, queue name. The queue as PublicQueue1 is created on the local host.

    Consider the following code to demonstrate the message queue.
    Code:
    using System;
    using System.Messaging;
    
    namespace CreateMessage1
    {
        class Program
        {
            static void Main ( )
            {
                using ( var queue = MessageQueue.Create(@".\PublicQueue1") ) 
                {
                    Console.WriteLine("Queue is created programmatically");
                    Console.WriteLine("Path:{0}", queue.Path);
                    Console.WriteLine("FormatName:{0}", queue.FormatName);
                }
            }
        }
    }
    
    
    Finding Queue

    The pathname and format name can be used for locating queues. The public queues are present in the Active Directory. User does not need the information about system for the queue location. For private queues, the system name is important.

    The class MessageQueue has static methods that can be used for searching queues. The GetPublicQueuesByLabel, GetPublicQueueByCategory and GetPublicQueuesByMachine are used for queue search.

    Consider the following code to demonstrate for finding queues.
    Code:
    using System;
    using System.Messaging;
    
    namepsace CreateMessage1
    {
        class Program
        {
            static void Main ( )
            {
                foreach( var queue in MessageQueue.GetPublicQueue())
                {
                    Console.WriteLine(queue.Path);
                }
            }
        }
    }
    
    The method GetPublicQueue returns an array of all public queues in the domain.

    Opening Queues

    If the user knows the queue name, it can be easily opened using path or format name. The constructor of the MessageQueue class is used for setting the values.

    Pathname

    The path states the queue name and the machine name for opening the queue.
    The following code snippet demonstrates the opening of the message queue.

    Code:
    
    using System;
    using System.Messaging;
    
    namepsace CreateMessage1
    {
        class Program
        {
            static void Main ( )
            {
                if ( MessageQueue.Exists(@".\PublicQueue1") )
                {
                    var queue = new MessageQueue(@".\PublicQueue1");
                }
                else
                {
                    Console.WriteLine("Queue does not exists");
                }
            }
        }
    }
    
    
    Format Name

    User can use format name for opening a queue. The format name is used for searching queue in the Active Directory for finding the host where queue is located.

    The format name has different users. The following protocols must be followed by the user while opening the private queue.
    1. The following string must be passed to the constructor for accessing the private queue.
      Code:
      FormatName: PRIVATE = MACHINEGUID\QueueNumber
      
      The queue number is produced when the queue is created.
    2. The following syntax is used to specify the protocol used for sending messages.
      Code:
      Format Name : DIRECT = Protocol : MachineAddress\QueueName 
      
      It is used to specify the protocol used to send the message. The HTTP protocol is supported.
    3. The following syntax is used to specify the queue in the format name.
      Code:
      Format Name : DIRECT = OS : MachineName\QueueName 
      
      It is used to specify the queue in the format name.
    Sending Message

    The Send method of the message queue is used to send the message. The object is serialized to the associated queue. It is overloaded so that the MessageQueueTransaction object can be passed.

    The following code is used to demonstrate the queue existence. If there is no queue, one is created. The queue is opened and the message is sent to the queue using the Send method.
    Code:
    using System;
    using System.Messaging;
    
    namespace Messaging1
    {
        class Program
        {
            static void Main ( )
            {
                try
                {
                    if ( !MessageQueue.Exists(@".\Private$\PrivateQueue1") )
                    {
                        MessageQueue.Create(@".\Private$\PrivateQueue1");
                    }
                    var queue = new MessageQueue (@".\Private$\PrivateQueue1");
                    queue.Send ( "Message", "Label");
                }
                catch(MessageQueueException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
    }
    
    Message Formatter

    The message format to be transferred in the queue is dependent on the formatter. The Formatter property is used for assigning the formatter. The XmlMessageFormatter is default format for the messages. The formatter implements IMessageFormatter interface. They are present in the System.Messaging namespace.

    The BinaryMessageFormatter is used for serializing the messages in binary format. The ActiveXMessageFormatter is the binary formatter used for reading and writing COM objects.

    Receiving Messages

    The Receive method is used for reading and removing the message from the queue. Message priorities are sent with the messages for reading them.

    The following code demonstrates the Receive method used for receiving messages.
    Code:
    using System;
    using System.Messaging;
    
    namespace Message1
    {
        class Program
        {
            static void Main ()
            {
                var queue = new MessageQueue(@".\Private$\PrivateQueue1");
                queue.Formatter = new XmlMessageFormatter ( new string[ ] { "System.String"} );
                Message msg = queue.Receive();
                Console.WriteLine(msg.Body);
            }
        }
    }
    
    The method acts as asynchronous and waits for the message in the queue.

    Acknowledgment Queues

    The acknowledge queue is useful for getting information about the message status. User can define if an answer is to be received for proper functioning. The acknowledgement is sent when the message reaches the destination queue or it is read by the user.

    Transactional Queues

    The recoverable message do not provide user with order and one occurrence delivery. If there is a network failure, multiple messages arrive at the receiver.

    The Transactional queues are used when the messages arrive in the similar order they were sent and they arrive only once. In transactional queues, the single transaction cannot span sending and receiving messages.

    The following code shows the transaction message queue for sending messages in a transaction.
    Code:
    using System;
    using System.Messaging;
    
    namespace Message1
    {
        class Program
        {
            static void Main ()
            {
                if ( !MessageQueue.Exists ( @".\TransactionQueue"))
                {
                    MessageQueue.Create(@".\TransactionQueue", true );
                }
                var queue = new MessageQueue(@".\TransactionQueue");
                var trans = new MessageQueueTransaction();
                
                try
                {
                    transaction.Begin();
                    queue.Send("msg1", transaction);
                    queue.Send("msg2", transaction);
                    transaction.Commit();
                }
                catch
                {
                    transaction.Abort();
                }
            }
        }
    }
    
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice