public string ReadMsg() { String strReturn = ""; try { queue = queueManager.AccessQueue(QueueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); queueMessage = new MQMessage(); queueMessage.Format = MQC.MQFMT_STRING; queueGetMessageOptions = new MQGetMessageOptions(); queue.Get(queueMessage, queueGetMessageOptions); strReturn = queueMessage.ReadString(queueMessage.MessageLength); } catch (MQException MQexp) { strReturn = "Exception : " + MQexp.Message; } catch (Exception exp) { strReturn = "Exception: " + exp.Message; } return(strReturn); }
private void tmrSubscribe_Tick(object sender, EventArgs e) { MQMessage message = new MQMessage(); try { if (subscriber != null) { subscriber.Get(message); } if (message != null) { txMessage.Text += message.ReadString(message.MessageLength) + Environment.NewLine; } } catch (MQException mqex) { if (mqex.ReasonCode == IBM.WMQ.MQC.MQRC_NO_MSG_AVAILABLE) { txMessage.Text += Environment.NewLine + "No new messages."; } else { MessageBox.Show(mqex.Message + Environment.NewLine + mqex.StackTrace + Environment.NewLine + mqex.Source + Environment.NewLine + mqex.GetBaseException()); } } }
/// <summary> /// Extracts the messages from an WMQ <see cref="MQMessage"/>. /// </summary> /// <param name="message">The WMQ message to extract from.</param> /// <returns>An array of handleable messages.</returns> protected IMessage[] Extract(MQMessage message) { // return this.messageSerializer.Deserialize((MemoryStream)message.ReadObject()); MemoryStream stream = new MemoryStream(StringToByteArray(message.ReadString(message.MessageLength))); return(this.messageSerializer.Deserialize(stream)); }
string sendMessage(string message, string queueName) { try { queue = qMgr.AccessQueue(queueName, MQC.MQOO_OUTPUT | MQC.MQOO_INPUT_SHARED | MQC.MQOO_INQUIRE); } catch (MQException e) { return("打开队列失败:" + e.Message); } var mqMsg = new MQMessage(); mqMsg.WriteString(message); var putOptions = new MQPutMessageOptions(); try { queue.Put(mqMsg, putOptions); return("消息放置完毕"); } catch (MQException mqe) { return("发送异常终止:" + mqe.Message); } finally { try { qMgr.Disconnect(); } catch (MQException e) { } } }
public void LoopThruMessages() { MQGetMessageOptions gmo = new MQGetMessageOptions(); gmo.Options |= MQC.MQGMO_WAIT | MQC.MQGMO_FAIL_IF_QUIESCING; gmo.WaitInterval = 2500; // 2.5 seconds wait time or use MQC.MQEI_UNLIMITED to wait forever MQMessage msg = null; while (running) { try { msg = new MQMessage(); inQ.Get(msg, gmo); System.Console.Out.WriteLine("Message Data: " + msg.ReadString(msg.MessageLength)); } catch (MQException mqex) { if (mqex.Reason == MQC.MQRC_NO_MSG_AVAILABLE) { // no meesage - life is good - loop again } else { running = false; // severe error - time to exit System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode); } } catch (System.IO.IOException ioex) { System.Console.Out.WriteLine("ioex=" + ioex); } } try { if (inQ != null) { inQ.Close(); System.Console.Out.WriteLine("Closed queue"); } } catch (MQException mqex) { System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode); } try { if (qMgr != null) { qMgr.Disconnect(); System.Console.Out.WriteLine("disconnected from queue manager"); } } catch (MQException mqex) { System.Console.Out.WriteLine("MQException CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode); } }
public bool CheckDumpIsValid(string filename, CancellationToken ct, out int messagesCount, out string error) { messagesCount = 0; error = null; try { using (var sr = new StreamReader(filename)) { var dr = new DumpReader(sr); MQMessage msg = null; // we simulate, so we don't need the mq message while (ReadFileMessage(dr, out msg, true)) { messagesCount++; } } return(true); } catch (DumpException ex) { error = ex.Message; return(false); } catch (Exception ex) { error = $"Unexpected error ({ex.Message})"; return(false); } }
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}"); } } }
internal override bool IsLast(MQMessage message) { cfh.Initialize(message); String current = null; int count = this.cfh.ParameterCount; while (count > 0) { PcfParameter p = PcfParameter.NextParameter(message); int id = p.Parameter; if (id == MQC.MQBACF_RESPONSE_SET) { this.set.Add(p.GetStringValue()); } else if (id == MQC.MQBACF_RESPONSE_ID) { current = p.GetStringValue(); this.set.Add(current); } count--; } message.Seek(0); if ((this.cfh.Control == 1) && (current != null)) { this.set.Remove(current); } return(this.set.Count == 0); }
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 T Call <T>(MQMessage sendMsg, int timeoutMilliseconds) where T : class { bool flag = false; Type type = typeof(T); T local = default(T); object obj2 = this._LockObj; lock (obj2) { this.Send(sendMsg); DataItem <MQMessage> item = this._lstDeviceDataQueue.Pull(f => f.Data != null && f.Data.MsgId == sendMsg.MsgId, TimeSpan.FromMilliseconds((double)timeoutMilliseconds)); if (((item != null) && (item.Data != null)) && (item.Data.Body != null)) { if (flag) { local = Encoding.UTF8.GetString(item.Data.Body) as T; } else { local = SerializationUtility.BytesToObject <T>(item.Data.Body); } } return(local); } }
public bool PutMessage(string queueName, string message) { bool success = false; MQQueue queue = null; try { //eventLog1.WriteEntry("Accessing queue {0}", queueName); queue = _queueManager.AccessQueue(queueName, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING); MQMessage queueMessage = new MQMessage(); queueMessage.CharacterSet = 1208; // force to UTF-8 for InService queueMessage.WriteString(message); queueMessage.Format = MQC.MQFMT_STRING; MQPutMessageOptions queuePutMessageOptions = new MQPutMessageOptions(); queue.Put(queueMessage, queuePutMessageOptions); success = true; } catch (MQException mqe) { success = false; //eventLog1.WriteEntry("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message); //throw new Exception(string.Format("Error writing to {0} queue", queueName)); } finally { if (queue != null) { //eventLog1.WriteEntry("Closing queue"); queue.Close(); } } return(success); }
private QueueMessage ConvertBack(MQMessage msg) { return(new QueueMessage() { Data = msg.ReadBytes(msg.DataLength), }); }
/// <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); }
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> /// Converts an WMQ <see cref="MQMessage"/> into an NServiceBus message. /// </summary> /// <param name="mqMessage">The WMQ message to convert.</param> /// <returns>An NServiceBus message.</returns> public TransportMessage ConvertToTransportMessage(MQMessage mqMessage) { TransportMessage result = new TransportMessage(); result.Id = ByteArrayToString(mqMessage.MessageId); result.CorrelationId = (ByteArrayToString(mqMessage.CorrelationId).Equals("00000000-0000-0000-0000-000000000000\\0", StringComparison.InvariantCulture) ? null : ByteArrayToString(mqMessage.CorrelationId)); // TODO Can we get recoverable and time to be received properties from Wmq? //result.Recoverable = mqMessage.Recoverable; //result.TimeToBeReceived = mqMessage.TimeToBeReceived; result.ReturnAddress = mqMessage.ReplyToQueueName; FillIdForCorrelationAndWindowsIdentity(result, mqMessage); if (string.IsNullOrEmpty(result.IdForCorrelation)) { result.IdForCorrelation = result.Id; } //TODO Does Wmq have a place to store header information //if (mqMessage.Extension != null) // if (mqMessage.Extension.Length > 0) // { // MemoryStream stream = new MemoryStream(mqMessage.Extension); // object o = headerSerializer.Deserialize(stream); // result.Headers = o as List<HeaderInfo>; // } return(result); }
public List <MQMessage> BrowseMessages(string queueName) { int totalMessages = MessageCount(queueName); MQQueue mqQueue = _mqQueueManager.AccessQueue(queueName, MQC.MQOO_BROWSE); MQGetMessageOptions messageOptions = new MQGetMessageOptions { Options = MQC.MQGMO_BROWSE_FIRST }; if (totalMessages > 0) { List <MQMessage> messages = new List <MQMessage>(); for (int i = 1; i <= totalMessages; i++) { // Gettin an IBM MQ message from the queue. MQMessage message = new MQMessage(); mqQueue.Get(message, messageOptions); messages.Add(message); // get next message messageOptions.Options = MQC.MQGMO_BROWSE_NEXT; } mqQueue.Close(); return(messages); } mqQueue.Close(); return(null); }
void PurgeInputQueue() { MQGetMessageOptions getMessageOptions = new MQGetMessageOptions(); getMessageOptions.Options |= MQC.MQGMO_NO_WAIT; bool isContinue = true; while (isContinue) { MQMessage message = new MQMessage(); try { receiveResourceManager.GetMessage(message, getMessageOptions); } catch (MQException mqe) { // report reason, if any if (mqe.Reason == MQC.MQRC_NO_MSG_AVAILABLE) { isContinue = false; } else { // general report for other reasons throw new ApplicationException("MQQueue::Get ended with " + mqe.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)); } } }
public MQCFH(MQMessage message) { this.version = 1; this.msgSeqNumber = 1; this.control = 1; this.Initialize(message); }
public IMessage NewMessage(string content, int?priority, int?characterSet, Dictionary <string, object> extendedProperties = null) { var ibmMsg = new MQMessage { Priority = priority ?? DefaultPriority, CharacterSet = characterSet ?? QueueManager.DefaultCharacterSet, Format = MQC.MQFMT_STRING }; if (extendedProperties != null) { if (extendedProperties.ContainsKey("CorrelationId")) { if (extendedProperties["CorrelationId"] is byte[] corrId && corrId.Length == 24) { // Fine we got a valid correlationid; set it ibmMsg.CorrelationId = corrId; } } if (extendedProperties.ContainsKey("GroupId")) { if (extendedProperties["GroupId"] is byte[] grpId && grpId.Length == 24) { // Fine we got a valid groupid; set it ibmMsg.GroupId = grpId; if (extendedProperties.ContainsKey("LogicalSequenceNumber") && extendedProperties["LogicalSequenceNumber"] is int lsn) { ibmMsg.MessageSequenceNumber = lsn; } } } } ibmMsg.WriteString(content); return(new WsMessage(ibmMsg)); }
private void CallBack(object obj, BasicDeliverEventArgs ea, Action <MQMessage> callAction) { if (callAction != null) { try { MQMessage message = ea.Body.ToMessage(); message.MsgId = ea.BasicProperties.MessageId; message.Label = ea.BasicProperties.CorrelationId; message.MsgId = ea.BasicProperties.MessageId; if (message.Response != null) { MQMsgRequest request1 = new MQMsgRequest { Exchange = message.Response.Exchange, RequestRouteKey = message.Response.ResponseRouteKey }; message.Request = request1; } callAction(message); } catch (Exception exception) { Console.WriteLine(exception.Message); } finally { this.Channel.BasicAck(ea.DeliveryTag, false); } } }
private string GetMessage(MQGetMessageOptions getMessageOptions) { // transactions: add wait // transactions: add rollback wait check try { // if transaction exists, add transaction complete handler var message = new MQMessage(); _queue.Get(message, getMessageOptions); var result = message.ReadString(message.MessageLength); message.ClearMessage(); return(result); } catch (MQException mqe) { // queue empty if (mqe.ReasonCode == 2033) { return(null); } // wrap exception throw; } }
private bool SetBrowseCursorAtMessageId(MQQueue queue, byte[] msgId) { var getMsgOpts = new MQGetMessageOptions() { Options = MQC.MQGMO_FAIL_IF_QUIESCING | MQC.MQGMO_BROWSE_FIRST }; try { getMsgOpts.MatchOptions = MQC.MQMO_MATCH_MSG_ID; var msg = new MQMessage { MessageId = msgId }; queue.Get(msg, getMsgOpts); return(true); } catch (MQException ex) { if (ex.ReasonCode != MQC.MQRC_NO_MSG_AVAILABLE) { throw; } return(false); } }
/// <summary> /// 消息侦听 /// </summary> /// <param name="message"></param> private static void consumer_Listener(MQMessage message) { try { message.Begin(); MQSendRequestModel obj = Newtonsoft.Json.JsonConvert.DeserializeObject <MQSendRequestModel>(message.messageContent); var plugin = PluginList.Find(p => p.Module == obj.MODULE); if (plugin != null) { plugin.Process(EasyJson.Parse(obj.Arguments.ToString())); } else { Logger.MQLog.Error("命令类型[" + obj.MODULE + "]未被识别!"); } // Logger.MQLog.Info("消息处理:" + message.messageContent); message.Commit(); } catch (Exception ex) { string logmsg = "消息[" + message.messageContent.ToString() + "]处理失败,准备回滚事务!原因:" + ex.Message; Logger.MQLog.Error(logmsg, ex); message.RollBack(); } }
/// <summary> /// Puts a message object in the queue. /// </summary> /// <param name="queueName"></param> /// <param name="message"></param> private void PutRequestMessage(string connectionKeyName, MQMessage message) { MQQueue queue = null; try { if (!IsConnected) { Connect(connectionKeyName); } MQPutMessageOptions queuePutMessageOptions = new MQPutMessageOptions(); queue = _queueManager.AccessQueue(_activeConnection.RequestQueue, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING); queue.Put(message, queuePutMessageOptions); } catch (MQException mqe) { _log.ErrorFormat("Exception in PutRequestMessage(). Message: {0}", mqe.Message); } finally { if (queue != null) { queue.Close(); } } }
public MQMsgRef receive(int timeout, MQMsgRef mqMsgRef) { if (cfgReceiveData == null) { throw new EisException("Fail to init receive queue."); } MQMessage receiveMsg = getMQMsg(mqMsgRef, timeout); if (receiveMsg == null) { throw new EisException("Fail to get mq msg."); } byte[] response = MQQueueAccesser.getBytesFromMQMessage(receiveMsg); // logUtil.info("replyToQueueManagerName::" + receiveMsg.replyToQueueManagerName); // if (logUtil.isInfoEnabled()) { // StringBuffer sb; // try { // sb = new StringBuffer().append("receive message:\n").append(new String(response, encoding)); // logUtil.info(sb.toString()); // } catch (UnsupportedEncodingException e) { // logUtil.error("Exception:", e); // } // sb = null; // } MQMsgRef mQMsgRef = new MQMsgRef(receiveMsg.MessageId, response); return(mQMsgRef); }
static void Main(string[] args) { IObserver <MQMessage> errorQueue = new OutboundMessageQueue("QM1", "DEV.DEAD.LETTER.QUEUE", host: "mqhost.local", port: 1414, channel: "DEV.APP.SVRCONN"); IObservable <MQMessage> inbound = new InboundMessageQueue("QM1", "DEV.QUEUE.1", host: "mqhost.local", port: 1414, channel: "DEV.APP.SVRCONN", errorQueue: errorQueue); IObserver <MQMessage> outbound = new OutboundMessageQueue("QM1", "DEV.QUEUE.1", host: "mqhost.local", port: 1414, channel: "DEV.APP.SVRCONN"); IObservable <string> stringObservable = new MQStringAdapterSubject(inbound); stringObservable.Subscribe(mqmessage => { log.Info($"Received message: {mqmessage}"); // throw new Exception("Opsy"); }); while (true) { MQMessage message = new MQMessage(); message.WriteString("hello"); outbound.OnNext(message); Thread.Sleep(250); } Console.ReadLine(); }
string getMessage(string queueName) { try { queue = qMgr.AccessQueue(queueName, MQC.MQOO_OUTPUT | MQC.MQOO_INPUT_SHARED | MQC.MQOO_INQUIRE); } catch (MQException e) { return("打开队列失败:" + e.Message); } try { MQMessage message = new MQMessage(); queue.Get(message); string s = message.ReadString(message.MessageLength); return(s); } catch (MQException mqe) { // return ("获取异常终止:" + mqe.Message); } finally { try { qMgr.Disconnect(); } catch (MQException e) { } } return(""); }
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 string WriteMsg(string strInputMsg) { string strReturn = ""; try { queue = queueManager.AccessQueue(QueueName, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING); message = strInputMsg; queueMessage = new MQMessage(); queueMessage.WriteString(message); queueMessage.Format = MQC.MQFMT_STRING; queuePutMessageOptions = new MQPutMessageOptions(); queue.Put(queueMessage, queuePutMessageOptions); strReturn = "Message sent to the queue successfully"; } catch (MQException MQexp) { strReturn = "Exception: " + MQexp.Message; } catch (Exception exp) { strReturn = "Exception: " + exp.Message; } return(strReturn); }
public void PutMessageOnQueue(string message) { MQMessage queueMessage = new MQMessage(); queueMessage.Format = MQC.MQFMT_STRING; queueMessage.Persistence = 0; queueMessage.WriteString(message); queueMessage.ReplyToQueueManagerName = this.queueManagerName; queueMessage.ReplyToQueueName = this.replyQueueName; this.queueManager.Put(this.queueName, this.queueManagerName, queueMessage); }
/// <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; }
/// <summary> /// Puts a message in an MQ Queue using the user Id provided /// <param name="message">The message to be put in the queue</param> /// <returns>Response message</returns> /// </summary> public string postMQRequestMessage(string message) { try { MQMessage requestMessage = new MQMessage(); requestMessage.Persistence = 0; requestMessage.ReplyToQueueName = mqRequestQueueName; requestMessage.ReplyToQueueManagerName = mqQueueManagerName; requestMessage.Format = MQC.MQFMT_STRING; requestMessage.CharacterSet = characterSet; requestMessage.MessageType = MQC.MQMT_REQUEST; requestMessage.MessageId = HexaDecimalUtility.ConvertToBinary(GenerateMQMsgId()); requestMessage.CorrelationId = requestMessage.MessageId; MQPutMessageOptions pmo = new MQPutMessageOptions(); pmo.Options = MQC.MQPMO_SET_IDENTITY_CONTEXT; requestMessage.WriteString(message); mqPutQueue.Put(requestMessage, pmo); string _msgId = BinaryUtility.ConvertToHexaDecimal(requestMessage.MessageId); return _msgId; } catch (MQException mqe) { // Close request Queue if still opened if(mqPutQueue.OpenStatus) mqPutQueue.Close(); // Close Queue manager if still opened if(mqQueueManager.OpenStatus) mqQueueManager.Close(); throw new MQAdapterException("Error Code: " + MQAdapterErrorReasons.GetMQFailureReasonErrorCode(mqe.Reason)); } }
public string WriteMsg(string strInputMsg) { string strReturn = ""; try { queue = queueManager.AccessQueue(QueueName, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING); message = strInputMsg; queueMessage = new MQMessage(); queueMessage.WriteBytes(strInputMsg); queueMessage.ReplyToQueueName = "MBK.SESION3.SALIDA"; queueMessage.OriginalLength = 120; queueMessage.ReplyToQueueManagerName = "IB9QMGR"; queueMessage.DataOffset = 328; queueMessage.Format = MQC.MQFMT_STRING; queuePutMessageOptions = new MQPutMessageOptions(); try { queue.Put(queueMessage, queuePutMessageOptions); strReturn = "Message sent to the queue successfully"; } catch (MQException e) { strReturn = "Exception: " + "error al colocar(put) el mensaje en la cola " + QueueName + ". " + e.ToString(); } } catch (MQException MQexp) { strReturn = "Exception: " + MQexp.Message; } catch (Exception exp) { strReturn = "Exception: " + exp.Message; } return strReturn; }
public string GetMessageOffQueue() { string message = ""; try { MQMessage queueMessage = new MQMessage(); MQQueue queue = this.queueManager.AccessQueue(this.queueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); queueMessage.Format = MQC.MQFMT_STRING; queue.Get(queueMessage); message = queueMessage.ReadString(queueMessage.MessageLength); queue.Close(); } catch (MQException mqexp) { } return message; }
/// <summary> /// Write Message to Local Queue /// </summary> /// <param name="strInputMsg">Text Message</param> /// <param name="strqueueName">Queue Name</param> /// <returns></returns> public MQMessageStatus WriteLocalQMsg(string strInputMsg, string strQueueName) { MQMessageStatus messageStatus = new MQMessageStatus(); string strReturn = string.Empty; SendQueueName = strQueueName; try { queue = queueManager.AccessQueue(SendQueueName, MQC.MQOO_OUTPUT + MQC.MQOO_FAIL_IF_QUIESCING); message = strInputMsg; queueMessage = new MQMessage(); queueMessage.WriteString(message); queueMessage.Format = MQC.MQFMT_STRING; queuePutMessageOptions = new MQPutMessageOptions(); queue.Put(queueMessage, queuePutMessageOptions); strReturn = "Message sent to the queue successfully"; messageStatus.Message = strReturn; messageStatus.Status = true; } catch (MQException MQexp) { strReturn = "Exception: " + MQexp.Message; messageStatus.Message = strReturn; messageStatus.Status = false; } catch (Exception exp) { strReturn = "Exception: " + exp.Message; messageStatus.Message = strReturn; messageStatus.Status = false; } return messageStatus; }
/// <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(); } } }
public string ReadMsg() { String strReturn = ""; try { queue = queueManager.AccessQueue("MBK.SESION3.SALIDA", MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); queueMessage = new MQMessage(); queueMessage.Format = MQC.MQFMT_STRING; queueGetMessageOptions = new MQGetMessageOptions(); queue.Get(queueMessage, queueGetMessageOptions); strReturn = queueMessage.ReadString(queueMessage.MessageLength); } catch (MQException MQexp) { strReturn = "Exception : " + MQexp.Message; } catch (Exception exp) { strReturn = "Exception: " + exp.Message; } return strReturn; }
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); }
public void PutMessage(string message) { try { // creating a message object MQMessage mqMessage = new MQMessage(); mqMessage.Format = MQC.MQFMT_STRING; //mqMessage.CharacterSet = 437; //mqMessage.CharacterSet = 1208; mqMessage.WriteString(message); // putting message _queue.Put(mqMessage); } 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)); } }
public string GetMessage() { string retVal = null; MQMessage mqMessage = new MQMessage(); mqMessage.Format = MQC.MQFMT_STRING; //mqMessage.CharacterSet = 437; //mqMessage.CharacterSet = 1208; _queue.Get(mqMessage); retVal = mqMessage.ReadString(mqMessage.MessageLength); //retVal = mqMessage.ReadString(mqMessage.DataLength); mqMessage.ClearMessage(); return retVal; }
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."); } } }
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); } }
/// <summary> /// Read Message from Local Queue /// </summary> /// <param name="strqueueName">Queue Name</param> /// <returns>Text Message</returns> public MQMessageStatus ReadLocalQMsg(string strQueueName) { MQMessageStatus messageStatus = new MQMessageStatus(); string strReturn = string.Empty; ReceiveQueueName = strQueueName; try { queue = queueManager.AccessQueue(ReceiveQueueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); queueMessage = new MQMessage(); queueMessage.Format = MQC.MQFMT_STRING; queueGetMessageOptions = new MQGetMessageOptions(); queue.Get(queueMessage, queueGetMessageOptions); strReturn = queueMessage.ReadString(queueMessage.MessageLength); messageStatus.Message = strReturn; messageStatus.Status = true; } catch (MQException MQexp) { strReturn = "Exception: " + MQexp.Message; messageStatus.Message = strReturn; messageStatus.Status = false; } catch (Exception exp) { strReturn = "Exception: " + exp.Message; messageStatus.Message = strReturn; messageStatus.Status = false; } return messageStatus; }