Example #1
0
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.Factory.StartNew(() =>
            {
                MemoryStream stream = new MemoryStream();
                readStream.CopyTo(stream);

                IEnumerable<string> xContentHeader;
                var success = content.Headers.TryGetValues("X-Content-Type", out xContentHeader);

                if (!success)
                {
                    throw Error.BadRequest("POST to binary must provide a Content-Type header");
                }

                string contentType = xContentHeader.FirstOrDefault();

                Binary binary = new Binary();
                binary.Content = stream.ToArray();
                binary.ContentType = contentType;

                //ResourceEntry entry = ResourceEntry.Create(binary);
                //entry.Tags = content.Headers.GetFhirTags();
                return (object)binary;
            });
        }
 public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
 {
     if (typeof(FhirModel.Binary).IsAssignableFrom(context.ObjectType))
     {
         FhirModel.Binary binary = (FhirModel.Binary)context.Object;
         var stream = new MemoryStream(binary.Data);
         context.HttpContext.Response.Headers.Add("Content-Type", binary.ContentType);
         await stream.CopyToAsync(context.HttpContext.Response.Body);
     }
 }
        public static DocumentReference DocumentToDocumentReference(Composition composition, Bundle bundle, Binary bin, Uri binLocation)
        {
            var reference = new DocumentReference();
            reference.MasterIdentifier = new Identifier(Identifier.SYSTMEM_URI, bundle.Id.ToString());
            reference.Identifier = composition.Identifier != null ? new List<Identifier>() { composition.Identifier } : null;
            reference.Subject = composition.Subject;
            reference.Type = composition.Type;
            reference.Class = composition.Class;
            reference.Author = new List<ResourceReference>( composition.Author );
            reference.Custodian = composition.Custodian;
            reference.Authenticator = composition.Attester != null ? composition.Attester.Where(att => att.Mode.Any(am => am == Composition.CompositionAttestationMode.Professional ||
                                                                    am == Composition.CompositionAttestationMode.Legal) && att.Party != null).Select(att => att.Party).Last() : null;
            reference.CreatedElement = composition.Date != null ? new FhirDateTime(composition.Date) : null;
            reference.IndexedElement = Instant.Now();
            reference.Status = DocumentReference.DocumentReferenceStatus.Current;

            reference.DocStatus = composition.Status != null ?
                new CodeableConcept { Coding = new List<Coding>() { new Coding("http://hl7.org/fhir/composition-status", composition.Status.ToString()) } } : null;
            // todo: Use proper Enumerator conversion for composition.Status

            reference.Description = composition.Title;
            reference.Confidentiality = composition.Confidentiality != null ? new List<CodeableConcept>() { new CodeableConcept() { Coding = new List<Coding>() { composition.Confidentiality } } } : null;
            reference.PrimaryLanguage = composition.Language;
            reference.MimeType = bin.ContentType;
            reference.Format = new List<Uri>( bundle.Tags.FilterOnFhirSchemes().Where(t => t.Scheme != Tag.FHIRTAGSCHEME_SECURITY).Select(tg => new Uri(tg.Term)) );
            reference.Size = bin.Content.Length;
            reference.Hash = calculateSHA1(bin.Content);
            reference.Location = binLocation;

            if (composition.Event != null)
            {
                reference.Context = new DocumentReference.DocumentReferenceContextComponent();
                reference.Context.Event = composition.Event.Code != null ? new List<CodeableConcept>(composition.Event.Code) : null;
                reference.Context.Period = composition.Event.Period != null ? composition.Event.Period : null;
            }

            return reference;
        }
Example #4
0
        public FhirResponse Mailbox(Bundle bundle, Binary body)
        {
            // DSTU2: mailbox
            /*
            if(bundle == null || body == null) throw new SparkException("Mailbox requires a Bundle body payload"); 
            // For the connectathon, this *must* be a document bundle
            if (bundle.GetBundleType() != BundleType.Document)
                throw new SparkException("Mailbox endpoint currently only accepts Document feeds");

            Bundle result = new Bundle("Transaction result from posting of Document " + bundle.Id, DateTimeOffset.Now);

            // Build a binary with the original body content (=the unparsed Document)
            var binaryEntry = new ResourceEntry<Binary>(KeyHelper.NewCID(), DateTimeOffset.Now, body);
            binaryEntry.SelfLink = KeyHelper.NewCID();

            // Build a new DocumentReference based on the 1 composition in the bundle, referring to the binary
            var compositions = bundle.Entries.OfType<ResourceEntry<Composition>>();
            if (compositions.Count() != 1) throw new SparkException("Document feed should contain exactly 1 Composition resource");
            
            var composition = compositions.First().Resource;
            var reference = ConnectathonDocumentScenario.DocumentToDocumentReference(composition, bundle, body, binaryEntry.SelfLink);

            // Start by copying the original entries to the transaction, minus the Composition
            List<BundleEntry> entriesToInclude = new List<BundleEntry>();

            //if(reference.Subject != null) entriesToInclude.AddRange(bundle.Entries.ById(new Uri(reference.Subject.Reference)));
            //if (reference.Author != null) entriesToInclude.AddRange(
            //         reference.Author.Select(auth => bundle.Entries.ById(auth.Id)).Where(be => be != null));
            //reference.Subject = composition.Subject;
            //reference.Author = new List<ResourceReference>(composition.Author);
            //reference.Custodian = composition.Custodian;

            foreach (var entry in bundle.Entries.Where(be => !(be is ResourceEntry<Composition>)))
            {
                result.Entries.Add(entry);
            }

            // Now add the newly constructed DocumentReference and the Binary
            result.Entries.Add(new ResourceEntry<DocumentReference>(KeyHelper.NewCID(), DateTimeOffset.Now, reference));
            result.Entries.Add(binaryEntry);

            // Process the constructed bundle as a Transaction and return the result
            return Transaction(result);
            */
            return Respond.WithError(HttpStatusCode.NotImplemented);
        }
        private static Binary makeBinaryResource(byte[] data, string contentType)
        {
            var binary = new Binary();

            binary.Content = data;
            binary.ContentType = contentType;

            return binary;
        }
        public static void SaveBody(this HttpRequestMessage request, string contentType, byte[] data)
        {
            Binary b = new Binary { Content = data, ContentType = contentType };

            request.Properties.Add(Const.UNPARSED_BODY, b);
        }
