Пример #1
0
        private static void SetResponseForClient(HttpActionExecutedContext context, Resource outCome)
        {
            // "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
            var acceptEntry = HttpContext.Current.Request.Headers["Accept"];
            var acceptJson  = acceptEntry.Contains(FhirMediaType.HeaderTypeJson);

            if (acceptJson)
            {
                var fhirJsonSerializer = new FhirJsonSerializer();
                var json = fhirJsonSerializer.SerializeToString(outCome);
                context.Response = new HttpResponseMessage
                {
                    Content    = new StringContent(json, Encoding.UTF8, "application/json"),
                    StatusCode = HttpStatusCode.InternalServerError
                };
            }
            else
            {
                var fhirXmlSerializer = new FhirXmlSerializer();
                var xml = fhirXmlSerializer.SerializeToString(outCome);
                context.Response = new HttpResponseMessage
                {
                    Content    = new StringContent(xml, Encoding.UTF8, "application/xml"),
                    StatusCode = HttpStatusCode.InternalServerError
                };
            }
        }
        public async System.Threading.Tasks.Task GivenAFhirObjectAndXmlContentType_WhenSerializing_ThenTheObjectIsSerializedToTheResponseStream()
        {
            var formatter = new FhirXmlOutputFormatter(new FhirXmlSerializer(), NullLogger <FhirXmlOutputFormatter> .Instance);

            var resource   = new OperationOutcome();
            var serializer = new FhirXmlSerializer();

            var defaultHttpContext = new DefaultHttpContext();

            defaultHttpContext.Request.ContentType = ContentType.XML_CONTENT_HEADER;
            var responseBody = new MemoryStream();

            defaultHttpContext.Response.Body = responseBody;

            var writerFactory = Substitute.For <Func <Stream, Encoding, TextWriter> >();

            writerFactory.Invoke(Arg.Any <Stream>(), Arg.Any <Encoding>()).Returns(p => new StreamWriter(p.ArgAt <Stream>(0)));

            await formatter.WriteResponseBodyAsync(
                new OutputFormatterWriteContext(
                    defaultHttpContext,
                    writerFactory,
                    typeof(OperationOutcome),
                    resource),
                Encoding.UTF8);

            Assert.Equal(serializer.SerializeToString(resource), Encoding.UTF8.GetString(responseBody.ToArray()));

            responseBody.Dispose();
        }
Пример #3
0
        private string SerializeResponse(Resource fhirResource, string responseType, SummaryType st)
        {
            string rv = string.Empty;

            OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse;

            if (responseType == "json")
            {
                FhirJsonSerializer fjs = new FhirJsonSerializer();
                rv = fjs.SerializeToString(fhirResource, st);
                //rv = FhirSerializer.SerializeResourceToJson(fhirResource,st);
                //context.ContentType = "application/json";
                context.ContentType = "application/fhir+json;charset=UTF-8"; // when IANA registered
                context.Format      = WebMessageFormat.Json;
            }
            else
            {
                FhirXmlSerializer fxs = new FhirXmlSerializer();
                rv = fxs.SerializeToString(fhirResource, st);
                //rv = FhirSerializer.SerializeResourceToXml(fhirResource,st);
                //context.ContentType = "application/xml";
                context.ContentType = "application/fhir+xml;charset=UTF-8"; // when IANA registered
                context.Format      = WebMessageFormat.Xml;
            }

            return(rv);
        }
Пример #4
0
        public OperationOutcome Validate(Resource resource, bool onlyErrors = true, bool threadedValidation = true)
        {
            OperationOutcome result = null;

            if (!(resource is Bundle) || !threadedValidation)
            {
                var xmlSerializer = new FhirXmlSerializer();
                //    using (var reader = XDocument.Parse(FhirSerializer.SerializeResourceToXml(resource)).CreateReader())
                using (var reader = XDocument.Parse(xmlSerializer.SerializeToString(resource)).CreateReader())
                {
                    result = RunValidation(onlyErrors, reader);
                }
            }
            else
            {
                var bundle = (Bundle)resource;
                result = RunBundleValidation(onlyErrors, bundle);
            }

            if (result.Issue.Count > 0)
            {
                Log.Warn("Validation failed");
                Log.Warn("Request: " + XDocument.Parse(new FhirXmlSerializer().SerializeToString(resource)));
                Log.Warn("Response:" + XDocument.Parse(new FhirXmlSerializer().SerializeToString(result)));
            }

            return(result);
        }
