예제 #1
0
        public ResourceBase DeleteResource(string resourceType, string id)
        {
            this.ThrowIfNotReady();

            try
            {
                // Setup outgoing content/
                RestOperationContext.Current.OutgoingResponse.StatusCode = (int)HttpStatusCode.NoContent;

                // Create or update?
                var handler = FhirResourceHandlerUtil.GetResourceHandler(resourceType);
                if (handler == null)
                {
                    throw new FileNotFoundException(); // endpoint not found!
                }
                var result = handler.Delete(id, TransactionMode.Commit);

                AuditUtil.AuditDataAction <ResourceBase>(EventTypeCodes.Import, ActionType.Delete, AuditableObjectLifecycle.LogicalDeletion, EventIdentifierType.Import, OutcomeIndicator.Success, id, result);
                return(null);
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error deleting FHIR resource {0}({1}): {2}", resourceType, id, e);
                AuditUtil.AuditDataAction <ResourceBase>(EventTypeCodes.Import, ActionType.Delete, AuditableObjectLifecycle.LogicalDeletion, EventIdentifierType.Import, OutcomeIndicator.EpicFail, id);
                throw;
            }
        }
예제 #2
0
        public void TestQueryObservation()
        {
            Resource retrievedResource;
            var      observation = TestUtil.GetFhirMessage("SetupObservation") as Observation;

            observation.Subject = new ResourceReference($"urn:uuid:{this.m_patient.Id}");
            observation.Performer.Add(new ResourceReference($"urn:uuid:{this.m_practitioner.Id}"));

            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                // get the resource handler
                var observationResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Observation);
                var createdObservation         = (Observation)observationResourceHandler.Create(observation, TransactionMode.Commit);

                retrievedResource = observationResourceHandler.Query(new NameValueCollection
                {
                    { "_id", createdObservation.Id }
                });

                //ensure query returns correct result
                Assert.AreEqual(1, ((Bundle)retrievedResource).Entry.Count);
                Assert.IsInstanceOf <Observation>(((Bundle)retrievedResource).Entry.First().Resource);

                var retrievedObservation = ((Bundle)retrievedResource).Entry.First().Resource as Observation;

                var retrievedObservationValue = retrievedObservation.Value as Quantity;

                Assert.AreEqual(22, retrievedObservationValue.Value.Value);
            }
        }
