Saturday, February 11, 2017

CONVERT HL7 MESSAGE INTO JSON USING MS .NET C#

This is pretty straight forward and fast way to parse HL7 message into JSON string then can be uses as their needs as in Mobile APP or Web App or Automation services at any part of healthcare.

It is fast because, it uses C# 4.5 async and await feature and neat, slick and smooth WPF windows APP.

How to Use :

1) Select or Browse HL7 Message file with only .hl7 extension from drive

2) Then just click on Convert button and within a second corresponding output with JSON format will be ready.





to view formatted JSON just go to the JSONLINT and paste Json output and click on validate Json, after json validation results will be like below :

{
"hl7": {
"@xml-space": "preserved",
"MSH": {
"@fieldDelimiter": "|",
"@componentDelimiter": "^",
"@repeatDelimiter": "~",
"@escapeDelimiter": "\\",
"@subcomponentDelimiter": "&",
"field": ["CERNER", null, "PriorityHealth", null, null, null, {
"#text": "ORU",
"component": "R01"
}, "Q479004375T431430612", "P", "2.3", null]
},
"PID": {
"field": [null, null, "001677980", null, {
"#text": "SMITH",
"component": "CURTIS"
}, null, "19680219", "M", null, null, null, null, null, null, null, null, null, "929645156318", "123456789", null]
},
"PD1": {
"field": [null, null, null, {
"#text": "1234567890",
"component": ["LAST", "FIRST", "M", null, null, null, null, "NPI"]
}, null]
},
"OBR": {
"field": ["1", {
"#text": "341856649",
"component": "HNAM_ORDERID"
}, "000002006326002362", {
"#text": "648088",
"component": "Basic Metabolic Panel"
}, null, null, "20061122151600", null, null, null, null, null, null, null, null, {
"#text": "1620",
"component": ["Hooker", "Robert", "L"]
}, null, null, null, null, null, "20061122154733", null, null, "F", null, null, null, null, null, null, null, null, null, null, "20061122140000", null]
},
"OBX": {
"field": ["1", "NM", {
"#text": "GLU",
"component": "Glucose Lvl"
}, "59", "mg/dL", {
"#text": "65-99",
"component": ["65", "99"]
}, "L", null, null, "F", null, null, "20061122154733", null]
}
}
}

Further information about HL7 messaging can be found on http://www.hl7.org.

PS: HL7 sample picked from http://www.priorityhealth.com/provider/manual/office-mgmt/data-exchange/hl7/hl7-samples

if anyone required to use this app or source code please let me know, I also would like welcome feedback and suggestions on this how improve and make more generic.

Thanks
Aifaz

Tuesday, June 28, 2016

SQL - Queries Tuning and Optimization Techniques


In SQL, it is very difficult to write complex SQL queries involving joins across many (at least 3-4) tables and involving several nested conditions because a SQL statement, once it reaches a certain level of complexity, is basically a little program in and of itself. 
A database index is a data structure that improves the speed of operations on a database table. Indexes can be created using one or more columns of a database table, providing the basis for both rapid random look ups and efficient access of ordered records. Indexing is incredibly important when working with large tables, however, occasionally smaller tables should be indexed, if they are expected to grow.


Try to consistently indent and don't be afraid to use multiple lines. You don't have to write it all at once. Complex queries can sometimes just be a collection of simple queries. You need to follow some basic guidelines and Take the time to think these through such as-

  1. List all of the columns that are to be returned
  2. List all of the columns that are used in the WHERE clause
  3. List all of the columns used in the JOINs (if applicable)
  4. List all the tables used in JOINs (if applicable)
  5. Get the correct records selected first
  6. Save the complex calculations for last
  7. If you do use a Common Table Expression (CTE), be aware that the query only persists until the next query is run, so in some cases where you are using the CTE in multiple queries, it might be better for performance to use a temp table.

