/// <summary> /// Connect to MQ Server /// </summary> /// <param name="strQueueManagerName">Queue Manager Name</param> /// <param name="strChannelInfo">Channel Information</param> /// <returns></returns> public MQMessageStatus ConnectMQ(string strQueueManagerName, string strChannelName, string strHostName, string port, string userName, string password) { MQMessageStatus messageStatus = new MQMessageStatus(); string strReturn = string.Empty; queueProperties[MQC.HOST_NAME_PROPERTY] = strHostName; queueProperties[MQC.PORT_PROPERTY] = port; queueProperties[MQC.CHANNEL_PROPERTY] = strChannelName; queueProperties[MQC.USER_ID_PROPERTY] = userName; queueProperties[MQC.PASSWORD_PROPERTY] = password; try { queueManager = new MQQueueManager(strQueueManagerName, queueProperties); messageStatus.Message = "Connected Successfully"; messageStatus.Status = true; } catch (MQException exp) { strReturn = "Exception: " + exp.Message; messageStatus.Message = strReturn; messageStatus.Status = false; } catch (Exception exp) { strReturn = "Exception: " + exp.Message; messageStatus.Message = strReturn; messageStatus.Status = false; } return messageStatus; }
internal void InitiateForRecovery() { uint method = 0x520; this.TrEntry(method); try { this.Qmgr = new MQQueueManager(this.qmgrName_, this.properties); log.WriteLog("QMgr Connection Details: ", this.connname_ + ";" + this.channel_); if ((this.Qmgr != null) && this.Qmgr.IsConnected) { this.Queue = this.Qmgr.AccessQueue("SYSTEM.DOTNET.XARECOVERY.QUEUE", this.openOpts); this.RunRecovery(); if (this.reenter) { this.RunRecovery(); this.reenter = false; } this.Qmgr.Disconnect(); } } catch (MQException exception) { base.TrException(method, exception); throw exception; } finally { base.TrExit(method); } }
private void listen(MQQueue queue, MQQueueManager manager, string queueName, HandleMessage handler, OfacStatus status) { while (!pendingStop) { while (!pendingStop && currentMessagesToBeProcessed >= maxNoOfMessagesToProcess) { Thread.Sleep(5000); } if (pendingStop) { return; } try { MQMessage message = getMessage(queue); if (message == null) { continue; } handler(message, status); manager.Commit(); } catch (MQException e) { LogUtil.log("Error when getting message from the " + queueName + " queue", e); manager.Backout(); Thread.Sleep(30000); throw; } } }
private bool sendMessage(string queueName, int requestId, MQQueue queue, MQQueueManager manager, string messageId, string message, string correlationId, Object lockObject) { lock (lockObject) { bool sentMessage = false; try { MQPutMessageOptions pmo = new MQPutMessageOptions(); pmo.Options = MQC.MQOO_INQUIRE | MQC.MQPMO_FAIL_IF_QUIESCING | MQC.MQPMO_SYNCPOINT; MQMessage mqMessage = new MQMessage(); mqMessage.Write(System.Text.ASCIIEncoding.ASCII.GetBytes(message)); mqMessage.Format = MQC.MQFMT_STRING; mqMessage.MessageId = System.Text.ASCIIEncoding.ASCII.GetBytes(messageId); mqMessage.CorrelationId = System.Text.ASCIIEncoding.ASCII.GetBytes(correlationId); queue.Put(mqMessage, pmo); manager.Commit(); sentMessage = true; LogUtil.logInfo("Sent message " + requestId + " to " + queueName); LogUtil.logInfo("End SendMesage:"); } catch (MQException e) { sentMessage = false; manager.Backout(); LogUtil.log("Error sending the message to " + queue.Name + " queue", e); } return(sentMessage); } }
//message.WriteString("Message from MQ NetCore PUT"); //mqmgr.PutInQueue("QL.ITG.ALERTRAN.SUBSCRIBER.BOQ", message); //q.Get(message, gmo); //Console.WriteLine(message.ReadString(message.DataLength)); static void ConnectWithAuthentication() { Console.WriteLine("Connect to MQ With User & Password"); var mqmgr = MQQueueManager.Connect("QM.GLA.ITG.TEST.01", MQC.MQCO_NONE, "SYSTEM.DEF.SVRCONN", "10.20.7.45(1414)", "mq_ITG_test", "nwvq4368!"); mqmgr.Disconnect(); }
private MQMessage getMessagebyCorelationId(MQQueue queue, string correlationId) { MQGetMessageOptions gmo = new MQGetMessageOptions(); gmo.Options = MQC.MQGMO_FAIL_IF_QUIESCING | MQC.MQGMO_WAIT | MQC.MQGMO_SYNCPOINT | MQC.MQMO_MATCH_CORREL_ID; ; gmo.WaitInterval = 5000; MQMessage message = new MQMessage(); message.CorrelationId = System.Text.ASCIIEncoding.ASCII.GetBytes(correlationId); MQQueueManager manager = _mqManagerReviewQueue; try { //wait for message queue.Get(message, gmo);; manager.Commit(); } catch (MQException ex) { message = null; if (ex.CompletionCode == MQC.MQCC_FAILED && ex.ReasonCode == MQC.MQRC_NO_MSG_AVAILABLE) { return(null); } else { throw ex; } } return(message); }
public string ConnectMQ(string strQueueManagerName, string strQueueName, string strChannelInfo) { QueueManagerName = strQueueManagerName; QueueName = strQueueName; ChannelInfo = strChannelInfo; Hashtable table = new Hashtable(); table.Add(MQC.HOST_NAME_PROPERTY, "192.168.1.37"); table.Add(MQC.PORT_PROPERTY, 2414); table.Add(MQC.CHANNEL_PROPERTY, strChannelInfo); String strReturn = ""; try { queueManager = new MQQueueManager(strQueueManagerName, table); strReturn = "Connected Successfully"; } catch (MQException exp) { strReturn = "Exception: " + exp.Message; } return strReturn; }
public void PutFile(string quename, byte[] file) { MQQueue queue; // mq properties properties = new Hashtable(); properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED); properties.Add(MQC.HOST_NAME_PROPERTY, hostName); properties.Add(MQC.PORT_PROPERTY, port); properties.Add(MQC.CHANNEL_PROPERTY, channelName); // create connection queueManager = new MQQueueManager(queueManagerName, properties); // accessing queue queue = queueManager.AccessQueue(quename, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING); // creating a message object message = new MQMessage(); message.Write(file); queue.Put(message); // closing queue queue.Close(); // disconnecting queue manager queueManager.Disconnect(); }
/// <summary> /// 获取队列消息 /// </summary> private string GetQueueMsg(string business) { string message = string.Empty; try { string queueName = string.Format(IBMWMQConfig.TOPIC_TEMPLATE, business); using (var mqmgr = MQQueueManager.Connect(IBMWMQConfig.QUEUE_MGR_NAME, MQC.MQCO_NONE, IBMWMQConfig.CHANNEL, IBMWMQConfig.CONNECTION_INFO)) using (var q = mqmgr.AccessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING)) { var incoming = new MQMessage(); MQGetMessageOptions gmo = new MQGetMessageOptions(); gmo.WaitInterval = 10 * 1000; //MQC.MQWI_UNLIMITED; gmo.Options |= MQC.MQGMO_WAIT; gmo.Options |= MQC.MQGMO_SYNCPOINT; q.Get(incoming, gmo); message = incoming.ReadString(incoming.DataLength); } } catch (MQException e) { message = e.Reason.ToString(); } return(message); }
/// <summary> /// 向消息队列推送一条消息 /// </summary> /// <param name="msg">消息内容</param> /// <param name="queueName">队列名称</param> public void PushMsgToQueue1(string msg, string queueName) { try { using (var mqmgr = MQQueueManager.Connect(IBMWMQConfig.QUEUE_MGR_NAME, MQC.MQCO_NONE, IBMWMQConfig.CHANNEL, IBMWMQConfig.CONNECTION_INFO)) { if (mqmgr.IsConnected) { var outgoing = new MQMessage() { CharacterSet = MQC.CODESET_UTF, Encoding = MQC.MQENC_NORMAL }; outgoing.WriteString(msg); var od = new MQObjectDescriptor { ObjectType = MQC.MQOT_Q, ObjectName = queueName }; mqmgr.Put1(od, outgoing, new MQPutMessageOptions()); } } } catch (MQException e) { Trace.WriteLine(e.ToString()); } }
/// <summary> /// Helper method to write a message to an MQ Series queue /// </summary> /// <param name="queueManagerName">The name of the MQ Series queue manager</param> /// <param name="queueName">The name of the MQ Series queue to read from</param> /// <param name="message">The MQ Series queue</param> /// <param name="correlId">The correlation ID to be set on the new message</param> /// <param name="context">The BizUnit context object which holds state and is passed between test steps</param> public static void WriteMessage(string queueManagerName, string queueName, string message, byte[] correlId, Context context) { context.LogInfo("Opening queue manager: \"{0}\"", queueManagerName); using (var queueManager = new MQQueueManager(queueManagerName)) { context.LogInfo("Opening queue: '{0}'.", queueName); using (var sendQueue = queueManager.AccessQueue(queueName, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING) ) { var mqMessage = new MQMessage(); var data = ConvertToBytes(message); mqMessage.Write(data); mqMessage.Format = MQC.MQFMT_STRING; var mqPutMsgOpts = new MQPutMessageOptions(); context.LogInfo("Writing {0} byte message to queue '{1}'.", data.Length, queueName); if (correlId != null) { mqMessage.CorrelationId = correlId; } sendQueue.Put(mqMessage, mqPutMsgOpts); } } }
public string ReadOneMensage() { MQQueueManager qMgr = new MQQueueManager(IbmConection.DbConection[5], _queueManagerProperties); // Agora especifique a fila que queremos abrir e as opções de abertura MQQueue fila = qMgr.AccessQueue(IbmConection.DbConection[6], MQC.MQQA_GET_ALLOWED + MQC.MQQA_GET_INHIBITED + MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_INQUIRE + MQC.MQOO_BROWSE); MQMessage retrievedMessage = new MQMessage(); // Defina as opções de obtenção de mensagens MQGetMessageOptions gmo = new MQGetMessageOptions(); // aceita os padrões // mesmo que MQGMO_DEFAULT string msgText = ""; if (fila.CurrentDepth > 0) { // Tire a mensagem da fila fila.Get(retrievedMessage, gmo); msgText = retrievedMessage.ReadUTF(); return(msgText); } else { return(msgText); } }
public string ConnectMQ(string strQueueManagerName, string strQueueName, string strChannelInfo) { QueueManagerName = strQueueManagerName; QueueName = strQueueName; ChannelInfo = strChannelInfo; Hashtable table = new Hashtable(); table.Add(MQC.HOST_NAME_PROPERTY, "192.168.1.37"); table.Add(MQC.PORT_PROPERTY, 2414); table.Add(MQC.CHANNEL_PROPERTY, strChannelInfo); String strReturn = ""; try { queueManager = new MQQueueManager(strQueueManagerName, table); strReturn = "Connected Successfully"; } catch (MQException exp) { strReturn = "Exception: " + exp.Message; } return(strReturn); }
/// <summary> /// Connect to MQ Server /// </summary> /// <param name="strQueueManagerName">Queue Manager Name</param> /// <param name="strChannelInfo">Channel Information</param> /// <returns></returns> public MQMessageStatus ConnectMQ(string strQueueManagerName, string strChannelName, string strHostName, string port, string userName, string password) { MQMessageStatus messageStatus = new MQMessageStatus(); string strReturn = string.Empty; queueProperties[MQC.HOST_NAME_PROPERTY] = strHostName; queueProperties[MQC.PORT_PROPERTY] = port; queueProperties[MQC.CHANNEL_PROPERTY] = strChannelName; queueProperties[MQC.USER_ID_PROPERTY] = userName; queueProperties[MQC.PASSWORD_PROPERTY] = password; try { queueManager = new MQQueueManager(strQueueManagerName, queueProperties); messageStatus.Message = "Connected Successfully"; messageStatus.Status = true; } catch (MQException exp) { strReturn = "Exception: " + exp.Message; messageStatus.Message = strReturn; messageStatus.Status = false; } catch (Exception exp) { strReturn = "Exception: " + exp.Message; messageStatus.Message = strReturn; messageStatus.Status = false; } return(messageStatus); }
public string ConnectMQ(string strQueueManagerName, string strQueueName, string strChannelInfo) { // QueueManagerName = strQueueManagerName; QueueName = strQueueName; ChannelInfo = strChannelInfo; // char[] separator = { '/' }; string[] ChannelParams; ChannelParams = ChannelInfo.Split(separator); channelName = ChannelParams[0]; transportType = ChannelParams[1]; connectionName = ChannelParams[2]; String strReturn = ""; try { queueManager = new MQQueueManager(QueueManagerName, channelName, connectionName); strReturn = "Connected Successfully"; } catch (MQException exp) { strReturn = "Exception: " + exp.Message; } return(strReturn); }
/// <summary> /// Disconnect from MQ server and release all resources used. /// </summary> /// <returns>True if success.</returns> public bool Disconnect() { bool success = false; try { MyQueueMessage.ClearMessage(); MyQueueMessage = null; MyQueue.Close(); MyQueue = null; MyQueueManager.Disconnect(); MyQueueManager = null; success = true; GC.Collect(); } catch (MQException exp) { throw exp; } catch (Exception exp) { throw exp; } return(success); }
/// <summary> /// Instantiates the Queue Manager /// </summary> /// <param name="mqManager">The Queue Manager controlling the Request and Response Queues</param> public MQAdapter(string mqManager,string channel, string ipAddress, string putQueue,int timeout, int charSet, int port) { try { MQEnvironment.Hostname = ipAddress; MQEnvironment.Channel = channel; MQEnvironment.Port = WSMQ_DEFAULT_PORT; mqQueueManagerName = mqManager; mqRequestQueueName = putQueue; characterSet = charSet; pollingTimeout = timeout; // Connect to an MQ Manager, and share the connection handle with other threads mqQueueManager = new MQQueueManager(mqManager, channel, ipAddress); // Open Queue for Inquiry, Put Message in, and fail if Queue Manager is stopping mqPutQueue = mqQueueManager.AccessQueue(putQueue, MQC.MQOO_INQUIRE | MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_SET_IDENTITY_CONTEXT); } catch (MQException mqe) { throw new MQAdapterException("Error Code: " + MQAdapterErrorReasons.GetMQFailureReasonErrorCode(mqe.Reason)); } }
private void Purge() { var properties = new Hashtable { { MQC.HOST_NAME_PROPERTY, Settings.Hostname }, { MQC.PORT_PROPERTY, Settings.Port }, { MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT }, { MQC.CHANNEL_PROPERTY, Settings.Channel } }; using (var queueManager = new MQQueueManager(Settings.QueueManager, properties)) { var agent = new PCFMessageAgent(queueManager); var request = new PCFMessage(CMQCFC.MQCMD_CLEAR_Q); request.AddParameter(MQC.MQCA_Q_NAME, endpointAddress.QueueName); try { agent.Send(request); } catch (PCFException ex) { Logger.Warn(string.Format("Could not purge queue ({0}) at startup", endpointAddress.QueueName), ex); } } }
/// <summary> /// Instantiates the Queue Manager /// </summary> /// <param name="mqManager">The Queue Manager controlling the Request and Response Queues</param> public MQAdapter(string mqManager, string channel, string ipAddress, string putQueue, string getQueue, int timeout, int charSet, int port) { try { MQEnvironment.Hostname = ipAddress; MQEnvironment.Channel = channel; MQEnvironment.Port = 1000; mqQueueManagerName = mqManager; mqRequestQueueName = putQueue; mqResponseQueueName = getQueue; characterSet = charSet; pollingTimeout = timeout; // Connect to an MQ Manager, and share the connection handle with other threads mqQueueManager = new MQQueueManager(mqManager, channel, ipAddress); // Open Queue for Inquiry, Put Message in, and fail if Queue Manager is stopping mqPutQueue = mqQueueManager.AccessQueue(putQueue, MQC.MQOO_INQUIRE | MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_SET_IDENTITY_CONTEXT); mqGetQueue = mqQueueManager.AccessQueue(getQueue, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); } catch (MQException mqe) { throw new MQAdapterException("Error Code: " + MQAdapterErrorReasons.GetMQFailureReasonErrorCode(mqe.Reason)); } }
/// <summary> /// Connect to WebSphere host, queue manager, and channel. /// </summary> /// <param name="connectionNameList"></param> /// <param name="queueManagerName"></param> /// <param name="channelName"></param> /// <returns></returns> private bool Connect(string hostName, string queueManagerName, string channelName, string port) { try { _log.DebugFormat("MQConnector::Connect() - hostName:{0}, queueManagerName:{1}, channelName:{2}, port:{3}", hostName, queueManagerName, channelName, port); Hashtable properties = new Hashtable(); properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED); properties.Add(MQC.HOST_NAME_PROPERTY, hostName); properties.Add(MQC.CHANNEL_PROPERTY, channelName); properties.Add(MQC.PORT_PROPERTY, port); properties.Add(MQC.USER_ID_PROPERTY, username); properties.Add(MQC.PASSWORD_PROPERTY, password); _queueManager = new MQQueueManager(queueManagerName, properties); return(_queueManager.IsConnected); } catch (MQException mqe) { _log.ErrorFormat("MQException in MQConnector::Connect(string, string, string, string) method. Message: {0}", mqe.Message); } catch (Exception ex) { _log.ErrorFormat("Exception in MQConnector::Connect(string, string, string, string) method. Message: {0}", ex.Message); } return(false); }
public static int GetQueueDepth(MQQueueManager queuemgr, string queue) { return(queuemgr.AccessQueue(queue, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_INQUIRE).CurrentDepth); }
private void Reconnect(ref MQQueueManager queueManager, ref MQQueue queue, string queueName) { try { LogMsg(string.Format("开始重连MQ:{0},queueName:{1}", host, queueName)); try { if (queueManager != null) { queueManager.Disconnect(); } if (queue != null) { queue.Close(); } } catch (Exception e) { LogMsg("释放连接失败" + e); } queueManager = new MQQueueManager(uri, properties); queue = queueManager.AccessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); LogMsg(string.Format("重连MQ成功:{0},{1}", host, queueName)); if (ReconnectEvent != null) { ReconnectEvent(this.Tag, null); } } catch (Exception ex) { LogMsg(string.Format("重连MQ失败:host:{0},exp:{1}", host, ex)); } }
public bool Connect(string connectionNameList, string queueManagerName, string channelName, string mqport) { try { Hashtable properties = new Hashtable(); properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED); properties.Add(MQC.HOST_NAME_PROPERTY, connectionNameList); properties.Add(MQC.CHANNEL_PROPERTY, channelName); properties.Add(MQC.PORT_PROPERTY, mqport); //properties.Add(MQC.CONNECT_OPTIONS_PROPERTY, MQC.MQCNO_RECONNECT); properties.Add(MQC.USER_ID_PROPERTY, "nlkommoj"); properties.Add(MQC.PASSWORD_PROPERTY, "KDhruvan#7702140404"); _queueManager = new MQQueueManager(queueManagerName, properties); //eventLog1.WriteEntry("Connected to MQ"); return(_queueManager.IsConnected); } catch (MQException mqe) { //eventLog1.WriteEntry(""); //eventLog1.WriteEntry("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message); //eventLog1.WriteEntry(mqe.StackTrace); return(false); } catch (Exception ex) { //eventLog1.WriteEntry(""); //eventLog1.WriteEntry("Exception caught in MQHelper.Connect"); //eventLog1.WriteEntry(ex); return(false); } }
/// <summary> /// 发送 /// </summary> /// <param name="queueName">队列名称</param> /// <param name="sendMessages">发送内容</param> public void SendMessages(string queueName, string sendMessages) { MQQueueManager sQMgr = null; //发送消息的队列管理器 MQQueue remoteQ = null; //发送消息的队列 try { // 创建一个连接到队列管理器 sQMgr = new MQQueueManager(queueManagerName, ConnProperties); //现在指定要打开的队列, //和打开选项… remoteQ = sQMgr.AccessQueue(queueName, MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_INQUIRE); // 定义一个简单的WebSphere MQ消息 MQMessage putMessage = new MQMessage(); putMessage.WriteString(sendMessages); // 指定消息选项… MQPutMessageOptions pmo = new MQPutMessageOptions(); // 放入消息到队列 remoteQ.Put(putMessage, pmo); remoteQ.Close(); //关闭队列 sQMgr.Disconnect(); //关闭队列管理器连接 } catch { } }
public void TopicPublish_Ok() { var message = "PublishInTopic"; using (var broker = MQQueueManager.Connect(QueueManagerName, 0, Channel, ConnectionInfo)) using (var topic = new MQTopic(broker, TopicName, string.Empty, MQC.MQTOPIC_OPEN_AS_PUBLICATION, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING)) { var outgoing = new MQMessage() { CharacterSet = MQC.CODESET_UTF, Encoding = MQC.MQENC_NORMAL }; outgoing.WriteString(message); topic.Publish(outgoing, new MQPutMessageOptions()); } using (var broker = MQQueueManager.Connect(QueueManagerName, 0, Channel, ConnectionInfo)) using (var q = broker.AccessQueue("QL.R4.EMPLEADOSANDREANI.SUBSCRIBER", MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING)) { var incoming = new MQMessage(); MQGetMessageOptions gmo = new MQGetMessageOptions(); gmo.WaitInterval = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; //MQC.MQWI_UNLIMITED; gmo.Options |= MQC.MQGMO_WAIT; gmo.Options |= MQC.MQGMO_SYNCPOINT; q.Get(incoming, gmo); Assert.AreEqual(message, incoming.ReadString(incoming.DataLength)); } }
/// <summary> /// /// </summary> /// <param name="mqManager"></param> /// <param name="channel"></param> /// <param name="ipAddress"></param> /// <param name="putQueue"></param> /// <param name="getQueue"></param> /// <param name="timeout"></param> /// <param name="charSet"></param> /// <param name="port"></param> private void InitializeAdapter(string mqManager, string channel, string ipAddress, string putQueue, string getQueue, int timeout, int charSet, int port) { try { MQEnvironment.Hostname = ipAddress; MQEnvironment.Channel = channel; MQEnvironment.Port = port; mqQueueManagerName = mqManager; mqRequestQueueName = putQueue; mqResponseQueueName = getQueue; characterSet = charSet; pollingTimeout = timeout; mqQueueManager = new MQQueueManager(mqManager);//,channel, ipAddress); // Open Queue for Inquiry, Put Message in, and fail if Queue Manager is stopping mqPutQueue = mqQueueManager.AccessQueue(putQueue, MQC.MQOO_INQUIRE | MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_SET_IDENTITY_CONTEXT); mqGetQueue = mqQueueManager.AccessQueue(getQueue, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); } catch (MQException mqe) { NBK.Common.Foundations.Logging.LoggerHelper.Error(mqe); throw new MQAdapterException("Error Code: " + MQAdapterErrorReasons.GetMQFailureReasonErrorCode(mqe.Reason)); } }
private static readonly Encoding OutputEncoding = Encoding.GetEncoding(28591); // "iso-8859-1" public static MQQueue GetMqQueue(string queueName, bool browse, MQQueueManager queueManager) { var openOptions = browse ? MQC.MQOO_BROWSE : MQC.MQOO_INPUT_EXCLUSIVE + MQC.MQOO_FAIL_IF_QUIESCING; var mqQueue = queueManager.AccessQueue(queueName, openOptions); return(mqQueue); }
private void GetMessage() { try { using (MQQueueManager queueManager = new MQQueueManager(qMgr, connectionParams)) { var openOptions = MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_INQUIRE; MQQueue queue = queueManager.AccessQueue(queueName, openOptions); MQGetMessageOptions getOptions = new MQGetMessageOptions { WaitInterval = 5, Options = MQC.MQGMO_WAIT }; MQMessage msg = new MQMessage { Format = MQC.MQFMT_STRING }; queue.Get(msg, getOptions); queue.Close(); } } catch (Exception ex) { if (!isLogger) { logger.Error($"Unable to maintain queue: {queueName}: {ex.Message}"); } } }
public void MaintainQueueInline() { try { using (MQQueueManager queueManager = new MQQueueManager(qMgr, connectionParams)) { int openOptions = MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_INQUIRE; MQQueue queue = queueManager.AccessQueue(queueName, openOptions); MQGetMessageOptions getOptions = new MQGetMessageOptions { WaitInterval = 5, Options = MQC.MQGMO_WAIT }; MQMessage msg = new MQMessage { Format = MQC.MQFMT_STRING }; while (queue.CurrentDepth > this.maxMessages) { GetMessage(); } queue.Close(); } } catch (Exception ex) { if (!isLogger) { logger.Error($"Unable to maintain queue: {queueName}: {ex.Message}"); } } }
public void SendMQ(string xm) { string messageXML = xm; bool sent = false; int tries = 1; lock (sendLock) { try { using (MQQueueManager queueManager = new MQQueueManager(qMgr, connectionParams)) { var openOptions = MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING; MQQueue queue = queueManager.AccessQueue(queueName, openOptions); var message = new MQMessage { CharacterSet = 1208 // UTF-8 }; message.WriteString(messageXML); message.Format = MQC.MQFMT_STRING; MQPutMessageOptions putOptions = new MQPutMessageOptions(); queue.Put(message, putOptions); queue.Close(); sent = true; logger.Trace($"===Message Sent to {queueName}"); } } catch (Exception ex) { tries++; logger.Info(ex.Message); logger.Info("Error send MQ Message"); } if (!sent) { logger.Trace($"===Message NOT Sent to {queueName}"); } } }
public void Connect() { try { if (fMQueueManager == null) { fMQueueManager = new MQQueueManager(fQueueManagerName, fInitTabl); } if (!fMQueueManager.IsConnected) { fMQueueManager.Connect(); } fIsConnected = true; } catch (MQException mqe) { fIsConnected = false; throw new Exception(string.Format("Ha ocurrido un error intentando realizar la conexión con MQ. Error: {0}", mqe.Message)); } catch (Exception ex) { ex = ex.GetBaseException(); fIsConnected = false; throw new Exception(string.Format("Ha ocurrido un error intentando realizar la conexión con MQ. Error: {0}", ex.Message)); } }
public void Put1InQueue_Ok() { string message = "Put1InQueue"; using (var broker = MQQueueManager.Connect(QueueManagerName, 0, Channel, ConnectionInfo)) { var outgoing = new MQMessage() { CharacterSet = MQC.CODESET_UTF, Encoding = MQC.MQENC_NORMAL }; outgoing.WriteString(message); var od = new MQObjectDescriptor { ObjectType = MQC.MQOT_Q, ObjectName = QueueName }; broker.Put1(od, outgoing, new MQPutMessageOptions()); using (var q = broker.AccessQueue(QueueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING)) { var incoming = new MQMessage(); MQGetMessageOptions gmo = new MQGetMessageOptions(); gmo.WaitInterval = (int)TimeSpan.FromSeconds(30).TotalMilliseconds; //MQC.MQWI_UNLIMITED; gmo.Options |= MQC.MQGMO_WAIT; gmo.Options |= MQC.MQGMO_SYNCPOINT; q.Get(incoming, gmo); Assert.AreEqual(message, incoming.ReadString(incoming.DataLength)); } } }
private void Reconnect(ref MQQueueManager queueManager, ref MQTopic topic, string topicName) { try { LogMsg(string.Format("开始重连MQ:{0},{1}", host, topicName)); try { if (queueManager != null) { queueManager.Disconnect(); } if (topic != null) { topic.Close(); } } catch (Exception e) { LogMsg("释放连接失败" + e); } queueManager = new MQQueueManager(uri, properties); topic = queueManager.AccessTopic(topicName, null, MQC.MQSO_CREATE | MQC.MQSO_FAIL_IF_QUIESCING | MQC.MQSO_RESUME, null, DurableSubscriptionName); LogMsg(string.Format("重连MQ成功:{0},{1}", host, topicName)); if (ReconnectEvent != null) { ReconnectEvent(this.Tag, null); } } catch (Exception ex) { LogMsg(string.Format("重连MQ失败:host:{0},exp:{1}", host, ex)); } }
public static int GetCurrentQueueDebth(XmsAddress address) { var manager = new MQQueueManager(address.Host.Manager, address.Host.Channel, address.Host.ConnectionName); var queue = manager.AccessQueue(address.Queue, MQC.MQOO_INQUIRE); int depth = queue.CurrentDepth; manager.Disconnect(); manager.Close(); return depth; }
public MQSeries(string queueName, string queueManagerName, string host, string channel, int port) { MQEnvironment.Hostname = host; MQEnvironment.Channel = channel; MQEnvironment.Port = port; this.queueName = queueName; this.queueManagerName = queueManagerName; this.queueManager = new MQQueueManager(this.queueManagerName); }
/// <summary> /// Helper method to read a message from an MQ Series queue /// </summary> /// /// <param name="queueManagerName">The name of the MQ Series queue manager</param> /// <param name="queueName">The name of the MQ Series queue to read from</param> /// <param name="waitDelay">The time to wait for the message to be read from the queue</param> /// <param name="context">The BizUnit context object which holds state and is passed between test steps</param> /// <param name="msgID">[out] the MQ Series message ID</param> /// <returns>String containing the data from the MQ series message</returns> static public string ReadMessage(string queueManagerName, string queueName, int waitDelay, Context context, out byte[] msgID) { MQQueueManager queueManager = null; MQQueue receiveQueue = null; string message = null; try { context.LogInfo("Opening queue manager: \"{0}\"", queueManagerName); queueManager = new MQQueueManager(queueManagerName); context.LogInfo("Opening queue: \"{0}\"", queueName); receiveQueue = queueManager.AccessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); MQMessage mqMsg = new MQMessage(); MQGetMessageOptions mqMsgOpts = new MQGetMessageOptions(); mqMsgOpts.WaitInterval = waitDelay*1000; mqMsgOpts.Options = MQC.MQGMO_WAIT; context.LogInfo("Reading message from queue '{0}'.", queueName); receiveQueue.Get(mqMsg,mqMsgOpts); if(mqMsg.Format.CompareTo(MQC.MQFMT_STRING)==0) { mqMsg.Seek(0); message = System.Text.UTF8Encoding.UTF8.GetString(mqMsg.ReadBytes(mqMsg.MessageLength)); msgID = mqMsg.MessageId; } else { throw new NotSupportedException(string.Format("Unsupported message format: '{0}' read from queue: {1}.", mqMsg.Format, queueName)); } } finally { if (receiveQueue != null) { receiveQueue.Close(); } if (queueManager != null) { queueManager.Close(); } } return message; }
private static Task startTask(MQQueueManager manager, string queueName, int taskNumber, CancellationTokenSource token) { long messageCount = 0; TimeSpan maxLatencyTime = TimeSpan.MinValue; var options = new MQGetMessageOptions() { WaitInterval = WAIT_TIMEOUT }; return Task.Factory.StartNew(() => { Console.WriteLine("#{0}:\tTask started", taskNumber); while (!token.IsCancellationRequested) { var message = new MQMessage(); try { // the actual reading of message manager .AccessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING) .Get(message, options); messageCount++; } catch (MQException ex) { if (ex.ReasonCode != 2033) // unless there is no message - code 2033 Console.WriteLine("#{0}:\tError reading message code: {1} message: {2}", taskNumber, ex.ReasonCode, ex.Message); continue; } // decode timestamp of message when it was putted in source queue var timestamp = DateTime.ParseExact( ASCIIEncoding.ASCII.GetString(message.MQMD.PutDate) + ASCIIEncoding.ASCII.GetString(message.MQMD.PutTime), "yyyyMMddHHmmssff", CultureInfo.InvariantCulture); var latency = DateTime.UtcNow - timestamp; if (latency > maxLatencyTime || messageCount % 100 == 0) { // will print only on each 100 messages or when the larger latency detected if (latency > maxLatencyTime) maxLatencyTime = latency; Console.WriteLine("#{0}:\tMax latency time after {1} messages is {2}", taskNumber, messageCount, maxLatencyTime); } } }, token.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
private void GetMessages() { try { // mq properties Hashtable properties = new Hashtable(); properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED); properties.Add(MQC.HOST_NAME_PROPERTY, HostName); properties.Add(MQC.PORT_PROPERTY, Port); properties.Add(MQC.CHANNEL_PROPERTY, ChannelName); // create connection Console.Write("Connecting to queue manager.. "); MQQueueManager queueManager = new MQQueueManager(QueueManagerName, properties); Console.WriteLine("done"); // accessing queue Console.Write("Accessing queue " + QueueName + ".. "); MQQueue queue = queueManager.AccessQueue(QueueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); Console.WriteLine("done"); // creating a message options object MQGetMessageOptions mqGetMsgOpts = new MQGetMessageOptions(); mqGetMsgOpts.WaitInterval = MessageWaitTimeout; mqGetMsgOpts.Options = MQC.MQGMO_FAIL_IF_QUIESCING | MQC.MQGMO_WAIT; // getting messages continuously bool done = false; while (!done && !ShuttingDown) { try { // creating a message object MQMessage message = new MQMessage(); queue.Get(message, mqGetMsgOpts); string messageString = message.ReadString(message.MessageLength); handler.HandleMessage(messageString); message.ClearMessage(); } catch (MQException mqe) { if (mqe.ReasonCode != 2033) { Console.WriteLine("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message); done = true; } } } // closing queue Console.Write("Closing queue.. "); queue.Close(); Console.WriteLine("done"); // disconnecting queue manager Console.Write("Disconnecting queue manager.. "); queueManager.Disconnect(); Console.WriteLine("done"); } catch (MQException mqe) { Console.WriteLine(""); Console.WriteLine("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message); Console.WriteLine(mqe.StackTrace); } }
public static int GetCurrentQueueDebth(XmsDestination destination) { var manager = new MQQueueManager(destination.Manager, destination.Channel, destination.ConnectionName); var queue = manager.AccessQueue(destination.Queue, MQC.MQOO_INQUIRE); int depth = queue.CurrentDepth; manager.Disconnect(); manager.Close(); return depth; }
public void Open() { try { // mq properties Hashtable properties; properties = new Hashtable(); properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED); properties.Add(MQC.HOST_NAME_PROPERTY, this.HostName); properties.Add(MQC.PORT_PROPERTY, this.Port); properties.Add(MQC.CHANNEL_PROPERTY, this.ChannelName); // create connection _queueManager = new MQQueueManager(this.QueueManager, properties); // accessing queue //_queue = _queueManager.AccessQueue(this.QueueName, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING); _queue = _queueManager.AccessQueue(this.QueueName, MQC.MQOO_OUTPUT + MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); } catch (MQException mqe) { throw new Exception(string.Format("MQ Error: {0}", mqe.Message)); } catch (Exception ex) { throw new Exception(string.Format("Error: {0}", ex.Message)); } }
/// <summary> /// Helper method to write a message to an MQ Series queue /// </summary> /// /// <param name="queueManagerName">The name of the MQ Series queue manager</param> /// <param name="queueName">The name of the MQ Series queue to read from</param> /// <param name="message">The MQ Series queue</param> /// <param name="correlId">The correlation ID to be set on the new message</param> /// <param name="context">The BizUnit context object which holds state and is passed between test steps</param> static public void WriteMessage(string queueManagerName, string queueName, string message, byte[] correlId, Context context) { MQQueueManager queueManager = null; MQQueue sendQueue = null; MQMessage mqMessage; MQPutMessageOptions mqPutMsgOpts; try { context.LogInfo("Opening queue manager: \"{0}\"", queueManagerName); queueManager = new MQQueueManager(queueManagerName); context.LogInfo("Opening queue: '{0}'.", queueName); sendQueue = queueManager.AccessQueue(queueName, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING ); mqMessage = new MQMessage(); byte[] data = ConvertToBytes(message); mqMessage.Write(data); mqMessage.Format = MQC.MQFMT_STRING; mqPutMsgOpts = new MQPutMessageOptions(); context.LogInfo("Writing {0} byte message to queue '{1}'.", data.Length, queueName); if (correlId != null) { mqMessage.CorrelationId = correlId; } sendQueue.Put( mqMessage, mqPutMsgOpts ); } finally { if (sendQueue != null) { sendQueue.Close(); } if (queueManager != null) { queueManager.Close(); } } }
void SendMessage(string msg) { try { // mq properties Hashtable properties = new Hashtable(); properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED); properties.Add(MQC.HOST_NAME_PROPERTY, HostName); properties.Add(MQC.PORT_PROPERTY, Port); properties.Add(MQC.CHANNEL_PROPERTY, ChannelName); // create connection Console.Write("Connecting to queue manager.. "); MQQueueManager queueManager = new MQQueueManager(QueueManagerName, properties); Console.WriteLine("done"); // accessing queue Console.Write("Accessing queue " + QueueName + ".. "); MQQueue queue = queueManager.AccessQueue(QueueName, MQC.MQOO_OUTPUT); Console.WriteLine("done"); // creating a message object MQMessage message = new MQMessage(); message.WriteString(msg); // send the message queue.Put(message); // closing queue Console.Write("Closing queue.. "); queue.Close(); Console.WriteLine("done"); // disconnecting queue manager Console.Write("Disconnecting queue manager.. "); queueManager.Disconnect(); Console.WriteLine("done"); } catch (MQException mqe) { Console.WriteLine(""); Console.WriteLine("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message); Console.WriteLine(mqe.StackTrace); } }
/// <summary> /// ITestStep.Execute() implementation /// </summary> /// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public void Execute(XmlNode testConfig, Context context) { string qmgr = context.ReadConfigAsString(testConfig, "QueueManager"); MQQueueManager queueManager; try { context.LogInfo("Opening queue manager '{0}'.", qmgr); queueManager = new MQQueueManager(qmgr); } catch (Exception e) { throw new ApplicationException(string.Format("Failed to open queue manager {0}.", qmgr), e); } bool errors = false; try { XmlNodeList queueNodes = testConfig.SelectNodes("Queue"); foreach (XmlNode queueNode in queueNodes) { string q = queueNode.InnerText; context.LogInfo("Opening queue '{0}'.", q); MQQueue queue = queueManager.AccessQueue(q, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); try { MQMessage mqMsg = new MQMessage(); MQGetMessageOptions mqMsgOpts = new MQGetMessageOptions(); int i = 0; bool finished = false; while (!finished) { try { // Get message from queue queue.Get(mqMsg,mqMsgOpts); i++; } catch (MQException mqe) { if (mqe.Reason == 2033) // No more messages. { finished = true; } else { throw; } } } context.LogInfo("Cleared {0} messages from queue '{1}'.", i, q); } catch (Exception e) { context.LogError("Failed to clear queue \"{0}\" with the following exception: {1}", q, e.ToString()); errors = true; } finally { if (queue != null) { queue.Close(); } } } } finally { if (queueManager != null) { queueManager.Close(); } if (errors) { throw new ApplicationException("Failed to clear at least one queue."); } } }
static void Main(string[] args) { var stopper = new Stopwatch(); stopper.Start(); AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); var options = new Options(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) return; var _prop = new Hashtable(); _prop.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED); _prop.Add(MQC.HOST_NAME_PROPERTY, options.Host); _prop.Add(MQC.PORT_PROPERTY, options.Port); _prop.Add(MQC.CHANNEL_PROPERTY, "SYSTEM.DEF.SVRCONN"); if (!String.IsNullOrEmpty(options.User)) { _prop.Add(MQC.USER_ID_PROPERTY, options.User); _prop.Add(MQC.PASSWORD_PROPERTY, options.Password); } MQQueueManager manager = null; try { Console.Write("Connecting to {0}:{1}...", _prop[MQC.HOST_NAME_PROPERTY], _prop[MQC.PORT_PROPERTY]); manager = new MQQueueManager(options.QueueManagerName, _prop); Console.WriteLine(" connected"); Console.WriteLine("Starting {0} threads...", options.ThreadsCount); var tasks = new List<Task>(); var cancelToken = new CancellationTokenSource(); // threads creation for (int i = 0; i < options.ThreadsCount; i++) tasks.Add(startTask(manager, options.QueueName, i + 1, cancelToken)); Console.WriteLine("You can hit any key now to exit"); Console.ReadKey(); Console.WriteLine("Stopping..."); // abort work on tasks cleanUp(tasks, cancelToken); } catch (MQException ex) { Console.WriteLine("MQException error code: {0} message: {0}", ex.ReasonCode, ex.Message); } catch (Exception ex) { Console.WriteLine("General error {0}", ex.Message); } finally { if (manager != null) manager.Disconnect(); } stopper.Stop(); Console.WriteLine("\nDone. All in all was up: {0}", stopper.Elapsed); }