MSMQ Samples

Here is a sample of  using MSMQ

The example in .NET Framework essentials does not seem to work.

This is still a simpliefied version, not actually handling timeouts very cleanly.

//This is Enque:
// Enque.cs
using System;
using System.Messaging;

namespace EnqueSample
{
    [Serializable]public struct Customer
    {
        public string Last;
        public string First;
    }
    class EnqueSample
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                string path = “.\\PRIVATE$\\NFE_queue”;
                if (!MessageQueue.Exists(path))
                {
                    MessageQueue.Create(path);
                }

                MessageQueue q = new MessageQueue(path);

                Customer c = new Customer();
                c.Last = “Eyre”;
                c.First = “Chris”;

                q.Send(c);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}
// Deque
// Deque.cs
using System;
using System.Messaging;

namespace Dequeue
{
    [Serializable]public struct Customer
    {
        public string Last;
        public string First;
    }
   
     class Dequeue
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                string strQueuePath = “.\\PRIVATE$\\NFE_queue”;

                if (!MessageQueue.Exists(strQueuePath))
                {
                    throw new Exception(strQueuePath + ” does’nt exist”);
                }
                MessageQueue q = new MessageQueue(strQueuePath);

                Type[] t = {typeof(Customer)};
                ((XmlMessageFormatter)q.Formatter).TargetTypes = t;

                Message m = q.Receive(new TimeSpan(0,0,5));

                Customer c = (Customer) m.Body;

                Console.WriteLine(“Customer: {0} {1}”, c.First, c.Last);

            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            System.Console.ReadLine();
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s