Пример #1
0
        public override Device FromXml(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var device = new Device
            {
                Id = Guid.NewGuid().ToString()
            };

            var location = new Location
            {
                Id = Guid.NewGuid().ToString()
            };

            Bundle?.AddResourceEntry(device);

            foreach (var child in element.Elements())
            {
                if (child.Name.LocalName == "id")
                {
                    var id = FromXml(new IdentifierParser(), child);

                    if (id != null)
                    {
                        device.Identifier.Add(id);
                    }
                }
                else if (child.Name.LocalName == "code")
                {
                    device.Type = FromXml(new CodeableConceptParser(), child);
                }
                else if (child.Name.LocalName == "addr")
                {
                    location.Address = FromXml(new AddressParser(), child);
                }
                else if (child.Name.LocalName == "telecom")
                {
                    var telecom = FromXml(new ContactPointParser(), child);
                    if (telecom != null)
                    {
                        location.Telecom.Add(telecom);
                    }
                }
                else if (child.Name.LocalName == "assignedAuthoringDevice")
                {
                    device.Model = child.CdaElement("manufacturerModelName")?.Value;
                }
            }


            return(device);
        }
Пример #2
0
        public HttpResponseMessage GetValueSets(
            [FromUri(Name = "_id")] int?valueSetId           = null,
            [FromUri(Name = "name")] string name             = null,
            [FromUri(Name = "_format")] string format        = null,
            [FromUri(Name = "_summary")] SummaryType?summary = null)
        {
            var valueSets             = this.tdb.ValueSets.Where(y => y.Id >= 0);
            ValueSetExporter exporter = new ValueSetExporter(this.tdb);

            if (valueSetId != null)
            {
                valueSets = valueSets.Where(y => y.Id == valueSetId);
            }

            if (!string.IsNullOrEmpty(name))
            {
                valueSets = valueSets.Where(y => y.Name.ToLower().Contains(name.ToLower()));
            }

            Bundle bundle = new Bundle()
            {
                Type = Bundle.BundleType.BatchResponse
            };

            foreach (var valueSet in valueSets)
            {
                var fhirValueSet = exporter.Convert(valueSet, summary);
                var fullUrl      = string.Format("{0}://{1}/api/FHIR2/{2}",
                                                 this.Request.RequestUri.Scheme,
                                                 this.Request.RequestUri.Authority,
                                                 fhirValueSet.Url);

                bundle.AddResourceEntry(fhirValueSet, fullUrl);
            }

            return(Shared.GetResponseMessage(this.Request, format, bundle));
        }
        public void GivenAResourceTypeRuleMatchBundleEntryNode_WhenProcess_NodesInBundleShouldBeRedact()
        {
            AnonymizationFhirPathRule[] rules = new AnonymizationFhirPathRule[]
            {
                new AnonymizationFhirPathRule("Person", "Person", "Person", "redact", AnonymizerRuleType.FhirPathRule, "Person.address"),
            };

            AnonymizationVisitor visitor = new AnonymizationVisitor(rules, CreateTestProcessors());

            var person = CreateTestPerson();
            var bundle = new Bundle();

            bundle.AddResourceEntry(person, "http://example.org/fhir/Person/1");

            var bundleNode = ElementNode.FromElement(bundle.ToTypedElement());

            bundleNode.Accept(visitor);
            bundleNode.RemoveEmptyNodes();
            person = bundleNode.Select("Bundle.entry[0].resource[0]").FirstOrDefault().ToPoco <Person>();

            Assert.NotNull(person);
            Assert.NotNull(person.Meta);
            Assert.Null(person.Active);
        }
        public override RelatedPerson FromXml(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var relatedPerson = new RelatedPerson
            {
                Id = Guid.NewGuid().ToString()
            };

            var classCode = element.Attribute("classCode")?.Value;

            if (!string.IsNullOrEmpty(classCode))
            {
                relatedPerson.Relationship = new CodeableConcept
                {
                    Coding = new List <Coding>
                    {
                        new Coding("urn:oid:2.16.840.1.113883.1.11.19563", classCode)
                    }
                }
            }
            ;

            foreach (var child in element.Elements())
            {
                switch (child.Name.LocalName)
                {
                case "code":
                    relatedPerson.Relationship = FromXml(new CodeableConceptParser(), child);
                    break;

                case "addr":
                    var addr = FromXml(new AddressParser(), child);
                    if (addr != null)
                    {
                        relatedPerson.Address.Add(addr);
                    }
                    break;

                case "telecom":
                    var contactPoint = FromXml(new ContactPointParser(), child);
                    if (contactPoint != null)
                    {
                        relatedPerson.Telecom.Add(contactPoint);
                    }
                    break;

                case "guardianPerson":
                case "relatedPerson":
                case "associatedPerson":
                    var name = FromXml(new HumanNameParser(), child.CdaElement("name"));
                    if (name != null)
                    {
                        relatedPerson.Name.Add(name);
                    }
                    break;
                }
            }

            if (!relatedPerson.Name.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have name element",
                                                        ParseErrorLevel.Warning));
            }

            var existingPerson = Bundle?.FirstOrDefault <RelatedPerson>(p => p.Name.IsExactly(relatedPerson.Name));

            if (existingPerson != null)
            {
                return(existingPerson);
            }

            Bundle?.AddResourceEntry(relatedPerson);

            return(relatedPerson);
        }
    }
        public IHttpActionResult GetTemplates(
            [FromUri(Name = "_id")] int?templateId           = null,
            [FromUri(Name = "name")] string name             = null,
            [FromUri(Name = "_summary")] SummaryType?summary = null)
        {
            var uri       = HttpContext.Current != null && HttpContext.Current.Request != null ? HttpContext.Current.Request.Url : new Uri(AppSettings.DefaultBaseUrl);
            var templates = this.tdb.Templates.Where(y => y.TemplateType.ImplementationGuideType == this.implementationGuideType);
            StructureDefinitionExporter exporter = new StructureDefinitionExporter(this.tdb, uri.Scheme, uri.Authority);

            if (!CheckPoint.Instance.IsDataAdmin)
            {
                User currentUser = CheckPoint.Instance.GetUser(this.tdb);
                templates = (from t in templates
                             join vtp in this.tdb.ViewTemplatePermissions on t.Id equals vtp.TemplateId
                             where vtp.UserId == currentUser.Id
                             select t);
            }

            if (templateId != null)
            {
                templates = templates.Where(y => y.Id == templateId);
            }

            if (!string.IsNullOrEmpty(name))
            {
                templates = templates.Where(y => y.Name.ToLower().Contains(name.ToLower()));
            }

            Bundle bundle = new Bundle()
            {
                Type = Bundle.BundleType.BatchResponse
            };

            foreach (var template in templates)
            {
                SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current, template.ImplementationGuideType);
                schema = schema.GetSchemaFromContext(template.PrimaryContextType);

                bool isMatch = true;
                StructureDefinition strucDef = exporter.Convert(template, schema, summary);
                var fullUrl = string.Format("{0}://{1}/api/FHIR2/StructureDefinition/{2}",
                                            this.Request.RequestUri.Scheme,
                                            this.Request.RequestUri.Authority,
                                            template.Id);

                // Skip adding the structure definition to the response if a criteria rules it out
                foreach (var queryParam in this.Request.GetQueryNameValuePairs())
                {
                    if (queryParam.Key == "_id" || queryParam.Key == "name" || queryParam.Key == "_format" || queryParam.Key == "_summary")
                    {
                        continue;
                    }

                    if (queryParam.Key.Contains("."))
                    {
                        throw new NotSupportedException(App_GlobalResources.TrifoliaLang.FHIRSearchCriteriaNotSupported);
                    }

                    var propertyDef = strucDef.GetType().GetProperty(queryParam.Key, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

                    if (propertyDef == null)
                    {
                        continue;
                    }

                    var value       = propertyDef.GetValue(strucDef);
                    var valueString = value != null?value.ToString() : string.Empty;

                    if (valueString != queryParam.Value)
                    {
                        isMatch = false;
                    }
                }

                if (isMatch)
                {
                    bundle.AddResourceEntry(strucDef, fullUrl);
                }
            }

            return(Content <Bundle>(HttpStatusCode.OK, bundle));
        }
        public override Patient FromXml(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var patient = new Patient
            {
                Id   = Guid.NewGuid().ToString(),
                Meta = new Meta
                {
                    Profile = new List <string>
                    {
                        "http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient"
                    }
                }
            };

            Bundle?.AddResourceEntry(patient);

            foreach (var child in element.Elements())
            {
                if (child.Name.LocalName == "id")
                {
                    var id = FromXml(new IdentifierParser(), child);

                    if (id != null)
                    {
                        patient.Identifier.Add(id);
                    }
                }
                else if (child.Name.LocalName == "addr")
                {
                    var addr = FromXml(new AddressParser(), child);

                    if (addr != null)
                    {
                        patient.Address.Add(addr);
                    }
                }
                else if (child.Name.LocalName == "telecom")
                {
                    var contactPoint = FromXml(new ContactPointParser(), child);

                    if (contactPoint != null)
                    {
                        patient.Telecom.Add(contactPoint);
                    }
                }
                else if (child.Name.LocalName == "patient")
                {
                    ParsePatient(patient, child);
                }
                else if (child.Name.LocalName == "providerOrganization")
                {
                    var org = FromXml(new OrganizationParser(Bundle), child);
                    if (org != null && Bundle != null)
                    {
                        patient.ManagingOrganization = new ResourceReference($"{org.TypeName}/{org.Id}");
                    }
                }
            }

            if (!patient.Identifier.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have id element", ParseErrorLevel.Error));
            }

            if (!patient.Name.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have name element", ParseErrorLevel.Error));
            }

            if (patient.Gender == null)
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have administrativeGenderCode element",
                                                        ParseErrorLevel.Error));
            }

            return(patient);
        }