Once you have the above information organized into this easy-to-comprehend form, it is much easier to identify those columns that could potentially make use of indexes when executed.
It makes a big difference to really understand how the data is combined, selected, filtered, and output. Here, query Optimization tricks comes into the picture to increase the performance of the program or software. There are a lot of guideline points to tune your query which do work as the boost of the query performance.  These guideline points are mentioned below: 

  1. SET NOCOUNT ON at the beginning of each stored procedure you write. This statement should be included in every stored procedure, trigger, etc. that you write.
  2. The SQL query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.
  3. HAVING clause is used to filter the rows after all the rows are selected if you are using aggregation functions. It is just like a filter. Do not use HAVING clause for any other purposes.
  4. It is the best practice to avoid sub queries in your SQL statement and try to minimize the number of subquery block in your query if possible.
  5. Use operator EXISTS, IN and table joins appropriately in your query. The reason is- Usually IN has the slowest performance 
  6. IN is efficient when most of the filter criteria are in the sub-query.  
  7. EXISTS is efficient when most of the filter criteria is in the main query.
  8. Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.
  9. Be careful while using conditions in WHERE clause.
  10. To write queries which provide efficient performance follow the general SQL standard rules.
  11. Use single case for all SQL verbs
  12. Begin all SQL verbs on a new line
  13. Separate all words with a single space 
  14. Right or left aligning verbs within the initial SQL verb
  15. Indexes have the advantages as well as disadvantages as given below-
  16. Do not automatically add indexes on a table because it seems like the right thing to do. Only add indexes if you know that they will be used by the queries run against the table.
  17. Indexes should be measured on all columns that are frequently used in WHERE, ORDER BY, GROUP BY, TOP and DISTINCT clauses.
  18. Do not add more indexes on your OLTP tables to minimize the overhead that occurs with indexes during data modifications.
  19. Drop all those indexes that are not used by the Query Optimizer, generally.
  20. If possible, try to create indexes on columns that have integer values instead of characters. Integer values use less overhead than character values.
  21. To provide up-to-date statistics, the query optimizer needs to make smart query optimization decisions. You will generally want to leave the "Auto Update Statistics" database option on. This helps to ensure that the optimizer statistics are valid, ensuring that queries are properly optimized when they are run.
  22. If you want to boost the performance of a query that includes an AND operator in the WHERE clause, consider the following:
  23. Of the search criteria in the WHERE clause, at least one of them should be based on a highly selective column that has an index.
  24. If at least one of the search criteria in the WHERE clause is not highly selective, consider adding indexes to all of the columns referenced in the WHERE clause.
  25. If none of the columns in the WHERE clause are selective enough to use an index on their own, consider creating a covering index for this query.
  26. Queries that include either the DISTINCT or the GROUP BY clauses can be optimized by including appropriate indexes. Any of the following indexing strategies can be used:
  27. Include a covering, non-clustered index (covering the appropriate columns) of the DISTINCT or the GROUP BY clauses.
  28. Include a clustered index on the columns in the GROUP BY clause.
  29. Include a clustered index on the columns found in the SELECT clause.
  30. Adding appropriate indexes to queries that include DISTINCT or GROUP BY is most important for those queries that run often.
  31. When you need to execute a string of Transact-SQL, you should use the sp_executesql stored procedure instead of the EXECUTE statement.
  32. When calling a stored procedure from your application, it is important that you call it using its qualified name.
  33. Use stored procedures instead of views because they offer better performance and don't include code, variable or parameters that don't do anything.
  34. If possible, avoid using SQL Server cursors. They generally use a lot of SQL Server resources and reduce the performance and scalability of your applications.
  35. Instead of using temporary tables, consider using a derived table instead. A derived table is the result of using a SELECT statement in the FROM clause of an existing SELECT statement. By using derived tables instead of temporary tables, you can reduce I/O and often boost your application's performance.
  36. Don't use the NVARCHAR or NCHAR data types unless you need to store 16-bit character (Unicode) data. They take up twice as much space as VARCHAR or CHAR data types, increasing server I/O and wasting unnecessary space in your buffer cache.
  37. If you use the CONVERT function to convert a value to a variable length data type such as VARCHAR, always specify the length of the variable data type. If you do not, SQL Server assumes a default length of 30.
  38. If you are creating a column that you know will be subject to many sorts, consider making the column integer-based and not character-based. This is because SQL Server can sort integer data much faster than character data.
  39. Don't use ORDER BY in your SELECT statements unless you really need to, as it adds a lot of extra overhead. For example, perhaps it may be more efficient to sort the data at the client than at the server.
  40. Don't return more data (both rows and columns) from SQL Server than you need to the client or middle-tier and then further reduce the data to the data you really need at the client or middle-tier. This wastes SQL Server resources and network bandwidth.