Example #7
0
        public static Binary GetDemoBinary()
        {
            var pat = DemoData.GetDemoPatient();
            var bin = new Binary();
            
            // NB: in the default patient-example there is no photo element.
            // Copy the photo element from the current example when replacing this file!
            bin.Content = pat.Photo[0].Data;

            bin.ContentType = pat.Photo[0].ContentType;

            return bin;
        }
        public static void SerializeBinary(Hl7.Fhir.Model.Binary value, IFhirWriter writer, bool summary)
        {
            writer.WriteStartRootObject("Binary");
            writer.WriteStartComplexContent();

            // Serialize element contentType
            if (value.ContentTypeElement != null && !summary)
            {
                writer.WritePrimitiveContents("contentType", value.ContentTypeElement, XmlSerializationHint.Attribute);
            }

            // Serialize element _id
            if (value.LocalIdElement != null)
            {
                writer.WritePrimitiveContents("_id", value.LocalIdElement, XmlSerializationHint.Attribute);
            }

            // Serialize element extension
            if (value.Extension != null && !summary && value.Extension.Count > 0)
            {
                writer.WriteStartArrayElement("extension");
                foreach (var item in value.Extension)
                {
                    writer.WriteStartArrayMember("extension");
                    ExtensionSerializer.SerializeExtension(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element language
            if (value.LanguageElement != null && !summary)
            {
                writer.WriteStartElement("language");
                CodeSerializer.SerializeCode(value.LanguageElement, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element text
            if (value.Text != null && !summary)
            {
                writer.WriteStartElement("text");
                NarrativeSerializer.SerializeNarrative(value.Text, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element contained
            if (value.Contained != null && !summary && value.Contained.Count > 0)
            {
                writer.WriteStartArrayElement("contained");
                foreach (var item in value.Contained)
                {
                    writer.WriteStartArrayMember("contained");
                    FhirSerializer.SerializeResource(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element content
            if (value.ContentElement != null && !summary)
            {
                writer.WritePrimitiveContents("content", value.ContentElement, XmlSerializationHint.TextNode);
            }


            writer.WriteEndComplexContent();
            writer.WriteEndRootObject();
        }
        /// <summary>
        /// Parse Binary
        /// </summary>
        public static Hl7.Fhir.Model.Binary ParseBinary(IFhirReader reader, ErrorList errors, Hl7.Fhir.Model.Binary existingInstance = null)
        {
            Hl7.Fhir.Model.Binary result = existingInstance != null ? existingInstance : new Hl7.Fhir.Model.Binary();
            string currentElementName    = reader.CurrentElementName;

            reader.EnterElement();

            while (reader.HasMoreElements())
            {
                var atName = reader.CurrentElementName;
                // Parse element extension
                if (atName == "extension")
                {
                    result.Extension = new List <Hl7.Fhir.Model.Extension>();
                    reader.EnterArray();

                    while (ParserUtils.IsAtArrayElement(reader, "extension"))
                    {
                        result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
                    }

                    reader.LeaveArray();
                }

                // Parse element language
                else if (atName == "language")
                {
                    result.LanguageElement = CodeParser.ParseCode(reader, errors);
                }

                // Parse element text
                else if (atName == "text")
                {
                    result.Text = NarrativeParser.ParseNarrative(reader, errors);
                }

                // Parse element contained
                else if (atName == "contained")
                {
                    result.Contained = new List <Hl7.Fhir.Model.Resource>();
                    reader.EnterArray();

                    while (ParserUtils.IsAtArrayElement(reader, "contained"))
                    {
                        result.Contained.Add(ParserUtils.ParseContainedResource(reader, errors));
                    }

                    reader.LeaveArray();
                }

                // Parse element _id
                else if (atName == "_id")
                {
                    result.LocalIdElement = Id.Parse(reader.ReadPrimitiveContents(typeof(Id)));
                }

                // Parse element content
                else if (atName == "content")
                {
                    result.ContentElement = Base64Binary.Parse(reader.ReadPrimitiveContents(typeof(Base64Binary)));
                }

                // Parse element contentType
                else if (atName == "contentType")
                {
                    result.ContentTypeElement = FhirString.Parse(reader.ReadPrimitiveContents(typeof(FhirString)));
                }

                else
                {
                    errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
                    reader.SkipSubElementsFor(currentElementName);
                    result = null;
                }
            }

            reader.LeaveElement();
            return(result);
        }