Пример #7
0
        public static Resource GetStatement(bool inBundle)
        {
            TerminologyCapabilities tsCapabilityStatement = new TerminologyCapabilities
            {
                Url          = ServerCapability.TERMINZ_CANONICAL + "/TerminologyCapabilities/Terminz-Example",
                Id           = "Terminz-Example",
                Description  = new Markdown("HL7© FHIR© terminology services for use in New Zealand."),
                Name         = "Patients First Terminology Server (Terminz)",
                Purpose      = new Markdown("Exemplar of terminology services approach for New Zealand."),
                Publisher    = "Patients First Ltd",
                Version      = "4.0.0",
                Status       = PublicationStatus.Draft,
                Date         = "2019-05-08",
                Experimental = true,
                Copyright    = new Markdown("© 2019+ Patients First Ltd"),
                LockedDate   = false
            };

            ContactDetail cd = new ContactDetail {
                Name = "Peter Jordan"
            };
            ContactPoint cp = new ContactPoint {
                System = ContactPoint.ContactPointSystem.Email, Value = "*****@*****.**"
            };

            cd.Telecom.Add(cp);
            tsCapabilityStatement.Contact.Add(cd);

            CodeableConcept cc = new CodeableConcept("http://hl7.org/fhir/ValueSet/jurisdiction", "NZL", "New Zealand", "New Zealand");

            tsCapabilityStatement.Jurisdiction.Add(cc);

            tsCapabilityStatement.CodeSystem.Add(FhirSnomed.GetCapabilities());
            tsCapabilityStatement.CodeSystem.Add(FhirLoinc.GetCapabilities());
            tsCapabilityStatement.CodeSystem.Add(NzMt.GetCapabilities());
            tsCapabilityStatement.CodeSystem.Add(FhirRxNorm.GetCapabilities());

            tsCapabilityStatement.Expansion = new TerminologyCapabilities.ExpansionComponent
            {
                Hierarchical = false,
                Paging       = true,
                Incomplete   = false,
                TextFilter   = new Markdown("Results include synonyms, not just preferred terms.")
            };

            tsCapabilityStatement.CodeSearch = TerminologyCapabilities.CodeSearchSupport.All;

            tsCapabilityStatement.ValidateCode = new TerminologyCapabilities.ValidateCodeComponent()
            {
                Translations = false
            };

            tsCapabilityStatement.Translation = new TerminologyCapabilities.TranslationComponent()
            {
                NeedsMap = true
            };

            tsCapabilityStatement.Closure = new TerminologyCapabilities.ClosureComponent()
            {
                Translation = false
            };

            // text element

            XNamespace ns = "http://www.w3.org/1999/xhtml";

            var summary = new XElement(ns + "div",
                                       new XElement(ns + "h2", tsCapabilityStatement.Name),
                                       new XElement(ns + "p", tsCapabilityStatement.Description),
                                       new XElement(ns + "table",
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", "Purpose"),
                                                                 new XElement(ns + "td", tsCapabilityStatement.Purpose.ToString())
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", "Publisher"),
                                                                 new XElement(ns + "td", tsCapabilityStatement.Publisher)
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", "Version"),
                                                                 new XElement(ns + "td", tsCapabilityStatement.Version)
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", "Date"),
                                                                 new XElement(ns + "td", tsCapabilityStatement.Date)
                                                                 )
                                                    ),
                                       new XElement(ns + "table",
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "th", "Code System"),
                                                                 new XElement(ns + "th", "Description"),
                                                                 new XElement(ns + "th", "URI"),
                                                                 new XElement(ns + "th", "Version")
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", FhirSnomed.TITLE),
                                                                 new XElement(ns + "td", FhirSnomed.DESCRIPTION),
                                                                 new XElement(ns + "td", FhirSnomed.URI),
                                                                 new XElement(ns + "td", FhirSnomed.CURRENT_VERSION)
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", FhirLoinc.TITLE),
                                                                 new XElement(ns + "td", FhirLoinc.DESCRIPTION),
                                                                 new XElement(ns + "td", FhirLoinc.URI),
                                                                 new XElement(ns + "td", FhirLoinc.CURRENT_VERSION)
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", NzMt.TITLE),
                                                                 new XElement(ns + "td", NzMt.DESCRIPTION),
                                                                 new XElement(ns + "td", NzMt.URI),
                                                                 new XElement(ns + "td", NzMt.CURRENT_VERSION)
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", FhirRxNorm.TITLE),
                                                                 new XElement(ns + "td", FhirRxNorm.DESCRIPTION),
                                                                 new XElement(ns + "td", FhirRxNorm.URI),
                                                                 new XElement(ns + "td", FhirRxNorm.CURRENT_VERSION)
                                                                 )
                                                    )
                                       );

            tsCapabilityStatement.Text = new Narrative
            {
                Status = Narrative.NarrativeStatus.Generated,
                Div    = summary.ToString()
            };

            // place in a bundle

            if (inBundle)
            {
                Bundle tcsBundle = new Bundle
                {
                    Id   = Guid.NewGuid().ToString(),
                    Type = Bundle.BundleType.Searchset
                };

                tcsBundle.Link.Add(new Bundle.LinkComponent {
                    Url = ServerCapability.TERMINZ_CANONICAL + "/TerminologyCapabilities", Relation = "self"
                });
                tcsBundle.AddResourceEntry(tsCapabilityStatement, tsCapabilityStatement.Url);
                tcsBundle.Total = tcsBundle.Entry.Count;

                return(tcsBundle);
            }

            return(tsCapabilityStatement);
        }
