Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » XML .NET » Message Queuing using C# 2005

Message Queuing using C# 2005

Message Queuing is a message infrastructure and a development platform for creating distributed messaging applications for the Microsoft Windows Operating System.

Total page views :  29061
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


Download Free Book

Message Queuing is a message infrastructure and a development platform for creating distributed messaging applications for the Microsoft Windows Operating System. Message Queuing applications can use the Message Queuing infrastructure to communicate heterogeneous networks and with computers that may be offline. Message Queuing provides guaranteed message delivery, efficient routing, security, transaction support and priority based messaging. Administrative Privileges are required to create a queue.

 

With the release of MS Windows 2000, the name of Microsoft's message queuing solution changed from Microsoft Messaging Queue Server to Message Queuing. In the Windows Platform SDK, the term Messaging Queuing refers to all versions of the product. There are three different types of Message Queuing versions: 

  • MSMQ 1.0: Microsoft Message Queue Server 1.0 product operates with MS Windows NT 4.0, Microsoft MS Windows 95, MS Windows 98, and MS Windows Me.
  • MSMQ 2.0: the Message Queuing service included in MS Windows 2000.
  • MSMQ 3.0: Message queuing service included in MS Windows XP Professional and Windows Server 2003 family. 

When to use Message Queue?

Message Queuing is useful when the client application is often disconnected from the network. For example, salespersons can enter order data directory at the customer's site. The application sends a message for each order to the message queue that is located on the client's system.

 

Message Queuing can also be useful in a connected environment. For example, the server of a website is fully loaded with order transactions at some specific time periods, say evening times or morning times, but the load is low at night time. The solution to this problem would be to buy a faster server or add an additional server to the system. However, the cheaper solution would be sending message queue.

 

There are different types of Message Queues: 

  1. Normal Message
  2. Acknowledgement Message
  3. Respond Message
  4. Report Message 

A message can have a priority that defines the order in which the message will be read from a queue. Commonly, messages are stored on the disk can be found in the <windir>\system32\msmq\stored directory.

 

Message Queuing Features

 

Message Queuing is a part of the Windows Operating System. Main features of this service are:

  • Messages can be sent in a disconnected environment. It is not necessary for the sending and receiving application to run at the same time.
  • A program can assign different priorities to messages when it puts the message in the queue.
  • Using Express mode, messages can be sent very fast. Express mode messages are just stored in memory.
  • Message Queues can be secured with access control lists to define which users can send or receive messages from a queue. We can also encrypt the data to avoid network sniffers from reading the data.
  • We can send the messages using guaranteed delivery. Recoverable messages are stored within files. They are delivered even in case the server reboots.
  • Message Queuing 3.0 supports sending multicast messages.

Message Queuing Products

Message Queuing 3.0 is a part of Windows Server 2003 and Windows XP, Windows 2000 comes with the Message Queuing 2.0, which did not have support for the HTTP protocol and multicast messages. You can install a message queue in Windows XP using Add or Remove Programs, a separate section within windows components where Message Queuing options can be selected. Within the message Queuing options, various components can be selected (refer Fig 1 and Fig 2).

Active Directory Integration:

Within this feature, message queue names are written to the Active Directory integration and to secure queues with Windows users and groups

Common:

The common subcomponent is required for base functionality with Message Queuing  

MSMQHTTP Support:

This support allows you to send and receive messages using the HTTP protocol.

Figure 1:

Figure 2:

Triggers:

With Triggers applications can be instantiated on the arrival of a new   message.

 

When Message Queuing is installed, the Message Queuing Service must be started. This service reads and writes messages and communicates with other Message Queuing servers to route messages across the network.

 

Now we will see how to send and receiving messages using C# programming.

Programming Message Queuing

Creating a Message Queue

In C#, we can also create Message Queues programmatically using the Create() method of MessageQueue class. With Create() method, the path of the new queue must be passed. The path consists of the hostname where the queue is located and the name of the queue. Now we will write an example, which will create on the localhost that is 'MynewPublicQueue'. To create a private queue, the path name must include private$. For example: \private$\MynewPrivateQueue.

 

Once the create() method is invoked, properties of the queue can be changed. Using label property, the label of the queue is set to "First Queue". The following program writes the path of the queue and the format name to the console. The format name is automatically created with a UUID (Universal Unique Identifiers) that can be used to access the queue without the name of the server. Check out Code 1.

Code 1:

using System;

using System.Collections.Generic;

using System.Messaging;

using System.Text;

 

namespace FirstQueue

{

    class Program

    {

        static void Main(string[] args)

        {

            using (MessageQueue queue = MessageQueue.Create(@". \myqueue"))

            {

                queue.Label = "First Queue";

                Console.WriteLine("Queue Created:");

                Console.WriteLine("Path: {0}, queue.Path");

                Console.Writeline("FormatName: {0}, queue.FormatName");

            }

        }

    }

}

 

Finding a Queue

To identify the queue, you can use the path name and format name. You can also differentiate between public and private queues. Public queues are published in the Active directory. For these queues, it is not necessary to know the system where they are located.

