Search

Sample code

C# code examples

The code snippets below show how to read FHIR bundles, send patient data and medical information. To start using the FHIR API, the API first has to be added to your project. This can be done with the NuGet package manager. The following packages have to be added:

  • Hl7.Fhir.Support
  • Hl7.Fhir.STU3
  • Hl7.FhirPath

Read FHIR bundle

To run the code below, an example FHIR bundle stored as JSON file is required. To generate a bundle you can use the FHIR document generator.
The generated bundle can be parsed using the function described below. This provides an accessible method of further processing the information provided by the bundle. Some examples are provided for retrieving specific information from a bundle.

using System;
using System.Linq;
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using System.IO;


namespace FhirBundleReader
{
    static class Program
    {
        static void ReadBundle()
        {
            // Read Document-Bundle in JSON-format
            var parser = new FhirJsonParser();

            // Edit path to json-file on filesystem. Generating this file can be done at: https://tio.zorgdomein.nl/fhir/tools/document.html

            StreamReader reader = new StreamReader(@"FILE PATH/file.json");
            string json = reader.ReadToEnd();
            var document = parser.Parse<Bundle>(json);

            var composition = (Composition)document.Entry[0].Resource;

            // Get author
            var authorref = composition.Author.First();
            Practitioner author = (Practitioner)document.FindEntry(authorref).First().Resource;

            // Get attachment, save the bytes of the pdf to data
            ResourceReference pdfref =
                composition.GetExtensionValue<ResourceReference>("http://zorgdomein.nl/fhir/StructureDefinition/zd-pdfDocument");
            var attachment = (DocumentReference)document.FindEntry(pdfref).First().Resource;
            var data = attachment.Content.First().Attachment.Data;

            // Write pdf-attachment to filesystem. Add a file path.
            System.IO.File.WriteAllBytes("FILE PATH/document.pdf", data);

            // Get destination
            ResourceReference destinationref =
                composition.GetExtensionValue<ResourceReference>("http://zorgdomein.nl/fhir/StructureDefinition/zd-destination");
            var destination = (PractitionerRole)document.FindEntry(destinationref).First().Resource;
            var destinationOrg = (Organization)document.FindEntry(destination.Organization).First().Resource;

            Console.WriteLine("Identifier of Organization in destination: " + destinationOrg.Identifier);


            // Get subject
            var patient = (Patient)document.FindEntry(composition.Subject).First().Resource;

            Console.WriteLine("Bsn is: " + patient.Identifier.Find(id => id.System.Equals("http://fhir.nl/fhir/NamingSystem/bsn")).Value);
            Console.WriteLine("Patient name is: " + patient.Name.First());

            // Data retrieval examples
            Console.WriteLine("Attachment type is: " + attachment.Content.First().Attachment.ContentType);
            Console.WriteLine("Document ID is: " + document.Id);
            Console.WriteLine("Author name is: " + author.Name.First());

            // Write data as XML
            Console.WriteLine(System.Xml.Linq.XElement.Parse(FhirSerializer.SerializeToXml(document)).ToString());
        }


        [STAThread]
        static void Main()
        {
            ReadBundle();

        }
    }
}

Write patient

This code snippet demonstrates how to create a resource containing patient data.

using System;
using System.Linq;
using System.Text;
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using System.Xml.Linq;
using System.Xml;



namespace FhirBundleReader
{
    static class Program
    {
        static string XMLparser(string xml)
        {
            var stringBuilder = new StringBuilder();

            var element = XElement.Parse(xml);

            var settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            settings.Indent = true;
            settings.NewLineOnAttributes = false;

            using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
            {
                element.Save(xmlWriter);
            }

            return stringBuilder.ToString();
        }