Пример #8
0
        public void Should_Match_Patient_Certain()
        {
            // Arrange

            var patient = Random.NextChoice(_testPatients);
            var matches = new Bundle();

            // Act

            var patientNhsNumber   = patient.GetNhsNumber();
            var patientFamilyName  = patient.GetFamilyName();
            var patientGivenName   = patient.GetGivenName();
            var patientDateOfBirth = patient.BirthDate;
            var patientGender      = patient.Gender.ToString();
            var patientAddress     = patient.Address.First().ToXml();

            foreach (var testPatient in _testPatients)
            {
                // 0. CHECK: NHS Number
                if (patientNhsNumber != null && testPatient.GetNhsNumber() != null && patientNhsNumber == testPatient.GetNhsNumber())
                {
                    matches.AddResourceEntry(testPatient, Guid.NewGuid().ToString());
                    matches.Entry.Last().AddExtension("http://hl7.org/fhir/StructureDefinition/match-grade", new CodeableConcept("MatchGrade", "certain", "Certain Match"));
                    continue;
                }

                // track score
                var score = 0.0;

                // 1. CHECK: Family Name
                if (patientFamilyName == testPatient.GetFamilyName())
                {
                    score += 0.2;
                }

                // 2. CHECK: Given Name
                if (patientGivenName == testPatient.GetGivenName())
                {
                    score += 0.2;
                }

                // REJECT-DECISION: these patients don't match
                if (score.IsEqualTo(0.0))
                {
                    continue;
                }

                // 3. CHECK: Date of Birth
                if (patientDateOfBirth == testPatient.BirthDate)
                {
                    score += 0.2;
                }

                // REJECT-DECISION: these patients don't match
                if (score.IsEqualTo(0.2))
                {
                    continue;
                }

                // ACCEPT-DECISION: these patients probably match
                if (score.IsEqualTo(0.6))
                {
                    matches.AddResourceEntry(testPatient, Guid.NewGuid().ToString());
                    matches.Entry.Last().AddExtension("http://hl7.org/fhir/StructureDefinition/match-grade", new CodeableConcept("MatchGrade", "probable", "Probable Match"));
                    continue;
                }

                // 4. CHECK: Gender
                if (patientGender == testPatient.Gender.ToString())
                {
                    score += 0.2;
                }

                // 5. CHECK: Address
                if (patientAddress == testPatient.Address.FirstOrDefault()?.ToXml())
                {
                    score += 0.2;
                }

                // REJECT-DECISION: these patients don't match
                if (score.IsEqualTo(0.4))
                {
                    continue;
                }

                // ACCEPT-DECISION: these patients probably match
                if (score.IsEqualTo(0.8))
                {
                    matches.AddResourceEntry(testPatient, Guid.NewGuid().ToString());
                    matches.Entry.Last().AddExtension("http://hl7.org/fhir/StructureDefinition/match-grade", new CodeableConcept("MatchGrade", "possible", "Possible Match"));
                }
            }

            matches.Entry = matches.Entry.OrderBy(x =>
                                                  ((CodeableConcept)x.GetExtension("http://hl7.org/fhir/StructureDefinition/match-grade").Value).Coding.First().Code == "certain" ? 1:
                                                  ((CodeableConcept)x.GetExtension("http://hl7.org/fhir/StructureDefinition/match-grade").Value).Coding.First().Code == "probable" ? 2:
                                                  ((CodeableConcept)x.GetExtension("http://hl7.org/fhir/StructureDefinition/match-grade").Value).Coding.First().Code == "possible" ? 3: 4).ToList();

            Console.WriteLine($"searched for patient:\n{patient.ToXml()}");
            Console.WriteLine($"\nfound {matches.Entry.Count} matches in {_testPatients.Count} patients.\n");
            Console.WriteLine(matches.ToXml());
            Assert.IsTrue(matches.Entry.Count > 0);
        }