Conclusion
To tune our SQL queries, understanding our database does play the most important role. In SQL, typically each table column has an associated data type. Text, Integer, Varchar, Date, and more, are typically available types for developers to choose from. When writing SQL statements, make sure you choose the proper data type for the column. Sometimes it's easier to break up sub groups into their own select statement. To write a query, we need to know about the actual need of the query and scope of the query also. 

Friday, January 30, 2015

Create 270 X12 Eligibility Request Message using C# (MS .NET)


Introduction:


Health Care Eligibility Benefit Inquiry and Response (270/271)



This post helps the provider to determine whether the information source (payer) has a particular subscriber or dependent on file and the health care eligibility and/or benefit information about that subscriber and/or dependent(s). 

The post provides the provider with the information at the time the patient checks in and makes the information available instantaneously, which is not possible through other methods like paper and phone. 

1.Create 270 Request using C#


Sample 270 Eligibility Request:

ISA*00* *00* *ZZ*SUBMITTERID *ZZ*CMS *140831*0734*^*00501*000005014*1*P*|~
GS*HS*SUBMITTERID*CMS*20140831*073411*5014*X*005010X279A1~
ST*270*000000001*005010X279A1~
BHT*0022*13*TRANSA*20140831*073411~
HL*1**20*1~
NM1*PR*2*CMS*****PI*CMS~
HL*2*1*21*1~
NM1*1P*2*IRNAME*****XX*1234567893~
HL*3*2*22*0~
TRN*1*TRACKNUM*ABCDEFGHIJ~
NM1*IL*1*LNAME*FNAME****MI*123456789A~
DMG*D8*19400401~
DTP*291*RD8*20140201-20141031~
EQ*10^14^30^42^45^48^67^A7^AD^AE^AG^BF^BG~
EQ**HC|80061~
EQ**HC|G0117~
SE*15*000000001~
GE*1*5014~

IEA*1*000005014~

I have created Main Class called as ManualX12Creation and it will call other segments  classes like ISA, IEA and NM1 etc..

public class ManualX12Creation
{
        Patient patient;
        Provider provider;
        Payer payer;
        DTP dtp;
        public ManualX12Creation(Patient opatient, Provider oprovider, Payer opayer, DTP odtp)
        {

            patient = opatient;
            provider = oprovider;
            payer = opayer;
            dtp = odtp;

        }