Пример #5
0
        private static void convertResourcePoco(string inputFile, string outputFile)
        {
            if (inputFile.EndsWith(".xml"))
            {
                var xml      = File.ReadAllText(inputFile);
                var resource = new FhirXmlParser(new ParserSettings {
                    PermissiveParsing = true
                }).Parse <Resource>(xml);

                var r2 = resource.DeepCopy();
                Assert.IsTrue(resource.Matches(r2 as Resource), "Serialization of " + inputFile + " did not match output - Matches test");
                Assert.IsTrue(resource.IsExactly(r2 as Resource), "Serialization of " + inputFile + " did not match output - IsExactly test");
                Assert.IsFalse(resource.Matches(null), "Serialization of " + inputFile + " matched null - Matches test");
                Assert.IsFalse(resource.IsExactly(null), "Serialization of " + inputFile + " matched null - IsExactly test");

                var json = new FhirJsonSerializer().SerializeToString(resource);
                File.WriteAllText(outputFile, json);
            }
            else
            {
                var json     = File.ReadAllText(inputFile);
                var resource = new FhirJsonParser(new ParserSettings {
                    PermissiveParsing = true
                }).Parse <Resource>(json);
                var xml = new FhirXmlSerializer().SerializeToString(resource);
                File.WriteAllText(outputFile, xml);
            }
        }
        public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            return(System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                XmlWriter writer = new XmlTextWriter(writeStream, new UTF8Encoding(false));
                var summary = RequestMessage.RequestSummary();
                var xmlSerializer = new FhirXmlSerializer();

                if (type == typeof(OperationOutcome))
                {
                    var resource = (Resource)value;
                    // FhirSerializer.SerializeResource(resource, writer, summary);
                    xmlSerializer.Serialize(resource, writer, summary);
                }
                else if (typeof(Resource).IsAssignableFrom(type))
                {
                    var resource = (Resource)value;
                    //FhirSerializer.SerializeResource(resource, writer, summary);
                    xmlSerializer.Serialize(resource, writer, summary);
                }
                else if (type == typeof(FhirResponse))
                {
                    if (value is FhirResponse response && response.HasBody)
                    {
                        //FhirSerializer.SerializeResource(response.Resource, writer, summary);
                        xmlSerializer.Serialize(response.Resource, writer, summary);
                    }
                }

                writer.Flush();
            }));
        }