Private queues can be found only in the name of the system where the queues located are known. You can find the public queues in the Active directory by searching for the queue's table, category or format name. You can also get all the queues on the machine.

The class MessageQueue has static methods to search for queues:

  • GetPublicQueuesByLable()
  • GetPublicQueuesByCategory()
  • GetPublicQueuesByMachine()

The method GetPublicQueues() return an array of all public queues in the domain.

Code 2:

using System;

using System.Messaging;

 

namespace FirstQueue

{

    class Program

    {

        static void Main(string[] args)

        {

            foreach (MessageQueue queue in MessageQueue.GetPublicQueues())

            {

                Console.WriteLine("queue.Path");

            }

        }

    }

}

 

You can also make queues private using the static method called GetPrivateQueuesByMachine(). This method returns all private queues from a specific system.

 

Opening Known Queues

If you the name of the queue, then it is not necessary to search for it. Queues can be opened using the path or format name.

 

Pathname

Pathname specifies the machine name and queue name to open the queue. The following code 3 opens the queue FirstQueue on local host. To make sure the queue exists, you use the static method MessageQueue.Exists().

Code 3:

using System;

using System.Messaging;

 

namespace FirstQueue

{

    class Program

    {

        static void Main(string[] args)

        {

            if (MessageQueue.Exists(@".\\FirstQueue"))

            {

                MessageQueue queue = new MessageQueue(@".\\FirstQueue");

            }

            else

            {

                Console.WriteLine("Queue .\\FirstQueue not Found");

            }

        }

    }

}

 

We can use different type identifiers when the queues are opened. Table 1 shows the syntax of the queue name for specific types.

 

Format Name

Format name can be given to open queue. The formatname is used for searching the queue in the Active Directory to get the host where the queue is located. In a disconnected environment, where the queue cannot be reached at the time the message is sent, it is necessary to use the format name.

Syntax of the format name queue is:

 

MessageQueue queue= new MessageQueue( @ "FormatName : Public=023423DFG-0984-3w45-K987-12638NU979HH") 
 

Table 1

Queue Type

Syntax

Private queue

MachineName\Private$\QueueName

Public  queue

MachineName\QueueName

Journal queue

MachineName\QueueName\Journal$

Machine Journal queue

MachineName\Journal$

Machine dead letter queue

MachineName\DeadLetter$

Machine transactional
dead-letter queue

MachineName\XactDeadLetter$

 

Sending a Message

By using the Send method of the MessageQueue class, you can send the message to the queue. The object passed as an argument of the Send() Method is serialized queue. The Send() method is overloaded so that a Label and a MessageQueueTransaction object  can be passed. Now we will write a small example to check if the queue exists and if it doesn't exist, a queue is created. Then the queue is opened and the message "First Message" is sent to the queue using the Send() method.


The path name specifies "."  for the server name, which is the local system. Path name to private queues only works locally. Add the following code 4 in your Visual Studio C# console environment.

Code 4:

 

using System;

using System.Messaging;

 

namespace FirstQueue

{

    class Program

    {

        static void Main(string[] args)

        {

            try

            {

                if (!MessageQueue.Exists(@".\Private$\FirstQueue"))

                {

                    MessageQueue.Create(@".\Private$\FirstQueue");

                }

                MessageQueue queue = new MessageQueue(@".\Private$FirstQueue");

                queue.Send("First Message ", " Label ");

            }

 

            catch (MessageQueueException ex)

            {

                Console.WriteLine(ex.Message);

            }

        }

    }

}

 

Build the application and view and run. You can view the message in the Component Management admin tool as shown in figure 3. By opening the message and selecting the body tab of the dialog, you can see the message was formatted using XML.

 

Receiving Messages

 

MessageQueue class can be used for reading messages. With the Receive() method, a single message is read and removed from the queue. We will write a small example to read the Private queue FirstQueue.

When you read a message using the XmlMessageFormatter, we have to pass the types of the objects that are read to the constructor or the formatter. In this example (Code 5), the type System.String is passed to the argument array if the XmlMessageFormatter constructor. The following program is read with the Receive() method and then the message body is written to the console.

 



Figure 3 :

Code 5:

using System;

using System.Messaging;

 

namespace FirstQueue

{

    class Program

    {

        static void Main(string[] args)

        {

            MessageQueue queue = new MessageQueue (@".\Private$\FirstQueue");

            Queue.Formatter = new XmlMessageFormatter( new string[]("System.String"));

            Message Mymessage = queue.Receive();

            Console.WriteLine(Mymessage.Body);                    

        }

    }

}

 

Receive() message behaves synchronously and waits until a message is in the queue if there is none. Try out the rest in Visual Studio 2005.

 

Conclusion

Message Queues can be created with MessageQueue.Create() method. But to create a Message queue you should have administrative rights.


Login to add your contents and source code to this article
 About the author
 
Rajkumar Krishnan
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2010  Mindcracker LLC. All Rights Reserved