C# .NET Code to Get a Message from a Remote Queue Manager

In my previous posting here, I did a write up of putting a message to a queue in a remote queue manager using C# .NET. In this blog posting, I’ll show you how to get a message from a queue of a remote queue manager using C# .NET.

If you are familiar with IBM MQ Classes for Java then writing code with IBM MQ Classes for .NET will be very straightforward.

The only word of warning I have for C# developers is to make sure you do NOT use a .NET Framework higher than what IBM MQ supports. Otherwise, you may get weird errors.

Here is a fully functioning C# .NET MQ example that will connect to a remote queue manager and get a message from a queue using a managed .NET environment. 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
/// MQTest02
///
/// Description
/// This C# class will connect to a remote queue manager
/// and get a message from a queue 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, Capitalware Inc.
/// </author>
namespace MQTest02
{
   class MQTest02
   {
      private Hashtable inParms = null;
      private Hashtable qMgrProp = null;
      private System.String qManager;
      private System.String outputQName;

      /*
      * The constructor
      */
      public MQTest02()
         : 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"]));

            System.Console.Out.WriteLine("MQTest02:");
            Console.WriteLine("  QMgrName ='{0}'", qManager);
            Console.WriteLine("  Output QName ='{0}'", outputQName);

            System.Console.Out.WriteLine("QMgr Property values:");
            foreach (DictionaryEntry de in qMgrProp)
            {
               Console.WriteLine("  {0} = '{1}'", de.Key, de.Value);
            }
         }
         else
         {
            throw new System.ArgumentException();
         }
      }

      /// <summary> Connect, open queue, read a message, close queue and disconnect.
      ///
      /// </summary>
      /// <throws>  MQException </throws>
      private void testReceive()
      {
         MQQueueManager qMgr = null;
         MQQueue inQ = null;
         int openOptions = MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING;
         MQGetMessageOptions gmo = new MQGetMessageOptions();
         MQMessage receiveMsg = null;

         try
         {
            qMgr = new MQQueueManager(qManager, qMgrProp);
            System.Console.Out.WriteLine("MQTest02 successfully connected to " + qManager);

            inQ = qMgr.AccessQueue(outputQName, openOptions);
            System.Console.Out.WriteLine("MQTest02 successfully opened " + outputQName);

            receiveMsg = new MQMessage();

            inQ.Get(receiveMsg, gmo);
            System.Console.Out.WriteLine("Message Data>>>" + receiveMsg.ReadString(receiveMsg.MessageLength));
         }
         catch (MQException mqex)
         {
            System.Console.Out.WriteLine("MQTest02 cc=" + mqex.CompletionCode + " : rc=" + mqex.ReasonCode);
         }
         catch (System.IO.IOException ioex)
         {
            System.Console.Out.WriteLine("MQTest02 ioex=" + ioex);
         }
         finally
         {
            try
            {
                if (inQ != null)
                {
                    inQ.Close();
                    System.Console.Out.WriteLine("MQTest02 closed: " + outputQName);
                }
            }
            catch (MQException mqex)
            {
                System.Console.Out.WriteLine("MQTest02 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
            }

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

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

         try
         {
            mqt.init(args);
            mqt.testReceive();
         }
         catch (System.ArgumentException e)
         {
            System.Console.Out.WriteLine("Usage: MQTest02 -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);
      }
   }
}

Here is the batch file I used to compiled the code as a 32-bit executable:

@echo off
setlocal

if "%MQ_FILE_PATH%".=="". set MQ_FILE_PATH=C:\Program Files\IBM\WebSphere MQ

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\csc.exe /nologo /t:exe /r:System.dll /r:"%MQ_FILE_PATH%\Tools\lib\amqmdnet.dll" /out:bin\Release\MQTest02.exe MQTest02.cs

endlocal

And here is the batch file I used to compiled the code as a 64-bit executable:

@echo off
setlocal

if "%MQ_FILE_PATH%".=="". set MQ_FILE_PATH=C:\Program Files\IBM\WebSphere MQ

C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\csc.exe /nologo /t:exe /platform:x64 /r:System.dll /r:"%MQ_FILE_PATH%\Tools\lib64\amqmdnet.dll" /out:bin\Release\MQTest02_64.exe MQTest02.cs

endlocal

As I mentioned in my other C# .NET posting, I’m using the .NET V2 Framework. It might be old but for basic C# code, it works perfectly.

Regards,
Roger Lacroix
Capitalware Inc.

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

Comments are closed.