public async Task <string> ProcessDocument(string companyId, TradingChannel.TradingChannel tradingChannel, TradingPartner.TradingPartner tradingPartner, string message, TradingPartnerMessage.TradingPartnerMessage messageData) { var ediStream = new MemoryStream(Encoding.Default.GetBytes(message)); List <IEdiItem> ediItems; using (var reader = new X12Reader(ediStream, EdiHelper.TypeFactory)) { var items = reader.ReadToEndAsync().Result; ediItems = items.ToList(); string controlNumber = string.Empty; string errorMessage = null; foreach (var item in ediItems) { if (item is ISA isa) { // find the company with the sender id var senderId = isa.InterchangeSenderID_6.Trim(); var rId = isa.InterchangeReceiverID_8.Trim(); continue; // VERIFY PARTNER INFORMATION IS CORRECT } if (item is GS gs) { controlNumber = gs.GroupControlNumber_6; continue; } var handler = _ediHandlers.FirstOrDefault(p => p.ForType.IsAssignableFrom(item.GetType())); if (handler != null) { try { if (item is EdiMessage edi) { if (edi.HasErrors) { errorMessage = "EDI VALIDATION: " + string.Join(Environment.NewLine, edi.ErrorContext.Flatten()); return(errorMessage); } } await handler.Handle(companyId, tradingChannel, tradingPartner, item, messageData); } catch (Exception ex) { errorMessage = ex.Message + Environment.NewLine + ex.StackTrace + (ex.InnerException?.Message ?? string.Empty) + (ex.InnerException?.StackTrace ?? string.Empty); return(errorMessage); } } } } return(null); }
/// <summary> /// Reads the EDI stream from start to end async. /// This method loads the file into memory. Do not use for large files. /// The sample file contains two purchase orders - a valid one and an invalid one. /// </summary> public static async void ReadAllPurchaseOrdersAsync() { Debug.WriteLine("******************************"); Debug.WriteLine(MethodBase.GetCurrentMethod().Name); Debug.WriteLine("******************************"); // 1. Load to a stream Stream ediStream = File.OpenRead(Directory.GetCurrentDirectory() + @"\..\..\..\Files.X12\PurchaseOrders.txt"); // 2. Read all the contents List <IEdiItem> ediItems; using (var ediReader = new X12Reader(ediStream, TemplateFactory.FullTemplateFactory)) { var items = await ediReader.ReadToEndAsync(); ediItems = items.ToList(); } // 3. Pull the purchase orders var purchaseOrders = ediItems.OfType <TS850>(); // 4. Validate each purchase order foreach (var po in purchaseOrders) { MessageErrorContext errorContext; if (po.IsValid(out errorContext)) { // The purchase order is valid, process it downstream } else { // The purchase order is invalid Debug.WriteLine("Message {0} with control number {1} is invalid with errors:", errorContext.Name, errorContext.ControlNumber); // List all error messages var errors = errorContext.Flatten(); foreach (var error in errors) { Debug.WriteLine(error); } } } }
/// <summary> /// Reads the EDI stream from start to end async. /// This method loads the file into memory. Do not use for large files. /// The sample file contains two purchase orders - a valid one and an invalid one. /// </summary> public static async void Run() { Debug.WriteLine("******************************"); Debug.WriteLine(MethodBase.GetCurrentMethod().Name); Debug.WriteLine("******************************"); // 1. Load to a stream Stream ediStream = File.OpenRead(Directory.GetCurrentDirectory() + @"\..\..\..\Files\X12\PurchaseOrders.txt"); // 2. Read all the contents List <IEdiItem> ediItems; using (var ediReader = new X12Reader(ediStream, "EdiFabric.Templates.X12")) { var items = await ediReader.ReadToEndAsync(); ediItems = items.ToList(); } // 3. Pull the purchase orders var purchaseOrders = ediItems.OfType <TS850>(); }
public async Task Run( [ServiceBusTrigger("%x12inboundqueuename%", Connection = "InboundServiceBusConnectionString", IsSessionsEnabled = true)] Message inboundMsg, [ServiceBus("%x12204inboundqueuename%", Connection = "InboundServiceBusConnectionString")] IAsyncCollector <Message> outMessages, ILogger log, CancellationToken cancellationToken) { log.LogInformation("C# Service Bus trigger function processed a request."); if (string.IsNullOrEmpty(inboundMsg.SessionId)) { throw new Exception($"No Session ID in this message."); } //Read EDI message List <IEdiItem> ediItems; using (Stream stream = new MemoryStream(inboundMsg.Body)) { using (var reader = new X12Reader(stream, "EdiFabric.Templates.X12")) { ediItems = (await reader.ReadToEndAsync()).ToList(); } } //Get Logic App Management Client using Azure Token if (client == null) { var provider = new AzureServiceTokenProvider(); var token = await provider.GetAccessTokenAsync("https://management.azure.com/"); client = new LogicManagementClient(new TokenCredentials(token)) { SubscriptionId = subscriptionId }; } //Get Agreements from Integration Account if (agreements == null) { agreements = new List <IntegrationAccountAgreement>(); IPage <IntegrationAccountAgreement> pages = await client.IntegrationAccountAgreements.ListAsync(rgName, iaName, null, cancellationToken); agreements.AddRange(pages); while (pages.NextPageLink != null) { pages = await client.IntegrationAccountAgreements.ListNextAsync(pages.NextPageLink); agreements.AddRange(pages); } } //Look for a matching agreement based on ISA header var isa = ediItems.OfType <ISA>().FirstOrDefault(); if (isa == null) { throw new Exception($"No ISA element found."); } var agreementName = from a in agreements where a.GuestIdentity.Qualifier == isa.SenderIDQualifier_5.Trim() && a.GuestIdentity.Value == isa.InterchangeSenderID_6.Trim() && a.HostIdentity.Value == isa.ReceiverIDQualifier_7.Trim() && a.HostIdentity.Value == isa.InterchangeReceiverID_8.Trim() select a.Name.FirstOrDefault(); if (agreementName == null) { throw new Exception($"Agreement between sender partner with qualifier {isa.SenderIDQualifier_5} and ID {isa.InterchangeSenderID_6} and receiver partner with qualifier {isa.ReceiverIDQualifier_7} and ID {isa.InterchangeReceiverID_8} not found"); } //Loop through each shipment and send to subsequent session enabled queue but this time using shipmentID in the session to fan out per order var shipmentItems = ediItems.OfType <TS204>().ToList(); foreach (var shipmentItem in shipmentItems) { //Todo: table lookup of where each customer puts their Shipment ID number as they might be different var shipmentID = shipmentItem.B2.ShipmentIdentificationNumber_04; var xml = Serialize(shipmentItem); Message outMessage = new Message(Encoding.UTF8.GetBytes(xml.ToString())); outMessage.SessionId = $"{inboundMsg.SessionId}+{shipmentID}"; await outMessages.AddAsync(outMessage); } }