Пример #7
0
        public Base Read(SearchParams searchParams)
        {
            var parameters    = searchParams.Parameters;
            var xmlSerializer = new FhirXmlSerializer();

            foreach (var parameter in parameters)
            {
                if (parameter.Item1.ToLower().Contains("log") && parameter.Item2.ToLower().Contains("normal"))
                {
                    throw new ArgumentException("Using " + nameof(SearchParams) +
                                                " in Read(SearchParams searchParams) should throw an exception which is put into an OperationOutcomes issues");
                }
                if (parameter.Item1.Contains("log") && parameter.Item2.Contains("operationoutcome"))
                {
                    var operationOutcome = new OperationOutcome {
                        Issue = new List <OperationOutcome.IssueComponent>()
                    };
                    var issue = new OperationOutcome.IssueComponent
                    {
                        Severity = OperationOutcome.IssueSeverity.Information,
                        Code     = OperationOutcome.IssueType.Incomplete,
                        Details  = new CodeableConcept("SomeExampleException", typeof(FhirOperationException).ToString(),
                                                       "Something expected happened and needs to be handled with more detail.")
                    };
                    operationOutcome.Issue.Add(issue);
                    //var errorMessage = fh

                    //var serialized = FhirSerializer.SerializeResourceToXml(operationOutcome);
                    var serialized = xmlSerializer.SerializeToString(operationOutcome);
                    throw new ArgumentException(serialized);
                }
            }
            throw new ArgumentException("Generic error");
        }
        public HttpResponseMessage MetaData()
        {
            var headers    = Request.Headers;
            var accept     = headers.Accept;
            var returnJson = accept.Any(x => x.MediaType.Contains(FhirMediaType.HeaderTypeJson));

            StringContent httpContent;
            var           metaData = _handler.CreateMetadata(_fhirServices, _abstractStructureDefinitionService, Request.RequestUri.AbsoluteUri);

            if (!returnJson)
            {
                var xmlSerializer = new FhirXmlSerializer();
                var xml           = xmlSerializer.SerializeToString(metaData);
                httpContent =
                    new StringContent(xml, Encoding.UTF8,
                                      "application/xml");
            }
            else
            {
                var jsonSerializer = new FhirJsonSerializer();
                var json           = jsonSerializer.SerializeToString(metaData);
                httpContent =
                    new StringContent(json, Encoding.UTF8,
                                      "application/json");
            }
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = httpContent
            };

            return(response);
        }
        //HttpActionExecutedContext
        public override void OnException(ExceptionContext context)
        {
            var exceptionType    = context.Exception.GetType();
            var expectedType     = GetExceptionType();
            var exceptionMessage = context.Exception.Message;

            if (exceptionType != expectedType && !(expectedType == typeof(Exception)))
            {
                return;
            }

            Resource operationOutcome = null;

            if (exceptionMessage.Contains("<" + nameof(OperationOutcome)))
            {
                var serializer = new FhirXmlParser();
                operationOutcome = serializer.Parse <OperationOutcome>(exceptionMessage);
            }
            var outCome         = operationOutcome ?? GetOperationOutCome(context.Exception);
            var xmlSerializer   = new FhirXmlSerializer();
            var xml             = xmlSerializer.SerializeToString(outCome);
            var internalOutCome = new FhirXmlParser().Parse <OperationOutcome>(xml);

            internalOutCome.Issue[0].Diagnostics = context.Exception.StackTrace;
            xml = xmlSerializer.SerializeToString(internalOutCome);
            var xmlDoc     = XDocument.Parse(xml);
            var error      = xmlDoc.ToString();
            var htmlDecode = WebUtility.HtmlDecode(error);

            Log.Error(htmlDecode);
            SetResponseForClient(context, outCome);
        }
Пример #10
0
        private static void convertResourcePoco(string inputFile, string outputFile)
        {
            //TODO: call validation after reading
            if (inputFile.Contains("expansions.") || inputFile.Contains("profiles-resources") || inputFile.Contains("profiles-others") || inputFile.Contains("valuesets."))
            {
                return;
            }
            if (inputFile.EndsWith(".xml"))
            {
                var xml      = File.ReadAllText(inputFile);
                var resource = new FhirXmlParser().Parse <Resource>(xml);

                var r2 = resource.DeepCopy();
                Assert.IsTrue(resource.Matches(r2 as Resource), "Serialization of " + inputFile + " did not match output - Matches test");
                Assert.IsTrue(resource.IsExactly(r2 as Resource), "Serialization of " + inputFile + " did not match output - IsExactly test");
                Assert.IsFalse(resource.Matches(null), "Serialization of " + inputFile + " matched null - Matches test");
                Assert.IsFalse(resource.IsExactly(null), "Serialization of " + inputFile + " matched null - IsExactly test");

                var json = new FhirJsonSerializer().SerializeToString(resource);
                File.WriteAllText(outputFile, json);
            }
            else
            {
                var json     = File.ReadAllText(inputFile);
                var resource = new FhirJsonParser().Parse <Resource>(json);
                var xml      = new FhirXmlSerializer().SerializeToString(resource);
                File.WriteAllText(outputFile, xml);
            }
        }
        private HttpResponseMessage SendResponse(Base resource)
        {
            var headers    = Request.Headers;
            var accept     = headers.Accept;
            var returnJson = ReturnJson(accept);

            if (!(resource is OperationOutcome))
            {
                resource = ValidateResource((Resource)resource, false);
            }
            StringContent httpContent;

            if (!returnJson)
            {
                var xmlSerializer = new FhirXmlSerializer();
                httpContent =
                    GetHttpContent(xmlSerializer.SerializeToString(resource), FhirMediaType.XmlResource);
            }
            else
            {
                var jsonSerializer = new FhirJsonSerializer();
                httpContent =
                    GetHttpContent(jsonSerializer.SerializeToString(resource), FhirMediaType.JsonResource);
            }
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = httpContent
            };

            return(response);
        }
