/// <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)); } }
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; }
/// <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; }
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; }
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); }
/// <summary> /// 取得佇列的目前數量 /// </summary> /// <param name="vstrQueueManagerName"></param> /// <param name="vstrRequestQueueName"></param> /// <returns>目前數量</returns> public int GetQueueCount(string vstrQueueManagerName, string vstrRequestQueueName) { MQQueueManager mqQMgr; MQQueue requestQueue; MQText mqrcText = new MQText(); //step0 MQEnvironment.Hostname = this.Hostname; MQEnvironment.Port = Convert.ToInt32(this.Port); MQEnvironment.Channel = this.Channel; //Step 1. Create Queue Manager Object. This will also CONNECT the Queue Manager try { mqQMgr = new MQQueueManager(vstrQueueManagerName); } catch (MQException mqe) { string strError = mqrcText.getMQText(mqe.Reason); throw new Exception("GetQueueCount create Queue Manager Object. Error: code " + mqe.Reason + ", " + mqe.Message + ", Details: " + strError); } //Step 2. Open Request Queue for reading/ getting the request try { requestQueue = mqQMgr.AccessQueue(vstrRequestQueueName, MQC.MQOO_INQUIRE); } catch (MQException mqe) { string strError = mqrcText.getMQText(mqe.Reason); if (mqQMgr.IsConnected) //if( mqQMgr.ConnectionStatus ) { mqQMgr.Disconnect(); } throw new Exception("GetQueueCount open Request Queue for reading. Error: code " + mqe.Reason + ", " + mqe.Message + ", Details: " + strError); } //inquire on a queue int[] selectors = new int[1]; int[] intAttrs = new int[1]; byte[] charAttrs = new byte[1]; selectors[0] = MQC.MQIA_CURRENT_Q_DEPTH; requestQueue.Inquire(selectors, intAttrs, charAttrs); ASCIIEncoding enc = new ASCIIEncoding(); String s1 = ""; s1 = enc.GetString(charAttrs); int s2 = intAttrs[0]; if (requestQueue.OpenStatus) { requestQueue.Close(); } if (mqQMgr.IsConnected) //if( mqQMgr.ConnectionStatus ) { mqQMgr.Disconnect(); } return(s2); //------------------------------------------------------- }
protected MQMessage[] Send(int command, PcfParameter[] parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } var oo = MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_INQUIRE; var responseQueue = _qMgr.AccessQueue("SYSTEM.DEFAULT.MODEL.QUEUE", oo); var cmdMessage = new MQMessage { ReplyToQueueName = responseQueue.Name, MessageType = MQC.MQMT_REQUEST, Feedback = MQC.MQFB_NONE, Format = MQC.MQFMT_ADMIN, Report = MQC.MQRO_NONE }; PCFAgentResponseTracker tracker; if (_qMgr.Platform == MQC.MQPL_ZOS) { tracker = new PCFAgentResponseTracker390(); Mqcfh.Write(cmdMessage, command, parameters.Length, Cmqcfc.MqcftCommandXr, Cmqcfc.MqcfhVersion3); } else { tracker = new PCFAgentResponseTrackerNon390(); Mqcfh.Write(cmdMessage, command, parameters.Length, Cmqcfc.MqcftCommand, Cmqcfc.MqcfhVersion1); } foreach (var p in parameters) { p.Write(cmdMessage); } var aqo = MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_OUTPUT | MQC.MQOO_INQUIRE; var cmdQueue = _qMgr.AccessQueue(_qMgr.CommandInputQueueName, aqo); var pmo = new MQPutMessageOptions { Options = MQC.MQPMO_NEW_MSG_ID }; cmdQueue.Put(cmdMessage, pmo); var gmo = new MQGetMessageOptions { Options = MQC.MQGMO_FAIL_IF_QUIESCING | MQC.MQGMO_WAIT, WaitInterval = _waitInterval, MatchOptions = MQC.MQMO_MATCH_CORREL_ID }; var list = new List <MQMessage>(); while (true) { var response = new MQMessage { CorrelationId = cmdMessage.MessageId }; responseQueue.Get(response, gmo); list.Add(response); if (tracker.IsLast(response)) { break; } } cmdQueue.Close(); responseQueue.Close(); return(list.ToArray()); }
/// <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."); } } }
void GetResponse() { MQQueue queue; try { // 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(queueNameRes, MQC.MQOO_BROWSE + MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); // creating a message object message = new MQMessage(); MQGetMessageOptions mqGetMsgOpts = new MQGetMessageOptions(); mqGetMsgOpts.Options = MQC.MQGMO_BROWSE_FIRST; try { queue.Get(message, mqGetMsgOpts); MQGetMessageOptions mqGetNextMsgOpts = new MQGetMessageOptions(); mqGetNextMsgOpts.Options = MQC.MQGMO_BROWSE_NEXT; while (true) { try { string messageText = message.ReadString(message.MessageLength); byte[] byteConent = new byte[message.MessageLength]; message.ReadFully(ref byteConent, 0, message.MessageLength); string str = Encoding.Default.GetString(byteConent); var doc = new XmlDocument(); doc.LoadXml(str); var ns = new XmlNamespaceManager(doc.NameTable); ns.AddNamespace("esb", "http://www.egovernment.gov.za/GMD/MessageIdentification/xml/schemas/version/7.1"); ns.AddNamespace("cbcMgt", "http://www.sars.gov.za/enterpriseMessagingModel/CountryByCountryReportManagement/xml/schemas/version/1.2"); var header = doc.SelectSingleNode("//esb:MessageIdentification", ns); var request = doc.SelectSingleNode("//cbcMgt:CountryByCountryReportManagementRequest", ns); if (header != null && request != null) { /*//Validate header xml * XmlReaderSettings settingsHeader = GetSettings(Assembly.GetExecutingAssembly().GetManifestResourceStream("FDRService.schemas.ESBHeaderV7.1.xsd")); * var readerHeader = XmlReader.Create(header.OuterXml, settingsHeader); * while (readerHeader.Read()); * readerHeader.Close(); * * //Validate Body xml * XmlReaderSettings settingsRequest = GetSettings(Assembly.GetExecutingAssembly().GetManifestResourceStream("FDRService.schemas.SARSCountryByCountryReportManagementV1.2.xsd")); * var readerRequest = XmlReader.Create(request.OuterXml, settingsRequest); * while (readerRequest.Read()); * readerRequest.Close();*/ //Parse XML to objects var headerReq = Sars.Systems.Serialization.XmlObjectSerializer.ConvertXmlToObject <MessageIdentificationStructure>(header.OuterXml); var subReq = Sars.Systems.Serialization.XmlObjectSerializer.ConvertXmlToObject <CountryByCountryReportManagementRequestStructure>(request.OuterXml); var fragments = UnzipToString(subReq.FileContent, subReq.Filename); //File.ReadAllText(string.Format("D:\\Sars\\Incoming\\{0}.xml", subReq.Filename.Replace(".zip", ""))); string fullxml = ""; foreach (string s in fragments) { fullxml += s; } var myRootedXml = "<root>" + fullxml + "</root>"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(myRootedXml); //Get CBC OECD data XmlNodeList xmlNodeList = xmlDoc.GetElementsByTagName("CBC_OECD", "*"); // xmlDoc.GetElementsByTagName("cbc:CBC_OECD"); List <XmlNode> nodees = new List <XmlNode>(xmlNodeList.Cast <XmlNode>()); string cbcXML = nodees[0].OuterXml; //Validate CBC OECD xml XmlReaderSettings settingsOECD = GetSettings(Assembly.GetExecutingAssembly().GetManifestResourceStream("FDRService.schemas.CbcXML_v1.0.1.xsd")); var readerOECD = XmlReader.Create(cbcXML, settingsOECD); while (readerOECD.Read()) { ; } readerOECD.Close(); //Add validation errors statusMessage.CbCStatusMessage.ValidationErrors.FileError = validationErrors.ToArray(); bool valErrors = validationErrors.Count() > 0; var valErrorList = validationErrors; validationErrors = new List <FileError_Type>(); var appResult = new ApplicationInformationStructureApplicationInformationResult { Code = valErrors ? "50007" : "0000", Description = valErrors ? string.Join(",", valErrorList) : "Processed", MessageType = valErrors ? MessageTypeEnum.ERROR : MessageTypeEnum.INFORMATION }; //Get Response XML string responseXML = CreateResponseXml(header.OuterXml, appResult); //Put response XML to Queue PutFile(queueNameReceiveRes, Encoding.ASCII.GetBytes(responseXML)); if (valErrors) { throw new Exception("Validation errors occured: " + string.Join(",", valErrorList)); } //Cast cbcXML to object var cbcOECD = Sars.Systems.Serialization.XmlObjectSerializer.ConvertXmlToObject <CBC_OECD>(cbcXML); if (cbcOECD == null) { throw new Exception("Couldn't cast cbcOECD data to object"); } //Create Message Spec statusMessage.MessageSpec = new CbcStatusMessage.MessageSpec_Type() { SendingCompanyIN = cbcOECD.MessageSpec.SendingEntityIN, TransmittingCountry = (CbcStatusMessage.CountryCode_Type)Enum.Parse(typeof(CbcStatusMessage.CountryCode_Type), cbcOECD.MessageSpec.TransmittingCountry.ToString()), ReceivingCountry = (CbcStatusMessage.CountryCode_Type)Enum.Parse(typeof(CbcStatusMessage.CountryCode_Type), cbcOECD.MessageSpec.ReceivingCountry.ToString()), MessageType = CbcStatusMessage.MessageType_EnumType.CbCMessageStatus, Warning = "", MessageRefId = cbcOECD.MessageSpec.MessageRefId, MessageTypeIndic = CbCMessageTypeIndic_EnumType.CbCMessageStatus, MessageTypeIndicSpecified = true, ReportingPeriod = cbcOECD.MessageSpec.ReportingPeriod, Timestamp = DateTime.Now }; //Add original message information statusMessage.CbCStatusMessage.OriginalMessage.OriginalMessageRefID = cbcOECD.MessageSpec.MessageRefId; statusMessage.CbCStatusMessage.OriginalMessage.FileMetaData.CTSSendingTimeStamp = DateTime.Now; statusMessage.CbCStatusMessage.OriginalMessage.FileMetaData.CTSSendingTimeStampSpecified = true; statusMessage.CbCStatusMessage.OriginalMessage.FileMetaData.UncompressedFileSizeKBQty = "0"; statusMessage.CbCStatusMessage.OriginalMessage.FileMetaData.CTSTransmissionID = ""; var recordErrors = new List <RecordError_Type>(); foreach (var item in cbcOECD.CbcBody) { foreach (var bodyItem in item.CbcReports) { var docRefId = bodyItem.DocSpec.DocRefId; //Check if docRefId exists if exists add to record error //recordErrors.Add(new RecordError_Type() { Code = "80000", Details = new ErrorDetail_Type() { Value = "DocRefID already used" }, DocRefIDInError = new[] { docRefId } }); //Check format of docrefid if not correct add to record error //recordErrors.Add(new RecordError_Type() { Code = "80001", Details = new ErrorDetail_Type() { Value = "DocRefID format" }, DocRefIDInError = new[] { docRefId } }); var corrDocRefID = bodyItem.DocSpec.CorrDocRefId; //Check if docRefid exist if NOT exist add to record error //recordErrors.Add(new RecordError_Type() { Code = "80002", Details = new ErrorDetail_Type() { Value = "CorrDocRefId unknown" }, DocRefIDInError = new[] { docRefId } }); } } //Add record errors statusMessage.CbCStatusMessage.ValidationErrors.RecordError = recordErrors.ToArray(); //Get File Metadata xmlNodeList = xmlDoc.GetElementsByTagName("CTSSenderFileMetadata"); nodees = new List <XmlNode>(xmlNodeList.Cast <XmlNode>()); //Get File metadata xml string sender = nodees[0].OuterXml; //Deserialize File Metadata to object XmlSerializer CTSSenderFileMetadata = new XmlSerializer(typeof(CTSSenderFileMetadataType)); CTSSenderFileMetadataType senderReq; using (TextReader sr = new StringReader(sender)) { senderReq = (CTSSenderFileMetadataType)CTSSenderFileMetadata.Deserialize(sr); } //Save CBC OECD Data to DB var cbcr = DBWriteManager.SaveIncomingCBCDeclaration(0, senderReq.CTSSenderCountryCd.ToString(), int.Parse(senderReq.TaxYear), cbcXML); statusMessage.CbCStatusMessage.ValidationResult.Status = FileAcceptanceStatus_EnumType.Accepted; XmlSerializer xsSubmit = new XmlSerializer(typeof(CbCStatusMessage_OECD)); var xml = ""; using (var sww = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sww)) { xsSubmit.Serialize(writer, statusMessage); xml = sww.ToString(); } } PutFile(queueNameStatusMessage, Encoding.Default.GetBytes(xml)); eventLog1.WriteEntry("got incoming file: " + headerReq.universalUniqueID); //Remove message from the Queue mqGetMsgOpts.Options = MQC.MQGMO_MSG_UNDER_CURSOR; queue.Get(message, mqGetMsgOpts); } else { if (header == null) { eventLog1.WriteEntry("Error (Incoming File): No header message found", EventLogEntryType.Error); } if (request == null) { eventLog1.WriteEntry("Error (Incoming File): No request message found", EventLogEntryType.Error); } //Application Results failed schema validation var appResult = new ApplicationInformationStructureApplicationInformationResult { Code = "50007", Description = "Failed Schema Validation", MessageType = MessageTypeEnum.ERROR }; //Get Response XML string responseXML = CreateResponseXml(header.OuterXml, appResult); //Put response XML to Queue PutFile(queueNameReceiveRes, Encoding.ASCII.GetBytes(responseXML)); } //Get next Message message = new MQMessage(); queue.Get(message, mqGetNextMsgOpts); } catch (MQException mqe) { if (mqe.ReasonCode == 2033) { //eventLog1.WriteEntry("No message available"); break; } else { eventLog1.WriteEntry(string.Format("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message), EventLogEntryType.Error); } } catch (Exception ex) { eventLog1.WriteEntry(string.Format("Exception caught (Incoming file): {0}", ex.Message), EventLogEntryType.Error); message = new MQMessage(); queue.Get(message, mqGetNextMsgOpts); } } } catch (MQException mqe) { if (mqe.ReasonCode == 2033) { //No message available do nothing //eventLog1.WriteEntry("No message available"); } else { eventLog1.WriteEntry(string.Format("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message), EventLogEntryType.Error); } } // closing queue queue.Close(); // disconnecting queue manager queueManager.Disconnect(); } catch (MQException mqe) { eventLog1.WriteEntry(string.Format("MQException caught: {0} - {1}", mqe.ReasonCode, mqe.Message), EventLogEntryType.Error); eventLog1.WriteEntry(mqe.StackTrace, EventLogEntryType.Error); } }
private void DequeueTask(object i) { int threadNum = (int)i; #if DEBUG logger.Info($" Dequeue thread {threadNum} running on thread ({Thread.CurrentThread.ManagedThreadId}: {Thread.CurrentThread.Name}) "); #endif MQQueueManager queueManager = null; MQQueue queue = null; while (!_cancellationTokenSource.Token.IsCancellationRequested) { if (queue == null || queueManager == null || !queueManager.IsConnected || !queue.IsOpen) { logger.Debug($"DequeueTask {threadNum}: Initializing connection to queue {_qname}"); queueManager = _mqQueueManagerFactory(); queue = queueManager.AccessQueue(_qname, MQC.MQOO_INPUT_AS_Q_DEF); } MQMessage message = _messageFactory(); bool commitOrBackoutRequired = false; try { try { queue.Get(message, _mqgmo); if (_useTransactions) { commitOrBackoutRequired = true; } int messageIdLength = message.MessageId.Length; string messageId = (messageIdLength > 8)? BitConverter.ToString(message.MessageId, messageIdLength - 8, 8) : BitConverter.ToString(message.MessageId, 0, messageIdLength); logger.Debug($"DequeueTask {threadNum}: Received message {messageId}"); try { _subject.OnNext(message); logger.Debug($"DequeueTask {threadNum}: Message {messageId} emitted successfully"); if (commitOrBackoutRequired) { logger.Debug($"DequeueTask {threadNum}: Committing message {messageId}"); queueManager.Commit(); } } catch (Exception subjectException) { logger.Error($"DequeueTask {threadNum}: Exception occurred within the subject, proceed to commit/rollback/errorqueue phase ", subjectException); try { if (commitOrBackoutRequired) { logger.Info($"DequeueTask {threadNum}: Exception occurred during transaction, message rollback count is {message.BackoutCount} "); if (message.BackoutCount < _numBackoutAttempts) { logger.Info($"DequeueTask {threadNum}: Proceeding to rollback message after exception: {message.BackoutCount} of {_numBackoutAttempts} attempts"); queueManager.Backout(); logger.Info($"DequeueTask {threadNum}: Message rollback is complete"); } else { logger.Info($"DequeueTask {threadNum}: Message backout count {message.BackoutCount} equals or exceeds max threshold of {_numBackoutAttempts} attempt(s), committing message off queue..."); queueManager.Commit(); if (_errorQueue == null) { logger.Info($"DequeueTask {threadNum}: Error queue has not been enabled, message will be discarded."); } else { logger.Info($"DequeueTask {threadNum}: Proceed to emit message to error queue {message.BackoutCount} / {_numBackoutAttempts}"); try { _errorQueue.OnNext(message); } catch (Exception exc2) { logger.Info($"DequeueTask {threadNum}: Exception occurred while emiting message to error queue", exc2); } } } } } catch (Exception exc2) { logger.Info($"DequeueTask {threadNum}: Exception occurred during commit/rollback/errorqueue phase", exc2); } finally { try { _exceptions?.OnNext(subjectException); } catch (Exception exc2) { logger.Info($"DequeueTask {threadNum}: Exception occurred while emiting exception event to subject", exc2); } } } } catch (MQException mqExc) { if (mqExc.Reason == 2033) { // message not available, ignore and micro-sleep Task.Delay(50); } else { throw; } } } catch (Exception exc) { logger.Error($"DequeueTask {threadNum}: Exception occurred during dequeue task loop", exc); } } }
static void Main(string[] args) { MQQueueManager mqQMgr; // Try to create a mqqueue manager instance try { mqQMgr = new MQQueueManager("QMA"); } catch (MQException mqe) { // stop if failed Console.WriteLine("create of MQQueueManager ended with " + mqe); return; } // Open the queue MQQueue mqQueue; try { mqQueue = mqQMgr.AccessQueue("QMA1", MQC.MQOO_OUTPUT | MQC.MQOO_INPUT_SHARED | MQC.MQOO_INQUIRE); } catch (MQException mqe) { // stop if failed Console.WriteLine("MQQueueManager::AccessQueue ended with " + mqe); return; } // Prepare hello world message var mqMsg = new MQMessage(); mqMsg.WriteString("Hello from the example client!"); mqMsg.Format = MQC.MQFMT_STRING; var mqPutMsgOpts = new MQPutMessageOptions(); // Place the message on the queue, using default put message options try { mqQueue.Put(mqMsg, mqPutMsgOpts); } catch (MQException mqe) { // report the error Console.WriteLine("MQQueue::Put ended with " + mqe); } // Get message mqMsg = new MQMessage(); var mqGetMsgOpts = new MQGetMessageOptions { WaitInterval = 15 * 1000 }; // 15 second limit for waiting mqGetMsgOpts.Options |= MQC.MQGMO_WAIT; try { mqQueue.Get(mqMsg, mqGetMsgOpts); Console.WriteLine(string.Compare(mqMsg.Format, MQC.MQFMT_STRING, StringComparison.Ordinal) == 0 ? mqMsg.ReadString(mqMsg.MessageLength) : "Non-text message"); } catch (MQException mqe) { // report reason, if any if (mqe.Reason == MQC.MQRC_NO_MSG_AVAILABLE) { // special report for normal end Console.WriteLine("Wait timeout happened"); } else { // general report for other reasons Console.WriteLine("MQQueue::Get ended with " + mqe); // treat truncated message as a failure for this sample if (mqe.Reason == MQC.MQRC_TRUNCATED_MSG_FAILED) { // TODO Handle connection error here } } } try { //Close the Queue mqQueue.Close(); //Close the Queue Manager mqQMgr.Disconnect(); } catch (MQException mqe) { Console.WriteLine("An IBM MQ error occurred :Completion code " + mqe.CompletionCode + "Reason code " + mqe.ReasonCode); } }
/// <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); }
/** * 连接到MQ队列管理器 * @param para 连接对象 * @param type 连接类型(发送,接收) * @param trycount 重试连接次数 * @param interval 重连等待时间 * @return TRUE:连接成功;FALSE:连接失败; * @throws EisException 当重试连接次数都失败,则返回异常 */ public static Boolean connectMQ(MQCParameter para, int type, int trycount, int interval) { LogUtil.Info("try to connect mq :", para.mqParameter.toString()); Boolean ret = false; MQParameter mqParameter = para.mqParameter; Hashtable props = new Hashtable(); if (mqParameter.getHostName() != null) { props.Add(MQC.HOST_NAME_PROPERTY, mqParameter.getHostName()); } if (mqParameter.getPort() != 0) { props.Add(MQC.PORT_PROPERTY, mqParameter.getPort()); } if (mqParameter.getChannel() != null) { props.Add(MQC.CHANNEL_PROPERTY, mqParameter.getChannel()); } if (mqParameter.getCcsid() != 0) { props.Add(MQC.CCSID_PROPERTY, mqParameter.getCcsid()); } // MQPoolToken token=MQEnvironment.addConnectionPoolToken(); int i = 0; MQQueue queue = null; MQQueueManager qManager = null; while (trycount <= 0 || (trycount > 0 && i < trycount)) { i++; try { para.release(); //连接到指定的队列管理器 qManager = new MQQueueManager(mqParameter.getQManagerName(), props); //根据参数不同连接到Q队列上 if (MQ_MSGRECEIVE_TYPE == type) { // queue = qManager.accessQueue(mqParameter.getQueueName(),MQC.MQOO_INPUT_AS_Q_DEF); //queue = qManager.AccessQueue(mqParameter.getQueueName(), MQC.MQOO_INQUIRE | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_INPUT_SHARED); queue = qManager.AccessQueue(mqParameter.getQueueName(), MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_INQUIRE); } else if (MQ_MSGSEND_TYPE == type) { queue = qManager.AccessQueue(mqParameter.getQueueName(), MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_INQUIRE); // queue = qManager.AccessQueue(mqParameter.getQueueName(), MQC.MQOO_OUTPUT); } para.qManager = qManager; para.queue = queue; ret = true; break; } catch (MQException mqe) { LogUtil.Error("", mqe); if (i == trycount) { LogUtil.Error( "不能连接到MQ Server :", para.mqParameter.toString() + "]," + "已经做了[" + i + "]次尝试!"); throw mqe; } else { try { // 在下一次重试之前等待一定时间 Thread.Sleep(interval); } catch (Exception e) { LogUtil.Error("Exception:", e); throw new EisException("interrupted when connect sleeping"); } } } }// end of while loop props.Clear(); return(ret); }
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)); } }
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> /// open the connection to the message queue /// </summary> public void Open() { mqm = (MQQueueManager)queueSession.AccessQueueManager(queueManager); queue = (MQQueue)mqm.AccessQueue(QueueName, (int)MQ.MQOO_INPUT_AS_Q_DEF + (int)MQ.MQOO_OUTPUT, "", "", ""); queue.Open(); }
/// <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."); } } }
public void start() { LogUtil.logInfo("config:" + config.ToString()); if (!config.isValid()) { throw new Exception("Configuration for the driver is incomplete"); } lock (syncLock) { try { ThreadPool.GetMaxThreads(out maxNoOfMessagesToProcess, out maxNoOfMessagesToProcess); maxNoOfMessagesToProcess = maxNoOfMessagesToProcess * 2; if (config.isRemote()) { _mqManagerInQueue = new MQQueueManager(config.queueManager, config.channelName, config.connectionName); _mqManagerOkQueue = new MQQueueManager(config.queueManager, config.channelName, config.connectionName); _mqManagerConfirmQueue = new MQQueueManager(config.queueManager, config.channelName, config.connectionName); _mqManagerErrorQueue = new MQQueueManager(config.queueManager, config.channelName, config.connectionName); _mqManagerReviewQueue = new MQQueueManager(config.queueManager, config.channelName, config.connectionName); _mqManagerOfacInQueue = new MQQueueManager(config.queueManager, config.channelName, config.connectionName); _mqManagerOfacOkQueue = new MQQueueManager(config.queueManager, config.channelName, config.connectionName); _mqManagerOfacConfirmQueue = new MQQueueManager(config.queueManager, config.channelName, config.connectionName); } else { _mqManagerInQueue = new MQQueueManager(config.queueManager); _mqManagerOkQueue = new MQQueueManager(config.queueManager); _mqManagerConfirmQueue = new MQQueueManager(config.queueManager); _mqManagerErrorQueue = new MQQueueManager(config.queueManager); _mqManagerReviewQueue = new MQQueueManager(config.queueManager); _mqManagerOfacInQueue = new MQQueueManager(config.queueManager); _mqManagerOfacOkQueue = new MQQueueManager(config.queueManager); _mqManagerOfacConfirmQueue = new MQQueueManager(config.queueManager); } LogUtil.logInfo("Successfully connected to the queue manager:" + config.queueManager); int openInputOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_INQUIRE; int openOutputOptions = MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_OUTPUT | MQC.MQOO_INPUT_SHARED; int openInputOutputOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_OUTPUT; _inQueue = _mqManagerInQueue.AccessQueue(config.inputQueue, openInputOptions); LogUtil.logInfo("Successfully connected to the queue:" + config.inputQueue); _okQueue = _mqManagerOkQueue.AccessQueue(config.okQueue, openOutputOptions); LogUtil.logInfo("Successfully connected to the queue:" + config.okQueue); _confirmQueue = _mqManagerConfirmQueue.AccessQueue(config.confirmQueue, openOutputOptions); LogUtil.logInfo("Successfully connected to the queue:" + config.confirmQueue); _errorQueue = _mqManagerErrorQueue.AccessQueue(config.errorQueue, openInputOutputOptions); LogUtil.logInfo("Successfully connected to the queue:" + config.errorQueue); // _reviewQueue = _mqManagerReviewQueue.AccessQueue(config.reviewQueue, openInputOptions); _reviewQueue = _mqManagerReviewQueue.AccessQueue(config.reviewQueue, openInputOutputOptions); LogUtil.logInfo("Successfully connected to the queue:" + config.reviewQueue); _ofacInQueue = _mqManagerOfacInQueue.AccessQueue(config.ofacInputQueue, openOutputOptions); LogUtil.logInfo("Successfully connected to the queue:" + config.ofacInputQueue); _ofacOkQueue = _mqManagerOfacOkQueue.AccessQueue(config.ofacOkQueue, openInputOptions); LogUtil.logInfo("Successfully connected to the queue:" + config.ofacOkQueue); _ofacConfirmQueue = _mqManagerOfacConfirmQueue.AccessQueue(config.ofacConfirmQueue, openInputOptions); LogUtil.logInfo("Successfully connected to the queue:" + config.ofacConfirmQueue); Thread threadInputQueue = new Thread(listenInputQueue); Thread threadOfacOkQueue = new Thread(listenOfacOkQueue); Thread threadOfacConfirmQueue = new Thread(listenOfacConfirmQueue); threadInputQueue.Start(); threadOfacOkQueue.Start(); threadOfacConfirmQueue.Start(); status = DriverStatus.Running; } catch (Exception e) { pendingStop = true; if (_inQueue != null && _inQueue.OpenStatus) { _inQueue.Close(); } if (_okQueue != null && _okQueue.OpenStatus) { _okQueue.Close(); } if (_confirmQueue != null && _confirmQueue.OpenStatus) { _confirmQueue.Close(); } if (_errorQueue != null && _errorQueue.OpenStatus) { _errorQueue.Close(); } if (_reviewQueue != null && _reviewQueue.OpenStatus) { _reviewQueue.Close(); } if (_ofacInQueue != null && _ofacInQueue.OpenStatus) { _ofacInQueue.Close(); } if (_ofacOkQueue != null && _ofacOkQueue.OpenStatus) { _ofacOkQueue.Close(); } if (_ofacConfirmQueue != null && _ofacConfirmQueue.OpenStatus) { _ofacConfirmQueue.Close(); } if (_mqManagerInQueue != null && _mqManagerInQueue.OpenStatus) { _mqManagerInQueue.Close(); } if (_mqManagerOkQueue != null && _mqManagerOkQueue.OpenStatus) { _mqManagerOkQueue.Close(); } if (_mqManagerConfirmQueue != null && _mqManagerConfirmQueue.OpenStatus) { _mqManagerConfirmQueue.Close(); } if (_mqManagerErrorQueue != null && _mqManagerErrorQueue.OpenStatus) { _mqManagerErrorQueue.Close(); } if (_mqManagerReviewQueue != null && _mqManagerReviewQueue.OpenStatus) { _mqManagerReviewQueue.Close(); } if (_mqManagerOfacInQueue != null && _mqManagerOfacInQueue.OpenStatus) { _mqManagerOfacInQueue.Close(); } if (_mqManagerOfacOkQueue != null && _mqManagerOfacOkQueue.OpenStatus) { _mqManagerOfacOkQueue.Close(); } if (_mqManagerOfacConfirmQueue != null && _mqManagerOfacConfirmQueue.OpenStatus) { _mqManagerOfacConfirmQueue.Close(); } status = DriverStatus.NotRunning; throw e; } } }
/// <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(); } } }
/// <summary> /// 由MQ的佇列取得資料 /// </summary> /// <param name="vstrQueueManagerName">佇列管理程式名稱</param> /// <param name="vstrRequestQueueName">佇列名稱</param> /// <returns>序列化的資料</returns> public string GetQueue(string vstrQueueManagerName, string vstrRequestQueueName) { MQQueueManager mqQMgr; MQQueue requestQueue; MQText MQText = new MQText(); MQMessage requestMessage; //step0 MQEnvironment.Hostname = this.Hostname; MQEnvironment.Port = Convert.ToInt32(this.Port); MQEnvironment.Channel = this.Channel; //Step 1. Create Queue Manager Object. This will also CONNECT the Queue Manager try { mqQMgr = new MQQueueManager(vstrQueueManagerName); } catch (MQException mqe) { string strError = MQText.getMQText(mqe.Reason); throw new Exception("GetQueue create Queue Manager Object 發生錯誤. Error: code " + mqe.Reason + ", " + mqe.Message + ", Details: " + strError); } //Step 2. Open Request Queue for reading/ getting the request try { requestQueue = mqQMgr.AccessQueue(vstrRequestQueueName, MQC.MQOO_INPUT_SHARED); } catch (MQException mqe) { if (mqQMgr.IsConnected) //if( mqQMgr.ConnectionStatus ) { mqQMgr.Disconnect(); } string strError = MQText.getMQText(mqe.Reason); throw new Exception("GetQueue open Request Queue for reading 發生錯誤. Error: code " + mqe.Reason + ", " + mqe.Message + ", Details: " + strError); } //step3. put content to MQ //建立MQMessage requestMessage = new MQMessage(); requestMessage.Format = this._MQMessageFormat; requestMessage.CharacterSet = this._MQMessageCharacterSet; requestMessage.Expiry = this._MQMessageExpiry; MQGetMessageOptions MQGetMessageOptions = new MQGetMessageOptions(); MQGetMessageOptions.WaitInterval = this._MQMessageTimeOut; MQGetMessageOptions.Options = MQC.MQGMO_WAIT; try { //讀取Replying Queue內的message requestQueue.Get(requestMessage, MQGetMessageOptions); string ReplyingMessage = requestMessage.ReadString(requestMessage.MessageLength); if (requestQueue.OpenStatus) { requestQueue.Close(); } if (mqQMgr.IsConnected) //if( mqQMgr.ConnectionStatus ) { mqQMgr.Disconnect(); } return(ReplyingMessage); //if (vGetMessageID == true) //{ // MQMessage.MessageId.CopyTo(_MessageID, 0); //} //if (vGetCorrelationID == true) //{ // MQMessage.CorrelationId.CopyTo(_CorrelationID, 0); //} } catch (MQException MQEx) { if (requestQueue.OpenStatus) { requestQueue.Close(); } if (mqQMgr.IsConnected) //if ( mqQMgr.ConnectionStatus ) { mqQMgr.Disconnect(); } string strError = MQText.getMQText(MQEx.Reason); throw new Exception("GetQueue send Reply 發生錯誤. Error: code " + MQEx.Reason + ", " + MQEx.Message + ", Details: " + strError); } }
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); } }
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); } }