 public string CreateISA(string row, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            ISA isa = new ISA();
            string[] ISA = new string[16];

            ISA[0] = "ISA";           // Interchange Control Header Segment ID 

            ISA[1] = "00";              // Author Info Qualifier 

            ISA[2] = String.Format("{0,10}", " "); //"".PadRight(10, ' ');          // Author Information 

            //ISA[2] = ISA[2].Substring(0, 10);

            ISA[3] = "00";                          //   Security Information Qualifier
            //   MEDI-CAL NOTE: For Leased-Line & Dial-Up use '01', 
            //   for BATCH use '00'.
            //   '00' No Security Information Present 
            //   (No Meaningful Information in I04)


            ISA[4] = String.Format("{0,10}", " ");//"".PadRight(10, ' ');    // Security Information 

            //ISA[4] = ISA[4].Substring(0, 10);

            ISA[5] = "ZZ".PadRight(2, ' ');             // Interchange ID Qualifier

            ISA[6] = isa.InterchangeSenderID.PadRight(15, ' '); //X12info[2].PadRight(15, ' ');      // INTERCHANGE SENDER ID 

            ISA[7] = "ZZ".PadRight(2, ' ');             // Interchange ID Qualifier 

            ISA[8] = isa.InterchangeReceiverID.PadRight(15, ' ');//X12info[3].PadRight(15, ' ');      // INTERCHANGE RECEIVER ID 

            ISA[9] = isa.InterchangeDate; //DateTime.Parse("2008/08/16").ToString("yyMMdd");//    // Interchange Date (YYMMDD) 

            ISA[10] = isa.InterchangeTime; //DateTime.Now.ToString("HHmm");//.PadRight(4, ' ');               // Interchange Time (HHMM)

            ISA[11] = "^";                                                          // Interchange Control Standards Identifier 

            ISA[12] = isa.InterchangeControlVersionNumber.PadRight(5, ' '); //"00501".PadRight(5, ' ');                                // Interchange Control Version Number 

            ISA[13] = isa.InterchangeControlNumber.PadRight(9, ' '); //"000000001".PadRight(9, ' ');                            // INTERCHANGE CONTROL NUMBER   

            ISA[14] = "0".PadRight(1, ' ');                                         // Acknowledgment Request [0= not requested, 1= requested]  

            ISA[15] = isa.UsageIndicatorProductionOrTest.PadRight(1, ' '); //"P".PadRight(1, ' ');                         // Usage Indicator [ P = Production Data, T = Test Data ]


            // string sep = "*";                                       // Data Element Separator 
            string sCreatedISA = String.Join(sep, ISA);
            sCreatedISA = sCreatedISA + "*";
            sCreatedISA = sCreatedISA + SegTerminator + ElementSeparator;

            return sCreatedISA.Trim();



        }


 // GS Segment  - EDI(x12 for A)-270 format 
        public string CreateGS(string row, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            GS gs = new GS();

            string[] GS = new string[9];

            GS[0] = "GS";                       // Functional Group Header Segment ID 

            GS[1] = "HS";                       // Functional ID Code [ HS = Eligibility, Coverage or Benefit Inquiry (270) ] 

            GS[2] = gs.GSApplicationSenderID; //X12info[2];                 // Application Sender's ID 

            GS[3] = gs.GSApplicationReceiverID; //X12info[3];                 // Application Receiver's ID 

            GS[4] = gs.GSDate; //DateTime.Parse("2007/08/16").ToString("yyyyMMdd");            // Date [CCYYMMDD] 

            GS[5] = gs.GSTime; //DateTime.Now.ToString("HHmmss");       // Time [HHMM] Group Creation Time  

            GS[6] = gs.GSGroupControlNumber; //"107018";                                           // Group Control Number 

            GS[7] = "X";                                                // Responsible Agency Code Accredited Standards Committee X12 ] 

            GS[8] = "005010X279A1";                                     // Version Release / Industry[ Identifier Code Query 

            //string sep = "*";
            string sCreatedGS = String.Join(sep, GS);
            sCreatedGS = sCreatedGS + ElementSeparator;

            return sCreatedGS.Trim();
        }


// ST Segment  - EDI(X12 A)-270 format 
        public string CreateST(string row, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            ST st = new ST();
            string[] ST = new string[4];
            ST[0] = "ST";                   // Transaction Set Header Segment ID 

            ST[1] = st.TransactionSetIdentifierCode; //"270";                  // Transaction Set Identifier Code (Inquiry Request) 

            ST[2] = st.STControlNumber; //"0001";                 // Transaction set control number must match SE

            ST[3] = "005010X279A1";

            // string sep = "*";
            string sCreatedST = String.Join(sep, ST);
            sCreatedST = sCreatedST + ElementSeparator;

            return sCreatedST.Trim();

        }