Пример #12
0
        public static string generateXML(Resource res)
        {
            var    serializer = new FhirXmlSerializer();
            string xmlText    = serializer.SerializeToString(res);

            return(xmlText);
        }
Пример #13
0
        //=============== Write ==================================================
        public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            return(System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                XmlWriter writer = new XmlTextWriter(writeStream, new System.Text.UTF8Encoding(false));
                if (type.IsAssignableFrom(typeof(Resource)))
                {
                    Resource Resource = (Resource)value;

                    var Summary = SummaryType.False;
                    if (Resource is IAnnotated Annotated)
                    {
                        var SummaryTypeAnnotationList = Annotated.Annotations(typeof(SummaryType));
                        if (SummaryTypeAnnotationList.FirstOrDefault() is SummaryType AnnotationSummary)
                        {
                            Summary = AnnotationSummary;
                        }
                    }

                    FhirXmlSerializer FhirXmlSerializer = new FhirXmlSerializer();
                    FhirXmlSerializer.Serialize(Resource, writer, Summary);

                    //Now obsolete in FHRI .NET API
                    //FhirSerializer.SerializeResource(Resource, writer, Summary);
                }
                writer.Flush();
                return System.Threading.Tasks.Task.CompletedTask;
            }));
        }
        public HttpResponseMessage Create(string type, Resource resource)
        {
            var xmlSerializer = new FhirXmlSerializer();
            var service       = _handler.FindServiceFromList(_fhirServices, _fhirMockupServices, type);

            resource = (Resource)ValidateResource(resource, true);
            return(resource is OperationOutcome?SendResponse(resource) : _handler.ResourceCreate(type, resource, service));
        }
Пример #15
0
        public void ParseMetaXml()
        {
            var poco = (Meta)(new FhirXmlParser().Parse(metaXml, typeof(Meta)));
            var xml  = new FhirXmlSerializer().SerializeToString(poco, root: "meta");

            Assert.IsTrue(poco.IsExactly(metaPoco));
            Assert.AreEqual(metaXml, xml);
        }
        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            var fhirResource      = context.Object as Base;
            var fhirXmlSerializer = new FhirXmlSerializer();
            var xml = fhirXmlSerializer.SerializeToString(fhirResource);

            return(context.HttpContext.Response.WriteAsync(xml));
        }
Пример #17
0
        public HttpResponseMessage Create(IKey key, Resource resource)
        {
            var request     = (CommunicationRequest)resource;
            var xmlAsString = new FhirXmlSerializer().SerializeToString(request);
            var result      = new FhirXmlParser().Parse <CommunicationRequest>(xmlAsString);

            result.Id = Guid.NewGuid().ToString();
            return(HttpResponseHelper.ConvertResourceToHttpResponseMessage(result, HttpStatusCode.OK));
        }
        public static string ConformanceToXML(this CapabilityStatement conformance)
        {
            var xmlSerializer = new FhirXmlSerializer();
            //var xml = FhirSerializer.SerializeResourceToXml(resource, summary);
            var xml = xmlSerializer.SerializeToString(conformance);

            //   return FhirSerializer.SerializeResourceToXml(conformance);
            return(xml);
        }
Пример #19
0
        public static void SerializeResourceToDiskAsXml(this Resource resource, string path)
        {
            EnsureArg.IsNotNullOrWhiteSpace(path, nameof(path));

            using (XmlWriter writer = new XmlTextWriter(new StreamWriter(path)))
            {
                var serializer = new FhirXmlSerializer();
                serializer.Serialize(resource, writer);
            }
        }
Пример #20
0
        public void CheckCopyAllFields()
        {
            string xml = ReadTestData("TestPatient.xml");

            var p    = new FhirXmlParser().Parse <Patient>(xml);
            var p2   = (Patient)p.DeepCopy();
            var xml2 = new FhirXmlSerializer().SerializeToString(p2);

            XmlAssert.AreSame("TestPatient.xml", xml, xml2);
        }
Пример #21
0
        public XmlFhirFormatter(FhirXmlParser parser, FhirXmlSerializer serializer) : base()
        {
            _parser     = parser ?? throw new ArgumentNullException(nameof(parser));
            _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));

            foreach (var mediaType in ContentType.XML_CONTENT_HEADERS)
            {
                SupportedMediaTypes.Add(new MediaTypeHeaderValue(mediaType));
            }
        }