예제 #3
0
        public void TestObservationValueType()
        {
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var observationResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Observation);

                var retrievedObservation = (Observation)observationResourceHandler.Read(this.m_observation.Id, null);

                //ensure the initial Quantity value is set correctly
                var quantityValue = retrievedObservation.Value as Quantity;
                Assert.AreEqual(22, quantityValue.Value.Value);

                //update  observation value to Textual type
                retrievedObservation.Value = new FhirString("test");
                var updatedObservation = observationResourceHandler.Update(retrievedObservation.Id, retrievedObservation, TransactionMode.Commit);

                //ensure the update took place correctly
                retrievedObservation = (Observation)observationResourceHandler.Read(updatedObservation.Id, null);
                var stringValue = retrievedObservation.Value as FhirString;
                Assert.AreEqual("test", stringValue.Value);

                //update  observation value to Codeable type
                retrievedObservation.Value = new CodeableConcept("http://hl7.org/fhir/v3/ObservationInterpretation", "H");
                updatedObservation         = observationResourceHandler.Update(retrievedObservation.Id, retrievedObservation, TransactionMode.Commit);

                //ensure the update took place correctly
                retrievedObservation = (Observation)observationResourceHandler.Read(updatedObservation.Id, null);
                var codeValue = retrievedObservation.Value as CodeableConcept;
                Assert.AreEqual(1, codeValue.Coding.Count);
                Assert.AreEqual("H", codeValue.Coding.First().Code);
            }
        }
        public void Setup()
        {
            // Force load of the DLL
            var p = FbCharset.Ascii;

            TestApplicationContext.TestAssembly = typeof(TestOrganizationResourceHandler).Assembly;
            TestApplicationContext.Initialize(TestContext.CurrentContext.TestDirectory);
            m_serviceManager = ApplicationServiceContext.Current.GetService <IServiceManager>();

            var testConfiguration = new FhirServiceConfigurationSection
            {
                Resources = new List <string>
                {
                    "Immunization",
                    "Patient",
                    "Encounter",
                    "Practitioner"
                },
                MessageHandlers = new List <TypeReferenceConfiguration>
                {
                    new TypeReferenceConfiguration(typeof(ImmunizationResourceHandler))
                }
            };

            using (AuthenticationContext.EnterSystemContext())
            {
                FhirResourceHandlerUtil.Initialize(testConfiguration, m_serviceManager);
                ExtensionUtil.Initialize(testConfiguration);
            }
        }
        public void TestCreateImmunization()
        {
            var patient      = TestUtil.GetFhirMessage("ObservationSubject");
            var encounter    = (Encounter)TestUtil.GetFhirMessage("CreateEncounter-Encounter");
            var immunization = (Immunization)TestUtil.GetFhirMessage("CreateImmunization");

            Resource actualPatient;
            Resource actualEncounter;
            Resource actualImmunization;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", AUTH))
            {
                var patientResourceHandler      = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Patient);
                var encounterResourceHandler    = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Encounter);
                var immunizationResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Immunization);

                actualPatient          = patientResourceHandler.Create(patient, TransactionMode.Commit);
                encounter.Subject      = new ResourceReference($"urn:uuid:{actualPatient.Id}");
                actualEncounter        = encounterResourceHandler.Create(encounter, TransactionMode.Commit);
                immunization.Patient   = new ResourceReference($"urn:uuid:{actualPatient.Id}");
                immunization.Encounter = new ResourceReference($"urn:uuid:{actualEncounter.Id}");
                actualImmunization     = immunizationResourceHandler.Create(immunization, TransactionMode.Commit);
                var retrievedImmunization = (Immunization)immunizationResourceHandler.Read(actualImmunization.Id, null);

                Assert.IsNotNull(retrievedImmunization);
                Assert.AreEqual(retrievedImmunization.Id, actualImmunization.Id);
                Assert.AreEqual(12, retrievedImmunization.DoseQuantity.Value);
            }
        }
        public void TestUpdateLocationInvalidResource()
        {
            var location = TestUtil.GetFhirMessage("UpdateLocation") as Location;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var locationResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Location);

                var actual = locationResourceHandler.Create(location, TransactionMode.Commit);

                Assert.IsNotNull(actual);
                Assert.IsInstanceOf <Location>(actual);

                var createdLocation = (Location)actual;

                Assert.IsNotNull(createdLocation);
                Assert.AreEqual(Location.LocationStatus.Active, createdLocation.Status);
                Assert.AreEqual(Location.LocationMode.Instance, createdLocation.Mode);
                Assert.AreEqual("Ontario", createdLocation.Address.State);

                createdLocation.Status        = Location.LocationStatus.Suspended;
                createdLocation.Mode          = Location.LocationMode.Kind;
                createdLocation.Address.State = "Alberta";

                Assert.Throws <InvalidDataException>(() => locationResourceHandler.Update(createdLocation.Id, new Patient(), TransactionMode.Commit));
            }
        }
        public void TestDeleteLocation()
        {
            var location = TestUtil.GetFhirMessage("CreateLocation") as Location;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var locationResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Location);

                var actual = locationResourceHandler.Create(location, TransactionMode.Commit);

                Assert.IsNotNull(actual);
                Assert.IsInstanceOf <Location>(actual);

                var createdLocation = (Location)actual;

                Assert.IsNotNull(createdLocation);

                var actualDeleted = locationResourceHandler.Delete(createdLocation.Id, TransactionMode.Commit);

                Assert.IsNotNull(actualDeleted);
                Assert.IsInstanceOf <Location>(actualDeleted);

                var deletedLocation = (Location)actualDeleted;

                Assert.IsNotNull(deletedLocation);
                Assert.AreEqual(Location.LocationStatus.Inactive, deletedLocation.Status);
            }
        }
예제 #8
0
        /// <summary>
        /// Rest definition creator
        /// </summary>
        private static RestDefinition CreateRestDefinition()
        {
            // Security settings
            String security = null;

            //var m_masterConfig = ApplicationServiceContext.Current.GetService<IConfigurationManager>().GetSection<RestConfigurationSection>();
            //var authorizationPolicy = m_masterConfig.Services.FirstOrDefault(o => o.Name == "FHIR").Behaviors.Select(o => o.GetCustomAttribute<AuthenticationSchemeDescriptionAttribute>()).FirstOrDefault(o => o != null)?.Scheme;
            if (ApplicationServiceContext.Current.GetService <FhirMessageHandler>().Capabilities.HasFlag(ServiceEndpointCapabilities.BasicAuth))
            {
                security = "Basic";
            }
            if (ApplicationServiceContext.Current.GetService <FhirMessageHandler>().Capabilities.HasFlag(ServiceEndpointCapabilities.BearerAuth))
            {
                security = "OAuth";
            }

            var retVal = new RestDefinition()
            {
                Mode          = "server",
                Documentation = "Default WCF REST Handler",
                Security      = new SecurityDefinition()
                {
                    Cors    = true,
                    Service = security == null ? null : new List <DataTypes.FhirCodeableConcept>()
                    {
                        new DataTypes.FhirCodeableConcept(new Uri("http://hl7.org/fhir/restful-security-service"), security)
                    }
                },
                Resource = FhirResourceHandlerUtil.GetRestDefinition().ToList()
            };

            return(retVal);
        }