        static void WritePatient()
        {
            Patient patient = new Patient();

            patient.Meta = new Meta();
            patient.Meta.ProfileElement.Add(new FhirUri("http://zorgdomein.nl/fhir/StructureDefinition/zd-patient"));
            patient.BirthDate = "1970-01-31";

            patient.Identifier.Add(new Identifier()
            {
                Use = Identifier.IdentifierUse.Official,
                System = "http://fhir.nl/fhir/NamingSystem/bsn",
                Value = "123456782"
            });

            var name = new HumanName().WithGiven("A").AndFamily("de Vries-van Dijk");
            name.GivenElement[0].AddExtension("http://hl7.org/fhir/StructureDefinition/iso21090-EN-qualifier", new Code("IN"));

            name.FamilyElement.AddExtension("http://hl7.org/fhir/StructureDefinition/humanname-partner-prefix", new FhirString("de"));
            name.FamilyElement.AddExtension("http://hl7.org/fhir/StructureDefinition/humanname-partner-name", new FhirString("Vries"));
            name.FamilyElement.AddExtension("http://hl7.org/fhir/StructureDefinition/humanname-own-prefix", new FhirString("van"));
            name.FamilyElement.AddExtension("http://hl7.org/fhir/StructureDefinition/humanname-own-name", new FhirString("Dijk"));
            name.AddExtension("http://hl7.org/fhir/StructureDefinition/humanname-assembly-order", new Code("NL3"));

            patient.Name.Add(name);

            patient.AddExtension("http://fhir.nl/fhir/StructureDefinition/nl-core-preferred-pharmacy", new ResourceReference("Organization/apotheek-1", "Apotheker Breukelen"));

            var address = new Address()
            {
                Line = new string[] { "Straatweg 68" },
                City = "Breukelen",
                PostalCode = "3621BR"

            };

            // Value from required binding AddressUse
            address.Use = Address.AddressUse.Home;

            // Because line is a repeatable element, first specify on which line you want to apply the extensions. 
            // In this case we use the first (and only) LineElement to apply the extension.   
            address.LineElement.First().
                   AddExtension("http://hl7.org/fhir/StructureDefinition/iso21090-ADXP-streetName", new FhirString("Straatweg"));

            address.LineElement.First().
                   AddExtension("http://hl7.org/fhir/StructureDefinition/iso21090-ADXP-houseNumber", new FhirString("68"));

            var serializer = new FhirXmlSerializer();
            Console.WriteLine(XMLparser(serializer.SerializeToString(patient)));
        }



        [STAThread]
        static void Main()
        {
            WritePatient();

        }
    }
}

Write observation

The code below gives an example of how to create a resource containing observations.

using System;
using System.Text;
using Hl7.Fhir.Model;
using Hl7.Fhir.Serialization;
using System.Xml.Linq;
using System.Xml;



namespace FhirBundleReader
{
    static class Program
    {
        static string XMLparser(string xml)
        {
            var stringBuilder = new StringBuilder();

            var element = XElement.Parse(xml);

            var settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            settings.Indent = true;
            settings.NewLineOnAttributes = false;

            using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
            {
                element.Save(xmlWriter);
            }

            return stringBuilder.ToString();
        }

        static void WriteObservation()
        {
            Observation observation = new Observation();
            observation.Meta = new Meta();
            observation.Meta.ProfileElement.Add(new FhirUri("http://zorgdomein.nl/fhir/StructureDefinition/zd-observation"));
            observation.Status = ObservationStatus.Final;
            observation.Code = new CodeableConcept("http://zorgdomein.nl/fhir/ValueSet/observation-codes/", "anamnesis", "Anamnese");
            observation.Subject = new ResourceReference("Patient/zd-patient-1", "Test Patient");
            observation.Context = new ResourceReference("Encounter/encounter1");
            observation.Performer.Add(new ResourceReference("Practitioner/zd-practioner-1", "Test Dokter"));
            observation.Value = new CodeableConcept(
                "",
                "",
                "ca 15 jaar geleden knie verdraaid met sporten. Sindsdien ca 2x per jaar klachten van linker knie. Nu ook weer heeft met lopen knie verdraaid. In het verleden wel fysiotherapie gehad, toen weinig baat van gehad.");
            var serializer = new FhirXmlSerializer();
            Console.WriteLine(XMLparser(serializer.SerializeToString(observation)));

        }




        [STAThread]
        static void Main()
        {
            WriteObservation();
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();


        }
    }
}

Other programming languages

Currently there are no code examples available for other programming languages than C#. If you are interested in code examples for a different programming language, please contact us so that we can notify you when new examples are available.