Пример #22
0
        public void CheckCopyCarePlan()
        {
            string xml = ReadTestData(@"careplan-example-f201-renal.xml");

            var p    = new FhirXmlParser().Parse <CarePlan>(xml);
            var p2   = (CarePlan)p.DeepCopy();
            var xml2 = new FhirXmlSerializer().SerializeToString(p2);

            XmlAssert.AreSame("careplan-example-f201-renal.xml", xml, xml2);
        }
Пример #23
0
        public AsyncResourceXmlOutputFormatter(FhirXmlSerializer serializer)
        {
            _serializer = serializer;
            SupportedEncodings.Clear();
            SupportedEncodings.Add(Encoding.UTF8);

            foreach (var mediaType in FhirMediaType.XmlMimeTypes)
            {
                SupportedMediaTypes.Add(mediaType);
            }
        }
        private static void RunSerialValidation(bool onlyErrors, IEnumerable <Resource> serialItems, OperationOutcome operationOutcome)
        {
            var xmlSerializer = new FhirXmlSerializer();

            foreach (var item in serialItems)
            {
                var localOperationOutCome = RunValidation(onlyErrors,
                                                          XDocument.Parse(xmlSerializer.SerializeToString(item)).CreateReader());
                operationOutcome.Issue.AddRange(localOperationOutCome.Issue);
            }
        }
Пример #25
0
        public static HttpResponseMessage ConvertResourceToHttpResponseMessage(Resource resource, HttpStatusCode statusCode)
        {
            var xml         = new FhirXmlSerializer().SerializeToString(resource);
            var httpContent = new StringContent(xml, Encoding.UTF8, "application/xml");
            var response    = new HttpResponseMessage(statusCode)
            {
                Content = httpContent
            };

            return(response);
        }
Пример #26
0
        public void TestValidatePersonInvalidGender()
        {
            var person    = GetPersonMissingBirthDate();
            var personXml = new FhirXmlSerializer().SerializeToDocument(person);

            Console.WriteLine(personXml);
            var validationResult = DoValidation(person);
            var xml = new FhirXmlSerializer().SerializeToDocument(validationResult);

            Console.WriteLine(xml);
            Assert.IsTrue(validationResult.Issue.Count > 0);
        }
Пример #27
0
        public void BundleLinksUnaltered()
        {
            var b = new Bundle();

            b.NextLink = new Uri("Organization/123456/_history/123456", UriKind.Relative);

            var xml = new FhirXmlSerializer().SerializeToString(b);

            b = FhirXmlParser.Parse <Bundle>(xml);

            Assert.IsTrue(!b.NextLink.ToString().EndsWith("/"));
        }
Пример #28
0
        public void RetainSpacesInAttribute()
        {
            var xml = "<Basic xmlns='http://hl7.org/fhir'><extension url='http://blabla.nl'><valueString value='Daar gaat ie dan" + "&#xA;" + "verdwijnt dit?' /></extension></Basic>";

            var basic = FhirXmlParser.Parse <DomainResource>(xml);

            Assert.IsTrue(basic.GetStringExtension("http://blabla.nl").Contains("\n"));

            var outp = FhirXmlSerializer.SerializeToString(basic);

            Assert.IsTrue(outp.Contains("&#xA;"));
        }
Пример #29
0
 public void ValidateOrganization(string path)
 {
     using (var stream = AssemblyHelper.GetStream(path, Assembly.GetExecutingAssembly()))
     {
         var xDocument    = XDocument.Load(stream);
         var organization = new FhirXmlParser().Parse <Organization>(xDocument.ToString());
         var valid        = _profileValidator.Validate(organization);
         var serialized   = new FhirXmlSerializer().SerializeToDocument(valid);
         Console.WriteLine(serialized);
         Assert.IsTrue(valid.Issue.Count == 0);
     }
 }
        private void test(Model.Resource resource, String expression, IEnumerable <XElement> expected)
        {
            var tpXml = new FhirXmlSerializer().SerializeToString(resource);
            var npoco = resource.ToTypedElement();
            //       FhirPathEvaluatorTest.Render(npoco);

            IEnumerable <ITypedElement> actual = npoco.Select(expression);

            Assert.Equal(expected.Count(), actual.Count());

            expected.Zip(actual, compare).Count();
        }