예제 #9
0
        public ResourceBase CreateResource(string resourceType, ResourceBase target)
        {
            this.ThrowIfNotReady();
            try
            {
                // Setup outgoing content

                // Create or update?
                var handler = FhirResourceHandlerUtil.GetResourceHandler(resourceType);
                if (handler == null)
                {
                    throw new FileNotFoundException(); // endpoint not found!
                }
                var result = handler.Create(target, TransactionMode.Commit);
                RestOperationContext.Current.OutgoingResponse.StatusCode = (int)HttpStatusCode.Created;


                AuditUtil.AuditDataAction <ResourceBase>(EventTypeCodes.Import, ActionType.Create, AuditableObjectLifecycle.Creation, EventIdentifierType.Import, OutcomeIndicator.Success, null, result);

                String baseUri = MessageUtil.GetBaseUri();
                RestOperationContext.Current.OutgoingResponse.Headers.Add("Content-Location", String.Format("{0}/{1}/{2}/_history/{3}", baseUri, resourceType, result.Id, result.VersionId));
                RestOperationContext.Current.OutgoingResponse.SetLastModified(result.Timestamp);
                RestOperationContext.Current.OutgoingResponse.SetETag($"W/\"{result.VersionId}\"");


                return(result);
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error creating FHIR resource {0}: {1}", resourceType, e);
                AuditUtil.AuditDataAction <ResourceBase>(EventTypeCodes.Import, ActionType.Create, AuditableObjectLifecycle.Creation, EventIdentifierType.Import, OutcomeIndicator.EpicFail, null);
                throw;
            }
        }
