public async Task GivenAResource_WhenUpserting_ThenTheNewResourceHasMetaSet() { var instant = new DateTimeOffset(DateTimeOffset.Now.Date, TimeSpan.Zero); using (Mock.Property(() => ClockResolver.UtcNowFunc, () => instant)) { var versionId = Guid.NewGuid().ToString(); var resource = Samples.GetJsonSample("Weight").UpdateVersion(versionId); var saveResult = await Mediator.UpsertResourceAsync(resource); Assert.NotNull(saveResult); Assert.Equal(SaveOutcomeType.Created, saveResult.Outcome); var deserializedResource = saveResult.RawResourceElement.ToResourceElement(Deserializers.ResourceDeserializer); Assert.NotNull(deserializedResource); var wrapper = await _fixture.DataStore.GetAsync(new ResourceKey("Observation", deserializedResource.Id), CancellationToken.None); Assert.NotNull(wrapper); Assert.True(wrapper.RawResource.IsMetaSet); Assert.NotEqual(wrapper.Version, versionId); var deserialized = _fhirJsonParser.Parse <Observation>(wrapper.RawResource.Data); Assert.NotEqual(versionId, deserialized.VersionId); } }
public HttpResponseMessage GetHistory(string resource, string id, string vid) { HttpResponseMessage response; var respval = ""; var item = storage.HistoryStore.GetResourceHistoryItem(resource, id, vid); if (item != null) { var retVal = (Resource)jsonparser.Parse(item, FhirHelper.ResourceTypeFromString(resource)); if (retVal != null) { respval = SerializeResponse(retVal); } response = Request.CreateResponse(HttpStatusCode.OK); response.Headers.TryAddWithoutValidation("Accept", CurrentAcceptType); response.Headers.Add("ETag", "W/\"" + retVal.Meta.VersionId + "\""); response.Content = new StringContent(respval, Encoding.UTF8); response.Content.Headers.LastModified = retVal.Meta.LastUpdated; } else { response = Request.CreateResponse(HttpStatusCode.NotFound); response.Content = new StringContent("", Encoding.UTF8); } response.Content.Headers.TryAddWithoutValidation("Content-Type", IsAccceptTypeJson ? Fhircontenttypejson : Fhircontenttypexml); return(response); }
public void EdgecaseRoundtrip() { string json = TestDataHelper.ReadTestData("json-edge-cases.json"); var tempPath = Path.GetTempPath(); var poco = FhirJsonParser.Parse <Resource>(json); Assert.IsNotNull(poco); var xml = FhirXmlSerializer.SerializeToString(poco); Assert.IsNotNull(xml); File.WriteAllText(Path.Combine(tempPath, "edgecase.xml"), xml); poco = FhirXmlParser.Parse <Resource>(xml); Assert.IsNotNull(poco); var json2 = FhirJsonSerializer.SerializeToString(poco); Assert.IsNotNull(json2); File.WriteAllText(Path.Combine(tempPath, "edgecase.json"), json2); List <string> errors = new List <string>(); JsonAssert.AreSame("edgecase.json", json, json2, errors); Console.WriteLine(String.Join("\r\n", errors)); Assert.AreEqual(0, errors.Count, "Errors were encountered comparing converted content"); }
public async Task GivenASavedResource_WhenUpsertIsAnUpdate_ThenTheExistingResourceIsUpdated() { var saveResult = await Mediator.UpsertResourceAsync(Samples.GetJsonSample("Weight")); var newResourceValues = Samples.GetJsonSample("WeightInGrams").ToPoco(); newResourceValues.Id = saveResult.RawResourceElement.Id; var updateResult = await Mediator.UpsertResourceAsync(newResourceValues.ToResourceElement(), WeakETag.FromVersionId(saveResult.RawResourceElement.VersionId)); var deserializedResource = updateResult.RawResourceElement.ToResourceElement(Deserializers.ResourceDeserializer); Assert.NotNull(deserializedResource); Assert.Equal(SaveOutcomeType.Updated, updateResult.Outcome); var wrapper = await _fixture.DataStore.GetAsync(new ResourceKey("Observation", deserializedResource.Id), CancellationToken.None); Assert.NotNull(wrapper); if (wrapper.RawResource.IsMetaSet) { Observation observation = _fhirJsonParser.Parse <Observation>(wrapper.RawResource.Data); Assert.Equal("2", observation.VersionId); } }
public void GivenEmptyElement_WhenCheckIFEmptyElement_ResultShouldBeTrue(string file) { var json = File.ReadAllText(Path.Join("TestResources", file)); var element = _parser.Parse <Resource>(json).ToTypedElement(); Assert.True(EmptyElement.IsEmptyElement(element)); Assert.True(EmptyElement.IsEmptyElement((object)element)); }
public FhirStorageTests(FhirStorageTestsFixture fixture) { _fixture = fixture; _searchService = Substitute.For <ISearchService>(); _dataStore = fixture.DataStore; _conformance = CapabilityStatementMock.GetMockedCapabilityStatement(); CapabilityStatementMock.SetupMockResource(_conformance, ResourceType.Observation, null); var observationResource = _conformance.Rest[0].Resource.Find(r => r.Type == ResourceType.Observation); observationResource.UpdateCreate = true; observationResource.Versioning = CapabilityStatement.ResourceVersionPolicy.Versioned; CapabilityStatementMock.SetupMockResource(_conformance, ResourceType.Organization, null); var organizationResource = _conformance.Rest[0].Resource.Find(r => r.Type == ResourceType.Organization); organizationResource.UpdateCreate = true; organizationResource.Versioning = CapabilityStatement.ResourceVersionPolicy.NoVersion; var provider = Substitute.For <ConformanceProviderBase>(); provider.GetCapabilityStatementAsync().Returns(_conformance.ToTypedElement().ToResourceElement()); // TODO: FhirRepository instantiate ResourceDeserializer class directly // which will try to deserialize the raw resource. We should mock it as well. var rawResourceFactory = Substitute.For <RawResourceFactory>(new FhirJsonSerializer()); var resourceWrapperFactory = Substitute.For <IResourceWrapperFactory>(); resourceWrapperFactory .Create(Arg.Any <ResourceElement>(), Arg.Any <bool>(), Arg.Any <bool>()) .Returns(x => { ResourceElement resource = x.ArgAt <ResourceElement>(0); return(new ResourceWrapper(resource, rawResourceFactory.Create(resource, keepMeta: true), new ResourceRequest(HttpMethod.Post, "http://fhir"), x.ArgAt <bool>(1), null, null, null)); }); var collection = new ServiceCollection(); var resourceIdProvider = new ResourceIdProvider(); _searchParameterUtilities = Substitute.For <ISearchParameterUtilities>(); collection.AddSingleton(typeof(IRequestHandler <CreateResourceRequest, UpsertResourceResponse>), new CreateResourceHandler(_dataStore, new Lazy <IConformanceProvider>(() => provider), resourceWrapperFactory, resourceIdProvider, new ResourceReferenceResolver(_searchService, new TestQueryStringParser()), DisabledFhirAuthorizationService.Instance, _searchParameterUtilities)); collection.AddSingleton(typeof(IRequestHandler <UpsertResourceRequest, UpsertResourceResponse>), new UpsertResourceHandler(_dataStore, new Lazy <IConformanceProvider>(() => provider), resourceWrapperFactory, resourceIdProvider, DisabledFhirAuthorizationService.Instance, ModelInfoProvider.Instance)); collection.AddSingleton(typeof(IRequestHandler <GetResourceRequest, GetResourceResponse>), new GetResourceHandler(_dataStore, new Lazy <IConformanceProvider>(() => provider), resourceWrapperFactory, resourceIdProvider, DisabledFhirAuthorizationService.Instance)); collection.AddSingleton(typeof(IRequestHandler <DeleteResourceRequest, DeleteResourceResponse>), new DeleteResourceHandler(_dataStore, new Lazy <IConformanceProvider>(() => provider), resourceWrapperFactory, resourceIdProvider, DisabledFhirAuthorizationService.Instance)); ServiceProvider services = collection.BuildServiceProvider(); Mediator = new Mediator(type => services.GetService(type)); _deserializer = new ResourceDeserializer( (FhirResourceFormat.Json, new Func <string, string, DateTimeOffset, ResourceElement>((str, version, lastUpdated) => _fhirJsonParser.Parse(str).ToResourceElement()))); }
public SearchPatientViewModel GetPatientDetails(string patientMRN) { //this.patientMRN = patientId; SearchPatientViewModel vm = new SearchPatientViewModel(); try { SearchParams parms = new SearchParams(); var resourceLink = string.Format("{0}|{1}", "www.citiustech.com", patientMRN); parms.Add("identifier", resourceLink); //Reading the Patient details using the FHIR Client var patientDetailsRead = FhirClient.Search <Patient>(parms); //Serializing the data to json string string patientDetails = fhirJsonSerializer.SerializeToString(patientDetailsRead); //deserializing the json string to patient model Bundle result = (Bundle)fhirJsonParser.Parse(patientDetails, typeof(Bundle)); vm.patient = result.Entry.Select(Resource => (Patient)Resource.Resource).ToList().FirstOrDefault(); LabService labService = new LabService(); if (vm.patient != null) { var labResults = labService.GetLabResultsByPatientId(vm.patient.Id); var labRequests = labService.GetLabResultsByPatientId(vm.patient.Id); vm.LabRequestRawJsonData = JValue.Parse(fhirJsonSerializer.SerializeToString(labResults)).ToString(); vm.LabResultRawJsonData = JValue.Parse(fhirJsonSerializer.SerializeToString(labRequests)).ToString(); } //Displaying the RAW json data in the view vm.ResourceRawJsonData = JValue.Parse(patientDetails).ToString(); } catch (FhirOperationException FhirOpExec) { var response = FhirOpExec.Outcome; var errorDetails = fhirJsonSerializer.SerializeToString(response); OperationOutcome error = (OperationOutcome)fhirJsonParser.Parse(errorDetails, typeof(OperationOutcome)); vm.ResourceRawJsonData = JValue.Parse(errorDetails).ToString(); } catch (WebException ex) { var response = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd(); var error = JsonConvert.DeserializeObject(response); vm.ResourceRawJsonData = error.ToString(); } return(vm); }
public void GivenAnInvalidBundleEntry_WhenValidateAResource_ThenValidationErrorsShouldBeReturned() { var bundle = _parser.Parse <Bundle>(File.ReadAllText("./TestResources/bundle-basic.json")); var validationErrors = _validator.Validate(bundle).ToList(); Assert.Empty(validationErrors); var observationEntry = bundle.FindEntry("http://example.org/fhir/Observation/123").FirstOrDefault().Resource as Observation; observationEntry.Status = null; validationErrors = _validator.Validate(bundle).ToList(); Assert.Single(validationErrors); }
public FHIRViewModel GetResourceDetails(string patientId, string resouceInfo) { this.patientId = patientId; this.resouceInfo = resouceInfo; FHIRViewModel vm = new FHIRViewModel(); switch (resouceInfo) { case "PatientInfo": //Patient Details vm.patientDataJson = GetData(OpenFHIRUrl + "/Patient/" + patientId); vm.patient = (Patient)fhirJsonParser.Parse(vm.patientDataJson, typeof(Patient)); vm.ResourceRawJsonData = JValue.Parse(vm.patientDataJson).ToString(); break; case "EncounterInfo": //Patient Encounter Details vm.patientEncounterBundle = GetData(OpenFHIRUrl + "/Encounter?patient=" + patientId); Bundle encounterBundle = (Bundle)fhirJsonParser.Parse(vm.patientEncounterBundle, typeof(Bundle)); vm.encounters = encounterBundle.Entry.Select(Resource => (Encounter)Resource.Resource).ToList(); vm.ResourceRawJsonData = JValue.Parse(vm.patientEncounterBundle).ToString(); break; case "MedicationInfo": //Patient Medication Details vm.patientMedBundle = GetData(OpenFHIRUrl + "/MedicationRequest?patient=" + patientId + "&status=active"); Bundle medicationOrderBundle = (Bundle)fhirJsonParser.Parse(vm.patientMedBundle, typeof(Bundle)); vm.medicationOrders = medicationOrderBundle.Entry.Select(Resource => (MedicationRequest)Resource.Resource).ToList(); vm.ResourceRawJsonData = JValue.Parse(vm.patientMedBundle).ToString(); break; case "ConditionInfo": //Patient condition Details vm.patientConditionsBundle = GetData(OpenFHIRUrl + "/Condition?patient=" + patientId); Bundle conditionBundle = (Bundle)fhirJsonParser.Parse(vm.patientConditionsBundle, typeof(Bundle)); vm.conditions = conditionBundle.Entry.Select(Resource => (Condition)Resource.Resource).ToList(); vm.ResourceRawJsonData = JValue.Parse(vm.patientConditionsBundle).ToString(); break; case "ObservationInfo": //Patient observation Details vm.patientObservationBundle = GetData(OpenFHIRUrl + "/Observation?patient=" + patientId); Bundle observationBundle = (Bundle)fhirJsonParser.Parse(vm.patientObservationBundle, typeof(Bundle)); vm.observations = observationBundle.Entry.Select(Resource => (Observation)Resource.Resource).ToList(); vm.ResourceRawJsonData = JValue.Parse(vm.patientObservationBundle).ToString(); break; } return(vm); }
public void WhenFhirCdaTransformedToHealthVault_ThenValuesEqual() { var json = SampleUtil.GetSampleContent("FhirCDA.json"); var fhirParser = new FhirJsonParser(); var documentReference = fhirParser.Parse <DocumentReference>(json); string fhirAttachmentDataBase64Encoded = JObject.Parse(json)["content"][0]["attachment"]["data"].ToString(); string fhirXmlRaw = Encoding.UTF8.GetString(Convert.FromBase64String(fhirAttachmentDataBase64Encoded)); XPathDocument fhirXPathDoc = DocumentReferenceHelper.GetXPathDocumentFromXml(fhirXmlRaw) ?? throw new Exception("Invalid XML"); // XML gets generated using a common method in order to use in Assert.AreEqual string fhirXml = DocumentReferenceHelper.GetXmlFromXPathNavigator(fhirXPathDoc.CreateNavigator()); var cda = documentReference.ToHealthVault() as CDA; Assert.IsNotNull(cda); Assert.IsNotNull(cda.TypeSpecificData); string cdaXml = DocumentReferenceHelper.GetXmlFromXPathNavigator(cda.TypeSpecificData.CreateNavigator()); Assert.AreEqual(fhirXml, cdaXml); }
public async Task GivenAValidConfigurationWithETagNoQuotes_WhenExportingAnonymizedData_ResourceShouldBeAnonymized() { if (!_isUsingInProcTestServer) { return; } _metricHandler.ResetCount(); (string fileName, string etag) = await UploadConfigurationAsync(RedactResourceIdAnonymizationConfiguration); etag = etag.Substring(1, 17); string containerName = Guid.NewGuid().ToString("N"); Uri contentLocation = await _testFhirClient.AnonymizedExportAsync(fileName, containerName, etag); HttpResponseMessage response = await WaitForCompleteAsync(contentLocation); IList <Uri> blobUris = await CheckExportStatus(response); IEnumerable <string> dataFromExport = await DownloadBlobAndParse(blobUris); FhirJsonParser parser = new FhirJsonParser(); foreach (string content in dataFromExport) { Resource result = parser.Parse <Resource>(content); Assert.Contains(result.Meta.Security, c => "REDACTED".Equals(c.Code)); } Assert.Single(_metricHandler.NotificationMapping[typeof(ExportTaskMetricsNotification)]); }
void Dump(CodeBlockNested b) { String dir = Path.Combine( DirHelper.FindParentDir(BaseDirName), "IG", "Content", "Resources" ); foreach (String file in Directory.GetFiles(dir, "*.json")) { String fhirText = File.ReadAllText(file); FhirJsonParser parser = new FhirJsonParser(); var resource = parser.Parse(fhirText, typeof(Resource)); switch (resource) { case StructureDefinition structureDefinition: this.Dump(b, structureDefinition); break; case CodeSystem codeSystem: this.Dump(b, codeSystem); break; case ValueSet valueSet: this.Dump(b, valueSet); break; default: throw new NotImplementedException($"Unknown resource type '{file}'"); } } }
private Provenance GetProvenanceFromHeader() { if (!_httpContextAccessor.HttpContext.Request.Headers.ContainsKey(KnownHeaders.ProvenanceHeader)) { return(null); } Provenance provenance; try { provenance = _fhirJsonParser.Parse <Provenance>(_httpContextAccessor.HttpContext.Request.Headers[KnownHeaders.ProvenanceHeader]); } catch { throw new ProvenanceHeaderException(Core.Resources.ProvenanceHeaderMalformed); } if (provenance.Target != null && provenance.Target.Count > 0) { throw new ProvenanceHeaderException(Core.Resources.ProvenanceHeaderShouldntHaveTarget); } return(provenance); }
public async void GivenAValidateRequest_WhenTheResourceIsNonConformToProfile_ThenAnErrorShouldBeReturned(string path, string filename, string profile) { OperationOutcome outcome = await _client.ValidateAsync(path, Samples.GetJson(filename), profile); Assert.NotEmpty(outcome.Issue.Where(x => x.Severity == OperationOutcome.IssueSeverity.Error)); Parameters parameters = new Parameters(); if (!string.IsNullOrEmpty(profile)) { parameters.Parameter.Add(new Parameters.ParameterComponent() { Name = "profile", Value = new FhirString(profile) }); } var parser = new FhirJsonParser(); parameters.Parameter.Add(new Parameters.ParameterComponent() { Name = "resource", Resource = parser.Parse <Resource>(Samples.GetJson(filename)) }); outcome = await _client.ValidateAsync(path, parameters.ToJson()); Assert.NotEmpty(outcome.Issue.Where(x => x.Severity == OperationOutcome.IssueSeverity.Error)); }
/// <summary>Round trip file.</summary> /// <param name="filename"> Filename of the file.</param> /// <param name="shortName"> Name of the short.</param> /// <param name="jsonParser"> [in,out] The JSON parser.</param> /// <param name="jsonSerializer"> [in,out] The JSON serializer.</param> /// <param name="verifyWithNetApi">True to verify with net API.</param> private static void RoundTripFile( string filename, string shortName, ref FhirJsonParser jsonParser, ref FhirJsonSerializer jsonSerializer, bool verifyWithNetApi) { Console.Write($"{shortName}... \r"); string contents = File.ReadAllText(filename); //var parsed = System.Text.Json.JsonSerializer.Deserialize<Fhir.R4.Models.Resource>(contents); //string serialized = System.Text.Json.JsonSerializer.Serialize<Fhir.R4.Models.Resource>(parsed, FhirSerializerOptions.Compact); //if (!verifyWithNetApi) //{ // return; //} var parsedOriginal = jsonParser.Parse(contents); string serializedOriginal = jsonSerializer.SerializeToString(parsedOriginal); //var parsedCS2 = jsonParser.Parse(serialized); //string serializedCS2 = jsonSerializer.SerializeToString(parsedCS2); //if (serializedOriginal.Length != serializedCS2.Length) //{ // Console.Write(""); //} }
public void AddResources(params String[] inputDirs) { foreach (String inputDir in inputDirs) { foreach (String file in Directory.GetFiles(inputDir)) { String fhirText = File.ReadAllText(file); FhirJsonParser parser = new FhirJsonParser(); var resource = parser.Parse(fhirText, typeof(Resource)); switch (resource) { case CodeSystem codeSystem: CodeSystems.Add(codeSystem.Url, codeSystem); break; case ValueSet valueSet: ValueSets.Add(valueSet.Url, valueSet); break; case StructureDefinition structureDefinition: StructureDefinitions.Add(structureDefinition.Url, structureDefinition); break; } } } }
public async Task GivenAValidRequestWithCustomizedTemplateSet_WhenConvertData_CorrectResponseShouldReturn() { var registry = GetTestContainerRegistryInfo(); // Here we skip local E2E test since we need Managed Identity for container registry token. // We also skip the case when environmental variable is not provided (not able to upload templates) Skip.If(_convertDataConfiguration != null || registry == null); await PushTemplateSet(registry, TestRepositoryName, TestRepositoryTag); var parameters = GetConvertDataParams(GetSampleHl7v2Message(), "hl7v2", $"{registry.Server}/{TestRepositoryName}:{TestRepositoryTag}", "ADT_A01"); var requestMessage = GenerateConvertDataRequest(parameters); HttpResponseMessage response = await _testFhirClient.HttpClient.SendAsync(requestMessage); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var bundleContent = await response.Content.ReadAsStringAsync(); var setting = new ParserSettings() { AcceptUnknownMembers = true, PermissiveParsing = true, }; var parser = new FhirJsonParser(setting); var bundleResource = parser.Parse <Bundle>(bundleContent); Assert.NotEmpty(bundleResource.Entry.ByResourceType <Patient>().First().Id); }
public void BreastAbnormalityTest() { FhirJsonParser fjp = new FhirJsonParser(); String jsonText = File.ReadAllText(@"TestFiles\breastrad-BreastAbnormality.json"); StructureDefinition s = fjp.Parse <StructureDefinition>(jsonText); ElementNode head = ElementNode.Create(s.Snapshot.Element); }
public void WhenAllergyInToleranceToHealthVault_ThenValuesEqual() { var json = SampleUtil.GetSampleContent("FhirAllergy.json"); var fhirParser = new FhirJsonParser(); var fhirAllergy = fhirParser.Parse <AllergyIntolerance>(json); var allergy = fhirAllergy.ToHealthVault(); Assert.IsNotNull(allergy); Assert.AreEqual(new Guid("1c855ac0-892a-4352-9a82-3dcbd22bf0bc"), allergy.Key.Id); Assert.AreEqual(new Guid("706ceafa-d506-43a8-9758-441fd9c3d407"), allergy.Key.VersionStamp); Assert.AreEqual(fhirAllergy.Code.Text, allergy.Name.Text); Assert.AreEqual(fhirAllergy.Code.Coding[0].Code, allergy.Name[0].Value); Assert.AreEqual(fhirAllergy.Code.Coding[0].System, allergy.Name[0].Family); Assert.AreEqual("animal", allergy.AllergenType.Text); Assert.AreEqual("39579001", allergy.Reaction[0].Value); Assert.AreEqual("Anaphylactic reaction", allergy.Reaction.Text); Assert.AreEqual(2004, allergy.FirstObserved.ApproximateDate.Year); Assert.AreEqual(false, allergy.IsNegated.Value); Assert.AreEqual("Hotwatertreament", allergy.Treatment.Text); Assert.AreEqual("animal", allergy.AllergenCode.Text); Assert.AreEqual("wc", allergy.AllergenCode[0].Family); Assert.AreEqual("animal", allergy.AllergenCode[0].Value); Assert.AreEqual("1", allergy.AllergenCode[0].Version); Assert.IsNotNull(allergy.TreatmentProvider); Assert.AreEqual("John Doe", allergy.TreatmentProvider.Name.ToString()); Assert.AreEqual("1 Back Lane", allergy.TreatmentProvider.ContactInformation.Address[0].Street[0]); Assert.AreEqual("Holmfirth", allergy.TreatmentProvider.ContactInformation.Address[0].City); Assert.AreEqual("HD7 1HQ", allergy.TreatmentProvider.ContactInformation.Address[0].PostalCode); Assert.AreEqual("UK", allergy.TreatmentProvider.ContactInformation.Address[0].Country); }
public ActionResult Index(ResourceHistoryViewModel model) { var patientId = model.patientID; try { // We have hard-coded the resource type to Patient to get history details of the patient var historyRead = FhirClient.History(ResourceIdentity.Build("Patient", patientId)); string _history = fhirJsonSerializer.SerializeToString(historyRead); Bundle historyBundle = (Bundle)fhirJsonParser.Parse(_history, typeof(Bundle)); model.OperationOutcomePatient = historyBundle.Entry.Select(Resource => (Patient)Resource.Resource).ToList(); //Displaying the Div element of the text section foreach (var hist in model.OperationOutcomePatient) { ViewBag.operationOutcomeText = hist.Text == null ? string.Empty : hist.Text.Div; } ViewBag.patientHistory = JValue.Parse(_history).ToString(); } catch (FhirOperationException FhirOpExec) { var response = FhirOpExec.Outcome; var errorDetails = fhirJsonSerializer.SerializeToString(response); ViewBag.error = JValue.Parse(errorDetails).ToString(); } return(View()); }
public void WhenExampleFhirImmunizationToHealthVaultImmunization_ThenValuesEqual() { var json = SampleUtil.GetSampleContent("FhirImmunization.json"); var fhirParser = new FhirJsonParser(); var fhirImmunization = fhirParser.Parse <Immunization>(json); var hvImmunization = fhirImmunization.ToHealthVault(); Assert.IsNotNull(hvImmunization); Assert.AreEqual("Fluvax (Influenza)", hvImmunization.Name.Text); Assert.IsNotNull(hvImmunization.DateAdministrated.ApproximateDate); Assert.AreEqual(2013, hvImmunization.DateAdministrated.ApproximateDate.Year); Assert.IsNotNull(hvImmunization.DateAdministrated.ApproximateDate.Month); Assert.AreEqual(1, hvImmunization.DateAdministrated.ApproximateDate.Month.Value); Assert.IsNotNull(hvImmunization.DateAdministrated.ApproximateDate.Day); Assert.AreEqual(10, hvImmunization.DateAdministrated.ApproximateDate.Day.Value); Assert.AreEqual("Injection, intramuscular", hvImmunization.Route.Text); Assert.AreEqual("Notes on adminstration of vaccine", hvImmunization.CommonData.Note); Assert.AreEqual("AAJN11K", hvImmunization.Lot); Assert.IsNotNull(hvImmunization.ExpirationDate); Assert.AreEqual(2015, hvImmunization.ExpirationDate.Year); Assert.IsNotNull(hvImmunization.ExpirationDate.Month); Assert.AreEqual(2, hvImmunization.ExpirationDate.Month.Value); Assert.IsNotNull(hvImmunization.ExpirationDate.Day); Assert.AreEqual(15, hvImmunization.ExpirationDate.Day.Value); Assert.AreEqual("left arm", hvImmunization.AnatomicSurface.Text); Assert.IsNull(hvImmunization.Administrator); Assert.IsNull(hvImmunization.Manufacturer); }
public async Task GivenAUserWithConvertDataPermissions_WhenConvertData_TheServerShouldReturnSuccess() { if (!_convertDataEnabled) { return; } TestFhirClient tempClient = _client.CreateClientForUser(TestUsers.ConvertDataUser, TestApplications.NativeClient); var parameters = Samples.GetDefaultConvertDataParameter().ToPoco <Parameters>(); var result = await tempClient.ConvertDataAsync(parameters); var setting = new ParserSettings() { AcceptUnknownMembers = true, PermissiveParsing = true, }; var parser = new FhirJsonParser(setting); var bundleResource = parser.Parse <Bundle>(result); Assert.Equal("urn:uuid:9d697ec3-48c3-3e17-db6a-29a1765e22c6", bundleResource.Entry.First().FullUrl); Assert.Equal(4, bundleResource.Entry.Count); var patient = bundleResource.Entry.First().Resource as Patient; Assert.Equal("Kinmonth", patient.Name.First().Family); Assert.Equal("1987-06-24", patient.BirthDate); }
public async Task GivenAValidConfigurationWithETag_WhenExportingAnonymizedData_ResourceShouldBeAnonymized(string path) { _metricHandler?.ResetCount(); var dateTime = DateTimeOffset.UtcNow; var resourceToCreate = Samples.GetDefaultPatient().ToPoco <Patient>(); resourceToCreate.Id = Guid.NewGuid().ToString(); await _testFhirClient.UpdateAsync(resourceToCreate); (string fileName, string etag) = await UploadConfigurationAsync(RedactResourceIdAnonymizationConfiguration); string containerName = Guid.NewGuid().ToString("N"); Uri contentLocation = await _testFhirClient.AnonymizedExportAsync(fileName, dateTime, containerName, etag, path); HttpResponseMessage response = await WaitForCompleteAsync(contentLocation); IList <Uri> blobUris = await CheckExportStatus(response); IEnumerable <string> dataFromExport = await DownloadBlobAndParse(blobUris); FhirJsonParser parser = new FhirJsonParser(); foreach (string content in dataFromExport) { Resource result = parser.Parse <Resource>(content); Assert.Contains(result.Meta.Security, c => "REDACTED".Equals(c.Code)); } // Only check metric for local tests if (_isUsingInProcTestServer) { Assert.Single(_metricHandler.NotificationMapping[typeof(ExportTaskMetricsNotification)]); } }
public void WhenMultipleFhirObservationsTransformedToHealthVault_TheValuesEqual() { var fhirParse = new FhirJsonParser(); var samples = new List <string>() { SampleUtil.GetSampleContent("FhirBloodGlucose.json"), SampleUtil.GetSampleContent("FhirWeight.json"), SampleUtil.GetSampleContent("FhirHeight.json"), }; var list = new List <ThingBase>(); foreach (var sample in samples) { list.Add(fhirParse.Parse <Observation>(sample).ToHealthVault()); } Assert.AreEqual(3, list.Count); Assert.AreEqual(BloodGlucose.TypeId, list[0].TypeId); Assert.IsTrue(list[0] is BloodGlucose); Assert.AreEqual(Weight.TypeId, list[1].TypeId); Assert.IsTrue(list[1] is Weight); Assert.AreEqual(Height.TypeId, list[2].TypeId); Assert.IsTrue(list[2] is Height); }
public IActionResult Create(JsonTextModel json = null) { if (json.JsonText_ != null) { var parser = new FhirJsonParser(); try { var res = parser.Parse <Resource>(json.JsonText_); FhirClient client = new FhirClient(url); var resEntry = client.Create(res); json.Status_ = JsonTextModel.CREATED; } catch (Exception e) { json.Status_ = JsonTextModel.FAILED; return(View(json)); } } else { json = new JsonTextModel(); json.Status_ = JsonTextModel.CREATING; } return(View(json)); }
public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (encoding == null) { throw new ArgumentNullException(nameof(encoding)); } if (encoding != Encoding.UTF8) { throw Error.BadRequest("FHIR supports UTF-8 encoding exclusively, not " + encoding.WebName); } context.HttpContext.AllowSynchronousIO(); try { using (TextReader reader = context.ReaderFactory(context.HttpContext.Request.Body, encoding)) { FhirJsonParser parser = context.HttpContext.RequestServices.GetRequiredService <FhirJsonParser>(); return(await InputFormatterResult.SuccessAsync(parser.Parse(await reader.ReadToEndAsync()))); } } catch (FormatException exception) { throw Error.BadRequest($"Body parsing failed: {exception.Message}"); } }
public Stream TerminzPost(string resource, string id, string operation) { // get Parameters from the Request Stream string reqBody = string.Empty; UTF8Encoding enc = new UTF8Encoding(); Stream reqStream = OperationContext.Current.RequestContext.RequestMessage.GetBody <Stream>(); using (StreamReader reader = new StreamReader(reqStream, enc)) { reqBody = reader.ReadToEnd(); } string reqType = WebOperationContext.Current.IncomingRequest.ContentType.ToLower(); Parameters fParam = new Parameters(); if (reqType.Contains("json")) { FhirJsonParser fjp = new FhirJsonParser(); fParam = fjp.Parse <Parameters>(reqBody); } else { FhirXmlParser fxp = new FhirXmlParser(); fParam = fxp.Parse <Parameters>(reqBody); } SetQueryParameters(fParam); return(TerminzGet(resource, id, operation)); }
private static Bundle ParseJSON(string content, bool permissive) { Bundle bundle = null; // Grab all errors found by visiting all nodes and report if not permissive if (!permissive) { List <string> entries = new List <string>(); ISourceNode node = FhirJsonNode.Parse(content, "Bundle", new FhirJsonParsingSettings { PermissiveParsing = permissive }); foreach (Hl7.Fhir.Utility.ExceptionNotification problem in node.VisitAndCatch()) { entries.Add(problem.Message); } if (entries.Count > 0) { throw new System.ArgumentException(String.Join("; ", entries).TrimEnd()); } } // Try Parse try { FhirJsonParser parser = new FhirJsonParser(GetParserSettings(permissive)); bundle = parser.Parse <Bundle>(content); } catch (Exception e) { throw new System.ArgumentException(e.Message); } return(bundle); }
public void BreastAbnormality() { String zipPath = Path.Combine("TestFiles", "BreastRadiology.zip"); using (ZipArchive archive = ZipFile.OpenRead(zipPath)) { FhirJsonParser fjp = new FhirJsonParser(); foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.FullName.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) { StructureDefinition profile; using (StreamReader streamReader = new StreamReader(entry.Open())) { String jsonText = streamReader.ReadToEndAsync().WaitResult(); profile = fjp.Parse <StructureDefinition>(jsonText); } SliceGenerator sliceGen = new SliceGenerator(SliceGenerator.OutputLanguageType.CSharp, OutputNameSpace, GenDir); //sliceGen.SaveFlag = false; sliceGen.AddProfile(profile); bool success = sliceGen.Process(); StringBuilder sb = new StringBuilder(); sliceGen.FormatMessages(sb); Trace.WriteLine(sb.ToString()); Assert.True(success == true); } } } }
public void AddFragments(String inputDir) { //const String fcn = "AddFragments"; void Save(DomainResource r, String outputName) { RemoveFragmentExtensions(r); String outputPath = Path.Combine(this.resourceDir, outputName); r.SaveJson(outputPath); this.fcGuide?.Mark(outputPath); } List <StructureDefinition> structureDefinitions = new List <StructureDefinition>(); foreach (String file in Directory.GetFiles(inputDir)) { String fhirText = File.ReadAllText(file); FhirJsonParser parser = new FhirJsonParser(); var resource = parser.Parse(fhirText, typeof(Resource)); switch (resource) { case StructureDefinition structureDefinition: Extension isFragmentExtension = structureDefinition.GetExtension(Global.IsFragmentExtensionUrl); // Onlu add fragments to IG. if (isFragmentExtension != null) { Int32 index = structureDefinition.Url.LastIndexOf('/'); structureDefinitions.Add(structureDefinition); } break; } } structureDefinitions.Sort((a, b) => String.Compare(a.Url, b.Url, new System.StringComparison())); foreach (StructureDefinition structureDefinition in structureDefinitions) { String fixedName = $"StructureDefinition-{structureDefinition.Name}"; if (structureDefinition.Snapshot == null) { SnapshotCreator.Create(structureDefinition); } Extension isFragmentExtension = structureDefinition.GetExtension(Global.IsFragmentExtensionUrl); { String groupId = "Fragments"; Save(structureDefinition, $"{fixedName}.json"); String shortDescription = $"Fragment '{structureDefinition.Snapshot.Element[0].Short}'"; this.implementationGuide.AddIGResource($"StructureDefinition/{structureDefinition.Name}", structureDefinition.Title, shortDescription, groupId, false); } } }