 // BHT Segment  - EDI(X12 A)-270 format 
        public string CreateBHT(string row, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            BHT bht = new BHT();
            string[] BHT = new string[6];

            BHT[0] = "BHT";                         // Beginning of Hierarchical Transaction Segment ID 

            BHT[1] = bht.SubscriberStructureCode; //"0022";                        // Subscriber Structure Code 

            BHT[2] = bht.PurposeCode; //"13";                          // Purpose Code - This is a Request   

            BHT[3] = bht.SubmitterTransactionIdentifier; //"TSG123";                      //  Submitter Transaction Identifier  
            //This information is required by the information Receiver 
            //when using Real Time transactions. 
            //For BATCH this can be used for optional information.

            BHT[4] = bht.TransactionCreatedDate; //DateTime.Parse("2007/08/16").ToString("yyyyMMdd");      // Date Transaction Set Created 

            BHT[5] = bht.TransactionCreatedTime; //DateTime.Now.ToString("HHmmss").ToString();    // Time Transaction Set Created 

            //string sep = "*";
            string sCreatedBHT = String.Join(sep, BHT);
            sCreatedBHT = sCreatedBHT + ElementSeparator;

            return sCreatedBHT.Trim();


        }

 // HL Segment  - EDI-270 format 
        public string CreateHL(string row, int nHLCounter, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            HL hl = new HL();
            string[] HL = new string[5];
            HL[0] = "HL";
            //HL_LEN[0] =  2;

            HL[1] = Convert.ToString(nHLCounter);               // Hierarchical ID No. 


            if (nHLCounter == 1)
            {
                HL[2] = "";
                HL[3] = hl.HLCounter1Value1; //"20"; // Description: Identifies the payor, maintainer, or source of the information.
                HL[4] = hl.HLCounter1Value2; //"1"; // 1 Additional Subordinate HL Data Segment in This Hierarchical Structure. 
            }
            else if (nHLCounter == 2)
            {
                HL[2] = hl.HLCounter2Value0; //"1"; // Hierarchical Parent ID Number 
                HL[3] = hl.HLCounter2Value1; //"21"; // Hierarchical Level Code. '21' Information Receiver
                HL[4] = hl.HLCounter2Value2; //"1"; // 1 Additional Subordinate HL Data Segment in This Hierarchical Structure. 
            }
            else
            {
                HL[2] = hl.HLCounter3Value0; //"2";
                HL[3] = hl.HLCounter3Value1; //"22"; // Hierarchical Level Code.'22' Subscriber 
                HL[4] = hl.HLCounter3Value2; //"0"; // 0 no Additional Subordinate in the Hierarchical Structure. 
            }

            //string sep = "*";
            string sCreatedHL = String.Join(sep, HL);
            sCreatedHL = sCreatedHL + ElementSeparator;

            return sCreatedHL.Trim();

        }