예제 #10
0
        /// <summary>
        /// Update a resource
        /// </summary>
        public Resource UpdateResource(string resourceType, string id, Resource target)
        {
            this.ThrowIfNotReady();

            try
            {
                // Setup outgoing content/

                // Create or update?
                var handler = FhirResourceHandlerUtil.GetResourceHandler(resourceType);
                if (handler == null)
                {
                    throw new FileNotFoundException(); // endpoint not found!
                }
                var result = handler.Update(id, target, TransactionMode.Commit);

                this.AuditDataAction(TypeRestfulInteraction.Update, OutcomeIndicator.Success, result);

                String baseUri = MessageUtil.GetBaseUri();
                RestOperationContext.Current.OutgoingResponse.Headers.Add("Content-Location", String.Format("{0}/{1}/_history/{2}", baseUri, result.Id, result.VersionId));
                RestOperationContext.Current.OutgoingResponse.SetLastModified(result.Meta.LastUpdated.Value.DateTime);
                RestOperationContext.Current.OutgoingResponse.SetETag($"W/\"{result.VersionId}\"");

                return(result);
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error updating FHIR resource {0}({1}): {2}", resourceType, id, e);
                this.AuditDataAction(TypeRestfulInteraction.Update, OutcomeIndicator.MinorFail);
                throw;
            }
        }
        public void Setup()
        {
            TestApplicationContext.TestAssembly = typeof(TestRelatedPersonResourceHandler).Assembly;
            TestApplicationContext.Initialize(TestContext.CurrentContext.TestDirectory);
            this.m_serviceManager = ApplicationServiceContext.Current.GetService <IServiceManager>();

            var testConfiguration = new FhirServiceConfigurationSection
            {
                Resources = new List <string>
                {
                    "Patient"
                },
                OperationHandlers = new List <TypeReferenceConfiguration>(),
                ExtensionHandlers = new List <TypeReferenceConfiguration>(),
                ProfileHandlers   = new List <TypeReferenceConfiguration>(),
                MessageHandlers   = new List <TypeReferenceConfiguration>
                {
                    new TypeReferenceConfiguration(typeof(BirthPlaceExtension))
                }
            };

            using (AuthenticationContext.EnterSystemContext())
            {
                FhirResourceHandlerUtil.Initialize(testConfiguration, this.m_serviceManager);
                ExtensionUtil.Initialize(testConfiguration);
            }
        }
        public void TestUpdateMedication()
        {
            var medication = new Medication
            {
                //Code = new CodeableConcept("http://snomed.info/sct", "261000", "Codeine phosphate (substance)", null),
                Id     = Guid.NewGuid().ToString(),
                Status = Medication.MedicationStatusCodes.Active,
                Batch  = new Medication.BatchComponent
                {
                    ExpirationDateElement = new FhirDateTime(2022, 12, 01),
                    LotNumber             = "12345"
                }
            };

            Resource actual;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);

            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var medicationResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Medication);

                Assert.NotNull(medicationResourceHandler);

                actual = medicationResourceHandler.Create(medication, TransactionMode.Commit);
                actual = medicationResourceHandler.Read(actual.Id, actual.VersionId);
            }

            Assert.NotNull(actual);
            Assert.IsInstanceOf <Medication>(actual);

            var actualMedication = (Medication)actual;

            Assert.AreEqual(medication.Id, actualMedication.Id);
            Assert.AreEqual(Medication.MedicationStatusCodes.Active, actualMedication.Status);
            Assert.AreEqual("2022-12-01T00:00:00-05:00", actualMedication.Batch.ExpirationDateElement.Value);
            Assert.AreEqual("12345", actualMedication.Batch.LotNumber);

            actualMedication.Status = Medication.MedicationStatusCodes.EnteredInError;

            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var medicationResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Medication);

                Assert.NotNull(medicationResourceHandler);

                actual = medicationResourceHandler.Update(actualMedication.Id, actualMedication, TransactionMode.Commit);
                actual = medicationResourceHandler.Read(actual.Id, actual.VersionId);
            }

            Assert.NotNull(actual);
            Assert.IsInstanceOf <Medication>(actual);

            actualMedication = (Medication)actual;

            Assert.AreEqual(medication.Id, actualMedication.Id);
            Assert.AreEqual(Medication.MedicationStatusCodes.EnteredInError, actualMedication.Status);
            Assert.AreEqual("2022-12-01T00:00:00-05:00", actualMedication.Batch.ExpirationDateElement.Value);
            Assert.AreEqual("12345", actualMedication.Batch.LotNumber);
        }
예제 #13
0
        public void TestReadPractitioner()
        {
            //load up a practitioner for read test
            var practitioner = TestUtil.GetFhirMessage("ReadPractitioner") as Practitioner;

            Resource result;

            //create and read the same practitioner
            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);

            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                // get the resource handler
                var practitionerResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Practitioner);

                // create the practitioner using the resource handler
                result = practitionerResourceHandler.Create(practitioner, TransactionMode.Commit);

                // retrieve the practitioner using the resource handler
                result = practitionerResourceHandler.Read(result.Id, result.VersionId);
            }

            //assert that the results are correct
            Assert.NotNull(result);
            Assert.IsInstanceOf <Practitioner>(result);

            var actual = (Practitioner)result;

            Assert.AreEqual("Practitioner", actual.Name.Single().Family);
            Assert.AreEqual("Test", actual.Name.Single().Given.Single());
            Assert.IsTrue(actual.Identifier.Any(i => i.Value == "6324"));
        }
        public void TestDeletePatientInvalidGuid()
        {
            var patient = TestUtil.GetFhirMessage("DeletePatient") as Patient;

            Resource result;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                // get the resource handler
                var patientResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Patient);

                // create the patient using the resource handler
                result = patientResourceHandler.Create(patient, TransactionMode.Commit);

                // retrieve the patient using the resource handler
                result = patientResourceHandler.Read(result.Id, result.VersionId);

                Assert.NotNull(result);
                Assert.IsInstanceOf <Patient>(result);

                var actual = (Patient)result;

                Assert.Throws <KeyNotFoundException>(() => patientResourceHandler.Delete(Guid.NewGuid().ToString(), TransactionMode.Commit));
            }
        }
