Search code examples
c#ibm-mqjndixms

How can I connect to IBM MQ using JNDI in c#?


I am currently able to connect to a IBM MQ using IBMXMSDotnetClient by specifying the connection properties directly in the c# code like below.

XMSFactoryFactory factory = XMSFactoryFactory.GetInstance(XMSC.CT_WMQ);
IConnectionFactory connFactory = factory.CreateConnectionFactory();
connFactory.SetStringProperty(XMSC.WMQ_HOST_NAME, "xxx");
connFactory.SetIntProperty(XMSC.WMQ_PORT, 1414);
connFactory.SetStringProperty(XMSC.WMQ_CHANNEL, "xxx");
connFactory.SetIntProperty(XMSC.WMQ_CONNECTION_MODE, XMSC.WMQ_CM_CLIENT);
connFactory.SetStringProperty(XMSC.WMQ_QUEUE_MANAGER, "xxx");

But in Java, it seems that it can be done by JNDI bindings file.

From what I can see, it looks like that JNDI is something like TNS file (which specifies the connection details such host, port, SID, etc.) used by the client to connect to server in Oracle. Is my understanding correct?

If it is the case, is it possible to connect to the IBM MQ by JNDI bindings files using IBMXMSDotnetClient? All examples I can find is to set the connection properties (connFactory.SetXXXProperty) directly.


Solution

  • I have this snippet to create initial context and use it to create connection factory and sessions. Hope it will get you started.

            InitialContext ic = null;
            IConnectionFactory confac = null;
            IConnection conn = null;
            ISession sess = null;
            IMessageConsumer cons = null;
            IDestination dest = null;
    
            try
            {
                System.Collections.Hashtable env = new System.Collections.Hashtable();
                // Set the URL or PATH where the bindings file is located
                env[XMSC.IC_URL] = "file://c:/mqbindings/.bindings";
                // Initialize the context
                ic = new InitialContext(env);
                // Lookup for the connection factory name
                confac = (IConnectionFactory)ic.Lookup("myconfactoryname");
                // Create connection using the details from connection factory
                conn = (IConnection)confac.CreateConnection();
                // Create an auto ack session
                sess = conn.CreateSession(false, AcknowledgeMode.AutoAcknowledge);
                // Lookup for the destination
                dest = (IDestination)ic.Lookup("myqueue");
                // ... rest of the code - create consumer or producer
            } 
            catch (XMSException xmsE)
            {
                    // Handle exception
            }