private static string GetMessageContent(this MQDestination mqQueue, MQMessage mqMsg, bool browse, bool isFirstMessage) { var mqGetMsgOpts = new MQGetMessageOptions { Options = GetMqGetOptions(browse, isFirstMessage) }; mqQueue.Get(mqMsg, mqGetMsgOpts); Logger.Info($"Message CCSID: {mqMsg.CharacterSet} ({MqEncoding} expected), Queue:{mqQueue.Name}"); var messageContent = new byte[0]; mqMsg.ReadFully(ref messageContent); return(OutputEncoding.GetString(messageContent)); }
private MQMessage CopyMDFromOldMsgIntoReportMsg(MQMessage oldMsg, MQMessage newMsg, int putOpts) { MQMessage message; uint method = 0x231; this.TrEntry(method, new object[] { oldMsg, newMsg, putOpts }); try { if (((oldMsg.Report & 0x4000) != 0) && ((oldMsg.Report & 0x8000000) != 0)) { newMsg.Report = 0x8000000; } else { newMsg.Report = 0; } newMsg.MessageType = 4; if ((oldMsg.Report & 0x4000) != 0) { newMsg.Expiry = oldMsg.Expiry; } else { newMsg.Expiry = -1; } if ((oldMsg.Report & 0x40) != 0) { newMsg.CorrelationId = oldMsg.CorrelationId; } else if ((putOpts & 0x80) == 0) { newMsg.CorrelationId = oldMsg.CorrelationId; } newMsg.ReplyToQueueName = ""; newMsg.ReplyToQueueManagerName = ""; byte[] b = new byte[oldMsg.MessageLength]; oldMsg.Seek(0); oldMsg.ReadFully(ref b); newMsg.Write(b); message = newMsg; } finally { base.TrExit(method); } return(message); }
private MQMessage CopyMDFromOldMsgIntoFwdMsg(MQMessage oldMsg, MQMessage newMsg) { MQMessage message; uint method = 0x22f; this.TrEntry(method, new object[] { oldMsg, newMsg }); try { newMsg.AccountingToken = oldMsg.AccountingToken; newMsg.ApplicationIdData = oldMsg.ApplicationIdData; newMsg.ApplicationOriginData = oldMsg.ApplicationOriginData; newMsg.CharacterSet = oldMsg.CharacterSet; newMsg.CorrelationId = oldMsg.CorrelationId; newMsg.Encoding = oldMsg.Encoding; newMsg.Expiry = oldMsg.Expiry; newMsg.Feedback = oldMsg.Feedback; newMsg.Format = oldMsg.Format; newMsg.GroupId = oldMsg.GroupId; newMsg.MessageFlags = oldMsg.MessageFlags; newMsg.MessageId = oldMsg.MessageId; newMsg.MessageSequenceNumber = oldMsg.MessageSequenceNumber; newMsg.MessageType = oldMsg.MessageType; newMsg.Offset = oldMsg.Offset; newMsg.OriginalLength = oldMsg.OriginalLength; newMsg.Persistence = oldMsg.Persistence; newMsg.Priority = oldMsg.Priority; newMsg.PutApplicationName = oldMsg.PutApplicationName; newMsg.PutApplicationType = oldMsg.PutApplicationType; newMsg.PutDateTime = oldMsg.PutDateTime; newMsg.ReplyToQueueManagerName = oldMsg.ReplyToQueueManagerName; newMsg.ReplyToQueueName = oldMsg.ReplyToQueueName; newMsg.Report = oldMsg.Report; newMsg.UserId = oldMsg.UserId; byte[] b = new byte[oldMsg.MessageLength]; oldMsg.Seek(0); oldMsg.ReadFully(ref b); newMsg.Write(b); message = newMsg; } finally { base.TrExit(method); } return(message); }
/** * 将MQ消费转换成byte流返回 * @param msg * @return * @throws EisException */ public static byte[] getBytesFromMQMessage(MQMessage msg) { if (null == msg) { return(null); } try { byte[] msgContent = new byte[msg.MessageLength]; msg.ReadFully(ref msgContent); return(msgContent); } catch (Exception t) { LogUtil.Error("Exception", t); if (msg != null) { throw new EisException("|msgId=" + msg.MessageId); } } return(null); }
public void CreateFileSubscriber(string name, string path, IMessageListener listener) { MQQueue queue = queueManager.AccessQueue(name, MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING); MQGetMessageOptions gmo = new MQGetMessageOptions(); gmo.Options = MQC.MQGMO_FAIL_IF_QUIESCING; gmo.Options = gmo.Options + MQC.MQGMO_SYNCPOINT; gmo.Options = gmo.Options + MQC.MQGMO_WAIT; gmo.WaitInterval = 3000; gmo.Options = gmo.Options + MQC.MQGMO_ALL_MSGS_AVAILABLE; gmo.Options = gmo.Options + MQC.MQGMO_LOGICAL_ORDER; gmo.MatchOptions = MQC.MQMO_MATCH_GROUP_ID; gmo.Version = MQC.MQMD_VERSION_2; Task.Factory.StartNew(() => { while (!listener.IsStop) { try { var message = new MQMessage(); message.MQMD.Version = MQC.MQMD_VERSION_2; List <byte> total = new List <byte>(); while (true) { queue.Get(message, gmo); int msgLength = message.MessageLength; byte[] buff = new byte[msgLength]; message.ReadFully(ref buff); total.AddRange(buff); if (gmo.GroupStatus == MQC.MQGS_LAST_MSG_IN_GROUP) { message.ClearMessage(); queueManager.Commit(); break; } } byte[] findStr = System.Text.Encoding.Default.GetBytes("|"); byte[] totalBytes = total.ToArray(); var ret = Search(totalBytes, 0, findStr); if (ret != -1) { byte[] fileNameHead = new byte[ret]; byte[] content = new byte[totalBytes.Length - ret - 1]; Array.Copy(totalBytes, 0, fileNameHead, 0, ret); Array.Copy(totalBytes, ret + 1, content, 0, totalBytes.Length - ret - 1); var fileName = System.Text.Encoding.Default.GetString(fileNameHead); var generateFile = System.IO.Path.Combine(path, fileName); using (FileStream fSteam = new FileStream(generateFile, FileMode.Create)) { fSteam.Write(content, 0, content.Length); fSteam.Flush(); fSteam.Close(); if (listener != null) { QueueMessage qm = new QueueMessage(); qm.Type = MessageType.File; qm.Data = fileName; listener.OnMessage(qm); } } } } catch (MQException mqe) { if (mqe.ReasonCode == 2033) { LogMsg(string.Format("获取MQ【FILE】消息异常,异常代码【2033】,队列:{0},MQ地址:{1},异常信息:{2}", name, host, mqe.ToString())); Thread.Sleep(500); } else { LogMsg(string.Format("获取MQ【FILE】消息异常,队列:{0},MQ地址:{1},异常信息:{2}", name, host, mqe.ToString())); Thread.Sleep(5000); Reconnect(ref queueManager, ref queue, name); } } catch (Exception e) { LogMsg(string.Format("获取MQ【FILE】消息异常,队列:{0},MQ地址:{1},异常信息:{2}", name, host, e.Message.ToString())); Thread.Sleep(5000); Reconnect(ref queueManager, ref queue, name); } } LogMsg(string.Format("队列{0},监控文件线程退出...")); queue.Close(); }); }
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 MQMessage CopyMDFromOldMsgIntoReplyMsg(MQMessage oldMsg, MQMessage newMsg, int putOpts) { MQMessage message; uint method = 560; this.TrEntry(method, new object[] { oldMsg, newMsg, putOpts }); try { if (((oldMsg.Report & 0x4000) != 0) && ((oldMsg.Report & 0x8000000) != 0)) { newMsg.Report = 0x8000000; } else { newMsg.Report = 0; } newMsg.MessageType = 2; if ((oldMsg.Report & 0x4000) != 0) { newMsg.Expiry = oldMsg.Expiry; } else { newMsg.Expiry = -1; } newMsg.Feedback = 0; if ((oldMsg.Report & 0x80) != 0) { newMsg.MessageId = oldMsg.MessageId; } else if ((putOpts & 0x40) == 0) { newMsg.MessageId = MQC.MQMI_NONE; } if ((oldMsg.Report & 0x40) != 0) { newMsg.CorrelationId = oldMsg.CorrelationId; } else if ((putOpts & 0x80) == 0) { newMsg.CorrelationId = oldMsg.CorrelationId; } newMsg.ReplyToQueueName = ""; newMsg.ReplyToQueueManagerName = ""; newMsg.GroupId = MQC.MQGI_NONE; newMsg.MessageSequenceNumber = 1; newMsg.Offset = 0; newMsg.MessageFlags = 0; newMsg.OriginalLength = -1; byte[] b = new byte[oldMsg.MessageLength]; oldMsg.Seek(0); oldMsg.ReadFully(ref b); newMsg.Write(b); message = newMsg; } finally { base.TrExit(method); } return(message); }