예제 #15
0
        public void TestCreateOrganization()
        {
            // set up the test data
            var      organization = TestUtil.GetFhirMessage("Organization") as Organization;
            Resource result;

            // execute the operation under test
            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var organizationResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Organization);
                result = organizationResourceHandler.Create(organization, TransactionMode.Commit);
                result = organizationResourceHandler.Read(result.Id, result.VersionId);
            }

            // assert create organization successfully
            Assert.NotNull(result);
            Assert.IsInstanceOf <Organization>(result);
            var actual = (Organization)result;

            Assert.AreEqual("Hamilton Health Sciences", actual.Name);
            Assert.IsTrue(actual.Alias.All(c => c == "hhs"));
            Assert.IsTrue(actual.Address.Count == 2);
            Assert.IsTrue(actual.Extension.Any(e => e.Url == "http://santedb.org/extensions/core/detectedIssue"));
            Assert.IsTrue(actual.Identifier.First().Value == "6324");
            Assert.AreEqual("http://santedb.org/fhir/test", actual.Identifier.First().System);
            Assert.IsTrue(actual.Identifier.Count == 1);
        }
예제 #16
0
        public void Setup()
        {
            // Force load of the DLL
            var p = FbCharset.Ascii;

            TestApplicationContext.TestAssembly = typeof(TestRelatedPersonResourceHandler).Assembly;
            TestApplicationContext.Initialize(TestContext.CurrentContext.TestDirectory);
            this.m_serviceManager = ApplicationServiceContext.Current.GetService <IServiceManager>();

            var testConfiguration = new FhirServiceConfigurationSection
            {
                Resources = new List <string>
                {
                    "Encounter",
                    "Bundle",
                    "Patient",
                    "Organization"
                },
                OperationHandlers = new List <TypeReferenceConfiguration>(),
                ExtensionHandlers = new List <TypeReferenceConfiguration>(),
                ProfileHandlers   = new List <TypeReferenceConfiguration>(),
                MessageHandlers   = new List <TypeReferenceConfiguration>
                {
                    new TypeReferenceConfiguration(typeof(EncounterResourceHandler)),
                    new TypeReferenceConfiguration(typeof(BundleResourceHandler)),
                    new TypeReferenceConfiguration(typeof(PatientResourceHandler))
                }
            };

            using (AuthenticationContext.EnterSystemContext())
            {
                FhirResourceHandlerUtil.Initialize(testConfiguration, this.m_serviceManager);
                ExtensionUtil.Initialize(testConfiguration);
            }
        }
        public void Setup()
        {
            TestApplicationContext.TestAssembly = typeof(TestOrganizationResourceHandler).Assembly;
            TestApplicationContext.Initialize(TestContext.CurrentContext.TestDirectory);
            m_serviceManager = ApplicationServiceContext.Current.GetService <IServiceManager>();

            TestApplicationContext.Current.AddBusinessRule <Core.Model.Roles.Patient>(typeof(SamplePatientBusinessRulesService));

            var testConfiguration = new FhirServiceConfigurationSection
            {
                Resources = new List <string>
                {
                    "Patient"
                },

                MessageHandlers = new List <TypeReferenceConfiguration>
                {
                    new TypeReferenceConfiguration(typeof(PatientResourceHandler))
                }
            };

            using (AuthenticationContext.EnterSystemContext())
            {
                FhirResourceHandlerUtil.Initialize(testConfiguration, m_serviceManager);
                ExtensionUtil.Initialize(testConfiguration);
            }
        }
예제 #18
0
        public void TestCreateEncounterStatusEnteredInError()
        {
            var patient = TestUtil.GetFhirMessage("CreateEncounter-Patient") as Patient;

            var encounter = TestUtil.GetFhirMessage("CreateEncounterStatusEnteredInError") as Encounter;

            Resource actualPatient;
            Resource actualEncounter;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", AUTH))
            {
                var patientResourceHandler   = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Patient);
                var encounterResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Encounter);

                actualPatient     = patientResourceHandler.Create(patient, TransactionMode.Commit);
                encounter.Subject = new ResourceReference($"urn:uuid:{actualPatient.Id}");
                actualEncounter   = encounterResourceHandler.Create(encounter, TransactionMode.Commit);
            }

            Assert.IsNotNull(actualPatient);
            Assert.IsNotNull(actualEncounter);

            Assert.IsInstanceOf <Patient>(actualPatient);
            Assert.IsInstanceOf <Encounter>(actualEncounter);

            var createdEncounter = (Encounter)actualEncounter;

            Assert.IsNotNull(createdEncounter.Status);
            Assert.AreEqual(Encounter.EncounterStatus.EnteredInError, createdEncounter.Status);
        }
