private QueueMessage ConvertBack(MQMessage msg) { return(new QueueMessage() { Data = msg.ReadBytes(msg.DataLength), }); }
private string saveRecvFile(MQMessage queueMessage, string path) { string filename = queueMessage.ReadString(200).Trim(); string fullName = Path.Combine(path, filename); FileStream fsNF = new FileStream(fullName, FileMode.Create, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fsNF); bw.Write(queueMessage.ReadBytes(queueMessage.MessageLength - 200)); bw.Close(); return(filename); }
internal override sealed void Initialize(MQMessage message) { base.Type = message.ReadInt4(); base.StrucLength = message.ReadInt4(); base.Parameter = message.ReadInt4(); this.stringLength = message.ReadInt4(); this.byteVal = message.ReadBytes(this.stringLength); int padding = (4 - ((Cmqcfc.MqcfbsStrucLengthFixed + this.stringLength) % 4)) % 4; message.SkipBytes(padding); }
private QueueMessage ToQueueMessage(MQMessage message) { QueueMessage resultMessage = null; if (message != null) { resultMessage = new QueueMessage { Data = System.Text.Encoding.UTF8.GetString(message.ReadBytes(message.MessageLength)) }; } return(resultMessage); }
/// <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.InhibitGet = MQC.MQQA_GET_ALLOWED; 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 void WriteMessageContent(MQMessage mQMessage) { var data = mQMessage.ReadBytes(mQMessage.DataLength); if (_settings.AsciiFile) { bool firstLine = true; int pStart = 0; int pEnd = data.Length; while (true) { int len = 0; int p = pStart; while (p < pEnd && IsInvariant(data[p])) { p++; len++; } /* As much as we can as string */ if (len > 0 || firstLine) { WriteString(ref data, pStart, len); } pStart += len; len = 0; p = pStart; if (p >= pEnd) { break; } while (p < pEnd && !IsInvariant(data[p])) { p++; len++; } WriteHex(ref data, pStart, len); pStart += len; p = pStart; if (p >= pEnd) { break; } firstLine = false; } } else { WriteHex(ref data, 0, data.Length); } }
/// <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 void DumpMessageContent(MQMessage mQMessage, TextWriter sw) { var data = mQMessage.ReadBytes(mQMessage.DataLength); var i = 0; while (true) { var len = Math.Min(25, data.Length - i); var dataline = new byte[len]; Array.Copy(data, i, dataline, 0, len); sw.WriteLine("X {0}", dataline.ToHexString()); i += len; if (i >= data.Length) { break; } } }
/// <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> public static string ReadMessage(string queueManagerName, string queueName, int waitDelay, Context context, out byte[] msgID) { string message = null; context.LogInfo("Opening queue manager: \"{0}\"", queueManagerName); using (var queueManager = new MQQueueManager(queueManagerName)) { context.LogInfo("Opening queue: \"{0}\"", queueName); using ( var receiveQueue = queueManager.AccessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING)) { var mqMsg = new MQMessage(); var mqMsgOpts = new MQGetMessageOptions { WaitInterval = waitDelay * 1000, 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 = Encoding.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)); } } } return(message); }
/// <summary> /// Receives a message from the input queue. /// </summary> /// <remarks> /// If a message is received the <see cref="TransportMessageReceived"/> event will be raised. /// </remarks> public void ReceiveFromQueue() { string messageId = string.Empty; try { MQGetMessageOptions getMessageOptions = new MQGetMessageOptions(); getMessageOptions.Options |= MQC.MQGMO_FAIL_IF_QUIESCING; MQMessage queueMessage = new MQMessage(); receiveResourceManager.GetMessage(queueMessage, getMessageOptions); messageId = ByteArrayToString(queueMessage.MessageId); foreach (IMessageModule module in this.modules) { module.HandleBeginMessage(); } this.OnStartedMessageProcessing(); if (this.IsTransactional) { if (MessageHasFailedMaxRetries(queueMessage)) { MoveToErrorQueue(queueMessage); ActivateEndMethodOnMessageModules(); this.OnFinishedMessageProcessing(); return; } } TransportMessage result = ConvertToTransportMessage(queueMessage); if (this.SkipDeserialization) { result.BodyStream = new MemoryStream(queueMessage.ReadBytes(queueMessage.MessageLength)); } else { try { result.Body = Extract(queueMessage); } catch (Exception e) { logger.Error("Could not extract message data.", e); MoveToErrorQueue(queueMessage); return; // deserialization failed - no reason to try again, so don't throw } } List <Exception> exceptions = new List <Exception>(); if (this.TransportMessageReceived != null) { try { this.TransportMessageReceived(this, new TransportMessageReceivedEventArgs(result)); } catch (Exception e) { exceptions.Add(e); logger.Error("Failed raising transport message received event.", e); } } exceptions.AddRange(ActivateEndMethodOnMessageModules()); if (exceptions.Count > 0) { throw new ApplicationException(string.Format("{0} exceptions occured while processing message.", exceptions.Count)); } } catch (MQException mqe) { if (mqe.ReasonCode == MQC.MQRC_NO_MSG_AVAILABLE || mqe.ReasonCode == MQC.MQRC_CONNECTION_QUIESCING) { return; } throw; } catch { if (this.IsTransactional) { throw; } else { this.OnFinishedMessageProcessing(); throw; } } if (needToAbort) { throw new AbortHandlingCurrentMessageException(); } this.OnFinishedMessageProcessing(); return; }
/// <summary> /// ITestStep.Execute() implementation /// </summary> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public override void Execute(Context context) { MQQueueManager queueManager = null; MQQueue receiveQueue = null; string message = null; var bLookForMessage = true; var bFound = false; var cnt = 0; try { // Remote or not? if (!string.IsNullOrEmpty(HostName)) { context.LogInfo("Host to connect to: \"{0}\" on port \"{1}\" with channel \"{2}\"", HostName, Port, Channel); MQEnvironment.Hostname = HostName; MQEnvironment.Port = Port; MQEnvironment.Channel = Channel; } context.LogInfo("Opening queue manager: \"{0}\"", QueueManager); queueManager = new MQQueueManager(QueueManager); context.LogInfo("Opening queue: \"{0}\" - remote queue: \"{1}\"", Queue, RemoteQueue); receiveQueue = queueManager.AccessQueue(Queue, MQC.MQOO_INPUT_SHARED + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_BROWSE + MQC.MQOO_SET); MQMessage mqMsg = new MQMessage(); MQGetMessageOptions mqMsgOpts = new MQGetMessageOptions(); mqMsgOpts.WaitInterval = WaitTimeout * 1000; mqMsgOpts.Options = MQC.MQGMO_WAIT + MQC.MQGMO_BROWSE_FIRST; mqMsgOpts.MatchOptions = MQC.MQMO_NONE; context.LogInfo("Browsing queue '{0}'.", Queue); // Loop until the required message is found while (!bFound) { if (cnt > 0) { mqMsgOpts.Options = MQC.MQGMO_WAIT + MQC.MQGMO_BROWSE_NEXT; } try { receiveQueue.InhibitGet = MQC.MQQA_GET_ALLOWED; receiveQueue.Get(mqMsg, mqMsgOpts); cnt++; } catch (MQException mqe) { if (mqe.ReasonCode == MQC.MQRC_NO_MSG_AVAILABLE) { break; } throw; } if ((mqMsg.Format.CompareTo(MQC.MQFMT_STRING) != 0) && (mqMsg.Format.CompareTo(MQC.MQFMT_XMIT_Q_HEADER) != 0)) { throw new NotSupportedException( string.Format("Unsupported message format: '{0}' read from queue: {1}.", mqMsg.Format, Queue)); } else { mqMsg.Seek(0); if (mqMsg.Format.CompareTo(MQC.MQFMT_XMIT_Q_HEADER) == 0) { var strucId = mqMsg.ReadString(4); var version = mqMsg.ReadInt(); var remoteQName = mqMsg.ReadString(48); var remoteQMgrName = mqMsg.ReadString(48); /* * struct tagMQMD { * MQCHAR4 StrucId; // Structure identifier * MQLONG Version; // Structure version number * MQLONG Report; // Options for report messages * MQLONG MsgType; // Message type * MQLONG Expiry; // Message lifetime * MQLONG Feedback; // Feedback or reason code * MQLONG Encoding; // Numeric encoding of message data * MQLONG CodedCharSetId; // Character set identifier of message data * MQCHAR8 Format; // Format name of message data * MQLONG Priority; // Message priority * MQLONG Persistence; // Message persistence * MQBYTE24 MsgId; // Message identifier * MQBYTE24 CorrelId; // Correlation identifier * MQLONG BackoutCount; // Backout counter * MQCHAR48 ReplyToQ; // Name of reply queue * MQCHAR48 ReplyToQMgr; // Name of reply queue manager * MQCHAR12 UserIdentifier; // User identifier * MQBYTE32 AccountingToken; // Accounting token * MQCHAR32 ApplIdentityData; // Application data relating to identity * MQLONG PutApplType; // Type of application that put the message * MQCHAR28 PutApplName; // Name of application that put the message * MQCHAR8 PutDate; // Date when message was put * MQCHAR8 PutTime; // Time when message was put * MQCHAR4 ApplOriginData; // Application data relating to origin * } */ var bytesMqmd = mqMsg.ReadBytes(324); } message = mqMsg.ReadLine(); //message = System.Text.UTF8Encoding.UTF8.GetString(mqMsg.ReadBytes(mqMsg.MessageLength)); context.LogData("MQSeries output message:", message); if ((null == SubSteps) || (SubSteps.Count == 0)) { bLookForMessage = false; } else { // Validate data... var msgData = StreamHelper.LoadMemoryStream(message); msgData.Seek(0, SeekOrigin.Begin); // Check it against the validate steps to see if it matches one of them foreach (var subStep in SubSteps) { try { // Try the validation and catch the exception var strm = subStep.Execute(msgData, context); bFound = true; } catch { } } } } } } finally { if (receiveQueue != null) { receiveQueue.Close(); } if (queueManager != null) { queueManager.Close(); } } context.LogInfo("Number of messages found: {0}, in queue '{1}'", cnt, Queue); switch (ExpectedNumberOfMessages) { case -1: break; default: if (ExpectedNumberOfMessages != cnt) { throw new Exception(String.Format("Queue '{2}' contained: {0} messages, but the step expected: {1} messages", cnt, ExpectedNumberOfMessages, Queue)); } break; } if (!bFound && bLookForMessage && (ExpectedNumberOfMessages > 0)) { throw new Exception(string.Format("Message not found in Queue '{0}', found {1} messages", Queue, cnt)); } }
public MqMessageGeneric GetNextMessage() { MqMessageGeneric res = null; String qname = this.queueName; if (String.IsNullOrWhiteSpace(qname)) { throw new ArgumentNullException("Не определено имя очереди"); } var getMessageOptions = new MQGetMessageOptions(); getMessageOptions.Options = MQC.MQGMO_WAIT + MQC.MQGMO_SYNCPOINT; getMessageOptions.WaitInterval = 100; // 1 seconds wait try { if (mqManager == null) { mqManager = createManager(); } message = new MQMessage(); using (var queue = mqManager.AccessQueue(queueName, MQC.MQOO_INQUIRE)) if (queue.CurrentDepth == 0) { return(res); } using (var q = mqManager.AccessQueue(qname, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING)) q.Get(message, getMessageOptions); res = new MqMessageGeneric(); res.Body = Encoding.UTF8.GetString(message.ReadBytes(message.MessageLength)); res.MessageID = message.MessageId; res.PutDateTime = message.PutDateTime; var inames = message.GetPropertyNames("%"); if (inames != null) { while (inames.MoveNext()) { String name = inames.Current.ToString(); if (name.ToLower().Contains("jms") || name.ToLower().Contains("mcd")) { continue; } res.AddedProperties.Add(name, message.GetStringProperty(name)); } } } catch (MQException mqex) { RollbackGet(); message = null; if (mqex.ReasonCode == 2033 && mqex.CompCode == 2) // В очереди нет сообщений { return(null); } throw new InvalidOperationException(String.Format("MQ {0}", mqex.Message)); } catch { RollbackGet(); throw; } return(res); }