/// <summary> /// Demonstrate using the message reader strategies to get results from a message reply /// </summary> /// <param name="loggingService"></param> /// <param name="messageToRead"></param> static void DemonstrateReadMessage(ILoggingService loggingService, XmlDocument messageToRead) { // Set up a message reading strategy IMessageReader messageReader = new DefaultMessageReader(loggingService, configurationRepository, messageToRead.ToXDocument()); messageReader.ReadMessage(); // We don't know what we've got back from the Gateway, but all replies are GovTalkMessages if(messageReader.HasErrors()) { //There are errors in the results file so we can deal with them // Get a DataTable of the results and have a look at that DataTable errorTable = messageReader.GetMessageResults<DataTable>(); // Or set up an error return strategy and do something with that IErrorReturnCalculator errorCalculator = new DefaultErrorReturnCalculator(); GovTalkMessageGovTalkDetailsError error = messageReader.GetMessageResults<GovTalkMessageGovTalkDetailsError>(); Console.WriteLine(errorCalculator.CalculateErrorReturn(error)); if(error.Number == "3001") { ErrorResponse errResponse = messageReader.GetMessageResults<ErrorResponse>(); } } else { // It's either an acknowledgement so we need to get the poll interval and URL, or a response. string[] results = messageReader.GetMessageResults<string[]>(); foreach(var result in results) { Console.WriteLine(result); } if(messageReader.GetQualifier() == "response") { string body = messageReader.GetBodyType(); if(body != null) { DataTable responseTable = messageReader.GetMessageResults<DataTable>(); LocalHelp.ConsolePrintDataTable(responseTable); } else { Console.WriteLine("No body content"); } } } GovTalkMessageFileName ReplyNamer = new GovTalkMessageFileName.FileNameBuilder() .AddLogger(loggingService) .AddConfigurationRepository(configurationRepository) .AddMessageIntention("ReplyMessage") .AddCorrelationId(messageReader.GetCorrelationId()) .AddFilePath(@"C:\Temp\") .BuildFileName(); string replyFileName = ReplyNamer.ToString(); messageToRead.Save(replyFileName); }
/// <summary> /// Shows how to create a Submit Request GovTalkMessage, the basic type for submitting a GiftAid claim. /// If the message is very large it can be compressed, or compression can be chosen at the start of the process. /// Password and IRmark are added after the message is created. /// </summary> /// <param name="loggingService"></param> static string DemonstrateCreateSubmitRequest(ILoggingService loggingService, IConfigurationRepository configurationRepository, string giftAidDataSourceCsvFile) { // Assign a reference data source ReferenceDataManager.SetSource(ReferenceDataManager.SourceTypes.ConfigFile); // Set logger for the repaymentPopulater DataTableRepaymentPopulater.SetLogger(loggingService); // Assign a source for the GiftAid repayments data // If a filepath has been passed in, the DataHelpers method will make a datatable from a CSV source // with a valid set of columns. Otherwise, grab a datatable from a database or some other source // If the repaymentpopulater is not given a datatable, the submission message will have no repayments in it if (!string.IsNullOrEmpty(giftAidDataSourceCsvFile)) DataTableRepaymentPopulater.GiftAidDonations = DataHelpers.GetDataTableFromCsv(giftAidDataSourceCsvFile, true); GovTalkMessageCreator submitMessageCreator = new GovTalkMessageCreator(new SubmitRequestMessageBuilder(loggingService), loggingService); submitMessageCreator.CreateGovTalkMessage(); GovTalkMessage submitMessage = submitMessageCreator.GetGovTalkMessage(); // Set a password if not using the password hard-coded in the configuration source GovTalkMessageHelper helper = new GovTalkMessageHelper(configurationRepository, loggingService); helper.SetPassword(submitMessage, "weirdpassword"); XmlDocument submitMessageXml = submitMessageCreator.SerializeGovTalkMessage(); GovTalkMessageHelper gtmHelper = new GovTalkMessageHelper(configurationRepository, loggingService); XmlDocument irMarkedMessageXml = gtmHelper.SetIRmark(submitMessageXml); // If the message is too big, compress it // byte[] xmlDocumentSize = xd.XmlToBytes(); // if (xmlDocumentSize.Length > 1000000) // { // XmlDocument compressedVersion = submitMessageCreator.CompressClaim(); // outputXmlDocument = GovTalkMessageHelper.SetIRmark(compressedVersion); // } // Optionally, create a filename using this helper class string outputFilename; string tempDirectory = configurationRepository.GetConfigurationValue<string>("TempFolder"); GovTalkMessageFileName FileNamer = new GovTalkMessageFileName.FileNameBuilder() .AddLogger(loggingService) .AddMessageIntention("GatewaySubmission") .AddFilePath(tempDirectory) .AddTimestamp(DateTime.Now.ToString("yyyyMMddHHmmss")) .AddEnvironment("local") .AddCustomNamePart("EmptyRepayment") .BuildFileName(); outputFilename = FileNamer.ToString(); irMarkedMessageXml.Save(outputFilename); return outputFilename; }
public static void DemonstrateLocalProcess() { // Set up the logging IConfigurationRepository configurationRepository = new ConfigFileConfigurationRepository(); ILoggingService loggingService = new Log4NetLoggingService(configurationRepository, new ThreadContextService()); DataTableRepaymentPopulater.SetLogger(loggingService); // Create a file of donations records DataTableRepaymentPopulater.GiftAidDonations = DataHelpers.GetDataTableFromCsv(@"C:\Temp\Donations.csv", true); // Set up app.config as a source for the reference data ReferenceDataManager.SetSource(ReferenceDataManager.SourceTypes.ConfigFile); // Build a GovTalkMessage GovTalkMessageCreator submitMessageCreator = new GovTalkMessageCreator(new SubmitRequestMessageBuilder(loggingService), loggingService); submitMessageCreator.CreateGovTalkMessage(); // Get the GovTalkMessage that has been built GovTalkMessage submitMessage = submitMessageCreator.GetGovTalkMessage(); // Serialize the GovTalkMessage to an XmlDocument XmlDocument xd = submitMessageCreator.SerializeGovTalkMessage(); // Set the IRmark for the GovTalkMessage XmlDocument GovTalkMessageHelper gtmHelper = new GovTalkMessageHelper(configurationRepository, loggingService); XmlDocument finalXd = gtmHelper.SetIRmark(xd); // Set the URI to send the file to string uri = configurationRepository.GetConfigurationValue<string>("SendURILocal"); // Create a client to send the file to the target gateway CharitiesOnline.MessageService.Client client = new MessageService.Client(loggingService); // Create an XmlDocument of the reply from the endpoint XmlDocument reply = client.SendRequest(xd, uri); // Set up a message reading strategy IMessageReader _messageReader = new DefaultMessageReader(loggingService,configurationRepository,reply.ToXDocument()); _messageReader.ReadMessage(); string[] results = _messageReader.GetMessageResults<string[]>(); //int correlationIdIndex = Array.IndexOf(results, "CorrelationId"); int correlationIdPosition = Array.FindIndex(results, element => element.StartsWith("CorrelationId")); if (correlationIdPosition < 0) throw new ArgumentNullException("CorrelationId"); int qualifierPosition = Array.FindIndex(results, element => element.StartsWith("Qualifier")); if (qualifierPosition < 0) throw new ArgumentNullException("Qualifier"); Console.WriteLine(string.Join("\n", results)); #region old // This bit, bunch of if-thens, should be covered by the reader strategy ... //string bodytype = _messageReader.GetBodyType(reply.ToXDocument()); //if(bodytype == null) //{ // //acknowledgment // Console.WriteLine("CorrelationId is {0}",_messageReader.ReadMessage<string>(reply.ToXDocument())); //} //else if(bodytype == "hmrcclasses.SuccessResponse") //{ // //success // string[] success = _messageReader.ReadMessage<string[]>(reply.ToXDocument()); // Console.WriteLine(string.Join("\n", success)); //} //else if(bodytype == "hmrcclasses.ErrorResponse") //{ // //error // string[] error = _messageReader.ReadMessage<string[]>(reply.ToXDocument()); // Console.WriteLine(string.Join("\n", error)); //} #endregion old // Need to get correlationId GovTalkMessageFileName fileNamer = new GovTalkMessageFileName.FileNameBuilder() .AddLogger(loggingService) .AddFilePath(configurationRepository.GetConfigurationValue<string>("TempFolder")) .AddEnvironment("local") .AddMessageIntention("reply") .AddCorrelationId(results[correlationIdPosition].Substring(results[correlationIdPosition].IndexOf("::") + 2)) .AddMessageQualifier(results[qualifierPosition].Substring(results[qualifierPosition].IndexOf("::") + 2)) //could check for < 0 here and pass empty string .BuildFileName(); string filename = fileNamer.ToString(); reply.Save(filename); // reply.Save(@"C:\Temp\localreply.xml"); }
public static void TestGovTalkMessageCreation(string SourceDataFileName, string Filename = "") { IConfigurationRepository configurationRepository = new ConfigFileConfigurationRepository(); ILoggingService loggingService = new Log4NetLoggingService(configurationRepository, new ThreadContextService()); ReferenceDataManager.SetSource(ReferenceDataManager.SourceTypes.ConfigFile); ReferenceDataManager.governmentGatewayEnvironment = GovernmentGatewayEnvironment.localtestservice; DataTableRepaymentPopulater.SetLogger(loggingService); if (!string.IsNullOrEmpty(SourceDataFileName)) DataTableRepaymentPopulater.GiftAidDonations = DataHelpers.GetDataTableFromCsv(@SourceDataFileName, true); GovTalkMessageCreator submitMessageCreator = new GovTalkMessageCreator(new SubmitRequestMessageBuilder(loggingService), loggingService); submitMessageCreator.CreateGovTalkMessage(); GovTalkMessage submitMessage = submitMessageCreator.GetGovTalkMessage(); GovTalkMessageHelper helper = new GovTalkMessageHelper(configurationRepository, loggingService); helper.SetPassword(submitMessage, "testing1"); XmlDocument xd = submitMessageCreator.SerializeGovTalkMessage(); xd.PreserveWhitespace = true; xd = helper.AddPassword(xd.ToXDocument(), "xdocpassword", "clear").ToXmlDocument(); byte[] xmlDocumentSize = xd.XmlToBytes(); Console.WriteLine("The document is {0} bytes big.", xmlDocumentSize.Length); XmlDocument outputXmlDocument = new XmlDocument(); outputXmlDocument.PreserveWhitespace = true; //if (xmlDocumentSize.Length > 1000000) //{ // XmlDocument compressedVersion = submitMessageCreator.CompressClaim(); // outputXmlDocument = GovTalkMessageHelper.SetIRmark(compressedVersion); //} //else //{ GovTalkMessageHelper gtmHelper = new GovTalkMessageHelper(configurationRepository, loggingService); outputXmlDocument = gtmHelper.SetIRmark(xd); //} string filename; if (Filename == "") { GovTalkMessageFileName FileNamer = new GovTalkMessageFileName.FileNameBuilder() .AddLogger(loggingService) .AddMessageIntention("GatewaySubmission") .AddFilePath(@"C:\Temp\") .AddTimestamp(DateTime.Now.ToString("yyyyMMddHHmmss")) .AddEnvironment(ReferenceDataManager.governmentGatewayEnvironment.ToString()) .BuildFileName(); filename = FileNamer.ToString(); } else { filename = Filename; } outputXmlDocument.Save(filename); #region old //BodyCreator bodyCreator = new BodyCreator(new SubmitRequestBodyBuilder()); //bodyCreator.CreateBody(); //GovTalkMessageBody body = bodyCreator.GetBody(); //BodyCreator pollBodyCreator = new BodyCreator(new SubmitPollBodyBuilder()); //pollBodyCreator.CreateBody(); //GovTalkMessageBody pollBody = pollBodyCreator.GetBody(); #endregion old }
public static void TestFileNaming(ILoggingService loggingService, IConfigurationRepository configurationRepository) { GovTalkMessageFileName filename = (new GovTalkMessageFileName.FileNameBuilder() .AddLogger(loggingService) .AddFilePath(@"") .AddEnvironment("Test") .AddMessageIntention("RequestMessage") .AddTimestamp(DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss", System.Globalization.CultureInfo.InvariantCulture)) .AddCustomNamePart("File" + 1) .BuildFileName() ); Console.WriteLine(filename.ToString()); Console.WriteLine(filename.Environment); filename.Environment = "production_"; Console.WriteLine(filename.ToString()); string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"); int FileSequence = 0; GovTalkMessageFileName FileNamer = new GovTalkMessageFileName.FileNameBuilder() .AddConfigurationRepository(configurationRepository) .AddLogger(loggingService) .AddEnvironment("localtest") .AddFilePath(@"C:\Temp\") .AddMessageIntention("SubmitRequest") .AddTimestamp(timestamp) .AddCustomNamePart(String.Concat("152",(FileSequence > 0 ? "_" + FileSequence.ToString() : ""))) .BuildFileName(); Console.WriteLine(FileNamer.ToString()); Console.ReadKey(); }
public static void TestDeserializeSuccessResponse(ILoggingService loggingService) { GovTalkMessageFileName FileNamer = new GovTalkMessageFileName.FileNameBuilder() .AddLogger(loggingService) .AddFilePath(@"C:\Temp\") .AddEnvironment("live") .AddMessageIntention("PollMessage") .AddTimestamp("2015_02_02_12_41") .AddCorrelationId("1853DE80F71CEF4C07B57CD5BDA969D577") .AddMessageQualifier("response") .AddCustomNamePart("20150202124118") .BuildFileName(); string filename = FileNamer.ToString(); XmlDocument successMessage = new XmlDocument(); successMessage.Load(filename); GovTalkMessage success = XmlSerializationHelpers.DeserializeMessage(successMessage); XmlDocument successXml = new XmlDocument(); successXml.LoadXml(success.Body.Any[0].OuterXml); SuccessResponse successResp = XmlSerializationHelpers.DeserializeSuccessResponse(successXml); loggingService.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, successResp.Message[0].Value); }