예제 #19
0
        public void TestDeletePractitioner()
        {
            //load the practitioner for delete
            var practitioner = TestUtil.GetFhirMessage("DeletePractitioner") as Practitioner;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);

            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                // get the resource handler
                var practitionerResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Practitioner);

                // create the practitioner using the resource handler
                var result = practitionerResourceHandler.Create(practitioner, TransactionMode.Commit);

                // retrieve the practitioner using the resource handler
                result = practitionerResourceHandler.Read(result.Id, result.VersionId);

                //ensure practitioner was saved properly
                Assert.NotNull(result);
                Assert.IsInstanceOf <Practitioner>(result);
                var actual = (Practitioner)result;
                Assert.AreEqual("Test", actual.Name.Single().Given.Single());
                Assert.AreEqual("Practitioner", actual.Name.Single().Family);

                //delete practitioner
                result = practitionerResourceHandler.Delete(actual.Id, TransactionMode.Commit);

                actual = (Practitioner)result;

                //ensure read is not successful
                Assert.Throws <KeyNotFoundException>(() => practitionerResourceHandler.Read(actual.Id, null));
            }
        }
        public void TestCreatePatientWithGeneralPractitioner()
        {
            var practitioner = TestUtil.GetFhirMessage("CreatePatientWithGeneralPractitioner-Practitioner") as Practitioner;

            var patient = TestUtil.GetFhirMessage("CreatePatientWithGeneralPractitioner-Patient") as Patient;

            Resource actualPatient;
            Resource actualPractitioner;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var patientResourceHandler      = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Patient);
                var practitionerResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Practitioner);

                actualPractitioner          = practitionerResourceHandler.Create(practitioner, TransactionMode.Commit);
                patient.GeneralPractitioner = new List <ResourceReference>
                {
                    new ResourceReference($"urn:uuid:{actualPractitioner.Id}")
                };
                actualPatient = patientResourceHandler.Create(patient, TransactionMode.Commit);
            }

            Assert.NotNull(actualPatient);
            Assert.NotNull(actualPractitioner);

            Assert.IsInstanceOf <Patient>(actualPatient);
            Assert.IsInstanceOf <Practitioner>(actualPractitioner);

            var createdPatient = (Patient)actualPatient;

            Assert.IsNotNull(createdPatient.GeneralPractitioner.First());
        }
예제 #21
0
        /// <summary>
        /// Get a resource's history
        /// </summary>
        public Bundle GetResourceInstanceHistory(string resourceType, string id)
        {
            this.ThrowIfNotReady();
            // Stuff for auditing and exception handling
            try
            {
                // Get query parameters
                var queryParameters   = RestOperationContext.Current.IncomingRequest.QueryString;
                var resourceProcessor = FhirResourceHandlerUtil.GetResourceHandler(resourceType);

                if (resourceProcessor == null) // Unsupported resource
                {
                    throw new FileNotFoundException("Specified resource type is not found");
                }

                // TODO: Appropriately format response
                // Process incoming request
                var result = resourceProcessor.History(id);
                this.AuditDataAction(TypeRestfulInteraction.HistoryInstance, OutcomeIndicator.Success, result.Entry.Select(o => o.Resource).ToArray());

                // Create the result
                RestOperationContext.Current.OutgoingResponse.SetLastModified(result.Meta.LastUpdated?.DateTime ?? DateTime.Now);
                return(result);
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error getting FHIR resource history {0}({1}): {2}", resourceType, id, e);
                this.AuditDataAction(TypeRestfulInteraction.HistoryInstance, OutcomeIndicator.MinorFail);
                throw;
            }
        }
예제 #22
0
        /// <summary>
        /// Searches a resource from the client registry data store
        /// </summary>
        public Bundle SearchResource(string resourceType)
        {
            this.ThrowIfNotReady();

            try
            {
                // Get query parameters
                var queryParameters   = RestOperationContext.Current.IncomingRequest.Url;
                var resourceProcessor = FhirResourceHandlerUtil.GetResourceHandler(resourceType);

                // Setup outgoing content
                RestOperationContext.Current.OutgoingResponse.SetLastModified(DateTime.Now);

                if (resourceProcessor == null) // Unsupported resource
                {
                    throw new FileNotFoundException();
                }

                // TODO: Appropriately format response
                // Process incoming request
                var result = resourceProcessor.Query(RestOperationContext.Current.IncomingRequest.QueryString);

                this.AuditDataAction(TypeRestfulInteraction.SearchType, OutcomeIndicator.Success, result.Entry.Select(o => o.Resource).ToArray());
                // Create the Atom feed
                return(result);
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error searching FHIR resource {0}: {1}", resourceType, e);
                this.AuditDataAction(TypeRestfulInteraction.SearchType, OutcomeIndicator.MinorFail);
                throw;
            }
        }
