示例#1
0
        //string json3 = @"{'Type': 'M',
        //    'Name': 'M_940',
        //    'Content': [{
        //        'Type': 'S',
        //        'Name': 'W05',
        //        'Content': [ { 'E': 'N' }, { 'E': '538686' }, { 'E': '' }, { 'E': '001001' }, { 'E': '538686' }]
        //    }]
        //}";
        //{'Type': 'M','Name': 'M_940','Content': [{'Type': 'S','Name': 'W05','Content': [ { 'E': 'N' }, { 'E': '538686' }, { 'E': '' }, { 'E': '001001' }, { 'E': '538686' }]}]}
        public string GetEDIDocFromJSON(string jsonEDIdata)
        {
            dynamic json = JsonConvert.DeserializeObject(jsonEDIdata, typeof(object));

            //TODO: convert logic to determine map to separate method

            MapLoop       map     = Factory.GetMap((string)json.Name); //TODO: add exception handling for the string cast operation
            JsonMapReader jReader = new JsonMapReader(map);
            EdiTrans      ediTxn  = jReader.ReadToEnd(jsonEDIdata);

            var eGroup = new EdiGroup("OW");

            eGroup.Transactions.Add(ediTxn);

            var eInterchange = new EdiInterchange();

            eInterchange.Groups.Add(eGroup);

            EdiBatch eBatch = new EdiBatch();

            eBatch.Interchanges.Add(eInterchange);

            //Add all service segments
            EdiDataWriterSettings settings = new EdiDataWriterSettings(
                new SegmentDefinitions.ISA(), new SegmentDefinitions.IEA(),
                new SegmentDefinitions.GS(), new SegmentDefinitions.GE(),
                new SegmentDefinitions.ST(), new SegmentDefinitions.SE(),
                "ZZ", "SENDER", "ZZ", "RECEIVER", "GSSENDER", "GSRECEIVER", "00401", "004010", "T", 100, 200, "\r\n", "*");

            EdiDataWriter ediWriter = new EdiDataWriter(settings);

            return(ediWriter.WriteToString(eBatch));
        }
示例#2
0
        private EdiSegment CreateAk1Segment(MapLoop map, EdiGroup g)
        {
            var sDef = (MapSegment)map.Content.First(s => s.Name == "AK1");
            var seg  = new EdiSegment(sDef);

            seg.Content.AddRange(new[]
            {
                new EdiSimpleDataElement((MapSimpleDataElement)sDef.Content[0], g.FunctionalCode),
                new EdiSimpleDataElement((MapSimpleDataElement)sDef.Content[1], g.GS.Content[5].Val),
            });
            return(seg);
        }
示例#3
0
        private EdiSegment CreateAk9Segment(MapLoop map, EdiGroup g, int includedTranCount, int receivedTranCount)
        {
            var sDef = (MapSegment)map.Content.First(s => s.Name == "AK9");
            var seg  = new EdiSegment(sDef);

            var status                    = "A";
            int acceptedTranCount         = g.Transactions.Count(t => !t.ValidationErrors.Any());
            var reportedAcceptedTranCount = g.Transactions.Count;

            switch (_settings.AckValidationErrorBehavour)
            {
            case AckValidationErrorBehavour.AcceptButNoteErrors:
                if (receivedTranCount > acceptedTranCount)
                {
                    status = "E";     //Accepted but errors were noted.
                }
                break;

            case AckValidationErrorBehavour.RejectValidationErrors:
                if (acceptedTranCount == 0)
                {
                    status = "R";     //Rejected - no accepted trans
                }
                else if (receivedTranCount > acceptedTranCount)
                {
                    status = "P";     //Partially accepted, at least one transaction set was rejected
                }
                reportedAcceptedTranCount = acceptedTranCount;
                break;
            }

            seg.Content.AddRange(new[]
            {
                new EdiSimpleDataElement((MapSimpleDataElement)sDef.Content[0], status),
                new EdiSimpleDataElement((MapSimpleDataElement)sDef.Content[1], includedTranCount.ToString()),
                new EdiSimpleDataElement((MapSimpleDataElement)sDef.Content[2], receivedTranCount.ToString()),
                new EdiSimpleDataElement((MapSimpleDataElement)sDef.Content[3], reportedAcceptedTranCount.ToString()),
            });

            return(seg);
        }
