-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathDeathRecord_util.cs
1278 lines (1193 loc) · 60.2 KB
/
DeathRecord_util.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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// DeathRecord_util.cs
// Contains utility methods used across the DeathRecords class.
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using Hl7.Fhir.ElementModel;
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using Hl7.FhirPath;
using Newtonsoft.Json;
using Hl7.Fhir.Utility;
namespace VRDR
{
/// <summary>Class <c>DeathRecord</c> models a FHIR Vital Records Death Reporting (VRDR) Death
/// Record. This class was designed to help consume and produce death records that follow the
/// HL7 FHIR Vital Records Death Reporting Implementation Guide, as described at:
/// http://hl7.org/fhir/us/vrdr and https://github.com/hl7/vrdr.
/// </summary>
public partial class DeathRecord
{
/// <summary>Getter helper for anything that uses PartialDateTime, allowing a particular date field (year, month, or day) to be read
/// from the extension. Returns either a numeric date part, or -1 meaning explicitly unknown, or null meaning not specified.</summary>
private int? GetPartialDate(Extension partialDateTime, string partURL)
{
Extension part = partialDateTime?.Extension?.Find(ext => ext.Url == partURL);
Extension dataAbsent = part?.Extension?.Find(ext => ext.Url == OtherExtensionURL.DataAbsentReason);
// extension for absent date can be directly on the part as with year, month, day
if (dataAbsent != null)
{
// The data absent reason is either a placeholder that a field hasen't been set yet (data absent reason of 'temp-unknown') or
// a claim that there's no data (any other data absent reason, e.g., 'unknown'); return null for the former and "-1" for the latter
string code = ((Code)dataAbsent.Value).Value;
if (code == "temp-unknown")
{
return null;
}
else
{
return -1;
}
}
// check if the part (e.g. "_valueUnsignedInt") has a data absent reason extension on the value
Extension dataAbsentOnValue = part?.Value?.Extension?.Find(ext => ext.Url == OtherExtensionURL.DataAbsentReason);
if (dataAbsentOnValue != null)
{
string code = ((Code)dataAbsentOnValue.Value).Value;
if (code == "temp-unknown")
{
return null;
}
else
{
return -1;
}
}
// If we have a value, return it
if (part?.Value != null)
{
return (int?)((UnsignedInt)part.Value).Value; // Untangle a FHIR UnsignedInt in an extension into an int
}
// No data present at all, return null
return null;
}
/// <summary>NewBlankPartialDateTimeExtension, Build a blank PartialDateTime extension (which means all the placeholder data absent
/// reasons are present to note that the data is not in fact present). This method takes an optional flag to determine if this extension
/// should include the time field, which is not always needed</summary>
private Extension NewBlankPartialDateTimeExtension(bool includeTime = true)
{
Extension partialDateTime = new Extension(includeTime ? ExtensionURL.PartialDateTime : ExtensionURL.PartialDate, null);
Extension year = new Extension(ExtensionURL.DateYear, null);
year.Extension.Add(new Extension(OtherExtensionURL.DataAbsentReason, new Code("temp-unknown")));
partialDateTime.Extension.Add(year);
Extension month = new Extension(ExtensionURL.DateMonth, null);
month.Extension.Add(new Extension(OtherExtensionURL.DataAbsentReason, new Code("temp-unknown")));
partialDateTime.Extension.Add(month);
Extension day = new Extension(ExtensionURL.DateDay, null);
day.Extension.Add(new Extension(OtherExtensionURL.DataAbsentReason, new Code("temp-unknown")));
partialDateTime.Extension.Add(day);
if (includeTime)
{
Extension time = new Extension(ExtensionURL.DateTime, null);
time.Extension.Add(new Extension(OtherExtensionURL.DataAbsentReason, new Code("temp-unknown")));
partialDateTime.Extension.Add(time);
}
return partialDateTime;
}
/// <summary>Setter helper for anything that uses PartialDateTime, allowing a particular date field (year, month, or day) to be
/// set in the extension. Arguments are the extension to poplulate, the part of the URL to populate, and the value to specify.
/// The value can be a positive number for an actual value, a -1 meaning that the value is explicitly unknown, or null meaning
/// the data has not been specified.</summary>
private void SetPartialDate(Extension partialDateTime, string partURL, int? value)
{
Extension part = partialDateTime.Extension.Find(ext => ext.Url == partURL);
part.Extension.RemoveAll(ext => ext.Url == OtherExtensionURL.DataAbsentReason);
if (value != null && value != -1)
{
part.Value = new UnsignedInt((int)value);
}
else
{
part.Value = new UnsignedInt();
// Determine which data absent reason to use based on whether the value is unknown or -1
part.Value.Extension.Add(new Extension(OtherExtensionURL.DataAbsentReason, new Code(value == -1 ? "unknown" : "temp-unknown")));
}
}
/// <summary>Getter helper for anything that uses PartialDateTime, allowing the time to be read from the extension</summary>
private string GetPartialTime(Extension partialDateTime)
{
Extension part = partialDateTime?.Extension?.Find(ext => ext.Url == ExtensionURL.DateTime);
Extension dataAbsent = part?.Extension?.Find(ext => ext.Url == OtherExtensionURL.DataAbsentReason);
// extension for absent date can be directly on the part as with year, month, day
if (dataAbsent != null)
{
// The data absent reason is either a placeholder that a field hasen't been set yet (data absent reason of 'temp-unknown') or
// a claim that there's no data (any other data absent reason, e.g., 'unknown'); return null for the former and "-1" for the latter
string code = ((Code)dataAbsent.Value).Value;
if (code == "temp-unknown")
{
return null;
}
else
{
return "-1";
}
}
// check if the part (e.g. "_valueTime") has a data absent reason extension on the value
Extension dataAbsentOnValue = part?.Value?.Extension?.Find(ext => ext.Url == OtherExtensionURL.DataAbsentReason);
if (dataAbsentOnValue != null)
{
string code = ((Code)dataAbsentOnValue.Value).Value;
if (code == "temp-unknown")
{
return null;
}
else
{
return "-1";
}
}
// If we have a value, return it
if (part?.Value != null)
{
return part.Value.ToString();
}
// No data present at all, return null
return null;
}
/// <summary>Setter helper for anything that uses PartialDateTime, allowing the time to be set in the extension</summary>
private void SetPartialTime(Extension partialDateTime, String value)
{
Extension part = partialDateTime.Extension.Find(ext => ext.Url == ExtensionURL.DateTime);
part.Extension.RemoveAll(ext => ext.Url == OtherExtensionURL.DataAbsentReason);
if (value != null && value != "-1")
{
// we need to force it to be 00:00:00 format to be compliant with the IG because the FHIR class doesn't
if (value.Length < 8)
{
value += ":";
value = value.PadRight(8, '0');
}
part.Value = new Time(value);
}
else
{
part.Value = new Time();
// Determine which data absent reason to use based on whether the value is unknown or -1
part.Value.Extension.Add(new Extension(OtherExtensionURL.DataAbsentReason, new Code(value == "-1" ? "unknown" : "temp-unknown")));
}
}
/// <summary>Getter helper for anything that can have a regular FHIR date/time
/// field (year, month, or day) to be read the value
/// supports dates and date times but does NOT support extensions</summary>
private int? GetDateFragment(Element value, string partURL)
{
if (value == null)
{
return null;
}
// If we have a basic value as a valueDateTime use that, otherwise pull from the PartialDateTime extension
DateTimeOffset? dateTimeOffset = null;
if (value is FhirDateTime && ((FhirDateTime)value).Value != null)
{
// Note: We can't just call ToDateTimeOffset() on the FhirDateTime because want the datetime in whatever local time zone was provided
dateTimeOffset = DateTimeOffset.Parse(((FhirDateTime)value).Value);
}
else if (value is Date && ((Date)value).Value != null)
{
// Note: We can't just call ToDateTimeOffset() on the Date because want the date in whatever local time zone was provided
dateTimeOffset = DateTimeOffset.Parse(((Date)value).Value);
}
if (dateTimeOffset != null)
{
switch (partURL)
{
case ExtensionURL.DateYear:
return ((DateTimeOffset)dateTimeOffset).Year;
case ExtensionURL.DateMonth:
return ((DateTimeOffset)dateTimeOffset).Month;
case ExtensionURL.DateDay:
return ((DateTimeOffset)dateTimeOffset).Day;
default:
throw new ArgumentException("GetDateFragment called with unsupported PartialDateTime segment");
}
}
return null;
}
/// <summary>Getter helper for anything that can have a regular FHIR date/time or a PartialDateTime extension, allowing a particular date
/// field (year, month, or day) to be read from either the value or the extension</summary>
private int? GetDateFragmentOrPartialDate(Element value, string partURL)
{
if (value == null)
{
return null;
}
var dateFragment = GetDateFragment(value, partURL);
if (dateFragment != null)
{
return dateFragment;
}
// Look for either PartialDate or PartialDateTime
Extension extension = value.Extension.Find(ext => ext.Url == ExtensionURL.PartialDateTime);
if (extension == null)
{
extension = value.Extension.Find(ext => ext.Url == ExtensionURL.PartialDate);
}
return GetPartialDate(extension, partURL);
}
private FhirDateTime ConvertFhirTimeToFhirDateTime(Time value)
{
return new FhirDateTime(DateTimeOffset.MinValue.Year, DateTimeOffset.MinValue.Month, DateTimeOffset.MinValue.Day,
FhirTimeHour(value), FhirTimeMin(value), FhirTimeSec(value), TimeSpan.Zero);
}
private int FhirTimeHour(Time value)
{
return int.Parse(value.ToString().Substring(0, 2));
}
private int FhirTimeMin(Time value)
{
return int.Parse(value.ToString().Substring(3, 2));
}
private int FhirTimeSec(Time value)
{
return int.Parse(value.ToString().Substring(6, 2));
}
/// <summary>Getter helper for anything that can have a regular FHIR date/time, allowing the time to be read from the value</summary>
private string GetTimeFragment(Element value)
{
if (value is FhirDateTime && ((FhirDateTime)value).Value != null)
{
// Using FhirDateTime's ToDateTimeOffset doesn't keep the time in the original time zone, so we parse the string representation, first using the appropriate segment of
// the Regex defined at http://hl7.org/fhir/R4/datatypes.html#dateTime to pull out everything except the time zone
string dateRegex = "([0-9]([0-9]([0-9][1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2][0-9]|3[0-1])(T([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)?)?)?)?";
Match dateStringMatch = Regex.Match(((FhirDateTime)value).ToString(), dateRegex);
DateTime dateTime;
if (dateStringMatch != null && DateTime.TryParse(dateStringMatch.ToString(), out dateTime))
{
TimeSpan timeSpan = new TimeSpan(0, dateTime.Hour, dateTime.Minute, dateTime.Second);
return timeSpan.ToString(@"hh\:mm\:ss");
}
}
return null;
}
/// <summary>Getter helper for anything that can have a regular FHIR date/time or a PartialDateTime extension, allowing the time to be read
/// from either the value or the extension</summary>
private string GetTimeFragmentOrPartialTime(Element value)
{
// If we have a basic value as a valueDateTime use that, otherwise pull from the PartialDateTime extension
string time = GetTimeFragment(value);
if (time != null)
{
return time;
}
return GetPartialTime(value.Extension.Find(ext => ext.Url == ExtensionURL.PartialDateTime));
}
/// <summary>Helper function to set a codeable value based on a code and the set of allowed codes.</summary>
// <param name="field">the field name to set.</param>
// <param name="code">the code to set the field to.</param>
// <param name="options">the list of valid options and related display strings and code systems</param>
private void SetCodeValue(string field, string code, string[,] options)
{
// If string is empty don't bother to set the value
if (code == null || code == "")
{
return;
}
// Iterate over the allowed options and see if the code supplies is one of them
for (int i = 0; i < options.GetLength(0); i += 1)
{
if (options[i, 0] == code)
{
// Found it, so call the supplied setter with the appropriate dictionary built based on the code
// using the supplied options and return
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("code", code);
dict.Add("display", options[i, 1]);
dict.Add("system", options[i, 2]);
typeof(DeathRecord).GetProperty(field).SetValue(this, dict);
return;
}
}
// If we got here we didn't find the code, so it's not a valid option
throw new System.ArgumentException($"Code '{code}' is not an allowed value for field {field}");
}
/// <summary>Convert a "code" dictionary to a FHIR Coding.</summary>
/// <param name="dict">represents a code.</param>
/// <returns>the corresponding Coding representation of the code.</returns>
private Coding DictToCoding(Dictionary<string, string> dict)
{
Coding coding = new Coding();
if (dict != null)
{
if (dict.ContainsKey("code") && !String.IsNullOrEmpty(dict["code"]))
{
coding.Code = dict["code"];
}
if (dict.ContainsKey("system") && !String.IsNullOrEmpty(dict["system"]))
{
coding.System = dict["system"];
}
if (dict.ContainsKey("display") && !String.IsNullOrEmpty(dict["display"]))
{
coding.Display = dict["display"];
}
return coding;
}
return null;
}
/// <summary>Convert a "code" dictionary to a FHIR CodableConcept.</summary>
/// <param name="dict">represents a code.</param>
/// <returns>the corresponding CodeableConcept representation of the code.</returns>
private CodeableConcept DictToCodeableConcept(Dictionary<string, string> dict)
{
CodeableConcept codeableConcept = new CodeableConcept();
Coding coding = DictToCoding(dict);
codeableConcept.Coding.Add(coding);
if (dict != null && dict.ContainsKey("text") && !String.IsNullOrEmpty(dict["text"]))
{
codeableConcept.Text = dict["text"];
}
return codeableConcept;
}
/// <summary>Check if a dictionary is empty or a default empty dictionary (all values are null or empty strings)</summary>
/// <param name="dict">represents a code.</param>
/// <returns>A boolean identifying whether the provided dictionary is empty or default.</returns>
private bool IsDictEmptyOrDefault(Dictionary<string, string> dict)
{
return dict.Count == 0 || dict.Values.All(v => v == null || v == "");
}
/// <summary>Convert a FHIR Coding to a "code" Dictionary</summary>
/// <param name="coding">a FHIR Coding.</param>
/// <returns>the corresponding Dictionary representation of the code.</returns>
private Dictionary<string, string> CodingToDict(Coding coding)
{
Dictionary<string, string> dictionary = EmptyCodeDict();
if (coding != null)
{
if (!String.IsNullOrEmpty(coding.Code))
{
dictionary["code"] = coding.Code;
}
if (!String.IsNullOrEmpty(coding.System))
{
dictionary["system"] = coding.System;
}
if (!String.IsNullOrEmpty(coding.Display))
{
dictionary["display"] = coding.Display;
}
}
return dictionary;
}
/// <summary>Convert a FHIR CodableConcept to a "code" Dictionary</summary>
/// <param name="codeableConcept">a FHIR CodeableConcept.</param>
/// <returns>the corresponding Dictionary representation of the code.</returns>
private Dictionary<string, string> CodeableConceptToDict(CodeableConcept codeableConcept)
{
if (codeableConcept != null && codeableConcept.Coding != null)
{
Coding coding = codeableConcept.Coding.FirstOrDefault();
var codeDict = CodingToDict(coding);
if (codeableConcept != null && !String.IsNullOrEmpty(codeableConcept.Text))
{
codeDict["text"] = codeableConcept.Text;
}
return codeDict;
}
else
{
return EmptyCodeableDict();
}
}
/// <summary>Convert an "address" dictionary to a FHIR Address.</summary>
/// <param name="dict">represents an address.</param>
/// <returns>the corresponding FHIR Address representation of the address.</returns>
private Address DictToAddress(Dictionary<string, string> dict)
{
Address address = new Address();
if (dict != null)
{
List<string> lines = new List<string>();
if (dict.ContainsKey("addressLine1") && !String.IsNullOrEmpty(dict["addressLine1"]))
{
lines.Add(dict["addressLine1"]);
}
if (dict.ContainsKey("addressLine2") && !String.IsNullOrEmpty(dict["addressLine2"]))
{
lines.Add(dict["addressLine2"]);
}
if (lines.Count() > 0)
{
address.Line = lines.ToArray();
}
if (dict.ContainsKey("addressCityC") && !String.IsNullOrEmpty(dict["addressCityC"]))
{
Extension cityCode = new Extension();
cityCode.Url = ExtensionURL.CityCode;
cityCode.Value = new PositiveInt(Int32.Parse(dict["addressCityC"]));
address.CityElement = new FhirString();
address.CityElement.Extension.Add(cityCode);
}
if (dict.ContainsKey("addressCity") && !String.IsNullOrEmpty(dict["addressCity"]))
{
if (address.CityElement != null)
{
address.CityElement.Value = dict["addressCity"];
}
else
{
address.City = dict["addressCity"];
}
}
if (dict.ContainsKey("addressCountyC") && !String.IsNullOrEmpty(dict["addressCountyC"]))
{
Extension countyCode = new Extension();
countyCode.Url = ExtensionURL.DistrictCode;
countyCode.Value = new PositiveInt(Int32.Parse(dict["addressCountyC"]));
address.DistrictElement = new FhirString();
address.DistrictElement.Extension.Add(countyCode);
}
if (dict.ContainsKey("addressCounty") && !String.IsNullOrEmpty(dict["addressCounty"]))
{
if (address.DistrictElement != null)
{
address.DistrictElement.Value = dict["addressCounty"];
}
else
{
address.District = dict["addressCounty"];
}
}
if (dict.ContainsKey("addressState") && !String.IsNullOrEmpty(dict["addressState"]))
{
address.State = dict["addressState"];
}
// Special address field to support the jurisdiction extension custom to VRDR to support YC (New York City)
// as used in the DeathLocationLoc
if (dict.ContainsKey("addressJurisdiction") && !String.IsNullOrEmpty(dict["addressJurisdiction"]))
{
if (address.StateElement == null)
{
address.StateElement = new FhirString();
}
address.StateElement.Extension.RemoveAll(ext => ext.Url == ExtensionURL.LocationJurisdictionId);
Extension extension = new Extension(ExtensionURL.LocationJurisdictionId, new FhirString(dict["addressJurisdiction"]));
address.StateElement.Extension.Add(extension);
}
if (dict.ContainsKey("addressZip") && !String.IsNullOrEmpty(dict["addressZip"]))
{
address.PostalCode = dict["addressZip"];
}
if (dict.ContainsKey("addressCountry") && !String.IsNullOrEmpty(dict["addressCountry"]))
{
address.Country = dict["addressCountry"];
}
if (dict.ContainsKey("addressStnum") && !String.IsNullOrEmpty(dict["addressStnum"]))
{
Extension stnum = new Extension();
stnum.Url = ExtensionURL.StreetNumber;
stnum.Value = new FhirString(dict["addressStnum"]);
address.Extension.Add(stnum);
}
if (dict.ContainsKey("addressPredir") && !String.IsNullOrEmpty(dict["addressPredir"]))
{
Extension predir = new Extension();
predir.Url = ExtensionURL.PreDirectional;
predir.Value = new FhirString(dict["addressPredir"]);
address.Extension.Add(predir);
}
if (dict.ContainsKey("addressStname") && !String.IsNullOrEmpty(dict["addressStname"]))
{
Extension stname = new Extension();
stname.Url = ExtensionURL.StreetName;
stname.Value = new FhirString(dict["addressStname"]);
address.Extension.Add(stname);
}
if (dict.ContainsKey("addressStdesig") && !String.IsNullOrEmpty(dict["addressStdesig"]))
{
Extension stdesig = new Extension();
stdesig.Url = ExtensionURL.StreetDesignator;
stdesig.Value = new FhirString(dict["addressStdesig"]);
address.Extension.Add(stdesig);
}
if (dict.ContainsKey("addressPostdir") && !String.IsNullOrEmpty(dict["addressPostdir"]))
{
Extension postdir = new Extension();
postdir.Url = ExtensionURL.PostDirectional;
postdir.Value = new FhirString(dict["addressPostdir"]);
address.Extension.Add(postdir);
}
if (dict.ContainsKey("addressUnitnum") && !String.IsNullOrEmpty(dict["addressUnitnum"]))
{
Extension unitnum = new Extension();
unitnum.Url = ExtensionURL.UnitOrAptNumber;
unitnum.Value = new FhirString(dict["addressUnitnum"]);
address.Extension.Add(unitnum);
}
}
return address;
}
/// <summary>Convert a Date Part Extension to an Array.</summary>
/// <param name="datePartAbsent">a Date Part Extension.</param>
/// <returns>the corresponding array representation of the date parts.</returns>
private Tuple<string, string>[] DatePartsToArray(Extension datePartAbsent)
{
List<Tuple<string, string>> dateParts = new List<Tuple<string, string>>();
if (datePartAbsent != null)
{
Extension yearAbsentPart = datePartAbsent.Extension.Where(ext => ext.Url == "year-absent-reason").FirstOrDefault();
Extension monthAbsentPart = datePartAbsent.Extension.Where(ext => ext.Url == "month-absent-reason").FirstOrDefault();
Extension dayAbsentPart = datePartAbsent.Extension.Where(ext => ext.Url == "day-absent-reason").FirstOrDefault();
Extension yearPart = datePartAbsent.Extension.Where(ext => ext.Url == "date-year").FirstOrDefault();
Extension monthPart = datePartAbsent.Extension.Where(ext => ext.Url == "date-month").FirstOrDefault();
Extension dayPart = datePartAbsent.Extension.Where(ext => ext.Url == "date-day").FirstOrDefault();
// Year part
if (yearAbsentPart != null)
{
if (yearAbsentPart.Value == null) throw new ArgumentException("Found an Extension resource (year-absent-reason) that does not contain a value. All extensions must include a value element.");
dateParts.Add(Tuple.Create("year-absent-reason", yearAbsentPart.Value.ToString()));
}
if (yearPart != null)
{
if (yearPart.Value == null) throw new ArgumentException("Found an Extension resource (date-year) that does not contain a value. All extensions must include a value element.");
dateParts.Add(Tuple.Create("date-year", yearPart.Value.ToString()));
}
// Month part
if (monthAbsentPart != null)
{
if (monthAbsentPart.Value == null) throw new ArgumentException("Found an Extension resource (month-absent-reason) that does not contain a value. All extensions must include a value element.");
dateParts.Add(Tuple.Create("month-absent-reason", monthAbsentPart.Value.ToString()));
}
if (monthPart != null)
{
if (monthPart.Value == null) throw new ArgumentException("Found an Extension resource (date-month) that does not contain a value. All extensions must include a value element.");
dateParts.Add(Tuple.Create("date-month", monthPart.Value.ToString()));
}
// Day Part
if (dayAbsentPart != null)
{
if (dayAbsentPart.Value == null) throw new ArgumentException("Found an Extension resource (day-absent-reason) that does not contain a value. All extensions must include a value element.");
dateParts.Add(Tuple.Create("day-absent-reason", dayAbsentPart.Value.ToString()));
}
if (dayPart != null)
{
if (dayPart.Value == null) throw new ArgumentException("Found an Extension resource (date-day) that does not contain a value. All extensions must include a value element.");
dateParts.Add(Tuple.Create("date-day", dayPart.Value.ToString()));
}
}
return dateParts.ToArray();
}
/// <summary>Convert an element to an integer or code depending on if the input element is a date part.</summary>
/// <param name="pair">A key value pair, the key will be used to identify whether the element is a date part.</param>
private Element DatePartToIntegerOrCode(Tuple<string, string> pair)
{
if (pair.Item1 == "date-year" || pair.Item1 == "date-month" || pair.Item1 == "date-day")
{
return new Integer(Int32.Parse(pair.Item2));
}
else
{
return new Code(pair.Item2);
}
}
/// <summary>Convert a FHIR Address to an "address" Dictionary.</summary>
/// <param name="addr">a FHIR Address.</param>
/// <returns>the corresponding Dictionary representation of the FHIR Address.</returns>
private Dictionary<string, string> AddressToDict(Address addr)
{
Dictionary<string, string> dictionary = EmptyAddrDict();
if (addr != null)
{
if (addr.Line != null && addr.Line.Count() > 0)
{
dictionary["addressLine1"] = addr.Line.First();
}
if (addr.Line != null && addr.Line.Count() > 1)
{
dictionary["addressLine2"] = addr.Line.Last();
}
if (addr.CityElement != null)
{
Extension cityCode = addr.CityElement.Extension.Where(ext => ext.Url == ExtensionURL.CityCode).FirstOrDefault();
if (cityCode != null && cityCode.Value != null)
{
dictionary["addressCityC"] = cityCode.Value.ToString();
}
}
if (addr.DistrictElement != null)
{
Extension districtCode = addr.DistrictElement.Extension.Where(ext => ext.Url == ExtensionURL.DistrictCode).FirstOrDefault();
if (districtCode != null && districtCode.Value != null)
{
dictionary["addressCountyC"] = districtCode.Value.ToString();
}
}
Extension stnum = addr.Extension.Where(ext => ext.Url == ExtensionURL.StreetNumber).FirstOrDefault();
if (stnum != null && stnum.Value != null)
{
dictionary["addressStnum"] = stnum.Value.ToString();
}
Extension predir = addr.Extension.Where(ext => ext.Url == ExtensionURL.PreDirectional).FirstOrDefault();
if (predir != null && predir.Value != null)
{
dictionary["addressPredir"] = predir.Value.ToString();
}
Extension stname = addr.Extension.Where(ext => ext.Url == ExtensionURL.StreetName).FirstOrDefault();
if (stname != null && stname.Value != null)
{
dictionary["addressStname"] = stname.Value.ToString();
}
Extension stdesig = addr.Extension.Where(ext => ext.Url == ExtensionURL.StreetDesignator).FirstOrDefault();
if (stdesig != null && stdesig.Value != null)
{
dictionary["addressStdesig"] = stdesig.Value.ToString();
}
Extension postdir = addr.Extension.Where(ext => ext.Url == ExtensionURL.PostDirectional).FirstOrDefault();
if (postdir != null && postdir.Value != null)
{
dictionary["addressPostdir"] = postdir.Value.ToString();
}
Extension unitnum = addr.Extension.Where(ext => ext.Url == ExtensionURL.UnitOrAptNumber).FirstOrDefault();
if (unitnum != null && unitnum.Value != null)
{
dictionary["addressUnitnum"] = unitnum.Value.ToString();
}
if (addr.State != null)
{
dictionary["addressState"] = addr.State;
}
if (addr.StateElement != null)
{
dictionary["addressJurisdiction"] = addr.State; // by default. If extension present, override
Extension stateExt = addr.StateElement.Extension.Where(ext => ext.Url == ExtensionURL.LocationJurisdictionId).FirstOrDefault();
if (stateExt != null && stateExt.Value != null)
{
dictionary["addressJurisdiction"] = stateExt.Value.ToString();
}
}
if (addr.City != null)
{
dictionary["addressCity"] = addr.City;
}
if (addr.District != null)
{
dictionary["addressCounty"] = addr.District;
}
if (addr.PostalCode != null)
{
dictionary["addressZip"] = addr.PostalCode;
}
if (addr.Country != null)
{
dictionary["addressCountry"] = addr.Country;
}
}
return dictionary;
}
/// <summary>Returns an empty "address" Dictionary.</summary>
/// <returns>an empty "address" Dictionary.</returns>
private Dictionary<string, string> EmptyAddrDict()
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("addressLine1", "");
dictionary.Add("addressLine2", "");
dictionary.Add("addressCity", "");
dictionary.Add("addressCityC", "");
dictionary.Add("addressCounty", "");
dictionary.Add("addressCountyC", "");
dictionary.Add("addressState", "");
dictionary.Add("addressJurisdiction", "");
dictionary.Add("addressZip", "");
dictionary.Add("addressCountry", "");
dictionary.Add("addressStnum", "");
dictionary.Add("addressPredir", "");
dictionary.Add("addressStname", "");
dictionary.Add("addressStdesig", "");
dictionary.Add("addressPostdir", "");
dictionary.Add("addressUnitnum", "");
return dictionary;
}
/// <summary>Returns an empty "code" Dictionary.</summary>
/// <returns>an empty "code" Dictionary.</returns>
private Dictionary<string, string> EmptyCodeDict()
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("code", "");
dictionary.Add("system", "");
dictionary.Add("display", "");
return dictionary;
}
/// <summary>Returns an empty "codeable" Dictionary.</summary>
/// <returns>an empty "codeable" Dictionary.</returns>
private Dictionary<string, string> EmptyCodeableDict()
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("code", "");
dictionary.Add("system", "");
dictionary.Add("display", "");
dictionary.Add("text", "");
return dictionary;
}
/// <summary>Given a FHIR path, return the elements that match the given path;
/// returns an empty array if no matches are found.</summary>
/// <param name="path">represents a FHIR path.</param>
/// <returns>all elements that match the given path, or an empty array if no matches are found.</returns>
public object[] GetAll(string path)
{
var matches = Navigator.Select(path);
ArrayList list = new ArrayList();
foreach (var match in matches)
{
list.Add(match.Value);
}
return list.ToArray();
}
/// <summary>Given a FHIR path, return the first element that matches the given path.</summary>
/// <param name="path">represents a FHIR path.</param>
/// <returns>the first element that matches the given path, or null if no match is found.</returns>
public object GetFirst(string path)
{
var matches = Navigator.Select(path);
if (matches.Count() > 0)
{
return matches.First().Value;
}
else
{
return null; // Nothing found
}
}
/// <summary>Given a FHIR path, return the last element that matches the given path.</summary>
/// <param name="path">represents a FHIR path.</param>
/// <returns>the last element that matches the given path, or null if no match is found.</returns>
public object GetLast(string path)
{
var matches = Navigator.Select(path);
if (matches.Count() > 0)
{
return matches.Last().Value;
}
else
{
return null; // Nothing found
}
}
/// <summary>Given a FHIR path, return the elements that match the given path as a string;
/// returns an empty array if no matches are found.</summary>
/// <param name="path">represents a FHIR path.</param>
/// <returns>all elements that match the given path as a string, or an empty array if no matches are found.</returns>
private string[] GetAllString(string path)
{
ArrayList list = new ArrayList();
foreach (var match in GetAll(path))
{
list.Add(Convert.ToString(match));
}
return list.ToArray(typeof(string)) as string[];
}
/// <summary>Given a FHIR path, return the first element that matches the given path as a string;
/// returns null if no match is found.</summary>
/// <param name="path">represents a FHIR path.</param>
/// <returns>the first element that matches the given path as a string, or null if no match is found.</returns>
private string GetFirstString(string path)
{
var first = GetFirst(path);
if (first != null)
{
return Convert.ToString(first);
}
else
{
return null; // Nothing found
}
}
/// <summary>Given a FHIR path, return the last element that matches the given path as a string;
/// returns an empty string if no match is found.</summary>
/// <param name="path">represents a FHIR path.</param>
/// <returns>the last element that matches the given path as a string, or null if no match is found.</returns>
private string GetLastString(string path)
{
var last = GetLast(path);
if (last != null)
{
return Convert.ToString(last);
}
else
{
return null; // Nothing found
}
}
/// <summary>Get a value from a Dictionary, but return null if the key doesn't exist or the value is an empty string.</summary>
private static string GetValue(Dictionary<string, string> dict, string key)
{
if (dict != null && dict.ContainsKey(key) && !String.IsNullOrWhiteSpace(dict[key]))
{
return dict[key];
}
return null;
}
// /// <summary>Check to make sure the given profile contains the given resource.</summary>
// private static bool MatchesProfile(string resource, string profile)
// {
// if (!String.IsNullOrWhiteSpace(profile) && profile.Contains(resource))
// {
// return true;
// }
// return false;
// }
/// <summary>Combine the given dictionaries and return the combined result.</summary>
private static Dictionary<string, string> UpdateDictionary(Dictionary<string, string> a, Dictionary<string, string> b)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> entry in a)
{
dictionary[entry.Key] = entry.Value;
}
foreach (KeyValuePair<string, string> entry in b)
{
dictionary[entry.Key] = entry.Value;
}
return dictionary;
}
/// <summary>Returns a JSON encoded structure that maps to the various property
/// annotations found in the DeathRecord class. This is useful for scenarios
/// where you may want to display the data in user interfaces.</summary>
/// <returns>a string representation of this Death Record in a descriptive format.</returns>
public string ToDescription()
{
Dictionary<string, Dictionary<string, dynamic>> description = new Dictionary<string, Dictionary<string, dynamic>>();
// the priority values should order the categories as: Decedent Demographics, Decedent Disposition, Death Investigation, Death Certification
foreach (PropertyInfo property in typeof(DeathRecord).GetProperties().OrderBy(p => p.GetCustomAttribute<Property>().Priority))
{
// Grab property annotation for this property
Property info = property.GetCustomAttribute<Property>();
// Skip properties that shouldn't be serialized.
if (!info.Serialize)
{
continue;
}
// Add category if it doesn't yet exist
if (!description.ContainsKey(info.Category))
{
description.Add(info.Category, new Dictionary<string, dynamic>());
}
// Add the new property to the category
Dictionary<string, dynamic> category = description[info.Category];
category[property.Name] = new Dictionary<string, dynamic>();
// Add the attributes of the property
category[property.Name]["Name"] = info.Name;
category[property.Name]["Type"] = info.Type.ToString();
category[property.Name]["Description"] = info.Description;
category[property.Name]["IGUrl"] = info.IGUrl;
category[property.Name]["CapturedInIJE"] = info.CapturedInIJE;
// Add snippets
FHIRPath path = property.GetCustomAttribute<FHIRPath>();
var matches = Navigator.Select(path.Path);
if (matches.Count() > 0)
{
if (info.Type == Property.Types.TupleCOD || info.Type == Property.Types.TupleArr || info.Type == Property.Types.Tuple4Arr)
{
// Make sure to grab all of the Conditions for COD
string xml = "";
string json = "";
foreach (var match in matches)
{
xml += match.ToXml();
json += match.ToJson() + ",";
}
category[property.Name]["SnippetXML"] = xml;
category[property.Name]["SnippetJSON"] = "[" + json + "]";
}
else if (!String.IsNullOrWhiteSpace(path.Element))
{
// Since there is an "Element" for this path, we need to be more
// specific about what is included in the snippets.
XElement root = XElement.Parse(matches.First().ToXml());
XElement node = root.DescendantsAndSelf("{http://hl7.org/fhir}" + path.Element).FirstOrDefault();
if (node != null)
{
node.Name = node.Name.LocalName;
category[property.Name]["SnippetXML"] = node.ToString();
}
else
{
category[property.Name]["SnippetXML"] = "";
}
Dictionary<string, dynamic> jsonRoot =
JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(matches.First().ToJson(),
new JsonSerializerSettings() { DateParseHandling = DateParseHandling.None });
if (jsonRoot != null && jsonRoot.Keys.Contains(path.Element))
{
category[property.Name]["SnippetJSON"] = "{" + $"\"{path.Element}\": \"{jsonRoot[path.Element]}\"" + "}";
}
else
{
category[property.Name]["SnippetJSON"] = "";
}
}
else
{
category[property.Name]["SnippetXML"] = matches.First().ToXml();
category[property.Name]["SnippetJSON"] = matches.First().ToJson();
}
}
else
{
category[property.Name]["SnippetXML"] = "";
category[property.Name]["SnippetJSON"] = "";
}
// Add the current value of the property