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); } }