示例#4
0
        public EdiBatch FromString(string fileContent)
        {
            if (string.IsNullOrWhiteSpace(fileContent))
            {
                throw new EdiParsingException("Empty File");
            }

            if (!fileContent.StartsWith("ISA"))
            {
                throw new EdiParsingException("ISA NOT FOUND");
            }

            _elementSeparator = fileContent[3].ToString();
            _segmentSeparator = fileContent.Substring(105, fileContent.IndexOf($"GS{_elementSeparator}", StringComparison.Ordinal) - 105);

            string[] segments = fileContent.Split(new [] { _segmentSeparator }, StringSplitOptions.RemoveEmptyEntries);

            EdiBatch batch = new EdiBatch();

            EdiInterchange currentInterchange = null;
            EdiGroup       currentGroup       = null;
            EdiTrans       currentTrans       = null;
            EdiMapReader   mapReader          = null;

            int tranSegCount = 0;
            int groupsCount  = 0;
            int transCount   = 0;

            foreach (string seg in segments)
            {
                string[]   elements = seg.Split(new [] { _elementSeparator }, StringSplitOptions.None);
                MapSegment segDef;
                switch (elements[0])
                {
                case "ISA":
                    groupsCount        = 0;
                    currentInterchange = new EdiInterchange
                    {
                        SegmentSeparator = _segmentSeparator,
                        ElementSeparator = _elementSeparator
                    };

                    segDef = GetSegDefinition("ISA", $"{elements[12]}0", MissingStandardFallbackVersion);
                    currentInterchange.ISA = MapReader.ProcessSegment(segDef, elements, 0, currentInterchange);
                    break;

                case "IEA":
                    if (currentInterchange == null)
                    {
                        throw new EdiParsingException("MALFORMED  DATA");
                    }

                    segDef = GetSegDefinition("IEA", $"{currentInterchange.ISA.Content[11].Val}0", MissingStandardFallbackVersion);
                    currentInterchange.IEA = MapReader.ProcessSegment(segDef, elements, 0, currentInterchange);
                    batch.Interchanges.Add(currentInterchange);

                    int declaredGroupCount;
                    int.TryParse(elements[1], out declaredGroupCount);

                    if (declaredGroupCount != groupsCount)
                    {
                        AddValidationError(currentInterchange, $"Expected {declaredGroupCount} groups. Found {groupsCount}. Interchange # {elements[2]}.");
                    }

                    if (!CheckControlNumbersAreEgual(currentInterchange.ISA.Content[12].Val, elements[2]))
                    {
                        AddValidationError(currentInterchange, $"Control numbers do not match. ISA {currentInterchange.ISA.Content[12].Val}. IEA {elements[2]}.");
                    }

                    currentInterchange = null;
                    break;

                case "GS":
                    groupsCount++;
                    transCount   = 0;
                    currentGroup = new EdiGroup(elements[1]);

                    segDef          = GetSegDefinition("GS", $"{elements[8]}", MissingStandardFallbackVersion);
                    currentGroup.GS = MapReader.ProcessSegment(segDef, elements, 0, currentGroup);
                    break;

                case "GE":
                    if (currentInterchange == null || currentGroup == null)
                    {
                        throw new EdiParsingException("MALFORMED DATA");
                    }

                    segDef          = GetSegDefinition("GE", $"{currentGroup.GS.Content[7].Val}", MissingStandardFallbackVersion);
                    currentGroup.GE = MapReader.ProcessSegment(segDef, elements, 0, currentGroup);
                    currentInterchange.Groups.Add(currentGroup);

                    int declaredTransCount;
                    int.TryParse(elements[1], out declaredTransCount);

                    if (declaredTransCount != transCount)
                    {
                        AddValidationError(currentGroup, $"Expected {declaredTransCount} transactions. Found {transCount}. Group # {elements[2]}.");
                    }

                    if (!CheckControlNumbersAreEgual(currentGroup.GS.Content[5].Val, elements[2]))
                    {
                        AddValidationError(currentGroup, $"Control numbers do not match. GS {currentGroup.GS.Content[5].Val}. GE {elements[2]}.");
                    }

                    currentGroup = null;
                    break;

                case "ST":
                    if (currentInterchange == null || currentGroup == null)
                    {
                        throw new EdiParsingException("MALFORMED DATA");
                    }

                    string asmName  = $"EdiEngine.Standards.X12_{currentGroup.GS.Content[7].Val}";
                    string typeName = $"{asmName}.Maps.M_{elements[1]}";

                    var map = Activator.CreateInstance(asmName, typeName).Unwrap();
                    if (!(map is MapLoop))
                    {
                        AddValidationError(currentTrans, $"Can not find map {elements[1]} for standard {currentGroup.GS.Content[7].Val}. Skipping Transaction.");
                        break;
                    }

                    transCount++;
                    currentTrans = new EdiTrans((MapBaseEntity)map);

                    segDef          = GetSegDefinition("ST", $"{currentGroup.GS.Content[7].Val}", MissingStandardFallbackVersion);
                    currentTrans.ST = MapReader.ProcessSegment(segDef, elements, 0, currentTrans);

                    tranSegCount = 1;

                    mapReader = new EdiMapReader((MapLoop)map, currentTrans);
                    break;

                case "SE":
                    if (currentInterchange == null || currentGroup == null || currentTrans == null)
                    {
                        throw new EdiParsingException("MALFORMED DATA");
                    }

                    tranSegCount++;

                    int declaredSegCount;
                    int.TryParse(elements[1], out declaredSegCount);

                    if (declaredSegCount != tranSegCount)
                    {
                        AddValidationError(currentTrans, $"Expected {declaredSegCount} segments. Found {tranSegCount}. Trans # {elements[2]}.");
                    }

                    if (!CheckControlNumbersAreEgual(currentTrans.ST.Content[1].Val, elements[2]))
                    {
                        AddValidationError(currentTrans, $"Control numbers do not match. ST {currentTrans.ST.Content[1].Val}. SE {elements[2]}.");
                    }

                    segDef          = GetSegDefinition("SE", $"{currentGroup.GS.Content[7].Val}", MissingStandardFallbackVersion);
                    currentTrans.SE = MapReader.ProcessSegment(segDef, elements, 0, currentTrans);

                    currentGroup.Transactions.Add(currentTrans);
                    currentTrans = null;
                    break;

                default:
                    tranSegCount++;
                    mapReader?.ProcessRawSegment(elements[0], elements, tranSegCount);
                    break;
                }
            }
            return(batch);
        }
