public void TestMultipleMessages() { // ARRANGE const string sample = "EdiFabric.UnitTests.X12.Edi.X12_810_00204_MultipleMessages.txt"; var ediStream = CommonHelper.LoadStream(sample); var expected = CommonHelper.LoadString(sample); List <EdiItem> ediItems; // ACT using (var ediReader = new X12Reader(ediStream, "EdiFabric.Rules.X12002040")) { ediItems = ediReader.ReadToEnd().ToList(); } var actual = X12Helper.Generate(ediItems, null, Environment.NewLine); // ASSERT Assert.IsTrue(ediItems.OfType <TS810>().Count() == 2); Assert.IsTrue(ediItems.OfType <ISA>().Count() == 1); Assert.IsTrue(ediItems.OfType <GS>().Count() == 1); Assert.IsTrue(ediItems.OfType <GE>().Count() == 1); Assert.IsTrue(ediItems.OfType <IEA>().Count() == 1); Assert.IsNull(ediItems.OfType <ErrorContext>().SingleOrDefault()); Assert.AreEqual(expected, actual); }
public static void TranslateX12(string ediSourcePath, string translatedFolderPath, Assembly templateAssembly, string fileNameFilter = null, bool withAcknowlegment = false) { var settings = new AckSettings { AckHandler = (s, a) => { var tsTa1 = a.Message as TSTA1; var ts997 = a.Message as TS997; // ts997.AK1.FunctionalIdentifierCode_01 = "A"; ts997.AK9.FunctionalGroupAcknowledgeCode_01 = "A"; ts997.AK9.NumberofAcceptedTransactionSets_04 = ts997.AK9.NumberofReceivedTransactionSets_03; foreach (var aa in ts997.AK2Loop1) { aa.AK5.TransactionSetAcknowledgmentCode_01 = "A"; aa.AK3Loop1 = null; } if (tsTa1 != null) { // a.Message is TA1 } if (ts997 != null) { // Inspect the acknowledgment var ackCode = ts997.AK9.FunctionalGroupAcknowledgeCode_01; var ack = AckBuilders.BuildAck(a.InterchangeHeader, a.GroupHeader, ts997, AckVersion.X12_997); Debug.Write(ack); } }, MessageHandler = (s, a) => { if (!a.ErrorContext.HasErrors) { // do something with the message a.Message Debug.WriteLine("Message {0} with control number {1} is valid.", a.ErrorContext.Name, a.ErrorContext.ControlNumber); } a.ErrorContext.Errors.Clear(); a.ErrorContext.HasErrors = false; }, AckVersion = AckVersion.X12_997, // Turn off AK2 for valid messages to reduce size GenerateForValidMessages = false }; foreach (var fileName in Directory.EnumerateFiles(ediSourcePath, fileNameFilter ?? "*")) { var ackMan = withAcknowlegment ? new EdiFabric.Plugins.Acknowledgments.X12.AckMan(settings) : null; try { using (X12Reader reader = new X12Reader(new FileStream(fileName, FileMode.Open), mc => { // return Assembly.GetAssembly(typeof(EdiFabric.Templates.EdifactD96A.ADR)); return(templateAssembly); })) { var ediItems = reader.ReadToEnd().ToList(); Console.WriteLine(Path.GetFileName(fileName)); foreach (var ediItem in ediItems) { if (withAcknowlegment) { ackMan.Publish(ediItem); } var resultFileName = Path.Combine(translatedFolderPath, Path.GetFileNameWithoutExtension(fileName) + ".txt"); if (ediItem is TS856) { var asn = (TS856)ediItem; using (var writer = new FieldWriter(File.CreateText(resultFileName))) { WriteLowesAsn(asn, writer); } } } } } finally { ackMan?.Dispose(); } } }
public IEnumerable <IEdiItem> ReadToEnd() { return(_x12Reader.ReadToEnd()); }
static void Main(string[] args) { var root = @"C:\work\dev\edi"; var dddd = LenovoCatalogClient.GetChangedLenovoMaterials().Result; return; // InventoryRecoSender.SendInventoryForReceivings(Path.Combine(root, @"sample\lenovo\to_respond")).Wait(); // return; // X12214Writer.Write214(Path.Combine(root, "lw_sample\\214.txt")); // write goods received /* DespatchAdviceWriter.WriteEdiFactAsnResponse( * Path.Combine(root, @"sample\lenovo\to_respond"), * Path.Combine(Path.Combine(root, @"sample\lenovo\response"))) * .Wait(); * * return;*/ //translate edi fact // EdiFactTranslator.TranslateEdiFact(Path.Combine(root, @"sample\lenovo"), // Path.Combine(root, @"sample\lenovo\translated")); /* X12Translator.TranslateX12(Path.Combine(root, @"lw_sample"), * Path.Combine(root, @"lw_sample\translated"), * Assembly.GetAssembly(typeof(TS856)));*/ // write wm asn // var asn = new AsnWriter(); // asn.WriteAsn(Path.Combine(root, Guid.NewGuid().ToString("D"))); #region wm ack /* * var settings = new AckSettings * { * AckHandler = (s, a) => * { * var tsTa1 = a.Message as TSTA1; * var ts997 = a.Message as TS997; * * // ts997.AK1.FunctionalIdentifierCode_01 = "A"; * ts997.AK9.FunctionalGroupAcknowledgeCode_01 = "A"; * ts997.AK9.NumberofAcceptedTransactionSets_04 = ts997.AK9.NumberofReceivedTransactionSets_03; * foreach (var aa in ts997.AK2Loop1) * { * aa.AK5.TransactionSetAcknowledgmentCode_01 = "A"; * aa.AK3Loop1 = null; * } * if (tsTa1 != null) * { * // a.Message is TA1 * } * * if (ts997 != null) * { * // Inspect the acknowledgment * var ackCode = ts997.AK9.FunctionalGroupAcknowledgeCode_01; * * var ack = AckBuilders.BuildAck(a.InterchangeHeader, a.GroupHeader, ts997, AckVersion.X12_997); * Debug.Write(ack); * } * }, * MessageHandler = (s, a) => * { * if (!a.ErrorContext.HasErrors) * { * // do something with the message a.Message * Debug.WriteLine("Message {0} with control number {1} is valid.", a.ErrorContext.Name, a.ErrorContext.ControlNumber); * } * * a.ErrorContext.Errors.Clear(); * a.ErrorContext.HasErrors = false; * }, * AckVersion = AckVersion.X12_997, * // Turn off AK2 for valid messages to reduce size * GenerateForValidMessages = false * }; * * * //TL_6637eb02-75b4-4b3a-9f32-5b2e7059d920.edi * var edi = File.OpenRead(@"C:\work\dev\edi\TL_42e0c5bf-ac84-441c-b9ca-0ccbe6170880.edi"); * using (var ackMan = new EdiFabric.Plugins.Acknowledgments.X12.AckMan(settings)) * { * using (var ediReader = new X12Reader(edi, mc => * { * // return Assembly.GetAssembly(typeof(EdiFabric.Templates.EdifactD96A.ADR)); * return Assembly.GetAssembly(typeof(EdiFabric.Templates.X12004010.AAA)); * })) * { * while (ediReader.Read()) * ackMan.Publish(ediReader.Item); * } * } * return;*/ #endregion #region wm staff using (var output = File.CreateText(Path.Combine(root, "stores.txt"))) { //*.edi Dictionary <string, Loop_N1_816_2> ids = new Dictionary <string, Loop_N1_816_2>(); foreach (var file in Directory.EnumerateFiles(root, "00000*").Select(f => new FileInfo(f)) .OrderBy(f => f.Name == "000005_X12_005010_816_OUT-7.011390366.523604" ? new DateTime() : f.CreationTimeUtc)) { // using (EdifactReader reader = new EdifactReader(new FileStream(Path.Combine(root, file), FileMode.Open), using (X12Reader reader = new X12Reader( new FileStream(Path.Combine(root, file.Name), FileMode.Open), mc => { // return Assembly.GetAssembly(typeof(EdiFabric.Templates.EdifactD96A.ADR)); return(Assembly.GetExecutingAssembly()); })) { var ediItems = reader.ReadToEnd().ToList(); if (ediItems.Any(i => i is EdiFabric.Core.Model.Edi.ErrorContexts.ReaderErrorContext)) { Console.WriteLine(file + " " + ediItems.First(i => i is EdiFabric.Core.Model.Edi.ErrorContexts.ReaderErrorContext)); } foreach (var ediItem in ediItems.Where(i => i is EdiFabric.Templates.X12005010.TS816) .Cast <EdiFabric.Templates.X12005010.TS816>()) { foreach (var h in ediItem.HLLoop) { /*WL("id", h.Id.ToString()); * WL("HierarchicalChildCode_04", h.HL.HierarchicalChildCode_04); * WL("HierarchicalIDNumber_01", h.HL.HierarchicalIDNumber_01); * WL("HierarchicalLevelCode_03", h.HL.HierarchicalLevelCode_03); * WL("HierarchicalParentIDNumber_02", h.HL.HierarchicalParentIDNumber_02); * */ foreach (var n in h.N1Loop) { /* WL("EntityIdentifierCode_01", n.N1.EntityIdentifierCode_01); * WL("Id", n.N1.Id.ToString()); * WL("IdentificationCodeQualifier_03", n.N1.IdentificationCodeQualifier_03); * WL("IdentificationCode_04", n.N1.IdentificationCode_04);*/ if (!ids.ContainsKey(n.N1.IdentificationCode_04)) { ids.Add(n.N1.IdentificationCode_04, n); } else { ids[n.N1.IdentificationCode_04] = n; } /* WL("Name_02", n.N1.Name_02); * * if (n.N3 != null) * { * foreach (var n3 in n.N3) * { * WL("AddressInformation_01", n3.AddressInformation_01); * WL("AddressInformation_02", n3.AddressInformation_02); * } * } * * WL("CityName_01", n.N4.CityName_01); * WL("CountryCode_04", n.N4.CountryCode_04); * WL("PostalCode_03", n.N4.PostalCode_03); * * * if (n.REF != null) * { * foreach (var r in n.REF) * { * * WL("ref:Description_03", r.Description_03); * WL("ref:ReferenceIdentificationQualifier_01", r.ReferenceIdentificationQualifier_01); * WL("ref:ReferenceIdentification_02", r.ReferenceIdentification_02); * if (r.ReferenceIdentifier_04 != null) * { * WL("ref:" + r.ReferenceIdentifier_04.ReferenceIdentificationQualifier_01, * r.ReferenceIdentifier_04.ReferenceIdentification_02); * WL("ref:" + r.ReferenceIdentifier_04.ReferenceIdentificationQualifier_03, * r.ReferenceIdentifier_04.ReferenceIdentification_04); * WL("ref:" + r.ReferenceIdentifier_04.ReferenceIdentificationQualifier_05, * r.ReferenceIdentifier_04.ReferenceIdentification_06); * } * * } * } * * if (n.PER != null) * { * foreach (var per in n.PER) * { * WL("communication:ContactFunctionCode_01", per.ContactFunctionCode_01); * WL("communication:ContactFunctionCode_01", per.ContactInquiryReference_09); * WL("communication:Name_02", per.Name_02); * WL("communication:" + per.CommunicationNumberQualifier_03, * per.CommunicationNumber_04); * WL("communication:" + per.CommunicationNumberQualifier_05, * per.CommunicationNumber_06); * WL("communication:" + per.CommunicationNumberQualifier_07, * per.CommunicationNumber_08); * * } * } * } * * WL("------ hl ------", "");*/ } } } } } /* WT( * "INSERT INTO table (IdentificationCode, StoreNumber, Phone, CountryCode, StateCode, CityName, PostalCode, AddressLine1, AddressLine2, AddressLine3, StoreName)", true); * WT("VALUES"); * foreach (var id in ids) * { * var n = id.Value; * var sn = n.REF?.FirstOrDefault(r => r.ReferenceIdentificationQualifier_01 == "ST") * ?.ReferenceIdentification_02; * if (sn == null || n.N3 == null) * continue; * WT("('" + n.N1.IdentificationCode_04 + "',"); * WT("'" + sn + "',"); * WT("'" + n.PER?.FirstOrDefault(r => r.CommunicationNumberQualifier_03 == "TE")?.CommunicationNumber_04 + "',"); * // WT("'" + n.N3.First().AddressInformation_01 + "',"); * WT("'" + n.N4.CountryCode_04 + "',"); * WT("'" + n.N4.StateorProvinceCode_02 + "',"); * WT("'" + n.N4.CityName_01 + "',"); * WT("'" + n.N4.PostalCode_03 + "',"); * WT("'" + n.N3.First().AddressInformation_01 + "',"); * WT(string.IsNullOrEmpty(n.N3.First().AddressInformation_02) ? "null," : * "'" + n.N3.First().AddressInformation_02 + "',"); * WT("null,"); * WT("'" + n.N1.Name_02 + "'),", true); * * * } * return;*/ foreach (var file1 in Directory.EnumerateFiles(root, "*RECONGROUP-925485US00-20200609114554603_519865969")) { // using (EdifactReader reader = new EdifactReader(new FileStream(Path.Combine(root, file), FileMode.Open), using (X12Reader reader = new X12Reader(new FileStream(Path.Combine(root, file1), FileMode.Open), mc => { // return Assembly.GetAssembly(typeof(EdiFabric.Templates.EdifactD96A.ADR)); return(Assembly.GetAssembly(typeof(EdiFabric.Templates.X12005010.AAA))); })) { var ediItems = reader.ReadToEnd().ToList(); if (ediItems.Any(i => i is EdiFabric.Core.Model.Edi.ErrorContexts.ReaderErrorContext)) { Console.WriteLine(file1 + " " + ediItems.First(i => i is EdiFabric.Core.Model.Edi.ErrorContexts.ReaderErrorContext)); } using (var fr = new FieldWriter(File.CreateText(@"c:\temp\wm_orders.csv"))) { fr.WT("PO#"); fr.WT("date purchased"); fr.WT("additional dates"); fr.WT("monetary amount"); fr.WT("store"); fr.WT("line#"); fr.WT("item#"); fr.WT("upc"); fr.WT("model"); fr.WT("color"); fr.WT("upc"); fr.WT("Qty"); fr.WT("UnitPrice"); fr.WT("other", true); foreach (var ediItem in ediItems.Where(i => i is EdiFabric.Templates.X12005010.TS850)) { var po = (EdiFabric.Templates.X12005010.TS850)ediItem; var storeDict = new Dictionary <string, List <(PO1 PO1, string qty)> >(); foreach (var line in po.PO1Loop) { foreach (var sdq in line.SDQ) { //WL("IdentificationCodeQualifier_02", sdq.IdentificationCodeQualifier_02); WL1(MapLocation(ids, sdq.IdentificationCode_03), line.PO1, sdq.Quantity_04, storeDict); WL1(MapLocation(ids, sdq.IdentificationCode_05), line.PO1, sdq.Quantity_06, storeDict); WL1(MapLocation(ids, sdq.IdentificationCode_07), line.PO1, sdq.Quantity_08, storeDict); WL1(MapLocation(ids, sdq.IdentificationCode_09), line.PO1, sdq.Quantity_10, storeDict); WL1(MapLocation(ids, sdq.IdentificationCode_11), line.PO1, sdq.Quantity_12, storeDict); WL1(MapLocation(ids, sdq.IdentificationCode_13), line.PO1, sdq.Quantity_14, storeDict); WL1(MapLocation(ids, sdq.IdentificationCode_15), line.PO1, sdq.Quantity_16, storeDict); WL1(MapLocation(ids, sdq.IdentificationCode_17), line.PO1, sdq.Quantity_18, storeDict); WL1(MapLocation(ids, sdq.IdentificationCode_19), line.PO1, sdq.Quantity_20, storeDict); WL1(MapLocation(ids, sdq.IdentificationCode_21), line.PO1, sdq.Quantity_22, storeDict); } } foreach (var store in storeDict) { foreach (var line in store.Value) { fr.WT(po.BEG.PurchaseOrderNumber_03); fr.WT(po.BEG.Date_05); fr.WT(string.Join("; ", po.DTM.Select(d => ParseDateType(d.DateTimeQualifier_01) + " " + d.Date_02 + " " + d.Time_03))); fr.WT(po.CTTLoop.AMT.MonetaryAmount_02); fr.WT(store.Key); fr.WT(line.PO1.AssignedIdentification_01); fr.WT(line.PO1.ProductServiceID_07); fr.WT("'" + line.PO1.ProductServiceID_09); fr.WT(line.PO1.ProductServiceID_11); fr.WT(line.PO1.ProductServiceID_13); fr.WT("'" + line.PO1.ProductServiceID_23); fr.WT(line.qty); fr.WT(line.PO1.UnitPrice_04); fr.WT(string.Join(";", po.REF.Select(r => MapRef(r.ReferenceIdentificationQualifier_01) + " = " + r.ReferenceIdentification_02 )), true); } } /* foreach (var n1 in po.N1Loop) * { * WL("EntityIdentifierCode_01", n1.N1.EntityIdentifierCode_01); * WL("Name_02", n1.N1.Name_02); * }*/ } } } } } #endregion }
/// <summary> /// Reads the EDI stream from start to end /// The interchange contains two purchase orders: /// The first one is valid /// The second one is invalid /// </summary> private static void ReadAllPurchaseOrders() { Debug.WriteLine("******************************"); Debug.WriteLine(MethodBase.GetCurrentMethod().Name); Debug.WriteLine("******************************"); // 1. Load the sample purchase order to a stream Stream purchaseOrderStream = Assembly.GetExecutingAssembly() .GetManifestResourceStream("EdiFabric.Sdk.X12.Edi.PurchaseOrders.txt"); // 2. Read all the contents at once List <EdiItem> ediItems; using (var ediReader = new X12Reader(purchaseOrderStream, "EdiFabric.Sdk.X12")) { ediItems = ediReader.ReadToEnd().ToList(); } // 3. Check that the stream contains a well formed ISA header and the contents can be parsed var readerErrors = ediItems.OfType <ReaderErrorContext>(); if (readerErrors.Any()) { // The stream is corrupt. Reject it and report back to the sender foreach (var readerError in readerErrors) { // Respond with the error context, which contains the standard EDI error code and fault reason var error = readerError.MessageErrorContext.Flatten(); } } // 4. Pull the transactions that are needed (multiple functional groups contain different transaction types, // e.g. the same document can contain invoices and dispatch advice notes) var purchaseOrders = ediItems.OfType <TS850>(); // 5. Validate all purchase orders. // Validation uses the validation attributes in the rule file as well as invokes all custom validators. 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 // Report it back to the sender, log, etc. // Inspect MessageErrorContext for the validation errors var errors = errorContext.Flatten(); // List all error messages Debug.WriteLine("Message {0} with control number {1} is invalid with errors:", errorContext.Name, errorContext.ControlNumber); foreach (var error in errors) { Debug.WriteLine(error); } } } }
/// <summary> /// Reads the EDI stream from start to end /// For full usage and features please refer to the X12 SDK /// </summary> static void ReadSingleBenefit() { Debug.WriteLine("******************************"); Debug.WriteLine(MethodBase.GetCurrentMethod().Name); Debug.WriteLine("******************************"); // 1. Load the sample benefit to a stream Stream benefitStream = Assembly.GetExecutingAssembly() .GetManifestResourceStream("EdiFabric.Sdk.Hipaa.Edi.BenefitEnrollment.txt"); // 2. Read all the contents at once List <EdiItem> ediItems; using (var ediReader = new X12Reader(benefitStream, AssemblyLoadFactory)) { ediItems = ediReader.ReadToEnd().ToList(); } // 3. Check that the stream contains a well formed ISA header var readerErrors = ediItems.OfType <ReaderErrorContext>(); if (readerErrors.Any()) { // The stream is corrupt. Reject it and report back to the sender foreach (var readerError in readerErrors) { // Respond with the error context, which contains the standard EDI error code and fault reason var error = readerError.MessageErrorContext.Flatten(); } } // 4. Pull the transactions that are needed (multiple functional groups contain different transaction types, // e.g. the same document can contain invoices and dispatch advice notes) var members = ediItems.OfType <TS834>(); // 5. Validate all claims. foreach (var member in members) { MessageErrorContext errorContext; if (member.IsValid(out errorContext)) { // The claim is valid, process it downstream } else { // The claim is invalid // Report it back to the sender, log, etc. // Inspect MessageErrorContext for the validation errors var errors = errorContext.Flatten(); // List all error messages Debug.WriteLine("Message {0} with control number {1} is invalid with errors:", errorContext.Name, errorContext.ControlNumber); foreach (var error in errors) { Debug.WriteLine(error); } } } }
public static void Run() { Debug.WriteLine("******************************"); Debug.WriteLine(MethodBase.GetCurrentMethod().Name); Debug.WriteLine("******************************"); // Init the AutoMapper map // Map by interface to reuse mapping Mapper.Initialize( cfg => { cfg.CreateMap <TS850, PurchaseOrder>() .ForPath(dest => dest.OrderLines, m => m.MapFrom(src => src.PO1Loop.Select(l => l.PO1))); cfg.CreateMap <I_BEG, PurchaseOrder>() .ForMember(dest => dest.RefNumber, m => m.MapFrom(src => src.PurchaseOrderNumber_03)) .ForMember(dest => dest.Date, m => m.MapFrom(src => src.Date_05.Substring(0, 4) + "-" + src.Date_05.Substring(4, 2) + "-" + src.Date_05.Substring(6, 2))); cfg.CreateMap <I_N1, PurchaseOrder>() .ForPath(dest => dest.Customer.RefNumber, m => m.MapFrom(src => src.IdentificationCode_04)) .ForPath(dest => dest.Customer.Name, m => m.MapFrom(src => src.Name_02)); cfg.CreateMap <I_N3, PurchaseOrder>() .ForPath(dest => dest.Customer.AddressLine, m => m.MapFrom(src => src.AddressInformation_01)); cfg.CreateMap <I_N4, PurchaseOrder>() .ForPath(dest => dest.Customer.City, m => m.MapFrom(src => src.CityName_01)) .ForPath(dest => dest.Customer.State, m => m.MapFrom(src => src.StateorProvinceCode_02)) .ForPath(dest => dest.Customer.PostCode, m => m.MapFrom(src => src.PostalCode_03)); cfg.CreateMap <I_PO1, OrderLine>() .ForMember(dest => dest.LineNumber, m => m.MapFrom(src => src.AssignedIdentification_01)) .ForMember(dest => dest.UPCNumber, m => m.MapFrom(src => src.ProductServiceID_07)) .ForMember(dest => dest.Quantity, m => m.MapFrom(src => src.QuantityOrdered_02)) .ForMember(dest => dest.Price, m => m.MapFrom(src => src.UnitPrice_04)) .ForMember(dest => dest.UOM, m => m.MapFrom(src => src.UnitorBasisforMeasurementCode_03)); } ); var ediStream = File.OpenRead(Directory.GetCurrentDirectory() + @"\..\..\..\Files\X12\PurchaseOrderCSV.txt"); List <IEdiItem> ediItems; using (var ediReader = new X12Reader(ediStream, "EdiFabric.Templates.X12")) { ediItems = ediReader.ReadToEnd().ToList(); } var transactions = ediItems.OfType <TS850>(); foreach (var transaction in transactions) { var n1Loop = transaction.N1Loop.Where(n1 => n1.N1.EntityIdentifierCode_01 == "ST").Single(); // Transform each transaction PurchaseOrder customTransaction = Mapper.Map <TS850, PurchaseOrder>(transaction); customTransaction = Mapper.Map <I_BEG, PurchaseOrder>(transaction.BEG, customTransaction); customTransaction = Mapper.Map <I_N1, PurchaseOrder>(n1Loop.N1, customTransaction); customTransaction = Mapper.Map <I_N3, PurchaseOrder>(n1Loop.N3.First(), customTransaction); customTransaction = Mapper.Map <I_N4, PurchaseOrder>(n1Loop.N4.First(), customTransaction); } }