Пример #9
0
        public override Practitioner FromXml(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var practitioner = new Practitioner
            {
                Id   = Guid.NewGuid().ToString(),
                Meta = new Meta
                {
                    Profile = new List <string>
                    {
                        "http://hl7.org/fhir/us/core/StructureDefinition/us-core-practitioner"
                    }
                }
            };

            var role = new PractitionerRole()
            {
                Id           = Guid.NewGuid().ToString(),
                Practitioner = new ResourceReference($"{practitioner.TypeName}/{practitioner.Id}")
            };

            var location = new Location
            {
                Id = Guid.NewGuid().ToString()
            };

            foreach (var child in element.Elements())
            {
                switch (child.Name.LocalName)
                {
                case "id":
                    var id = FromXml(new IdentifierParser(), child);
                    if (id != null)
                    {
                        practitioner.Identifier.Add(id);
                    }
                    break;

                case "code":
                    var code = FromXml(new CodeableConceptParser(), child);
                    if (code != null)
                    {
                        role.Specialty.Add(code);
                    }
                    break;

                case "addr":
                    location.Address = FromXml(new AddressParser(), child);
                    break;

                case "telecom":
                    var telecom = FromXml(new ContactPointParser(), child);
                    if (telecom != null)
                    {
                        location.Telecom.Add(telecom);
                    }
                    break;

                case "assignedPerson":
                case "informationRecipient":
                    var name = FromXml(new HumanNameParser(), child.CdaElement("name"));
                    if (name != null)
                    {
                        practitioner.Name.Add(name);
                    }
                    break;

                case "receivedOrganization":
                    break;
                }
            }

            if (!practitioner.Identifier.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have identifier", ParseErrorLevel.Error));
            }

            if (!practitioner.Name.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have name", ParseErrorLevel.Warning));
            }

            var existingPractitioner = Bundle?.FirstOrDefault <Practitioner>(p => p.Identifier.IsExactly(practitioner.Identifier));

            if (existingPractitioner != null)
            {
                practitioner = existingPractitioner;
            }
            else
            {
                Bundle?.AddResourceEntry(practitioner);
            }

            role.Practitioner = practitioner.GetResourceReference();

            if (location.Address != null || location.Telecom.Any())
            {
                var existingLocation = Bundle?.FirstOrDefault <Location>(l =>
                                                                         l.Address.IsExactly(location.Address) && l.Telecom.IsExactly(location.Telecom));

                if (existingLocation != null)
                {
                    location = existingLocation;
                }
                else
                {
                    Bundle?.AddResourceEntry(location);
                }

                role.Location.Add(location.GetResourceReference());
            }

            var existingRole = Bundle?.FirstOrDefault <PractitionerRole>(pr =>
                                                                         pr.Location.IsExactly(role.Location) &&
                                                                         pr.Specialty.IsExactly(role.Specialty) &&
                                                                         pr.Practitioner.IsExactly(role.Practitioner));

            if (existingRole == null && (role.Location.Any() || role.Specialty.Any()))
            {
                Bundle?.AddResourceEntry(role);
            }

            return(practitioner);
        }
        public static Resource GetRequest(string id, NameValueCollection queryParam)
        {
            Bundle locBundle = new Bundle
            {
                Id   = Guid.NewGuid().ToString(),
                Type = Bundle.BundleType.Searchset
            };

            locBundle.Link.Add(new Bundle.LinkComponent {
                Url = ServerCapability.TERMINZ_CANONICAL + "/Location", Relation = "self"
            });

            Location     location = new Location();
            Organization org      = new Organization();

            string identifier         = GetIdentifier(id, queryParam);
            string address            = Utilities.GetQueryValue("address", queryParam);
            string address_city       = Utilities.GetQueryValue("address-city", queryParam);
            string address_postalcode = Utilities.GetQueryValue("address-postalcode", queryParam);
            string name     = Utilities.GetQueryValue("name", queryParam);
            string type     = Utilities.GetQueryValue("type", queryParam);
            bool   idPassed = !string.IsNullOrEmpty(id);
            int    matches  = 0;

            // facilitate (more efficient) postcode and city filtering at DB layer
            if (!string.IsNullOrEmpty(address_postalcode) && string.IsNullOrEmpty(address))
            {
                address = address_postalcode;
            }

            if (!string.IsNullOrEmpty(address_city) && string.IsNullOrEmpty(address))
            {
                address = address_city;
            }

            if (string.IsNullOrEmpty(identifier) && string.IsNullOrEmpty(name) && string.IsNullOrEmpty(address) && string.IsNullOrEmpty(type))
            {
                return(OperationOutcome.ForMessage("No valid search parameters.", OperationOutcome.IssueType.Invalid, OperationOutcome.IssueSeverity.Error));
            }

            //CodeableConcept hpiFac = new CodeableConcept { Text = "HPI-FAC" };

            try
            {
                List <HpiFacility> facilities = SnomedCtSearch.GetLocations(identifier, name, address, type);

                foreach (HpiFacility fac in facilities)
                {
                    bool addLocation = true;

                    Address locAddress = Utilities.GetAddress(fac.FacilityAddress.Trim());

                    if (!string.IsNullOrEmpty(address_city) && locAddress.City.ToUpper() != address_city.ToUpper())
                    {
                        addLocation = false;
                    }

                    if (!string.IsNullOrEmpty(address_postalcode) && locAddress.PostalCode.ToUpper() != address_postalcode.ToUpper())
                    {
                        addLocation = false;
                    }

                    if (addLocation)
                    {
                        bool addOrg = false;
                        org      = new Organization();
                        location = new Location
                        {
                            Id = fac.FacilityId.Trim()
                        };
                        location.Identifier.Add(new Identifier {
                            Value = fac.FacilityId.Trim(), System = NAMING_SYSTEM_IDENTIFIER
                        });
                        location.Name   = fac.FacilityName.Trim();
                        location.Status = Location.LocationStatus.Active;
                        location.Mode   = Location.LocationMode.Instance;
                        location.Type.Add(new CodeableConcept {
                            Text = fac.FacilityTypeName.Trim()
                        });
                        location.Address = locAddress;
                        AddNarrative(location);

                        if (!string.IsNullOrEmpty(fac.OrganisationId))
                        {
                            try
                            {
                                org = (Organization)AdministrationOrganisation.GetRequest(fac.OrganisationId, null);
                                location.ManagingOrganization = new ResourceReference {
                                    Reference = fac.OrganisationId
                                };
                                addOrg = true;
                            }
                            catch { }
                        }

                        locBundle.AddResourceEntry(location, ServerCapability.TERMINZ_CANONICAL + "/Location/" + fac.FacilityId.Trim());
                        matches++;

                        if (addOrg)
                        {
                            locBundle.AddResourceEntry(org, ServerCapability.TERMINZ_CANONICAL + "/Organization" + "/" + fac.OrganisationId.Trim());
                        }
                    }
                }

                if (matches == 0)
                {
                    return(OperationOutcome.ForMessage("No Locations match search parameter values.", OperationOutcome.IssueType.NotFound, OperationOutcome.IssueSeverity.Information));
                }

                locBundle.Total = matches;
            }
            catch (Exception ex)
            {
                return(OperationOutcome.ForMessage("Error: " + ex.Message, OperationOutcome.IssueType.Invalid, OperationOutcome.IssueSeverity.Error));
            }

            // always return bundle because of contained resources <TODO> implement _include so user can specify this

            return(locBundle);
        }