示例#5
0
        public static async Task <String> SplitEDIFile(string BLOBFileName, string splitHalf, ILogger log)
        {
            log.LogInformation("SplitEDIFile function processing a request.");

            //Incoming JSON Payload:
            //{ "ediFileName":"916386MS210_202001190125_000000001.raw","splitHalf":"1"}


            // Parse the connection string and get a reference to the blob.
            var storageCredentials  = new StorageCredentials("jbupsbtspaassagenv2", "Pi5FpNwJgcwJiAj7fxyCc4ncM4llKu3184a0OrTE1Jn0VxSYLGPIOZAO1j36DjT1Plmw8udLR3NXUBVNUWnucA==");
            var cloudStorageAccount = new CloudStorageAccount(storageCredentials, true);
            var cloudBlobClient     = cloudStorageAccount.CreateCloudBlobClient();

            //Define BlobIN Stream
            CloudBlobClient    blobINClient    = cloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer blobINContainer = blobINClient.GetContainerReference("edi-process-split");
            CloudBlockBlob     blobIN          = blobINContainer.GetBlockBlobReference(BLOBFileName);
            Stream             blobINStream    = await blobIN.OpenReadAsync();

            //Define BlobOUT FileName - for FIRST OR SECOND half of transactions
            string blobOUTPreFix = "";

            if (splitHalf == "1")
            {
                blobOUTPreFix = "A_";
            }
            else
            {
                blobOUTPreFix = "B_";
            }
            CloudBlobClient    blobOUTClient    = cloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer blobOUTContainer = blobOUTClient.GetContainerReference("edi-process-split");
            CloudBlockBlob     blobOUT          = blobOUTContainer.GetBlockBlobReference(blobOUTPreFix + BLOBFileName);

            //Read blobIN
            EdiDataReader r = new EdiDataReader();
            EdiBatch      b = r.FromStream(blobINStream);

            int totEDITransCtr = 0;

            totEDITransCtr = b.Interchanges[0].Groups[0].Transactions.Count();

            // **********************************************************
            // ** SAVE Original EDI Interchange: Data & Transactions
            // **********************************************************
            EdiInterchange OrigInter = new EdiInterchange();

            OrigInter = b.Interchanges[0];

            List <EdiTrans> OrigTrans = new List <EdiTrans>();

            OrigTrans = b.Interchanges[0].Groups[0].Transactions;

            // **********************************************************
            // ** Calculate SPLIT
            // **********************************************************

            //1st Half
            int EDI_Trans_Ctr1 = totEDITransCtr / 2;

            //2nd Half
            int EDI_Trans_Ctr2 = totEDITransCtr - (totEDITransCtr / 2);

            // **********************************************************
            // ** Write-Out 1st Half to file
            // **********************************************************
            List <EdiTrans> HalfTrans = new List <EdiTrans>();

            //Define LOOP Parameters - for FIRST OR SECOND half of transactions
            int loopStart = 0;
            int loopEnd   = 0;

            if (splitHalf == "1")
            {
                loopStart = 0;
                loopEnd   = EDI_Trans_Ctr1;
            }
            else
            {
                loopStart = EDI_Trans_Ctr1 + 1;
                loopEnd   = totEDITransCtr;
            }
            //Process TRANSACTIONS
            for (int i = loopStart; i < loopEnd; i++)
            {
                EdiTrans ediItem = new EdiTrans();
                ediItem = b.Interchanges[0].Groups[0].Transactions[i];
                HalfTrans.Add(ediItem);
            }
            EdiBatch b2 = new EdiBatch();

            //Handle InterChange
            EdiInterchange ediInterChgItem = new EdiInterchange();

            ediInterChgItem = b.Interchanges[0];

            //Remove existing
            EdiGroup jbEdiGroupItem = new EdiGroup("");

            jbEdiGroupItem = b.Interchanges[0].Groups[0];
            ediInterChgItem.Groups.RemoveRange(0, 1);

            //Add Interchange
            b2.Interchanges.Add(ediInterChgItem);

            //Handle Group
            jbEdiGroupItem.Transactions.RemoveRange(0, totEDITransCtr);
            ediInterChgItem.Groups.Add(jbEdiGroupItem);

            //Add Transactions
            for (int i = 0; i < HalfTrans.Count(); i++) //Hardcoded to 91
            {
                EdiTrans ediItem = new EdiTrans();
                ediItem = HalfTrans[i];
                b2.Interchanges[0].Groups[0].Transactions.Add(ediItem);
            }

            EdiDataWriterSettings settings = new EdiDataWriterSettings(
                new SegmentDefinitions.ISA(),
                new SegmentDefinitions.IEA(),
                new SegmentDefinitions.GS(),
                new SegmentDefinitions.GE(),
                new SegmentDefinitions.ST(),
                new SegmentDefinitions.SE(),
                OrigInter.ISA.Content[4].ToString(), //isaSenderQual
                OrigInter.ISA.Content[5].ToString(), //isaSenderId
                OrigInter.ISA.Content[6].ToString(), //isaReceiverQual
                                                     // OrigInter.ISA.Content[7].ToString(), //isaReceiverId
                "9163863M210",                       //isaReceiverId
                OrigInter.ISA.Content[8].ToString(), //gsSenderId
                OrigInter.ISA.Content[9].ToString(), //gsReceiverId

                // OrigInter.ISA.Content[10].ToString(), //JB Test

                OrigInter.ISA.Content[11].ToString(),   //isaEdiVersion
                OrigInter.ISA.Content[12].ToString(),   //gsEdiVersion
                                                        //  "00403", //gsEdiVersion
                OrigInter.ISA.Content[14].ToString(),   //P //isaUsageIndicator //[
                000,                                    //isaFirstControlNumber
                001,                                    //gsFirstControlNumber
                OrigInter.SegmentSeparator.ToString(),  //segmentSeparator
                OrigInter.ElementSeparator.ToString()); //elementSeparator

            EdiDataWriter w      = new EdiDataWriter(settings);
            string        JBData = w.WriteToString(b2);

            log.LogInformation("trigger function - WRITING SPLIT FILE : " + blobOUT.Name.ToString());
            await blobOUT.UploadTextAsync(JBData);

            blobINStream.Close();
            return(" ");
        }