 public string CreateNM1(string row, string NM1Cast, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            NM1 nm1 = new NM1();
            string[] NM1 = new string[10];

            NM1[0] = "NM1";

            if (NM1Cast == nm1.NM1PR)//nm1.NM1PR
            {
                NM1[1] = "PR"; // Entity ID Code - Payer [PR Payer] 
                NM1[2] = "2"; // Entity Type - Non-Person 
                NM1[3] = payer.PayerName;            // Organizational Name 
                NM1[4] = ""; // Data Element not required.
                NM1[5] = ""; // Data Element not required.
                NM1[6] = ""; // Data Element not required.
                NM1[7] = ""; // Data Element not required.
                NM1[8] = "PI"; // 46 - Electronic Transmitter Identification Number (ETIN) 
                NM1[9] = payer.PayerID; //"ABC123";//X12info[3]; // Application Sender's ID 
            }
            else if (NM1Cast == nm1.NM1P1)//nm1.1P
            {
                NM1[1] = "1P"; // Entity ID Code - Provider [1P Provider]
                NM1[2] = "2"; // Entity Type - Person 
                NM1[3] = provider.ProviderName; //"TestOrg..";               //row['facility_name']; // Organizational Name 
                //NM1[4] = row['provider_lname']; // Data Element not required.
                //NM1[5] = row['provider_fname']; // Data Element not required.
                NM1[4] = ""; // Data Element not required.
                NM1[5] = ""; // Data Element not required.
                NM1[6] = ""; // Data Element not required.
                NM1[7] = ""; // Data Element not required.
                NM1[8] = "XX";
                NM1[9] = provider.NPI; //"ABC123";                           //row['provider_npi'];
            }
            else if (NM1Cast == nm1.NM1IL)////nm1.IL
            {
                NM1[1] = "IL"; // Insured or Subscriber 
                NM1[2] = "1"; // Entity Type - Person 
                // NM1[3] = "Khan";   patient.LastName    
                NM1[3] = patient.LastName; //row['lname']; // last Name
                NM1[4] = patient.FirstName;//"Aifaz";           //row['fname']; // first Name
                NM1[5] = "";                   //row['mname']; // middle Name
                NM1[6] = ""; // data element 
                NM1[7] = ""; // data element 
                NM1[8] = "MI"; // Identification Code Qualifier 
                NM1[9] = patient.IdentificationCode; //"12345";            //row['subscriber_ss']; // Identification Code 
            }

            //string sep = "*";
            string sCreatedNM1 = String.Join(sep, NM1);
            sCreatedNM1 = sCreatedNM1 + ElementSeparator;

            return sCreatedNM1.Trim();


        }

  public string CreateREF(string row, string sref, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            REF oref = new REF();
            string[] REF = new string[3];
            REF[0] = "REF";

            if (sref == "1P")
            {
                REF[1] = "4A"; // Reference Identification Qualifier 
                REF[2] = oref.REFProviderPIN;//"ABC123"; // Provider Pin. 
            }
            else
            {
                REF[1] = "TJ"; // 'EJ' for Patient Account Number 
                REF[2] = oref.REFPatAccountNO; //"ABC123"; // Patient Account No. 
            }

            // string sep = "*";
            string sCreatedREF = String.Join(sep, REF);
            sCreatedREF = sCreatedREF + ElementSeparator;

            return sCreatedREF.Trim();
        }

public string CreateTRN(string row, string trancNO, string refIdentifier, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            TRN trn = new TRN();
            // trn.TraceNumber = trancNO;
            string[] TRN = new string[5];
            TRN[0] = "TRN";
            TRN[1] = "1";
            TRN[2] = trn.TraceNumber; //trancNO;               // Trace Number 
            TRN[3] = trn.CompanyID; //"9000000000";        // Originating Company ID  must be 10 positions in length 
            TRN[4] = trn.RefIdentifier; //refIdentifier;         // Additional Entity Identifier (i.e. Subdivision) 

            // string sep = "*";
            string sCreatedTRN = String.Join(sep, TRN);
            sCreatedTRN = sCreatedTRN + ElementSeparator;

            return sCreatedTRN.Trim();
        }

//Demographics


    public string CreateDMG(string row, string[] X12info, string SegTerminator, string ElementSeparator)

        {


            string[] DMG = new string[4];

            DMG[0] = "DMG";
            DMG[1] = "D8";              // Date Format Qualifier - (D8 means CCYYMMDD)
            DMG[2] = patient.DOB;//"1990/01/01";        // Subscriber's Birth date
            DMG[3] = patient.Gender;
            string sep = "*";
            string sCreatedDMG = String.Join(sep, DMG);
            sCreatedDMG = sCreatedDMG + ElementSeparator;

            return sCreatedDMG.Trim();

        }