예제 #23
0
        /// <summary>
        /// Delete a resource
        /// </summary>
        public Resource DeleteResource(string resourceType, string id)
        {
            this.ThrowIfNotReady();

            try
            {
                // Setup outgoing content/
                RestOperationContext.Current.OutgoingResponse.StatusCode = (int)HttpStatusCode.NoContent;

                // Create or update?
                var handler = FhirResourceHandlerUtil.GetResourceHandler(resourceType);
                if (handler == null)
                {
                    throw new FileNotFoundException(); // endpoint not found!
                }
                var result = handler.Delete(id, TransactionMode.Commit);

                this.AuditDataAction(TypeRestfulInteraction.Delete, OutcomeIndicator.Success, result);
                return(null);
            }
            catch (Exception e)
            {
                this.m_tracer.TraceError("Error deleting FHIR resource {0}({1}): {2}", resourceType, id, e);
                this.AuditDataAction(TypeRestfulInteraction.Delete, OutcomeIndicator.MinorFail);
                throw;
            }
        }
        public void TestRegisterResourceHandler()
        {
            FhirResourceHandlerUtil.RegisterResourceHandler(new DummyResourceHandler());

            Assert.NotNull(FhirResourceHandlerUtil.GetResourceHandler(ResourceType.DomainResource));
            Assert.IsInstanceOf <DummyResourceHandler>(FhirResourceHandlerUtil.GetResourceHandler(ResourceType.DomainResource));
            Assert.IsTrue(FhirResourceHandlerUtil.ResourceHandlers.Any(c => c.GetType() == typeof(DummyResourceHandler)));
        }
        public void TestQueryPatientByGeneralPractitioner()
        {
            var practitioner = TestUtil.GetFhirMessage("CreatePatientWithGeneralPractitioner-Practitioner") as Practitioner;

            var patient = TestUtil.GetFhirMessage("CreatePatientWithGeneralPractitioner-Patient") as Patient;

            Resource actualPatient;
            Resource actualPractitioner;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var patientResourceHandler      = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Patient);
                var practitionerResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Practitioner);

                actualPractitioner          = practitionerResourceHandler.Create(practitioner, TransactionMode.Commit);
                patient.GeneralPractitioner = new List <ResourceReference>
                {
                    new ResourceReference($"urn:uuid:{actualPractitioner.Id}")
                };
                actualPatient = patientResourceHandler.Create(patient, TransactionMode.Commit);
            }

            Assert.NotNull(actualPatient);
            Assert.NotNull(actualPractitioner);

            Assert.IsInstanceOf <Patient>(actualPatient);
            Assert.IsInstanceOf <Practitioner>(actualPractitioner);

            var createdPatient = (Patient)actualPatient;

            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var patientResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Patient);

                var queryResult = patientResourceHandler.Query(new NameValueCollection
                {
                    { "_id", createdPatient.Id },
                    { "_include", "Practitioner:generalPractitioner" }
                });

                Assert.NotNull(queryResult);
                Assert.IsInstanceOf <Bundle>(queryResult);
                Assert.AreEqual(2, queryResult.Entry.Count);

                var queriedPatient       = (Patient)queryResult.Entry.First(c => c.Resource is Patient).Resource;
                var includedPractitioner = (Practitioner)queryResult.Entry.First(c => c.Resource is Practitioner).Resource;

                Assert.IsNotNull(queriedPatient);
                Assert.IsNotNull(includedPractitioner);

                Assert.AreEqual("Jordan", queriedPatient.Name.First().Given.First());
                Assert.AreEqual("Final", queriedPatient.Name.First().Given.ToList()[1]);
                Assert.IsTrue(queriedPatient.Active);
                Assert.AreEqual("905 905 9055", queriedPatient.Telecom.First().Value);
                Assert.AreEqual("123 Main Street", queriedPatient.Address.First().Line.First());
            }
        }