示例#6
0
        public EdiBatch GetnerateAcknowledgment(EdiBatch input)
        {
            string mapVersion = null;
            var    firstGroup = input?.Interchanges?.FirstOrDefault()?.Groups?.FirstOrDefault();

            if (firstGroup != null)
            {
                mapVersion = firstGroup.GS.Content[7].Val;
            }

            if (string.IsNullOrWhiteSpace(mapVersion))
            {
                throw new InvalidDataException(
                          "Can not determine EDI X12 version from batch. Check there is at least one interchange with at least one group in it");
            }

            EdiBatch b997 = new EdiBatch();

            foreach (EdiInterchange ich in input.Interchanges)
            {
                var ich997 = new EdiInterchange();
                b997.Interchanges.Add(ich997);

                string asmName  = $"EdiEngine.Standards.X12_{mapVersion}";
                string typeName = $"{asmName}.Maps.M_997";

                var map     = (MapLoop)Activator.CreateInstance(asmName, typeName).Unwrap();
                var lAk2Def = (MapLoop)map.Content.First(s => s.Name == "L_AK2");

                foreach (EdiGroup g in ich.Groups)
                {
                    var g997 = new EdiGroup("FA");
                    ich997.Groups.Add(g997);

                    var t997 = new EdiTrans(map);
                    g997.Transactions.Add(t997);

                    int includedTranCount = int.Parse(g.GE.Content[0].Val);
                    int receivedTranCount = g.Transactions.Count;
                    int acceptedTranCount = g.Transactions.Count(t => !t.ValidationErrors.Any());

                    t997.Content.Add(CreateAk1Segment(map, g));

                    if (((_settings.AckValidationErrorBehavour == AckValidationErrorBehavour.AcceptButNoteErrors ||
                          _settings.AckValidationErrorBehavour == AckValidationErrorBehavour.RejectValidationErrors) &&
                         acceptedTranCount < receivedTranCount) ||
                        (_settings.AlwaysGenerateAk2Loop))
                    {
                        foreach (EdiTrans t in g.Transactions)
                        {
                            EdiLoop lAk2 = new EdiLoop(lAk2Def, null);
                            t997.Content.Add(lAk2);

                            lAk2.Content.Add(CreateAk2Segment(lAk2Def, t));
                            lAk2.Content.Add(CreateAk5Segment(lAk2Def, t));
                        }
                    }


                    t997.Content.Add(CreateAk9Segment(map, g, includedTranCount, receivedTranCount));
                }
            }

            return(b997);
        }