C# .Net Program That Adds Message Properties to an MQ Message

The other day, a colleague emailed me asking if I had a sample C# .Net/MQ program that adds message properties to a message. So. I thought I would post it for everyone to use.

You can download the source code from here.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using IBM.WMQ;

/// <summary> Program Name
/// MQTest01P
///
/// Description
/// This C# class will connect to a remote queue manager
/// and put a message to a queue with a message property using a managed .NET environment.
///
/// Sample Command Line Parameters
/// -h 127.0.0.1 -p 1414 -c TEST.CHL -m MQA1 -q TEST.Q1 -u tester -x mypwd
/// </summary>
/// <author>  Roger Lacroix
/// </author>
namespace MQTest01P
{
   class MQTest01P
   {
      private Hashtable inParms = null;
      private Hashtable qMgrProp = null;
      private System.String qManager;
      private System.String outputQName;

      /*
      * The constructor
      */
      public MQTest01P()
         : base()
      {
      }

      /// <summary> Make sure the required parameters are present.</summary>
      /// <returns> true/false
      /// </returns>
      private bool allParamsPresent()
      {
         bool b = inParms.ContainsKey("-h") && inParms.ContainsKey("-p") &&
                  inParms.ContainsKey("-c") && inParms.ContainsKey("-m") &&
                  inParms.ContainsKey("-q");
         if (b)
         {
            try
            {
               System.Int32.Parse((System.String)inParms["-p"]);
            }
            catch (System.FormatException e)
            {
               b = false;
            }
         }

         return b;
      }

      /// <summary> Extract the command-line parameters and initialize the MQ variables.</summary>
      /// <param name="args">
      /// </param>
      /// <throws>  IllegalArgumentException </throws>
      private void init(System.String[] args)
      {
         inParms = Hashtable.Synchronized(new Hashtable());
         if (args.Length > 0 && (args.Length % 2) == 0)
         {
            for (int i = 0; i < args.Length; i += 2)
            {
               inParms[args[i]] = args[i + 1];
            }
         }
         else
         {
            throw new System.ArgumentException();
         }

         if (allParamsPresent())
         {
            qManager = ((System.String)inParms["-m"]);
            outputQName = ((System.String)inParms["-q"]);

            qMgrProp = new Hashtable();
            qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);

            qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ((System.String)inParms["-h"]));
            qMgrProp.Add(MQC.CHANNEL_PROPERTY, ((System.String)inParms["-c"]));

            try
            {
               qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse((System.String)inParms["-p"]));
            }
            catch (System.FormatException e)
            {
               qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
            }

            if (inParms.ContainsKey("-u"))
               qMgrProp.Add(MQC.USER_ID_PROPERTY, ((System.String)inParms["-u"]));

            if (inParms.ContainsKey("-x"))
               qMgrProp.Add(MQC.PASSWORD_PROPERTY, ((System.String)inParms["-x"]));

            logger("MQ Parms:");
            logger("  QMgrName ='" + qManager + "'");
            logger("  Output QName ='" + outputQName+"'");

            logger("Connection values:");
            foreach (DictionaryEntry de in qMgrProp)
            {
               logger("  " + de.Key + " = '" + de.Value + "'");
            }
         }
         else
         {
            throw new System.ArgumentException();
         }
      }

      /// <summary> Connect, open queue, write a message, close queue and disconnect.
      ///
      /// </summary>
      /// <throws>  MQException </throws>
      private void testSend()
      {
         MQQueueManager qMgr = null;
         MQQueue outQ = null;
         System.String line = "This is a test message embedded in the MQTest01P program.";
         int openOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING;
         MQPutMessageOptions pmo = new MQPutMessageOptions();

         try
         {
            qMgr = new MQQueueManager(qManager, qMgrProp);
            logger("successfully connected to " + qManager);

            outQ = qMgr.AccessQueue(outputQName, openOptions);
            logger("successfully opened " + outputQName);

            // Define a simple MQ message, and write some text in UTF format..
            MQMessage sendmsg = new MQMessage();
            sendmsg.Format = MQC.MQFMT_STRING;
            sendmsg.MessageType = MQC.MQMT_DATAGRAM;
            sendmsg.MessageId = MQC.MQMI_NONE;
            sendmsg.CorrelationId = MQC.MQCI_NONE;

            // .NET defaults to 1200 which is Windows double byte
            // So, use 819 to get single byte character set.
            sendmsg.CharacterSet = 819;

            // Add string property with key of "ABC" and value of "test1"
            sendmsg.SetStringProperty("ABC", "test1");

            sendmsg.WriteString(line);

            // put the message on the outQ
            outQ.Put(sendmsg, pmo);
            logger("Message Data:> " + line);
         }
         catch (MQException mqex)
         {
            logger("CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
         }
         catch (System.IO.IOException ioex)
         {
            logger("ioex=" + ioex);
         }
         finally
         {
            try
            {
                if (outQ != null)
                {
                    outQ.Close();
                    logger("closed: " + outputQName);
                }
            }
            catch (MQException mqex)
            {
                logger("CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
            }

            try
            {
                if (qMgr != null)
                {
                    qMgr.Disconnect();
                    logger("disconnected from " + qManager);
                }
            }
            catch (MQException mqex)
            {
                logger("CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
            }
         }
      }

      private void logger(String data)
      {
         DateTime myDateTime = DateTime.Now;
         System.Console.Out.WriteLine(myDateTime.ToString("yyyy/MM/dd HH:mm:ss.fff") + " " + this.GetType().Name + ": " + data);
      }

      /// <summary> main line</summary>
      /// <param name="args">
      /// </param>
      //        [STAThread]
      public static void Main(System.String[] args)
      {
         MQTest01P mqt = new MQTest01P();

         try
         {
            mqt.init(args);
            mqt.testSend();
         }
         catch (System.ArgumentException e)
         {
            System.Console.Out.WriteLine("Usage: MQTest01P -h host -p port -c channel -m QueueManagerName -q QueueName [-u userID] [-x passwd]");
            System.Environment.Exit(1);
         }
         catch (MQException e)
         {
            System.Console.Out.WriteLine(e);
            System.Environment.Exit(1);
         }

         System.Environment.Exit(0);
      }
   }
}

Regards,
Roger Lacroix
Capitalware Inc.

This entry was posted in .NET, C#, IBM MQ, Open Source, Programming, Windows.

Comments are closed.