Пример #11
0
        public override Organization FromXml(XElement element)
        {
            if (element == null)
            {
                return(null);
            }

            var org = new Organization
            {
                Id   = Guid.NewGuid().ToString(),
                Meta = new Meta
                {
                    Profile = new List <string>
                    {
                        "http://hl7.org/fhir/us/core/StructureDefinition/us-core-organization"
                    }
                },
                Active = true
            };

            foreach (var child in element.Elements())
            {
                if (child.Name.LocalName == "id")
                {
                    var id = new IdentifierParser().FromXml(child, Errors);

                    if (id != null)
                    {
                        org.Identifier.Add(id);
                    }
                }
                else if (child.Name.LocalName == "name")
                {
                    org.Name = child.Value;
                }
                else if (child.Name.LocalName == "telecom")
                {
                    var telecom = new ContactPointParser().FromXml(child, Errors);

                    if (telecom != null)
                    {
                        org.Telecom.Add(telecom);
                    }
                }
                else if (child.Name.LocalName == "addr")
                {
                    var addr = new AddressParser().FromXml(child, Errors);

                    if (addr != null)
                    {
                        org.Address.Add(addr);
                    }
                }
            }

            if (!org.Identifier.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have id element", ParseErrorLevel.Error));
            }

            if (string.IsNullOrEmpty(org.Name))
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have name element", ParseErrorLevel.Error));
            }

            if (!org.Telecom.Any())
            {
                Errors.Add(
                    ParserError.CreateParseError(element, "does NOT have telecom element", ParseErrorLevel.Error));
            }

            if (!org.Address.Any())
            {
                Errors.Add(ParserError.CreateParseError(element, "does NOT have addr element", ParseErrorLevel.Error));
            }

            var existingOrg = Bundle?.FirstOrDefault <Organization>(p => p.Identifier.IsExactly(org.Identifier));

            if (existingOrg == null)
            {
                Bundle?.AddResourceEntry(org);
            }
            else
            {
                org = existingOrg;
            }

            return(org);
        }
Пример #12
0
        /// <summary>
        /// To save time, store all structure definitions in a fhir bundle file. This need only be run when we get a new
        /// FHIR version.
        /// </summary>
        public void StoreFhirElements()
        {
            const String fcn = "StoreFhirElements";

            // const String fcn = "StoreFhirElements";
            foreach (String f in Directory.GetFiles(this.bundleDir))
            {
                File.Delete(f);
            }

            foreach (String d in Directory.GetDirectories(this.bundleDir))
            {
                Directory.Delete(d, true);
            }

            {
                String rDir = Path.Combine(this.bundleDir, "StructDefs");
                if (Directory.Exists(rDir))
                {
                    Directory.Delete(rDir, true);
                }
            }
            String primitiveDir = Path.Combine(this.bundleDir, "StructDefs", "Primitive");

            Directory.CreateDirectory(primitiveDir);

            String logicalDir = Path.Combine(this.bundleDir, "StructDefs", "Logical");

            Directory.CreateDirectory(logicalDir);

            String complexDir = Path.Combine(this.bundleDir, "StructDefs", "Complex");

            Directory.CreateDirectory(complexDir);

            String resourceDir = Path.Combine(this.bundleDir, "StructDefs", "Resources");

            Directory.CreateDirectory(resourceDir);

            Bundle b = new Bundle();

            foreach (string uri in this.source.ListResourceUris())
            {
                StructureDefinition sDef = this.source.ResolveByUri(uri) as StructureDefinition;
                if (sDef != null)
                {
                    // This is to get rid of the http://....//de-... entries.
                    if (sDef.Snapshot.Element[0].Path.Split('.').Length == 1)
                    {
                        b.AddResourceEntry(sDef, sDef.Url);

                        switch (sDef.Kind)
                        {
#if FHIR_R4 || FHIR_R3
                        case StructureDefinition.StructureDefinitionKind.PrimitiveType:
                            sDef.SaveJson(Path.Combine(primitiveDir, $"{sDef.Name}.json"));
                            break;

                        case StructureDefinition.StructureDefinitionKind.ComplexType:
                            sDef.SaveJson(Path.Combine(complexDir, $"{sDef.Name}.json"));
                            break;
#endif
                        case StructureDefinition.StructureDefinitionKind.Logical:
                            sDef.SaveJson(Path.Combine(logicalDir, $"{sDef.Name}.json"));
                            break;

                        case StructureDefinition.StructureDefinitionKind.Resource:
                            sDef.SaveJson(Path.Combine(resourceDir, $"{sDef.Name}.json"));
                            break;

                        default:
                            throw new ConvertErrorException(this.GetType().Name, fcn, $"Invalid kind {sDef.Kind}. Item {sDef.Name}");
                        }
                    }
                }
            }
            b.SaveJson(this.bundlePath);
        }
        public static Resource GetRequest(string id, NameValueCollection queryParam)
        {
            Bundle orgBundle = new Bundle
            {
                Id   = Guid.NewGuid().ToString(),
                Type = Bundle.BundleType.Searchset
            };

            orgBundle.Link.Add(new Bundle.LinkComponent {
                Url = ServerCapability.TERMINZ_CANONICAL + "/Organization", Relation = "self"
            });

            Organization organization = new Organization();

            string identifier         = GetIdentifier(id, queryParam);
            string address            = Utilities.GetQueryValue("address", queryParam);
            string address_city       = Utilities.GetQueryValue("address-city", queryParam);
            string address_postalcode = Utilities.GetQueryValue("address-postalcode", queryParam);
            string name     = Utilities.GetQueryValue("name", queryParam);
            string type     = Utilities.GetQueryValue("type", queryParam);
            bool   idPassed = !string.IsNullOrEmpty(id);
            int    matches  = 0;

            // facilitate (more efficient) postcode and city filtering at DB layer
            if (!string.IsNullOrEmpty(address_postalcode) && string.IsNullOrEmpty(address))
            {
                address = address_postalcode;
            }

            if (!string.IsNullOrEmpty(address_city) && string.IsNullOrEmpty(address))
            {
                address = address_city;
            }

            if (string.IsNullOrEmpty(identifier) && string.IsNullOrEmpty(name) && string.IsNullOrEmpty(address) && string.IsNullOrEmpty(type))
            {
                return(OperationOutcome.ForMessage("No valid search parameters.", OperationOutcome.IssueType.Invalid, OperationOutcome.IssueSeverity.Error));
            }

            //CodeableConcept hpiFac = new CodeableConcept { Text = "HPI-ORG" };

            List <HpiOrganisation> organisations = SnomedCtSearch.GetOrganisations(identifier, name, address, type);

            foreach (HpiOrganisation org in organisations)
            {
                bool addOrg = true;

                Address orgAddress = Utilities.GetAddress(org.OrganisationAddress.Trim());

                if (!string.IsNullOrEmpty(address_city) && orgAddress.City.ToUpper() != address_city.ToUpper())
                {
                    addOrg = false;
                }

                if (!string.IsNullOrEmpty(address_postalcode) && orgAddress.PostalCode.ToUpper() != address_postalcode.ToUpper())
                {
                    addOrg = false;
                }

                if (addOrg)
                {
                    organization = new Organization
                    {
                        Id = org.OrganisationId.Trim()
                    };
                    organization.Identifier.Add(new Identifier {
                        Value = org.OrganisationId.Trim(), System = NAMING_SYSTEM_IDENTIFIER
                    });
                    organization.Name   = org.OrganisationName.Trim();
                    organization.Active = true;
                    organization.Type.Add(new CodeableConcept {
                        Text = org.OrganisationTypeName.Trim()
                    });
                    organization.Address.Add(orgAddress);
                    AddNarrative(organization);
                    orgBundle.AddResourceEntry(organization, ServerCapability.TERMINZ_CANONICAL + "/Organization/ " + org.OrganisationId.Trim());
                    matches++;
                }
            }

            if (matches == 0)
            {
                return(OperationOutcome.ForMessage("No Organisations match search parameter values.", OperationOutcome.IssueType.NotFound, OperationOutcome.IssueSeverity.Information));
            }
            else if (matches == 1 && idPassed)
            {
                return(organization);
            }

            orgBundle.Total = matches;

            return(orgBundle);
        }