예제 #26
0
        /// <summary>
        /// Searches a resource from the client registry datastore
        /// </summary>
        public Bundle SearchResource(string resourceType)
        {
            this.ThrowIfNotReady();

            // Get the services from the service registry
            var auditService = ApplicationContext.Current.GetService(typeof(IAuditorService)) as IAuditorService;

            // Stuff for auditing and exception handling
            AuditData            audit   = null;
            List <IResultDetail> details = new List <IResultDetail>();
            FhirQueryResult      result  = null;

            try
            {
                // Get query parameters
                var queryParameters   = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;
                var resourceProcessor = FhirResourceHandlerUtil.GetResourceHandler(resourceType);

                // Setup outgoing content
                WebOperationContext.Current.OutgoingRequest.Headers.Add("Last-Modified", DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz"));

                if (resourceProcessor == null) // Unsupported resource
                {
                    throw new FileNotFoundException();
                }

                // TODO: Appropriately format response
                // Process incoming request
                result = resourceProcessor.Query(WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters);

                if (result == null || result.Outcome == ResultCode.Rejected)
                {
                    throw new InvalidDataException("Message was rejected");
                }
                else if (result.Outcome != ResultCode.Accepted)
                {
                    throw new DataException("Query failed");
                }

                audit = AuditUtil.CreateAuditData(result.Results);
                // Create the Atom feed
                return(MessageUtil.CreateBundle(result));
            }
            catch (Exception e)
            {
                audit         = AuditUtil.CreateAuditData(null);
                audit.Outcome = OutcomeIndicator.EpicFail;
                return(this.ErrorHelper(e, result, true) as Bundle);
            }
            finally
            {
                if (auditService != null)
                {
                    auditService.SendAudit(audit);
                }
            }
        }
예제 #27
0
 public void TestCreateInvalidResource()
 {
     TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);
     using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
     {
         var organizationResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Organization);
         Assert.Throws <InvalidDataException>(() => organizationResourceHandler.Create(new Practitioner(), TransactionMode.Commit));
     }
 }
        public void TestQueryPatientByManagingOrganization()
        {
            var patient = TestUtil.GetFhirMessage("CreatePatient") as Patient;

            var patientLink = TestUtil.GetFhirMessage("CreatePatient-PatientLink") as Patient;

            var organization = TestUtil.GetFhirMessage("CreatePatientWithOrganization-Organization") as Organization;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var patientResourceHandler      = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Patient);
                var organizationResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Organization);

                // Create the independent resources for the main Resource.
                var actualOrganization = organizationResourceHandler.Create(organization, TransactionMode.Commit);
                var createdPatientLink = patientResourceHandler.Create(patientLink, TransactionMode.Commit);

                // Connect the independent resources to the dependent resource
                patient.ManagingOrganization = new ResourceReference($"urn:uuid:{actualOrganization.Id}");
                patient.Link.First().Other = new ResourceReference($"urn:uuid:{createdPatientLink.Id}");

                // Create the dependent resource
                var actualPatient = patientResourceHandler.Create(patient, TransactionMode.Commit);

                Assert.IsNotNull(actualPatient);
                Assert.IsInstanceOf <Patient>(actualPatient);

                var createdPatient = (Patient)actualPatient;

                Assert.IsNotNull(patient.ManagingOrganization);

                var queryResult = patientResourceHandler.Query(new NameValueCollection
                {
                    { "_id", createdPatient.Id },
                    { "_include", "Organization:managingOrganization" }
                });

                Assert.NotNull(queryResult);
                Assert.IsInstanceOf <Bundle>(queryResult);
                Assert.AreEqual(2, queryResult.Entry.Count);

                var queriedPatient       = (Patient)queryResult.Entry.First(c => c.Resource is Patient).Resource;
                var includedOrganization = (Organization)queryResult.Entry.First(c => c.Resource is Organization).Resource;

                Assert.IsNotNull(queriedPatient);
                Assert.IsNotNull(includedOrganization);

                Assert.AreEqual("Jordan", queriedPatient.Name.First().Given.First());
                Assert.AreEqual("Webber", queriedPatient.Name.First().Family);
                Assert.AreEqual(AdministrativeGender.Male, queriedPatient.Gender);
                Assert.AreEqual("Hamilton", queriedPatient.Address.First().City);
                Assert.AreEqual("mailto:[email protected]", queriedPatient.Telecom.First().Value);
                Assert.AreEqual("2021-11-23", queriedPatient.BirthDate);
            }
        }
        public void TestDelete()
        {
            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var bundleResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Bundle);

                Assert.Throws <NotSupportedException>(() => bundleResourceHandler.Delete(Guid.NewGuid().ToString(), TransactionMode.Commit));
            }
        }
        public void TestQuery()
        {
            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", this.AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", this.AUTH))
            {
                var bundleResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Bundle);

                Assert.Throws <NotSupportedException>(() => bundleResourceHandler.Query(new NameValueCollection()));
            }
        }