This repository has been archived by the owner on Jul 6, 2024. It is now read-only.
forked from j4jayant/hl7-cSharp-parser
-
Notifications
You must be signed in to change notification settings - Fork 115
/
Message.cs
971 lines (839 loc) · 38.8 KB
/
Message.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace HL7.Dotnetcore
{
public class Message
{
private List<string> allSegments = null;
internal Dictionary<string, List<Segment>> SegmentList { get; set; } = new Dictionary<string, List<Segment>>();
public string HL7Message { get; set; }
public string Version { get; set; }
public string MessageStructure { get; set; }
public string MessageControlID { get; set; }
public string ProcessingID { get; set; }
public int SegmentCount { get; set; }
public HL7Encoding Encoding { get; set; } = new HL7Encoding();
private static readonly char[] _queryDelimiter = { '.' };
private const string segmentRegex = @"^([A-Z][A-Z][A-Z1-9])([\(\[]([0-9]+)[\)\]]){0,1}$";
private const string fieldRegex = @"^([0-9]+)([\(\[]([0-9]+)[\)\]]){0,1}$";
private const string otherRegEx = @"^[1-9]([0-9]{1,2})?$";
public Message()
{
}
public Message(string strMessage)
{
HL7Message = strMessage;
}
public override bool Equals(object obj)
{
if (obj is Message)
return this.Equals((obj as Message).HL7Message);
if (obj is string)
{
var arr1 = this.HL7Message.Split(this.Encoding.SegmentDelimiter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var arr2 = (obj as string).Split(this.Encoding.SegmentDelimiter.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
return arr1.SequenceEqual(arr2);
}
return false;
}
public override int GetHashCode()
{
return this.HL7Message.GetHashCode();
}
/// <summary>
/// Parse the HL7 message in text format, throws HL7Exception if error occurs
/// </summary>
/// <param name="bypassValidation">To parse the message without any validation</param>
/// <returns>boolean</returns>
public bool ParseMessage(bool bypassValidation = false)
{
bool isValid = false;
bool isParsed = false;
try
{
if (!bypassValidation)
isValid = this.validateMessage();
else
isValid = true;
}
catch (HL7Exception)
{
throw;
}
catch (Exception ex)
{
throw new HL7Exception("Unhandled Exception in validation - " + ex.Message, HL7Exception.BAD_MESSAGE, ex);
}
if (isValid)
{
try
{
if (this.allSegments == null || this.allSegments.Count <= 0)
this.allSegments = MessageHelper.SplitMessage(HL7Message);
int segSeqNo = 0;
foreach (string strSegment in this.allSegments)
{
if (string.IsNullOrWhiteSpace(strSegment))
continue;
Segment newSegment = new Segment(this.Encoding)
{
Name = strSegment.Substring(0, 3),
Value = strSegment,
SequenceNo = segSeqNo++
};
this.AddNewSegment(newSegment);
}
this.SegmentCount = segSeqNo;
string strSerializedMessage;
try
{
strSerializedMessage = this.SerializeMessage(false);
}
catch (HL7Exception ex)
{
throw new HL7Exception("Failed to serialize parsed message with error - " + ex.Message, HL7Exception.PARSING_ERROR, ex);
}
if (!string.IsNullOrEmpty(strSerializedMessage))
{
if (this.Equals(strSerializedMessage))
isParsed = true;
}
else
{
throw new HL7Exception("Unable to serialize to original message - ", HL7Exception.PARSING_ERROR);
}
}
catch (Exception ex)
{
throw new HL7Exception("Failed to parse the message with error - " + ex.Message, HL7Exception.PARSING_ERROR, ex);
}
}
return isParsed;
}
/// <summary>
/// Serialize the message in text format
/// </summary>
/// <param name="validate">Validate the message before serializing</param>
/// <returns>string with HL7 message</returns>
public string SerializeMessage(bool validate)
{
if (validate && !this.validateMessage())
throw new HL7Exception("Failed to validate the updated message", HL7Exception.BAD_MESSAGE);
var strMessage = new StringBuilder();
string currentSegName = string.Empty;
List<Segment> _segListOrdered = getAllSegmentsInOrder();
try
{
try
{
foreach (Segment seg in _segListOrdered)
{
currentSegName = seg.Name;
strMessage.Append(seg.Name);
if (seg.FieldList.Count > 0)
strMessage.Append(Encoding.FieldDelimiter);
int startField = currentSegName == "MSH" ? 1 : 0;
for (int i = startField; i<seg.FieldList.Count; i++)
{
if (i > startField)
strMessage.Append(Encoding.FieldDelimiter);
var field = seg.FieldList[i];
if (field.IsDelimitersField)
{
strMessage.Append(field.UndecodedValue);
continue;
}
if (field.HasRepetitions)
{
for (int j = 0; j < field.RepetitionList.Count; j++)
{
if (j > 0)
strMessage.Append(Encoding.RepeatDelimiter);
serializeField(field.RepetitionList[j], strMessage);
}
}
else
{
serializeField(field, strMessage);
}
}
strMessage.Append(Encoding.SegmentDelimiter);
}
}
catch (Exception ex)
{
if (currentSegName == "MSH")
throw new HL7Exception("Failed to serialize the MSH segment with error - " + ex.Message, HL7Exception.SERIALIZATION_ERROR, ex);
else
throw;
}
return strMessage.ToString();
}
catch (Exception ex)
{
throw new HL7Exception("Failed to serialize the message with error - " + ex.Message, HL7Exception.SERIALIZATION_ERROR, ex);
}
}
/// <summary>
/// Get the Value of specific Field/Component/SubComponent, throws error if field/component index is not valid
/// </summary>
/// <param name="strValueFormat">Field/Component position in format SEGMENTNAME.FieldIndex.ComponentIndex.SubComponentIndex example PID.5.2</param>
/// <returns>Value of specified field/component/subcomponent</returns>
public string GetValue(string strValueFormat)
{
string segmentName = string.Empty;
int segmentOccurrence = 0;
int componentIndex = 0;
int subComponentIndex = 0;
string strValue = string.Empty;
var allComponents = strValueFormat.Split(_queryDelimiter);
int comCount = allComponents.Length;
bool isValid = validateValueFormat(allComponents);
if (isValid)
{
var matches = System.Text.RegularExpressions.Regex.Matches(allComponents[0], segmentRegex);
if (matches.Count < 1)
throw new HL7Exception("Request format is not valid: " + strValueFormat);
segmentName = matches[0].Groups[1].Value;
if (matches[0].Length > 3)
{
Int32.TryParse(matches[0].Groups[3].Value, out segmentOccurrence);
segmentOccurrence--;
}
if (SegmentList.ContainsKey(segmentName))
{
var segment = SegmentList[segmentName][segmentOccurrence];
if (comCount == 4)
{
Int32.TryParse(allComponents[2], out componentIndex);
Int32.TryParse(allComponents[3], out subComponentIndex);
try
{
var field = this.getField(segment, allComponents[1]);
strValue = field.ComponentList[componentIndex - 1].SubComponentList[subComponentIndex - 1].Value;
}
catch (Exception ex)
{
throw new HL7Exception("SubComponent not available - " + strValueFormat + " Error: " + ex.Message, ex);
}
}
else if (comCount == 3)
{
Int32.TryParse(allComponents[2], out componentIndex);
try
{
var field = this.getField(segment, allComponents[1]);
strValue = field.ComponentList[componentIndex - 1].Value;
}
catch (Exception ex)
{
throw new HL7Exception("Component not available - " + strValueFormat + " Error: " + ex.Message, ex);
}
}
else if (comCount == 2)
{
try
{
var field = this.getField(segment, allComponents[1]);
strValue = field.Value;
}
catch (Exception ex)
{
throw new HL7Exception("Field not available - " + strValueFormat + " Error: " + ex.Message, ex);
}
}
else
{
try
{
strValue = segment.Value;
}
catch (Exception ex)
{
throw new HL7Exception("Segment value not available - " + strValueFormat + " Error: " + ex.Message, ex);
}
}
}
else
{
throw new HL7Exception("Segment name not available: " + strValueFormat);
}
}
else
{
throw new HL7Exception("Request format is not valid: " + strValueFormat);
}
return this.Encoding.Decode(strValue);
}
/// <summary>
/// Sets the Value of specific Field/Component/SubComponent in matching Segments, throws error if field/component index is not valid
/// </summary>
/// <param name="strValueFormat">Field/Component position in format SEGMENTNAME.FieldIndex.ComponentIndex.SubComponentIndex example PID.5.2</param>
/// <param name="strValue">Value for the specified field/component</param>
/// <returns>boolean</returns>
public bool SetValue(string strValueFormat, string strValue)
{
bool isSet = false;
string segmentName = string.Empty;
int componentIndex = 0;
int subComponentIndex = 0;
var allComponents = strValueFormat.Split(_queryDelimiter);
int comCount = allComponents.Length;
bool isValid = validateValueFormat(allComponents);
if (isValid)
{
segmentName = allComponents[0];
if (SegmentList.ContainsKey(segmentName))
{
foreach (var segment in SegmentList[segmentName])
{
if (comCount == 4)
{
Int32.TryParse(allComponents[2], out componentIndex);
Int32.TryParse(allComponents[3], out subComponentIndex);
try
{
var field = this.getField(segment, allComponents[1]);
field.ComponentList[componentIndex - 1].SubComponentList[subComponentIndex - 1].Value = strValue;
isSet = true;
}
catch (Exception ex)
{
throw new HL7Exception("SubComponent not available - " + strValueFormat + " Error: " + ex.Message, ex);
}
}
else if (comCount == 3)
{
Int32.TryParse(allComponents[2], out componentIndex);
try
{
var field = this.getField(segment, allComponents[1]);
field.ComponentList[componentIndex - 1].Value = strValue;
isSet = true;
}
catch (Exception ex)
{
throw new HL7Exception("Component not available - " + strValueFormat + " Error: " + ex.Message, ex);
}
}
else if (comCount == 2)
{
try
{
var field = this.getField(segment, allComponents[1]);
field.Value = strValue;
isSet = true;
}
catch (Exception ex)
{
throw new HL7Exception("Field not available - " + strValueFormat + " Error: " + ex.Message, ex);
}
}
else
{
throw new HL7Exception("Cannot overwrite a segment value");
}
}
}
else
{
throw new HL7Exception("Segment name not available");
}
}
else
{
throw new HL7Exception("Request format is not valid");
}
return isSet;
}
/// <summary>
/// Checks if specified field has components
/// </summary>
/// <param name="strValueFormat">Field/Component position in format SEGMENTNAME.FieldIndex.ComponentIndex.SubComponentIndex example PID.5.2</param>
/// <returns>boolean</returns>
public bool IsComponentized(string strValueFormat)
{
bool isComponentized = false;
string segmentName = string.Empty;
var allComponents = strValueFormat.Split(_queryDelimiter);
int comCount = allComponents.Length;
bool isValid = validateValueFormat(allComponents);
if (isValid)
{
segmentName = allComponents[0];
if (comCount >= 2)
{
try
{
var segment = SegmentList[segmentName].First();
var field = this.getField(segment, allComponents[1]);
isComponentized = field.IsComponentized;
}
catch (Exception ex)
{
throw new HL7Exception("Field not available - " + strValueFormat + " Error: " + ex.Message, ex);
}
}
else
{
throw new HL7Exception("Field not identified in request");
}
}
else
{
throw new HL7Exception("Request format is not valid");
}
return isComponentized;
}
/// <summary>
/// Checks if specified fields has repetitions
/// </summary>
/// <param name="strValueFormat">Field/Component position in format SEGMENTNAME.FieldIndex.ComponentIndex.SubComponentIndex example PID.5.2</param>
/// <returns>boolean</returns>
public bool HasRepetitions(string strValueFormat)
{
var allComponents = strValueFormat.Split(_queryDelimiter);
int comCount = allComponents.Length;
bool isValid = validateValueFormat(allComponents);
if (isValid)
{
var segmentName = allComponents[0];
var segment = SegmentList[segmentName].First();
if (comCount >= 2)
{
try
{
var count = this.getFieldRepetitions(segment, allComponents[1]);
return count > 1;
}
catch (Exception ex)
{
throw new HL7Exception("Field not available - " + strValueFormat + " Error: " + ex.Message, ex);
}
}
else
{
throw new HL7Exception("Field not identified in request");
}
}
else
{
throw new HL7Exception("Request format is not valid");
}
}
/// <summary>
/// Checks if specified component has sub components
/// </summary>
/// <param name="strValueFormat">Field/Component position in format SEGMENTNAME.FieldIndex.ComponentIndex.SubComponentIndex example PID.5.2</param>
/// <returns>boolean</returns>
public bool IsSubComponentized(string strValueFormat)
{
bool isSubComponentized = false;
string segmentName = string.Empty;
int componentIndex = 0;
var allComponents = strValueFormat.Split(_queryDelimiter);
int comCount = allComponents.Length;
bool isValid = validateValueFormat(allComponents);
if (isValid)
{
segmentName = allComponents[0];
if (comCount >= 3)
{
try
{
var segment = SegmentList[segmentName].First();
var field = this.getField(segment, allComponents[1]);
Int32.TryParse(allComponents[2], out componentIndex);
isSubComponentized = field.ComponentList[componentIndex - 1].IsSubComponentized;
}
catch (Exception ex)
{
throw new HL7Exception("Component not available - " + strValueFormat + " Error: " + ex.Message, ex);
}
}
else
{
throw new HL7Exception("Component not identified in request");
}
}
else
{
throw new HL7Exception("Request format is not valid");
}
return isSubComponentized;
}
/// <summary>
/// Builds the acknowledgement message for this message
/// </summary>
/// <param name="bypassValidation">Bypasses validation of the resulting ACK message</param>
/// <returns>An ACK message if success, otherwise null</returns>
public Message GetACK(bool bypassValidation = false)
{
return this.createAckMessage("AA", false, null, bypassValidation);
}
/// <summary>
/// Builds a negative ack for this message
/// </summary>
/// <param name="code">ack code like AR, AE</param>
/// <param name="errMsg">Error message to be sent with NACK</param>
/// <param name="bypassValidation">Bypasses validation of the resulting NACK message</param>
/// <returns>A NACK message if success, otherwise null</returns>
public Message GetNACK(string code, string errMsg, bool bypassValidation = false)
{
return this.createAckMessage(code, true, errMsg, bypassValidation);
}
/// <summary>
/// Adds a segment to the message
/// </summary>
/// <param name="newSegment">Segment to be appended to the end of the message</param>
/// <returns>True if added successfully, otherwise false</returns>
public bool AddNewSegment(Segment newSegment)
{
try
{
newSegment.SequenceNo = SegmentCount++;
if (!SegmentList.ContainsKey(newSegment.Name))
SegmentList[newSegment.Name] = new List<Segment>();
SegmentList[newSegment.Name].Add(newSegment);
return true;
}
catch (Exception ex)
{
SegmentCount--;
throw new HL7Exception("Unable to add new segment. Error - " + ex.Message, ex);
}
}
/// <summary>
/// Removes a segment from the message
/// </summary>
/// <param name="segmentName">Segment to be removed</param>
/// <param name="index">Zero-based index of the segment to be removed, in case of multiple. Default is 0.</param>
/// <returns>True if found and removed successfully, otherwise false</returns>
public bool RemoveSegment(string segmentName, int index = 0)
{
try
{
if (!SegmentList.ContainsKey(segmentName))
return false;
var list = SegmentList[segmentName];
if (list.Count <= index)
return false;
list.RemoveAt(index);
SegmentCount--;
return true;
}
catch (Exception ex)
{
throw new HL7Exception("Unable to add remove segment. Error - " + ex.Message, ex);
}
}
public List<Segment> Segments()
{
return getAllSegmentsInOrder();
}
public List<Segment> Segments(string segmentName)
{
return getAllSegmentsInOrder().FindAll(o=> o.Name.Equals(segmentName));
}
public Segment DefaultSegment(string segmentName)
{
return getAllSegmentsInOrder().First(o => o.Name.Equals(segmentName));
}
/// <summary>
/// Addsthe header segment to a new message
/// </summary>
/// <param name="sendingApplication">Sending application name</param>
/// <param name="sendingFacility">Sending facility name</param>
/// <param name="receivingApplication">Receiving application name</param>
/// <param name="receivingFacility">Receiving facility name</param>
/// <param name="security">Security features. Can be null.</param>
/// <param name="messageType">Message type ^ trigger event</param>
/// <param name="messageControlID">Message control unique ID</param>
/// <param name="processingID">Processing ID ^ processing mode</param>
/// <param name="version">HL7 message version (2.x)</param>
public void AddSegmentMSH(string sendingApplication, string sendingFacility, string receivingApplication, string receivingFacility,
string security, string messageType, string messageControlID, string processingID, string version)
{
var dateString = MessageHelper.LongDateWithFractionOfSecond(DateTime.Now);
var delim = this.Encoding.FieldDelimiter;
string response = "MSH" + this.Encoding.AllDelimiters + delim +
sendingApplication + delim +
sendingFacility + delim +
receivingApplication + delim +
receivingFacility + delim +
this.Encoding.Encode(dateString) + delim +
(security ?? string.Empty) + delim +
messageType + delim +
messageControlID + delim +
processingID + delim +
version + this.Encoding.SegmentDelimiter;
var message = new Message(response);
message.ParseMessage();
this.AddNewSegment(message.DefaultSegment("MSH"));
}
/// <summary>
/// Serialize to MLLP escaped byte array
/// </summary>
/// <param name="validate">Optional. Validate the message before serializing</param>
/// <returns>MLLP escaped byte array</returns>
public byte[] GetMLLP(bool validate = false)
{
string hl7 = this.SerializeMessage(validate);
return MessageHelper.GetMLLP(hl7);
}
/// <summary>
/// Builds an ACK or NACK message for this message
/// </summary>
/// <param name="code">ack code like AA, AR, AE</param>
/// <param name="isNack">true for generating a NACK message, otherwise false</param>
/// <param name="errMsg">error message to be sent with NACK</param>
/// <param name="bypassValidation">Bypasses validation of the resulting ACK/NACK message</param>
/// <returns>An ACK or NACK message if success, otherwise null</returns>
private Message createAckMessage(string code, bool isNack, string errMsg, bool bypassValidation)
{
var response = new StringBuilder();
if (this.MessageStructure != "ACK")
{
var dateString = MessageHelper.LongDateWithFractionOfSecond(DateTime.Now);
var msh = this.SegmentList["MSH"].First();
var delim = this.Encoding.FieldDelimiter;
response.Append("MSH").Append(this.Encoding.AllDelimiters).Append(delim).Append(msh.FieldList[4].Value).Append(delim).Append(msh.FieldList[5].Value).Append(delim)
.Append(msh.FieldList[2].Value).Append(delim).Append(msh.FieldList[3].Value).Append(delim)
.Append(dateString).Append(delim).Append(delim).Append("ACK").Append(delim).Append(this.MessageControlID).Append(delim)
.Append(this.ProcessingID).Append(delim).Append(this.Version).Append(this.Encoding.SegmentDelimiter);
response.Append("MSA").Append(delim).Append(code).Append(delim).Append(this.MessageControlID).Append((isNack ? delim + errMsg : string.Empty)).Append(this.Encoding.SegmentDelimiter);
}
else
{
return null;
}
try
{
var message = new Message(response.ToString());
message.ParseMessage(bypassValidation);
return message;
}
catch
{
return null;
}
}
/// <summary>
/// Gets a field object within a segment by index
/// </summary>
/// <param name="segment">The segment object to search in/param>
/// <param name="index">The index of the field within the segment/param>
/// <returns>A Field object</returns>
private Field getField(Segment segment, string index)
{
int repetition = 0;
var matches = System.Text.RegularExpressions.Regex.Matches(index, fieldRegex);
if (matches.Count < 1)
throw new Exception("Invalid field index");
Int32.TryParse(matches[0].Groups[1].Value, out int fieldIndex);
fieldIndex--;
if (matches[0].Length > 3)
{
Int32.TryParse(matches[0].Groups[3].Value, out repetition);
repetition--;
}
var field = segment.FieldList[fieldIndex];
if (field.HasRepetitions)
return field.RepetitionList[repetition];
else if (repetition == 0)
return field;
else
return null;
}
/// <summary>
/// Determines if a segment field has repetitions
/// </summary>
/// <param name="segment">The segment object to search in/param>
/// <param name="index">The index of the field within the segment/param>
/// <returns>A boolean indicating whether the field has repetitions</returns>
private int getFieldRepetitions(Segment segment, string index)
{
var matches = System.Text.RegularExpressions.Regex.Matches(index, fieldRegex);
if (matches.Count < 1)
return 0;
Int32.TryParse(matches[0].Groups[1].Value, out int fieldIndex);
fieldIndex--;
var field = segment.FieldList[fieldIndex];
if (field.HasRepetitions)
return field.RepetitionList.Count;
else
return 1;
}
/// <summary>
/// Validates the HL7 message for basic syntax
/// </summary>
/// <returns>A boolean indicating whether the whole message is valid or not</returns>
private bool validateMessage()
{
try
{
if (!string.IsNullOrEmpty(HL7Message))
{
// Check message length - MSH+Delimeters+12Fields in MSH
if (HL7Message.Length < 20)
throw new HL7Exception("Message Length too short: " + HL7Message.Length + " chars.", HL7Exception.BAD_MESSAGE);
// Check if message starts with header segment
if (!HL7Message.StartsWith("MSH"))
throw new HL7Exception("MSH segment not found at the beginning of the message", HL7Exception.BAD_MESSAGE);
this.Encoding.EvaluateSegmentDelimiter(this.HL7Message);
this.allSegments = MessageHelper.SplitMessage(HL7Message);
this.HL7Message = string.Join(this.Encoding.SegmentDelimiter, allSegments) + this.Encoding.SegmentDelimiter;
// Check Segment Name & 4th character of each segment
char fourthCharMSH = HL7Message[3];
foreach (string strSegment in this.allSegments)
{
if (string.IsNullOrWhiteSpace(strSegment))
continue;
string segmentName = strSegment.Substring(0, 3);
bool isValidSegmentName = System.Text.RegularExpressions.Regex.IsMatch(segmentName, segmentRegex);
if (!isValidSegmentName)
throw new HL7Exception("Invalid segment name found: " + strSegment, HL7Exception.BAD_MESSAGE);
if (strSegment.Length > 3 && fourthCharMSH != strSegment[3])
throw new HL7Exception("Invalid segment found: " + strSegment, HL7Exception.BAD_MESSAGE);
}
string _fieldDelimiters_Message = this.allSegments[0].Substring(3, 8 - 3);
this.Encoding.EvaluateDelimiters(_fieldDelimiters_Message);
// Count field separators, MSH.12 is required so there should be at least 11 field separators in MSH
int countFieldSepInMSH = this.allSegments[0].Count(f => f == Encoding.FieldDelimiter);
if (countFieldSepInMSH < 11)
throw new HL7Exception("MSH segment doesn't contain all the required fields", HL7Exception.BAD_MESSAGE);
// Find Message Version
var MSHFields = this.allSegments[0].Split(Encoding.FieldDelimiter);
if (MSHFields.Length >= 12)
this.Version = this.Encoding.Decode(MSHFields[11]).Split(Encoding.ComponentDelimiter)[0];
else
throw new HL7Exception("HL7 version not found in the MSH segment", HL7Exception.REQUIRED_FIELD_MISSING);
// Find Message Type & Trigger Event
try
{
string MSH_9 = this.Encoding.Decode(MSHFields[8]);
if (!string.IsNullOrEmpty(MSH_9))
{
var MSH_9_comps = MSH_9.Split(this.Encoding.ComponentDelimiter);
if (MSH_9_comps.Length >= 3)
this.MessageStructure = MSH_9_comps[2];
else if (MSH_9_comps.Length > 0 && MSH_9_comps[0] != null && MSH_9_comps[0].Equals("ACK"))
this.MessageStructure = "ACK";
else if (MSH_9_comps.Length == 2)
this.MessageStructure = MSH_9_comps[0] + "_" + MSH_9_comps[1];
else
throw new HL7Exception("Message Type & Trigger Event value not found in message", HL7Exception.UNSUPPORTED_MESSAGE_TYPE);
}
else
{
throw new HL7Exception("MSH.9 not available", HL7Exception.UNSUPPORTED_MESSAGE_TYPE);
}
}
catch (System.IndexOutOfRangeException e)
{
throw new HL7Exception("Can't find message structure (MSH.9.3) - " + e.Message, HL7Exception.UNSUPPORTED_MESSAGE_TYPE, e);
}
try
{
this.MessageControlID = this.Encoding.Decode(MSHFields[9]);
if (string.IsNullOrEmpty(this.MessageControlID))
throw new HL7Exception("MSH.10 - Message Control ID not found", HL7Exception.REQUIRED_FIELD_MISSING);
}
catch (Exception ex)
{
throw new HL7Exception("Error occured while accessing MSH.10 - " + ex.Message, HL7Exception.REQUIRED_FIELD_MISSING, ex);
}
try
{
this.ProcessingID = this.Encoding.Decode(MSHFields[10]);
if (string.IsNullOrEmpty(this.ProcessingID))
throw new HL7Exception("MSH.11 - Processing ID not found", HL7Exception.REQUIRED_FIELD_MISSING);
}
catch (Exception ex)
{
throw new HL7Exception("Error occured while accessing MSH.11 - " + ex.Message, HL7Exception.REQUIRED_FIELD_MISSING, ex);
}
}
else
throw new HL7Exception("No Message Found", HL7Exception.BAD_MESSAGE);
}
catch (Exception ex)
{
throw new HL7Exception("Failed to validate the message with error - " + ex.Message, HL7Exception.BAD_MESSAGE, ex);
}
return true;
}
/// <summary>
/// Serializes a field into a string with proper encoding
/// </summary>
/// <returns>A serialized string</returns>
private void serializeField(Field field, StringBuilder strMessage)
{
if (field.ComponentList.Count > 0)
{
int indexCom = 0;
foreach (Component com in field.ComponentList)
{
indexCom++;
if (com.SubComponentList.Count > 0)
strMessage.Append(string.Join(Encoding.SubComponentDelimiter.ToString(), com.SubComponentList.Select(sc => Encoding.Encode(sc.Value))));
else
strMessage.Append(Encoding.Encode(com.Value));
if (indexCom < field.ComponentList.Count)
strMessage.Append(Encoding.ComponentDelimiter);
}
}
else
{
strMessage.Append(Encoding.Encode(field.Value));
}
}
/// <summary>
/// Get all segments in order as they appear in original message. This the usual order: IN1|1 IN2|1 IN1|2 IN2|2
/// </summary>
/// <returns>A list of segments in the proper order</returns>
private List<Segment> getAllSegmentsInOrder()
{
List<Segment> _list = new List<Segment>();
foreach (string segName in SegmentList.Keys)
{
foreach (Segment seg in SegmentList[segName])
{
_list.Add(seg);
}
}
return _list.OrderBy(o => o.SequenceNo).ToList();
}
/// <summary>
/// Validates the components of a value's position descriptor
/// </summary>
/// <returns>A boolean indicating whether all the components are valid or not</returns>
private bool validateValueFormat(string[] allComponents)
{
bool isValid = false;
if (allComponents.Length > 0)
{
if (Regex.IsMatch(allComponents[0], segmentRegex))
{
for (int i = 1; i < allComponents.Length; i++)
{
if (i == 1 && Regex.IsMatch(allComponents[i], fieldRegex))
isValid = true;
else if (i > 1 && Regex.IsMatch(allComponents[i], otherRegEx))
isValid = true;
else
return false;
}
}
else
{
isValid = false;
}
}
return isValid;
}
}
}