Пример #14
0
        public void Should_Match_Multiple_Varied()
        {
            // Arrange

            var certainPatient  = RandomHelper.GetRandomFhirPatient();
            var probablePatient = new Patient();
            var possiblePatient = new Patient();

            certainPatient.CopyTo(probablePatient);
            certainPatient.CopyTo(possiblePatient);

            // remove nhs number so we don't get certain match
            probablePatient.Identifier = new List <Identifier>();
            possiblePatient.Identifier = new List <Identifier>();

            possiblePatient.Name.First().Family = string.Empty;

            _testPatients[RandomHelper.GetRandomInteger(0, _testPatients.Count - 1)] = certainPatient;
            _testPatients[RandomHelper.GetRandomInteger(0, _testPatients.Count - 1)] = probablePatient;
            _testPatients[RandomHelper.GetRandomInteger(0, _testPatients.Count - 1)] = possiblePatient;

            var matches = new Bundle();

            // Act

            var patientNhsNumber   = certainPatient.GetNhsNumber();
            var patientFamilyName  = certainPatient.GetFamilyName();
            var patientGivenName   = certainPatient.GetGivenName();
            var patientDateOfBirth = certainPatient.BirthDate;
            var patientGender      = certainPatient.Gender.ToString();
            var patientAddress     = certainPatient.Address.First().ToXml();

            foreach (var testPatient in _testPatients)
            {
                // 0. CHECK: NHS Number
                if (patientNhsNumber != null && testPatient.GetNhsNumber() != null && patientNhsNumber == testPatient.GetNhsNumber())
                {
                    matches.AddResourceEntry(testPatient, Guid.NewGuid().ToString());
                    matches.Entry.Last().AddExtension("http://hl7.org/fhir/StructureDefinition/match-grade", new CodeableConcept("MatchGrade", "certain", "Certain Match"));
                    Console.WriteLine($"Successfully matched patient on NHS number.");
                    continue;
                }

                // track score
                var score = 0.0;

                // 1. CHECK: Family Name
                if (patientFamilyName == testPatient.GetFamilyName())
                {
                    score += 0.2;
                }

                // 2. CHECK: Given Name
                if (patientGivenName == testPatient.GetGivenName())
                {
                    score += 0.2;
                }

                // REJECT-DECISION: these patients don't match
                if (score.IsEqualTo(0.0))
                {
                    continue;
                }

                // 3. CHECK: Date of Birth
                if (patientDateOfBirth == testPatient.BirthDate)
                {
                    score += 0.2;
                }

                // REJECT-DECISION: these patients don't match
                if (score.IsEqualTo(0.2))
                {
                    continue;
                }

                // ACCEPT-DECISION: these patients probably match
                if (score.IsEqualTo(0.6))
                {
                    matches.AddResourceEntry(testPatient, Guid.NewGuid().ToString());
                    matches.Entry.Last().AddExtension("http://hl7.org/fhir/StructureDefinition/match-grade", new CodeableConcept("MatchGrade", "probable", "Probable Match"));
                    continue;
                }

                // 4. CHECK: Gender
                if (patientGender == testPatient.Gender.ToString())
                {
                    score += 0.2;
                }

                // 5. CHECK: Address
                if (patientAddress == testPatient.Address.FirstOrDefault()?.ToXml())
                {
                    score += 0.2;
                }

                // REJECT-DECISION: these patients don't match
                if (score.IsEqualTo(0.4))
                {
                    continue;
                }

                // ACCEPT-DECISION: these patients probably match
                if (score.IsEqualTo(0.8))
                {
                    matches.AddResourceEntry(testPatient, Guid.NewGuid().ToString());
                    matches.Entry.Last().AddExtension("http://hl7.org/fhir/StructureDefinition/match-grade", new CodeableConcept("MatchGrade", "possible", "Possible Match"));
                }
            }

            matches.Entry = matches.Entry.OrderBy(x =>
                                                  ((CodeableConcept)x.GetExtension("http://hl7.org/fhir/StructureDefinition/match-grade").Value).Coding.First().Code == "certain" ? 1 :
                                                  ((CodeableConcept)x.GetExtension("http://hl7.org/fhir/StructureDefinition/match-grade").Value).Coding.First().Code == "probable" ? 2 :
                                                  ((CodeableConcept)x.GetExtension("http://hl7.org/fhir/StructureDefinition/match-grade").Value).Coding.First().Code == "possible" ? 3 : 4).ToList();

            Console.WriteLine($"searched for patient:\n{certainPatient.ToXml()}");
            Console.WriteLine($"\nfound {matches.Entry.Count} matches in {_testPatients.Count} patients.\n");
            Console.WriteLine(matches.ToXml());
            Assert.IsTrue(matches.Entry.Count > 0);
        }
        public Bundle GetImplementationGuides(SummaryType?summary = null, string include = null, int?implementationGuideId = null, string name = null)
        {
            // TODO: Should not be using constant string for IG type name to find templates... Not sure how else to identify FHIR DSTU1 templates though
            var implementationGuides = this.tdb.ImplementationGuides.Where(y => y.ImplementationGuideTypeId == this.implementationGuideType.Id);

            if (!CheckPoint.Instance.IsDataAdmin)
            {
                User currentUser = CheckPoint.Instance.GetUser(this.tdb);
                implementationGuides = (from ig in implementationGuides
                                        join igp in this.tdb.ImplementationGuidePermissions on ig.Id equals igp.UserId
                                        where igp.UserId == currentUser.Id
                                        select ig);
            }

            if (implementationGuideId != null)
            {
                implementationGuides = implementationGuides.Where(y => y.Id == implementationGuideId);
            }

            if (!string.IsNullOrEmpty(name))
            {
                implementationGuides = implementationGuides.Where(y => y.Name.ToLower().Contains(name.ToLower()));
            }

            Bundle bundle = new Bundle()
            {
                Type = Bundle.BundleType.BatchResponse
            };

            foreach (var ig in implementationGuides)
            {
                FhirImplementationGuide fhirImplementationGuide = Convert(ig, summary);

                // Add the IG before the templates
                bundle.AddResourceEntry(fhirImplementationGuide, this.GetFullUrl(ig));

                // TODO: Need to implement a more sophisticated approach to parsing "_include"
                if (!string.IsNullOrEmpty(include) && include == "ImplementationGuide:resource")
                {
                    List <Template> templates = ig.GetRecursiveTemplates(this.tdb, inferred: true);

                    /*
                     * // TODO: Add additional query parameters for indicating parent template ids and categories?
                     * IGSettingsManager igSettings = new IGSettingsManager(this.tdb, ig.Id);
                     * string templateBundleXml = FHIRExporter.GenerateExport(this.tdb, templates, igSettings);
                     * Bundle templateBundle = (Bundle)FhirParser.ParseResourceFromXml(templateBundleXml);
                     *
                     * var templateEntries = templateBundle.Entry.Where(y =>
                     *  y.Resource.ResourceType != ResourceType.ImplementationGuide &&
                     *  y.Resource.Id != fhirImplementationGuide.Id);
                     *
                     * // TODO: Make sure that if multiple IGs are returned, that there are distinct bundle entries
                     * // (no duplicate template/profile entries that are referenced by two separate IGs)
                     * bundle.Entry.AddRange(templateEntries);
                     */

                    StructureDefinitionExporter strucDefExporter = new StructureDefinitionExporter(this.tdb, this.scheme, this.authority);
                    foreach (var template in templates)
                    {
                        var templateSchema = this.schema.GetSchemaFromContext(template.PrimaryContextType);
                        var strucDef       = strucDefExporter.Convert(template, schema);
                        bundle.AddResourceEntry(strucDef, this.GetFullUrl(template));
                    }
                }
            }

            return(bundle);
        }
