### Setup Patient Resource Example Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/model/patient-example.md.txt Use this example to create a Patient resource with fictional data. It covers setting identifiers, names (official and nickname), gender, birth date, birth place extension, mother's maiden name extension, addresses, and contact components. ```csharp // example Patient setup, fictional data only var pat = new Patient(); var id = new Identifier(); id.System = "http://hl7.org/fhir/sid/us-ssn"; id.Value = "000-12-3456"; pat.Identifier.Add(id); var name = new HumanName().WithGiven("Christopher").WithGiven("C.H.").AndFamily("Parks"); name.Prefix = new string[] { "Mr." }; name.Use = HumanName.NameUse.Official; var nickname = new HumanName(); nickname.Use = HumanName.NameUse.Nickname; nickname.GivenElement.Add(new FhirString("Chris")); pat.Name.Add(name); pat.Name.Add(nickname); pat.Gender = AdministrativeGender.Male; pat.BirthDate = "1983-04-23"; var birthAddress = new Address() { City = "Seattle" }; pat.AddExtension("http://hl7.org/fhir/StructureDefinition/birthPlace", birthAddress); pat.BirthDate = "1983-04-23"; pat.BirthDateElement.AddExtension("http://hl7.org/fhir/StructureDefinition/patient-birthTime", newFhirDateTime(1983, 4, 23, 7, 44)); pat.SetString("http://hl7.org/fhir/StructureDefinition/patient-mothersMaidenName", "Kramer"); var address = new Address() { Line = new string[] { "3300 Washtenaw Avenue, Suite 227" }, City = "Ann Arbor", State = "MI", PostalCode = "48104", Country = "USA" }; pat.Address.Add(address); var contact = new Patient.ContactComponent(); contact.Name = new HumanName(); contact.Name.Given = new string[] { "Susan" }; contact.Name.Family = "Parks"; contact.Gender = AdministrativeGender.Female; contact.Relationship.Add(new CodeableConcept("http://hl7.org/fhir/v2/0131", "N")); contact.Telecom.Add(new ContactPoint(ContactPoint.ContactPointSystem.Phone, null, "")); pat.Contact.Add(contact); pat.Deceased = new FhirBoolean(false); ``` -------------------------------- ### Example JSON Resource Data Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/parsing/isourcenode.md.txt Illustrates the raw instance data for an example Observation resource. ```json { "resourceType": "Observation", "code": { "coding": [ { "code": "7113001", "system": "http://snomed.info/sct" }, { "et" : "cetera" } ] }, "valueQuantity": { "value": "185" } } ``` -------------------------------- ### Using Catch() with a using Statement Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/parsing/errorhandling.md.txt Installs an error callback using the Catch() extension method and uninstalls it upon exiting the using block. This example collects all exceptions encountered during navigation. ```csharp List allExceptions = new List(); var src = FhirXmlNode.Parse("...."); using (src.Catch((_, arg) => allExceptions.Add(arg.Exception))) { // navigate through src, or feed the instance to another // consumer, which will navigate it for you: var poco = src.ToPoco(); } ``` -------------------------------- ### Complete Example with Multiple FHIR Versions Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/model/multiple-fhir-versions.md.txt A full C# example demonstrating the use of `extern alias` and `using` aliases to work with STU3 and R4 versions of FHIR resources within the same file. ```csharp extern alias r4; extern alias stu3; using System; using Hl7.Fhir.Model; using R4 = r4::Hl7.Fhir.Model; using STU3 = stu3::Hl7.Fhir.Model; namespace MultipleVersions { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); var code = new Code(); var patient1 = new STU3.Patient(); var patient2 = new R4.Patient(); } } } ``` -------------------------------- ### ExternalTerminologyService Example Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/validation/terminology-service.rst.txt Demonstrates how to use the ExternalTerminologyService to connect to an external terminology server and expand a ValueSet using the $expand operation. ```APIDOC ## ExternalTerminologyService ### Description Implements all functions of ITerminologyService using a FhirClient to connect to an external terminology server. All functions include a `bool useGet = false` parameter to optionally use the GET REST operation instead of POST. ### Example ```csharp var client = new FhirClient("https://someterminologyserver.org/fhir"); var svc = new ExternalTerminologyService(client); var parameters = new ExpandParameters() .WithValueSet(url: "http://snomed.info/sct?fhir_vs=refset/142321000036106") .WithFilter("met") .WithPaging(count: 10); var result = await svc.Expand(parameters) as ValueSet; ``` ``` -------------------------------- ### Using Standard Resource Resolvers Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/resource-resolving/standard-resolvers.rst.txt Demonstrates how to combine multiple resolvers, including a directory source, a zip source for validation data, and a web resolver, with caching. This setup allows resolving resources from different locations. ```csharp var resolver = new CachedResolver( new MultiResolver( new DirectorySource("path/to/directory"), ZipSource.CreateValidationSource(), new WebResolver())); var resource = resolver.ResolveByUri("http://hl7.org/fhir/StructureDefinition/Patient"); ``` -------------------------------- ### Create FhirPackageSource from Package Server Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/resource-resolving/fhirpackagesource.rst.txt Create a FhirPackageSource by specifying a package server URL and an array of package names with versions. Packages will be installed locally if not found. ```csharp var package1 = "hl7.fhir.r3.core.xml@3.0.2"; var package2 = "hl7.fhir.r3.expansions@3.0.2"; FhirPackageSource resolver = new(ModelInfo.ModelInspector, "https://packages.simplifier.net", new string[] { package1, package 2}); ``` -------------------------------- ### Implement Custom LanguageTerminologyService Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/validation/terminology-service.html Create a custom terminology service by inheriting from CustomValueSetTerminologyService. This example implements language code validation using a regex. ```csharp public class LanguageTerminologyService : CustomValueSetTerminologyService { private const string LANGUAGE_SYSTEM = "urn:ietf:bcp:47"; public const string LANGUAGE_VALUESET = "http://hl7.org/fhir/ValueSet/all-languages"; public LanguageTerminologyService() : base("language", LANGUAGE_SYSTEM, [LANGUAGE_VALUESET]) { } override protected bool ValidateCodeType(string code) { var regex = new Regex("^[a-z]{2}(-[A-Z]{2})?$"); // matches either two lowercase letters OR 2 lowercase letters followed by a dash and two uppercase letters return regex.IsMatch(code); } } ``` -------------------------------- ### Installing FHIR Dialect for ITypedElement Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/fhirpath/dialects.rst.txt Shows how to enable FHIR-specific functions for ITypedElement by installing the FHIR dialect. This is a global setting and may cause issues if different parts of an application require different dialects. ```csharp FhirPathCompiler.DefaultSymbolTable.AddFhirExtensions(); ``` -------------------------------- ### LanguageTerminologyService Example Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/validation/terminology-service.rst.txt An example implementation of a CustomValueSetTerminologyService for validating language codes according to BCP 47. ```APIDOC ## LanguageTerminologyService ### Description Verifies that a code is a valid language code using a custom ValueSet. It implements the `ValidateCodeType` function to match the BCP 47 format. ### Example ```csharp public class LanguageTerminologyService : CustomValueSetTerminologyService { private const string LANGUAGE_SYSTEM = "urn:ietf:bcp:47"; public const string LANGUAGE_VALUESET = "http://hl7.org/fhir/ValueSet/all-languages"; public LanguageTerminologyService() : base("language", LANGUAGE_SYSTEM, [LANGUAGE_VALUESET]) { } override protected bool ValidateCodeType(string code) { var regex = new Regex("^[a-z]{2}(-[A-Z]{2})?$"); // matches either two lowercase letters OR 2 lowercase letters followed by a dash and two uppercase letters return regex.IsMatch(code); } } ``` ``` -------------------------------- ### Expand ValueSet using ExternalTerminologyService Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/validation/terminology-service.rst.txt Connect to an external terminology server to expand a ValueSet. This example demonstrates creating a FhirClient, initializing the ExternalTerminologyService, and constructing an ExpandParameters object to query the server. ```csharp var client = new FhirClient("https://someterminologyserver.org/fhir"); var svc = new ExternalTerminologyService(client); var parameters = new ExpandParameters() .WithValueSet(url: "http://snomed.info/sct?fhir_vs=refset/142321000036106") .WithFilter("met") .WithPaging(count: 10); var result = await svc.Expand(parameters) as ValueSet; ``` -------------------------------- ### Instantiate FhirPathCompiler with SymbolTable Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/fhirpath/invoking-compiler.html Instantiate the FhirPath compiler with a custom SymbolTable to control the installed dialect. Add standard FHIRPath features and extensions as needed. ```csharp var symbolTable = new SymbolTable() .AddStandardFP() .AddFhirExtensions(); var newCompiler = new FhirPathCompiler(symbolTable); ``` -------------------------------- ### Convert ISourceNode to ITypedElement with External Metadata Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/parsing/itypedelement.md.txt This example demonstrates how to convert an ISourceNode into an ITypedElement using an external metadata provider. It initializes an ISourceNode, creates a resource resolver, and then calls ToTypedElement. Finally, it accesses a child element and asserts its type. ```csharp ISourceNode patientNode = ... IResourceResolver zipSource = ZipSource.CreateValidationSource(); ITypedElement patientRootElement = patientNode.ToTypedElement(zipSource); ITypedElement activeElement = patientRootElement.Children("active").First(); Assert.AreEqual("boolean", activeElement.InstanceType); ``` -------------------------------- ### Start FHIRPath Evaluation from Bundle Root Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/fhirpath/best-practices.html Always start FHIRPath evaluations from the root of a Bundle to ensure the `resolve()` function can correctly navigate and find entries or contained resources. Evaluating from nested nodes may prevent the engine from resolving external references. ```csharp Bundle b = new() {...} // The engine has worked from the root of the bundle down, so it knows how to resolve to other entries var active = b.Select("Bundle.entry.ofType(Patient).organization.resolve()"); // The engine was started from the nested Patient node, so does not know how to find other entries. var org = Bundle.entry.OfType[0]; var active2 = org.Select("organization.resolve()"); // This is fine too, since the context is transferred from call to call. var org2 = b.Select("Bundle.entry.ofType(Patient)"); var active3 = org2.Select("organization.resolve()"); ``` -------------------------------- ### Expand ValueSet using ExternalTerminologyService Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/validation/terminology-service.html Connect to an external terminology server and expand a ValueSet using the $expand operation. The `useGet` parameter can be set to true to use HTTP GET instead of POST. ```csharp var client = new FhirClient("https://someterminologyserver.org/fhir"); var svc = new ExternalTerminologyService(client); var parameters = new ExpandParameters() .WithValueSet(url: "http://snomed.info/sct?fhir_vs=refset/142321000036106") .WithFilter("met") .WithPaging(count: 10); var result = await svc.Expand(parameters) as ValueSet; ``` -------------------------------- ### Retrieve ClassMapping instances using ModelInspector Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/model/model-metadata.html Demonstrates how to get a ModelInspector and find ClassMapping instances by FHIR name, .NET type, or canonical URL. Use ModelInfo.ModelInspector or ModelInspector.ForAssembly() to get the inspector. ```csharp var inspector = ModelInfo.ModelInspector; // Equivalent: var inspector = ModelInspector.ForAssembly(typeof(ModelInfo).Assembly); var someDatatypeMapping = inspector.FindClassMapping("HumanName"); var aResourceMapping = inspector.FindClassMapping(typeof(Observation)); var anotherResource = inspector.FindClassMappingByCanonical("http://hl7.org/fhir/StructureDefinition/Procedure"); ``` -------------------------------- ### Instantiate FhirPath Compiler with Custom SymbolTable Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/fhirpath/invoking-compiler.rst.txt Create a FhirPathCompiler instance with a custom SymbolTable to control the installed dialect. This involves adding standard FhirPath features and Fhir extensions. ```csharp var symbolTable = new SymbolTable() .AddStandardFP() .AddFhirExtensions(); var newCompiler = new FhirPathCompiler(symbolTable); ``` -------------------------------- ### Initialize FhirClient with Settings Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/client/setup.html Create a FhirClient instance with custom settings, such as timeout, preferred resource format, conformance check, and return preference. The FhirClientSettings object allows fine-grained control over communication. ```csharp var settings = new FhirClientSettings { Timeout = 0, PreferredFormat = ResourceFormat.Json, VerifyFhirVersion = true, ReturnPreference = ReturnPreference.Minimal }; var client = new FhirClient("http://server.fire.ly", settings) ``` -------------------------------- ### Initialize FhirClient with Server URL Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/client/setup.html Create a new FhirClient instance by passing the FHIR server's endpoint URL to the constructor. This is the basic step before any server interactions. ```csharp var client = new FhirClient("http://server.fire.ly"); ``` -------------------------------- ### Initialize MultiTerminologyService Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/validation/terminology-service.html Combine a local and an external terminology service. The order determines the consultation priority. If a service returns a definitive result, subsequent services are not consulted. ```csharp var local = new LocalTerminologyService(ZipSource.CreateValidationSource()); var client = new FhirClient("https://someterminologyserver.org/fhir"); var multi = new ExternalTerminologyService(client); var multiTermService = new MultiTerminologyService(local, multi); ``` -------------------------------- ### Initialize and Use Validator Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/validation/profile-validation.html Initializes a package resolver, terminology service, and validator. Then, it performs a validation on an Organization resource against its profile. Recommended to reuse validator instances. ```csharp var packageServer = "https://packages.simplifier.net"; var fhirRelease = FhirRelease.STU3; var packageResolver = FhirPackageSource.CreateCorePackageSource(ModelInfo.ModelInspector, fhirRelease, packageServerUrl); var resourceResolver = new CachedResolver(packageResolver); var terminologyService = new LocalTerminologyService(resourceResolver); var validator = new Validator(resourceResolver, terminologyService); var testOrganization = new Organization { }; var profile = Canonical.ForCoreType("Organization").ToString(); var result = validator.Validate(testOrganization, profile); ``` -------------------------------- ### Serialize with Custom Summary Filter Factory Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/parsing/serialization.html Use a custom filter factory to control the summary output, for example, to include only summary elements. ```csharp var json = FhirJsonSerializer.Default.SerializeToString( patient, filterFactory: () => SerializationFilter.ForSummary()); ``` -------------------------------- ### Set %resource and %rootResource using EvaluationContext Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/fhirpath/best-practices.rst.txt Pass a correctly constructed FhirEvaluationContext to ensure environment variables like %resource and %rootResource are properly set. Use ScopedNode for the context's data. ```csharp Patient p = new() {...} var hasName = p.IsTrue("Patient.name.exists()", new FhirEvaluationContext(p.ToScopedNode())); ``` -------------------------------- ### Get History of a Resource Type Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/client/history.md.txt Retrieve the version history for all resources of a specific type. You can optionally filter by date and limit the number of results. ```csharp var pat_hist = await client.TypeHistoryAsync(); ``` -------------------------------- ### Add Hl7.Fhir.R4 NuGet Package Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/getting-started.html Use this command to add the R4 FHIR package to your .NET project. Ensure you have the .NET SDK installed. ```bash dotnet add package Hl7.Fhir.R4 ``` -------------------------------- ### Create a new resource Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/client/crud.md.txt Use `CreateAsync` to create and store a new resource on the server. The call typically throws a `FhirOperationException` on failure. On success, the server returns the stored representation of the resource, including its id and metadata. ```APIDOC ## Create Resource ### Description Creates and stores a new FHIR resource on the server. ### Method `CreateAsync(TResource resource)` ### Parameters #### Request Body - **resource** (TResource) - Required - The FHIR resource to create. ### Request Example ```csharp var patient = new Patient { /* set up data */ }; var createdPatient = await client.CreateAsync(patient); ``` ### Response #### Success Response (200) - **createdResource** (TResource) - The stored representation of the resource, including its id and metadata. #### Error Response - **FhirOperationException** - Thrown on failure, with an `Outcome` property containing an `OperationOutcome` resource. ``` -------------------------------- ### Navigate to Specific Pages Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/client/paging.md.txt Access specific pages of a FHIR Bundle using ContinueAsync with the PageDirection enum. This example shows how to retrieve the last page. ```csharp // go to the last page with the direction filled in: var last_page = await client.ContinueAsync(result, PageDirection.Last); ``` -------------------------------- ### Fluent Initialization of HumanName Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/model/other-features.md.txt Use fluent methods like WithGiven() and AndFamily() to construct a HumanName object in a single statement. This simplifies object creation and leverages IntelliSense for discoverability. ```csharp pat.Name.Add(new HumanName().WithGiven("Christopher").WithGiven("C.H.").AndFamily("Parks")); ``` -------------------------------- ### Chain Authorization and Logging Handlers Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/client/request-response.md.txt Chain multiple HttpMessageHandlers by setting the InnerHandler property. This example chains a LoggingHandler with an AuthorizationMessageHandler to create a request/response processing pipeline. ```csharp var authHandler = new AuthorizationMessageHandler(); var loggingHandler = new LoggingHandler() { InnerHandler = authHandler }; var client = new FhirClient("http://server.fire.ly", FhirClientSettings.CreateDefault(), loggingHandler); ``` -------------------------------- ### Build and Send a Transaction Bundle Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/client/transactions.md.txt Use TransactionBuilder to construct a transaction bundle with create and delete operations, then send it to the server using FhirClient.TransactionAsync. Ensure the FhirClient is initialized with the server's URL. ```csharp var pat = new Patient() { /* set up data */ }; var client = new FhirClient("http://server.fire.ly"); var builder = new TransactionBuilder("http://server.fire.ly", Bundle.BundleType.Transaction); // or Batch // Add a new entry to the bundle including the patient resource that needs to be created. builder.Create(pat); // Add a new entry to the bundle with instructions that Patient with id "1337" needs to be deleted. builder.Delete("Patient", "1337"); // returns the transaction bundle var bundle = builder.ToBundle(); // Send the transaction to the server. var response = await client.TransactionAsync(bundle); ``` -------------------------------- ### Delete FHIR Resource by URL or Identifier Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/client/crud.md.txt Delete a FHIR resource from the server. This example demonstrates deleting a resource using its URL or a string identifier like 'ResourceType/Id'. ```csharp // Delete based on a url or resource location var location = new Uri("http://server.fire.ly/Patient/33"); await client.DeleteAsync(location); // or await client.DeleteAsync("Patient/33"); ``` -------------------------------- ### Resolve Resources and Files by URI, Name, or Path Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/resource-resolving/fps-resolve-artifacts.rst.txt Find resources by their type and ID, or load files by their name or relative filepath using FhirPackageSource. Initialization with package locations is required. ```csharp FhirPackageSource resolver = new(new string[] { package1, package 2}); //find resource by id StructureDefinition pat = await resolver.ResolveByUriAsync("StructureDefinition/Patient") as StructureDefinition; //find file by name Stream file = resolver.LoadArtifactByName("StructureDefinition-Patient.xml"); //find file by path Stream file2 = resolver.LoadArtifactByPath("package/StructureDefinition-Patient.xml"); ``` -------------------------------- ### Custom LanguageTerminologyService Implementation Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/validation/terminology-service.rst.txt Implement a custom terminology service for validating language codes. This example extends CustomValueSetTerminologyService and overrides ValidateCodeType to enforce a specific format for language codes. ```csharp public class LanguageTerminologyService : CustomValueSetTerminologyService { private const string LANGUAGE_SYSTEM = "urn:ietf:bcp:47"; public const string LANGUAGE_VALUESET = "http://hl7.org/fhir/ValueSet/all-languages"; public LanguageTerminologyService() : base("language", LANGUAGE_SYSTEM, [LANGUAGE_VALUESET]) { } override protected bool ValidateCodeType(string code) { var regex = new Regex("^[a-z]{2}(-[A-Z]{2})?$"); // matches either two lowercase letters OR 2 lowercase letters followed by a dash and two uppercase letters return regex.IsMatch(code); } } ``` -------------------------------- ### Concise Dynamic Access with Indexers Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/model/dynamic-features.md.txt Utilize indexers for a more concise syntax that internally calls TryGetValue and SetValue. ```csharp var isActive = patient["active"]?.Value; isActive.Should().Be(patient.Active); ``` -------------------------------- ### Set %resource and %rootResource using FhirEvaluationContext Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/fhirpath/best-practices.html Ensure environment variables like `%resource` and `%rootResource` function correctly by providing a `FhirEvaluationContext` to FHIRPath functions. Construct the context with a `ScopedNode` representing the root of the object being evaluated. ```csharp Patient p = new() {...} var hasName = p.IsTrue("Patient.name.exists()", new FhirEvaluationContext(p.ToScopedNode())); ``` -------------------------------- ### Resolve Resources and Files by URI, Name, or Path Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/resource-resolving/fps-resolve-artifacts.html Find resources by their type and ID using ResolveByUriAsync, or load any file by its name or relative path using LoadArtifactByName and LoadArtifactByPath. These methods are useful for accessing specific artifacts within packages. ```csharp FhirPackageSource resolver = new(new string[] { package1, package 2}); //find resource by id StructureDefinition pat = await resolver.ResolveByUriAsync("StructureDefinition/Patient") as StructureDefinition; //find file by name Stream file = resolver.LoadArtifactByName("StructureDefinition-Patient.xml"); //find file by path Stream file2 = resolver.LoadArtifactByPath("package/StructureDefinition-Patient.xml"); ``` -------------------------------- ### AllowedTypes Attribute Example Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/validation/poco-validation.rst.txt Demonstrates the use of the AllowedTypes attribute to specify valid data types for a 'choice' property. This attribute ensures that the assigned value conforms to one of the specified types. ```csharp [FhirElement("occurrence", InSummary=true, Order=160, Choice=ChoiceType.DatatypeChoice)] [AllowedTypes(typeof(Hl7.Fhir.Model.FhirDateTime),typeof(Hl7.Fhir.Model.Period),typeof(Hl7.Fhir.Model.Timing))] public Hl7.Fhir.Model.DataType Occurrence { } ``` -------------------------------- ### Create a FHIR Bundle with Manual Entry and AddResourceEntry Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/model/bundles.html Demonstrates creating a FHIR Bundle of type 'Collection'. Resources can be added manually by creating 'EntryComponent' instances or using the 'AddResourceEntry' helper method. ```csharp var collection = new Bundle(); collection.Type = Bundle.BundleType.Collection; // Adding the first entry manually var first_entry = new Bundle.EntryComponent(); first_entry.FullUrl = $"{res1.ResourceBase}{res1.ResourceType}{res1.Id}"; first_entry.Resource = res1; collection.Entry.Add(first_entry); // Adding a second entry using AddResourceEntry collection.AddResourceEntry(res2, "urn:uuid:01d04293-ed74-4f93-aa0a-2f096a693fb1"); ``` -------------------------------- ### Ignoring Specific Error Codes Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/parsing/error-handling.md.txt Fine-tune deserialization by ignoring specific error codes on top of a chosen mode. This example shows how to make duplicate properties acceptable within the `Recoverable` mode. ```csharp // Recoverable, but additionally treat duplicate properties as acceptable var settings = new DeserializerSettings() .UsingMode(DeserializationMode.Recoverable) .Ignoring([FhirJsonException.DUPLICATE_PROPERTY_CODE]); ``` -------------------------------- ### Create and Use Serialization Engine Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/parsing/serialization-engine.md.txt Instantiate a recoverable serialization engine and use it to deserialize JSON to a resource and serialize a resource to XML. Requires ModelInfo.ModelInspector. ```csharp var engine = FhirSerializationEngineFactory.Recoverable(ModelInfo.ModelInspector); Resource? patient = engine.DeserializeFromJson(json); string xml = engine.SerializeToXml(patient); ``` -------------------------------- ### Get System-Wide Resource History Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/client/history.md.txt Retrieve the version history for all resources in the FHIR system. You can specify a date to retrieve changes since then and a page size to limit results. Paging through the Bundle is supported. ```csharp var lastMonth = DateTime.Today.AddMonths(-1); var last_month_hist = await client.WholeSystemHistoryAsync(since: lastMonth, pageSize: 10); ``` -------------------------------- ### Get History of a Specific Resource Instance Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/client/history.md.txt Retrieve the version history for a specific FHIR resource instance. You can optionally filter by date and limit the number of results. The result is a Bundle containing the history. ```csharp var pat_31_hist = await client.HistoryAsync("Patient/31"); ``` ```csharp var pat_31_hist = await client.HistoryAsync("Patient/31", new FhirDateTime("2016-11-29").ToDateTimeOffset()); ``` ```csharp var pat_31_hist = await client.HistoryAsync("Patient/31", new FhirDateTime("2016-11-29").ToDateTimeOffset(), 5); ``` -------------------------------- ### Retrieve History of a Specific Resource - Firely .NET SDK Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/client/history.html Use `HistoryAsync` to get the version history of a specific resource. You can optionally filter by date and limit the number of results. The result is a `Bundle` containing the history. ```csharp var pat_31_hist = await client.HistoryAsync("Patient/31"); ``` ```csharp // or var pat_31_hist = await client.HistoryAsync("Patient/31", new FhirDateTime("2016-11-29").ToDateTimeOffset()); ``` ```csharp // or var pat_31_hist = await client.HistoryAsync("Patient/31", new FhirDateTime("2016-11-29").ToDateTimeOffset(), 5); ``` -------------------------------- ### Combine Multiple Resolvers with Caching Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/resource-resolving/standard-resolvers.html Use this snippet to create a resolver that caches results from a combination of directory, zip, and web sources. Ensure the 'path/to/directory' is valid. ```csharp var resolver = new CachedResolver( new MultiResolver( new DirectorySource("path/to/directory"), ZipSource.CreateValidationSource(), new WebResolver())); var resource = resolver.ResolveByUri("http://hl7.org/fhir/StructureDefinition/Patient"); ``` -------------------------------- ### Configure FhirClient with Settings Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/client/setup.md.txt Initialize a FhirClient with custom settings, such as timeout, preferred resource format, conformance check, and return preference. The FhirClientSettings object allows fine-grained control over communication. ```csharp var settings = new FhirClientSettings { Timeout = 0, PreferredFormat = ResourceFormat.Json, VerifyFhirVersion = true, ReturnPreference = ReturnPreference.Minimal }; var client = new FhirClient("http://server.fire.ly", settings) ``` -------------------------------- ### Using FHIR-Specific Functions with POCOs Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/fhirpath/dialects.rst.txt Demonstrates how FHIR-specific functions are available when working with POCOs (Plain Old CLR Objects) generated for FHIR. FHIR-specific functions are not available when using ITypedElement without installing the FHIR dialect. ```csharp Base fhirData = new FhirString("hello!"); Assert.IsTrue(fhirData.IsTrue("hasValue()")); // FHIR specific functions do not work via the ITypedElement extension methods ITypedElement data = ElementNode.ForPrimitive("hello!"); Assert.ThrowsException(() => data.IsTrue("hasValue()")); ``` -------------------------------- ### Create FhirClient Instance Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/client/setup.md.txt Instantiate a FhirClient by providing the FHIR server's endpoint URL. The client is not thread-safe and requires a new instance per thread if used concurrently. ```csharp var client = new FhirClient("http://server.fire.ly"); ``` -------------------------------- ### Evaluate FhirPath from Bundle Root Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/fhirpath/best-practices.rst.txt Always start FhirPath evaluation from the root of a Bundle to ensure the 'resolve()' function can correctly access contained or referenced resources. Evaluating from nested nodes may prevent proper resolution. ```csharp Bundle b = new() {...} // The engine has worked from the root of the bundle down, so it knows how to resolve to other entries var active = b.Select("Bundle.entry.ofType(Patient).organization.resolve()"); // The engine was started from the nested Patient node, so does not know how to find other entries. var org = Bundle.entry.OfType[0]; var active2 = org.Select("organization.resolve()"); // This is fine too, since the context is transferred from call to call. var org2 = b.Select("Bundle.entry.ofType(Patient)"); var active3 = org2.Select("organization.resolve()"); ``` -------------------------------- ### Handling Version-Specific Primitive Types in Shared Data Types Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/model/datatypes.html When working with shared data types that have version-specific primitive elements (like 'size' in Attachment), assign the appropriate type based on the FHIR version. IntelliSense will guide you. ```csharp var att = new Attachment(); att.SizeElement = new Integer64(); // in R5 att.SizeElement = new UnsignedInt(); // in STU3 att.SizeElement = new FhirBoolean(); // incorrect ``` -------------------------------- ### Concise Error Catching with VisitAndCatch() Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/parsing/errorhandling.md.txt A more concise way to visit all nodes and collect errors using the VisitAndCatch() method. ```csharp List errors = src.VisitAndCatch(); ``` -------------------------------- ### Combining Helper and Element Properties Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/model/datatypes.html You can set the helper property first and then add extensions to the automatically created Element property. ```csharp pat.Active = true; pat.ActiveElement.Extensions.Add(...); ``` -------------------------------- ### Using JsonValue for Primitive Data Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/model/dynamic-features.md.txt The JsonValue property on primitive datatypes like FhirString allows getting or setting the raw JSON value. This is particularly useful when dealing with invalid primitive data that cannot be directly represented by the .NET type. ```csharp var fhirString = new FhirString(); fhirString.JsonValue = true; var invalidCode = new Code(); invalidCode.JsonValue = "fmale"; ``` -------------------------------- ### Use Format Parameter for Preferred Format Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/client/setup.html Enable the use of the `_format` URL parameter instead of the `Accept` HTTP header to specify the preferred resource format. This can be useful for specific server configurations. ```csharp client.Settings.UseFormatParameter = true; ``` -------------------------------- ### Custom Equality Comparer for FHIR Base Types Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/model/equality-and-cloning.md.txt Implement custom equality logic for FHIR model instances by creating a comparer that adheres to .NET's `IEqualityComparer` and `IEqualityComparer>`. This example shows how to delegate recursive comparison to `CompareChildren`. ```csharp public class MyCustomEqualityComparer : IEqualityComparer, IEqualityComparer> { public bool Equals(Base? x, Base? y) { if (ReferenceEquals(x, y)) return true; if (x is null || y is null) return false; if (x.GetType() != y.GetType()) return false; return x.CompareChildren(y, this); } public int GetHashCode(Base obj) => obj.GetHashCode(); public bool Equals(IReadOnlyCollection? x, IReadOnlyCollection? y) { // Implement collection equality comparison throw new NotImplementedException(); } public int GetHashCode(IReadOnlyCollection obj) { // Implement a suitable hash code calculation for collections throw new NotImplementedException(); } } ``` -------------------------------- ### Serialize POCO to Different Output Formats Source: https://docs.fire.ly/projects/Firely-NET-SDK/en/latest/_sources/parsing/serialization.md.txt Demonstrates serializing a POCO to a string, UTF-8 byte array, JObject document, or directly to a writer. ```csharp string json = FhirJsonSerializer.Default.SerializeToString(patient); byte[] utf8 = FhirJsonSerializer.Default.SerializeToBytes(patient); JObject doc = FhirJsonSerializer.Default.SerializeToDocument(patient); FhirJsonSerializer.Default.Serialize(patient, utf8JsonWriter); ```