 public string CreateDTP(string row, string qual, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            //DTP dtp = new DTP();
            //qual=291
            //dtp.Qualifier = qual;
            string[] DTP = new string[4];
            DTP[0] = "DTP";

            DTP[1] = dtp.Qualifier; //qual; // Qualifier - Date of Service 

            DTP[2] = dtp.DateFormatQualifier; // Date Format Qualifier - (D8 means CCYYMMDD) 

            if (qual == "102")
            {
                DTP[3] = dtp.EventDate; //"Date";//row['date']; // Date 
            }
            else
            {
                DTP[3] = dtp.EventDate; //"1990/01/01";//row['pc_eventDate']; // Date of Service 
            }

            //string sep = "*";
            string sCreatedDTP = String.Join(sep, DTP);
            sCreatedDTP = sCreatedDTP + ElementSeparator;

            return sCreatedDTP.Trim();
        }

 public string CreateEQ(string row, string[] X12info, string SegTerminator, string ElementSeparator)
        {
            EQ eq = new EQ();
            string[] EQ = new string[2];
            EQ[0] = "EQ";
            EQ[1] = eq.ServiceTypeCode; //"30";               // Service Type Code 

            string sep = "*";
            string sCreatedEQ = String.Join(sep, EQ);
            sCreatedEQ = sCreatedEQ + ElementSeparator;

            return sCreatedEQ.Trim();


        }

  public string CreateSE(string row, string SegmentCount, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            //SegmentCount=14
            SE se = new SE();
            // se.SegmentCount = SegmentCount;
            string[] SE = new string[3];

            SE[0] = "SE";

            SE[1] = se.SegmentCount;// SegmentCount;       // Segment Count 

            SE[2] = se.TransactionSetControlNumber; //"0001"; // Transaction Set Control Number - Must match ST's 

            //string sep = "*";
            string sCreatedSE = String.Join(sep, SE);
            sCreatedSE = sCreatedSE + ElementSeparator;

            return sCreatedSE.Trim();

        }

 public string CreateGE(string row, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            GE ge = new GE();
            string[] GE = new string[3];

            GE[0] = "GE";
            GE[1] = ge.NumberofIncludedTrans; //"1";                // Number of included Transaction Sets 
            GE[2] = ge.GroupControlNumber; //"1048";                 // Group Control Number match with GS06

            //string sep = "*";
            string sCreatedGE = String.Join(sep, GE);
            sCreatedGE = sCreatedGE + ElementSeparator;

            return sCreatedGE.Trim();

        }

 public string CreateIEA(string row, string[] X12info, string SegTerminator, string ElementSeparator, string sep)
        {
            IEA iea = new IEA();

            string[] IEA = new string[3];

            IEA[0] = "IEA";

            IEA[1] = iea.NumberofIncludedTrans; //"1";                               // Number of included Functional Groups 

            IEA[2] = iea.InterchangeControlNumber; //"000000001"; // Interchange Control Number 

            //string sep = "*";
            string sCreatedIEA = String.Join(sep, IEA);
            sCreatedIEA = sCreatedIEA + ElementSeparator;

            return sCreatedIEA.Trim();

        }


 public string PrintEDI(string row, string res, string[] X12info, string SegTerminator, string ElementSeparator)