Пример #16
0
        public Stream TerminzBatch()
        {
            string rv = string.Empty;

            string responseType = GetResponseType();
            string fhirVersion  = GetFhirVersion();

            // get Bundle from the Request Stream

            string       reqBody   = string.Empty;
            UTF8Encoding enc       = new UTF8Encoding();
            Stream       reqStream = OperationContext.Current.RequestContext.RequestMessage.GetBody <Stream>();

            using (StreamReader reader = new StreamReader(reqStream, enc))
            {
                reqBody = reader.ReadToEnd();
            }

            string reqType = WebOperationContext.Current.IncomingRequest.ContentType.ToLower();

            Resource fhirResource;

            if (reqType.Contains("json"))
            {
                FhirJsonParser fjp = new FhirJsonParser();
                fhirResource = fjp.Parse <Resource>(reqBody);
            }
            else
            {
                FhirXmlParser fxp = new FhirXmlParser();
                fhirResource = fxp.Parse <Resource>(reqBody);
            }

            if (fhirResource.ResourceType == ResourceType.Bundle)
            {
                Bundle fb = (Bundle)fhirResource;
                if (fb.Type == Bundle.BundleType.Batch)
                {
                    Bundle responseBundle = new Bundle();

                    responseBundle.Id   = Guid.NewGuid().ToString();
                    responseBundle.Type = Bundle.BundleType.BatchResponse;

                    foreach (Bundle.EntryComponent comp in fb.Entry)
                    {
                        Bundle.RequestComponent rc = comp.Request;

                        if (rc.Method == Bundle.HTTPVerb.GET)
                        {
                            if (rc.Url.IndexOf("$validate-code") > 0)
                            {
                                // extract and parse query string to get parameters
                                int    qsPos       = rc.Url.IndexOf('?');
                                string querystring = (qsPos < rc.Url.Length - 1) ? rc.Url.Substring(qsPos + 1) : String.Empty;
                                qParam = System.Web.HttpUtility.ParseQueryString(querystring);
                                // extract resource (CodeSystem or ValueSet) ID
                                string resourceID   = string.Empty;
                                string resourceName = resourceID.IndexOf("/ValueSet/") > 0 ? "ValueSet" : "CodeSystem";
                                try
                                {
                                    resourceID = rc.Url.Remove(qsPos);
                                    int resNamePos = resourceID.IndexOf("/" + resourceName + "/");
                                    resourceID = resourceID.Substring(resNamePos + 9).Replace("/", "").Replace("$validate-code", "");
                                }
                                catch { }
                                ServiceInterface appSi = new ServiceInterface();
                                responseBundle.AddResourceEntry(appSi.GetFhirResource(resourceName, resourceID, "$validate-code", qParam, fhirVersion), string.Empty);
                            }
                            else
                            {
                                responseBundle.AddResourceEntry(OperationOutcome.ForMessage("Unrecognised Operation in Request..." + rc.Url, OperationOutcome.IssueType.Unknown), string.Empty);
                            }
                        }
                        else if (rc.Method == Bundle.HTTPVerb.POST)
                        {
                            if (rc.Url.IndexOf("$translate") > 0 && comp.Resource.ResourceType == ResourceType.Parameters)
                            {
                                // extract ConceptMap ID
                                string cmID = string.Empty;
                                try
                                {
                                    cmID = rc.Url.Replace("ConceptMap/", "").Replace("$translate", "").Replace("/", "");
                                }
                                catch { }
                                // get parameters
                                Parameters fParam = (Parameters)comp.Resource;
                                SetQueryParameters(fParam);
                                ServiceInterface appSi = new ServiceInterface();
                                responseBundle.AddResourceEntry(appSi.GetFhirResource("ConceptMap", cmID, "$translate", qParam, fhirVersion), string.Empty);
                            }
                            else
                            {
                                responseBundle.AddResourceEntry(OperationOutcome.ForMessage("Unrecognised Operation in Request..." + rc.Url, OperationOutcome.IssueType.Unknown), string.Empty);
                            }
                        }
                        else
                        {
                            responseBundle.AddResourceEntry(OperationOutcome.ForMessage("Method Not Supported in Batch Mode '" + rc.Method.ToString() + "'", OperationOutcome.IssueType.NotSupported), string.Empty);
                        }
                    }

                    fhirResource = responseBundle;
                }
                else
                {
                    fhirResource = OperationOutcome.ForMessage("No module could be found to handle the bundle type '" + fb.TypeName + "'", OperationOutcome.IssueType.NotFound);
                }
            }
            else
            {
                fhirResource = OperationOutcome.ForMessage("No module could be found to handle the request '" + fhirResource.ResourceType.ToString() + "'", OperationOutcome.IssueType.NotFound);
            }

            if (fhirResource.ResourceType == ResourceType.OperationOutcome)
            {
                AddNarrativeToOperationOutcome(fhirResource);
                OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
                response.StatusCode = HttpStatusCode.BadRequest;
                // if wish for more granular response codes, need Issue Type
                //OperationOutcome oo = (OperationOutcome)fhirResource;
                //OperationOutcome.IssueType opOutcome = (OperationOutcome.IssueType)oo.Issue[0].Code;
            }

            // convert to stream to remove leading XML elements and json quotes
            rv = SerializeResponse(fhirResource, responseType, SummaryType.False);
            return(new System.IO.MemoryStream(UTF8Encoding.Default.GetBytes(rv)));
        }
        private static Resource GetAllCodeSystems(NameValueCollection queryParam)
        {
            string contentMode = Utilities.GetQueryValue("content-mode", queryParam);
            string supplements = Utilities.GetQueryValue("supplements", queryParam);

            if (supplements == "bundle-type" || supplements == "http://hl7.org/fhir/bundle-type")
            {
                return(GetRequest("bundle-type-german", string.Empty, queryParam));
            }

            Bundle csBundle = new Bundle();

            csBundle.Id   = Guid.NewGuid().ToString();
            csBundle.Type = Bundle.BundleType.Searchset;
            csBundle.Link.Add(new Bundle.LinkComponent {
                Url = ServerCapability.TERMINZ_CANONICAL + "/CodeSystem", Relation = "self"
            });

            if (string.IsNullOrEmpty(contentMode) || contentMode == "not-present")
            {
                csBundle.AddResourceEntry(GetRequest(string.Empty, FhirSnomed.URI, queryParam), FhirSnomed.URI);
                csBundle.AddResourceEntry(GetRequest(string.Empty, FhirLoinc.URI, queryParam), FhirLoinc.URI);
                csBundle.AddResourceEntry(GetRequest(string.Empty, NzMt.URI, queryParam), NzMt.URI);
                csBundle.AddResourceEntry(GetRequest(string.Empty, FhirRxNorm.URI, queryParam), FhirRxNorm.URI);
            }

            if (string.IsNullOrEmpty(contentMode) || contentMode == "complete")
            {
                csBundle.AddResourceEntry(GetRequest("NzEthnicityL1", string.Empty, queryParam), NzEthnicityL1.URI);
                csBundle.AddResourceEntry(GetRequest("NzEthnicityL2", string.Empty, queryParam), NzEthnicityL2.URI);
                csBundle.AddResourceEntry(GetRequest("NzEthnicityL3", string.Empty, queryParam), NzEthnicityL3.URI);
                csBundle.AddResourceEntry(GetRequest("NzEthnicityL4", string.Empty, queryParam), NzEthnicityL4.URI);
                csBundle.AddResourceEntry(GetRequest("NzRegion", string.Empty, queryParam), NzRegion.URI);
                csBundle.AddResourceEntry(GetRequest("bundle-type", string.Empty, queryParam), "http://hl7.org/fhir/bundle-type");
            }

            if (string.IsNullOrEmpty(contentMode) || contentMode == "supplement")
            {
                csBundle.AddResourceEntry(GetRequest("bundle-type-german", string.Empty, queryParam), "http://hl7.org/fhir/bundle-type-de");
            }

            csBundle.Total = csBundle.Entry.Count();

            if (csBundle.Total == 0)
            {
                return(OperationOutcome.ForMessage("No Code Systems match search parameter values.", OperationOutcome.IssueType.NotFound, OperationOutcome.IssueSeverity.Information));
            }

            return(csBundle);
        }
Пример #18
0
 public static void AddEntryToBundle(Bundle b, Resource r)
 {
     b.AddResourceEntry(r, "urn:uuid:" + r.Id);
 }
Пример #19
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Press any key to create Bundle resource for Transaction.....");
            Console.ReadLine();
            Console.WriteLine("Request : ");

            //creating a patient resource model with hard coded values

            var myPatient   = new Patient();
            var patientName = new HumanName();

            patientName.Use     = HumanName.NameUse.Official;
            patientName.Prefix  = new string[] { "Mr" };
            patientName.Given   = new string[] { "John" };
            patientName.Family  = "Doe";
            myPatient.Gender    = AdministrativeGender.Male;
            myPatient.BirthDate = "1991-05-04";
            myPatient.Name      = new List <HumanName>();
            myPatient.Name.Add(patientName);

            var raceExtension = new Extension();

            raceExtension.Url   = "http://hl7api.sourceforge.net/hapi-fhir/res/raceExt.html";
            raceExtension.Value = new Code {
                Value = "WHITE"
            };
            myPatient.Extension.Add(raceExtension);

            //Creating a Encounter resource model with hard coded values

            var myEncounter = new Encounter();

            myEncounter.Text = new Narrative()
            {
                Status = Narrative.NarrativeStatus.Generated, Div = "<div xmlns=\"http://www.w3.org/1999/xhtml\">Encounter with patient @example</div>"
            };
            myEncounter.Status = Encounter.EncounterStatus.InProgress;
            myEncounter.Class  = new Coding()
            {
                System = "http://terminology.hl7.org/CodeSystem/v3-ActCode", Code = "IMP", Display = "inpatient encounter"
            };


            //Updating a Patient resource considering the patient ID already exist on the server
            //If the patient ID is not present kindly select a patient Id already existing on the server else it will give error since we are hard coding it

            var updatePatient = new Patient(); //1354839

            updatePatient.Id = patientId;
            var patientNameUpdate = new HumanName();

            patientNameUpdate.Use    = HumanName.NameUse.Official;
            patientNameUpdate.Prefix = new string[] { "Mr" };
            patientNameUpdate.Given  = new string[] { "Smith" };
            patientNameUpdate.Family = "Carl";
            updatePatient.Name       = new List <HumanName>();
            updatePatient.Name.Add(patientNameUpdate);

            //creating bundle for the transaction
            var bundle = new Bundle();

            bundle.AddResourceEntry(myPatient, "https://hapi.fhir.org/baseDstu3/Patient").Request = new Bundle.RequestComponent {
                Method = Bundle.HTTPVerb.POST, Url = "Patient"
            };
            bundle.AddResourceEntry(myEncounter, "https://hapi.fhir.org/baseDstu3/Encounter").Request = new Bundle.RequestComponent {
                Method = Bundle.HTTPVerb.POST, Url = "Encounter"
            };
            bundle.AddResourceEntry(updatePatient, "https://hapi.fhir.org/baseDstu3/Patient/1354839").Request = new Bundle.RequestComponent {
                Method = Bundle.HTTPVerb.PUT, Url = "Patient/1354839"
            };

            //Create a client to send to the server at a given endpoint.
            var FhirClient = new Hl7.Fhir.Rest.FhirClient(OpenFHIRUrl);

            string requestData = new FhirJsonSerializer().SerializeToString(bundle);

            Console.Write(JValue.Parse(requestData).ToString());

            //sending the Request to the server
            var response = FhirClient.Transaction(bundle);

            Console.WriteLine();
            Console.WriteLine("Press any key to get the response from the server.....");
            Console.ReadLine();
            Console.WriteLine("Response : ");

            string responseData = new FhirJsonSerializer().SerializeToString(response);

            Console.Write(JValue.Parse(responseData).ToString());

            Console.ReadKey();
        }