        {

            int i = 1;

            StringBuilder sbEDI = new StringBuilder();
            string PatEDI = "";

            // For Header Segment 
            int segmentcount = 1;
            int nHlCounter = 1;
            int rowCount = 1;
            int trcNo = 1234501;
            int refiden = 5432101;

            //while (row = sqlFetchArray(res)) 
            while (i == rowCount)
            {
                if (nHlCounter == 1)
                {
                    // create ISA 

                    sbEDI.AppendLine(CreateISA(row, X12info, SegTerminator, ElementSeparator, "*"));
                    // create GS 

                    sbEDI.AppendLine(CreateGS(row, X12info, SegTerminator, ElementSeparator, "*"));
                    // create ST 

                    sbEDI.AppendLine(CreateST(row, X12info, SegTerminator, ElementSeparator, "*"));
                    // create BHT 

                    sbEDI.AppendLine(CreateBHT(row, X12info, SegTerminator, ElementSeparator, "*"));

                    // For Payer Segment 


                    sbEDI.AppendLine(CreateHL(row, 1, X12info, SegTerminator, ElementSeparator, "*"));

                    sbEDI.AppendLine(CreateNM1(row, "PR", X12info, SegTerminator, ElementSeparator, "*"));

                    // For Provider Segment


                    sbEDI.AppendLine(CreateHL(row, 2, X12info, SegTerminator, ElementSeparator, "*"));

                    sbEDI.AppendLine(CreateNM1(row, "1P", X12info, SegTerminator, ElementSeparator, "*"));

                    sbEDI.AppendLine(CreateREF(row, "TJ", X12info, SegTerminator, ElementSeparator, "*"));//1P initially

                    nHlCounter = nHlCounter + 2;

                    segmentcount = 7; // segement counts - start from ST 
                }


                // For Subscriber Segment

                // PatEDI += CreateHL(row, nHlCounter, X12info, SegTerminator, ElementSeparator);
                sbEDI.AppendLine(CreateHL(row, nHlCounter, X12info, SegTerminator, ElementSeparator, "*"));

                sbEDI.AppendLine(CreateTRN(row, Convert.ToString(trcNo), Convert.ToString(refiden), X12info, SegTerminator, ElementSeparator, "*"));

                sbEDI.AppendLine(CreateNM1(row, "IL", X12info, SegTerminator, ElementSeparator, "*"));

                // sbEDI.AppendLine(CreateREF(row, "IL", X12info, SegTerminator, ElementSeparator, "*")); //Commented repeating

                sbEDI.AppendLine(CreateDMG(row, X12info, SegTerminator, ElementSeparator));

                sbEDI.AppendLine(CreateDTP(row, "472", X12info, SegTerminator, ElementSeparator, "*"));

                sbEDI.AppendLine(CreateEQ(row, X12info, SegTerminator, ElementSeparator));

                segmentcount = segmentcount + 7;
                nHlCounter = nHlCounter + 1;
                rowCount = rowCount + 1;
                trcNo = trcNo + 1;
                refiden = refiden + 1;
                //i = i + 1;
                //if(rowCount == sqlNumRows(res))
                if (i == 1)
                {
                    segmentcount = segmentcount + 1;
                    // PatEDI += CreateSE(row, Convert.ToString(segmentcount), X12info, SegTerminator, ElementSeparator);
                    sbEDI.AppendLine(CreateSE(row, Convert.ToString(segmentcount), X12info, SegTerminator, ElementSeparator, "*"));
                    // PatEDI += CreateGE(row, X12info, SegTerminator, ElementSeparator);
                    sbEDI.AppendLine(CreateGE(row, X12info, SegTerminator, ElementSeparator, "*"));
                    //PatEDI += CreateIEA(row, X12info, SegTerminator, ElementSeparator);
                    sbEDI.AppendLine(CreateIEA(row, X12info, SegTerminator, ElementSeparator, "*"));
                }

            }
            //print $PATEDI;
            return PatEDI = sbEDI.ToString();
        }

    } // End of ManualX12Creation Class
}

Segments Classes:



















































Similarly we create other segments classes as like above and passed it to above main class.

To input data into 270 string using class








































And finally invoke class as below

ManualX12Creation objManualX12Creation = new ManualX12Creation(oPatient, oProvider, oPayer, oDTP);
            string[] X12info = new string[5];


            string FileContent = objManualX12Creation.PrintEDI("row", "res", X12info, ":", "~");