private static void ProcessEncounters(List<TimelineEntry> timeline, Bundle matchingEncounters)
        {
            foreach (var encounter in matchingEncounters.Entries.Select(x => (ResourceEntry<Encounter>)x))
            {
                DateTimeOffset? startTime;
                DateTimeOffset? endTime;

                if (encounter.Resource.Hospitalization != null)
                {
                    startTime = DateTimeOffset.Parse(encounter.Resource.Hospitalization.Period.Start);
                    endTime = DateTimeOffset.Parse(encounter.Resource.Hospitalization.Period.End);
                }
                else
                {
                    startTime = encounter.Published;
                    endTime = encounter.Published;
                }

                timeline.Add(new TimelineEntry
                {
                    StartTime = startTime,
                    EndTime = endTime,
                    TypeOfEntry = TimelineEntryType.Encounter,
                    Summary = encounter.Resource.Reason.ToString()
                });
            }
        }
        internal static IMongoQuery ResourceFilter(string resourceType)
        {
            var queries = new List<IMongoQuery>();
            queries.Add(M.Query.EQ(InternalField.LEVEL, 0));
            queries.Add(M.Query.EQ(InternalField.RESOURCE, resourceType));

            return M.Query.And(queries);
        }
        public static void SetBundleType(this Bundle bundle, BundleType type)
        {
            List<Tag> result = new List<Tag>(bundle.Tags.Exclude(new Tag[] { MESSAGE_TAG, DOCUMENT_TAG }));

            if (type == BundleType.Document)
                result.Add(DOCUMENT_TAG);
            else if (type == BundleType.Message)
                result.Add(MESSAGE_TAG);

            bundle.Tags = result;
        }
        public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var result = new List<ValidationResult>();
            result.AddRange(base.Validate(validationContext));

            if (When == null)
                result.Add(new ValidationResult("A DeletedEntry must have a non-null deletion time (When)"));

            if (!result.Any()) result.Add(ValidationResult.Success);

            return result;
        }
Exemple #5
0
        public static Expression ToExpression(this Quantity quantity)
        {
            quantity = System.Canonical(quantity);
            string searchable = quantity.LeftSearchableString();

            var values = new List<ValueExpression>();
            values.Add(new IndexValue("system", new StringValue(UCUM.Uri.ToString())));
            values.Add(new IndexValue("value", new NumberValue(quantity.Value.ToDecimal())));
            values.Add(new IndexValue("decimals", new StringValue(searchable)));
            values.Add(new IndexValue("unit", new StringValue(quantity.Metric.ToString())));

            return new CompositeValue(values);
        }
        public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var result = new List<ValidationResult>();
            result.AddRange(base.Validate(validationContext));

            if (Content == null)
                result.Add(new ValidationResult("Entry must contain (possibly 0-length) data in Content element"));

            if (ContentType == null)
                result.Add(new ValidationResult("Entry must contain a ContentType"));

            return result;
        }
        public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var result = new List<ValidationResult>(base.Validate(validationContext));

            if (this.Contained != null)
            {
                if (!Contained.OfType<DomainResource>().All(dr => dr.Text == null))
                    result.Add(new ValidationResult("Resource has contained resources with narrative"));

                if(!Contained.OfType<DomainResource>().All(cr => cr.Contained == null || !cr.Contained.Any()))
                    result.Add(new ValidationResult("Resource has contained resources with nested contained resources"));
            }

            return result;
        }
        public IEnumerable<Patient> GetAllPatients()
        {
            var patients = new List<Patient>();

            var patientsExist = true;
            var i = 1;

            while (patientsExist)
            {
                try
                {
                    var patient = _client.Read<Patient>(i.ToString());

                    patients.Add(patient.Resource);

                    i++;
                }
                catch (FhirOperationException)
                {
                    patientsExist = false;
                }
            }

            return patients;
        }
Exemple #9
0
        public static ICollection<Tag> ParseCategoryHeader(string value)
        {
            if (String.IsNullOrEmpty(value)) return new List<Tag>();

            var result = new List<Tag>();

            var categories = value.SplitNotInQuotes(',').Where(s => !String.IsNullOrEmpty(s));

            foreach (var category in categories)
            {
                var values = category.SplitNotInQuotes(';').Where(s => !String.IsNullOrEmpty(s));

                if (values.Count() >= 1)
                {
                    var term = values.First();

                    var pars = values.Skip(1).Select( v =>
                        { 
                            var vsplit = v.Split('=');
                            var item1 = vsplit[0].Trim();
                            var item2 = vsplit.Length > 1 ? vsplit[1].Trim() : null;
                            return new Tuple<string,string>(item1,item2);
                        });

                    var scheme = new Uri(pars.Where(t => t.Item1 == "scheme").Select(t => t.Item2.Trim('\"')).FirstOrDefault(), UriKind.RelativeOrAbsolute);
                    var label = pars.Where(t => t.Item1 == "label").Select(t => t.Item2.Trim('\"')).FirstOrDefault();
                       
                    result.Add(new Tag(term,scheme,label));
                }
            }

            return result;
        }
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var result = new List<ValidationResult>();

            if (String.IsNullOrWhiteSpace(Title))
                result.Add(new ValidationResult("Feed must contain a title"));

            if (!UriHasValue(Id))
                result.Add(new ValidationResult("Feed must have an id"));
            else
                if (!Id.IsAbsoluteUri)
                    result.Add(new ValidationResult("Feed id must be an absolute URI"));

            if (LastUpdated == null)
                result.Add(new ValidationResult("Feed must have a updated date"));

            if (Links.SearchLink != null)
                result.Add(new ValidationResult("Links with rel='search' can only be used on feed entries"));

            bool feedHasAuthor = !String.IsNullOrEmpty(this.AuthorName);

            if (Entries != null)
            {
                foreach (var entry in Entries.Where(e => e != null))
                {
                    if (!feedHasAuthor && entry is ResourceEntry && String.IsNullOrEmpty(((ResourceEntry)entry).AuthorName))
                        result.Add(new ValidationResult("Bundle's author and Entry author cannot both be empty"));

                    Validator.TryValidateObject(entry, ValidationContextFactory.Create(entry, null), result, true);
                }
            }

            return result;
        }
Exemple #11
0
        public static Expression NonUcumIndexedExpression(this FM.Quantity quantity)
        {
            var values = new List<ValueExpression>();
            if (quantity.System != null)
                values.Add(new IndexValue("system", new StringValue(quantity.System)));

            if (quantity.Unit != null)
                values.Add(new IndexValue("unit", new StringValue(quantity.Unit)));

            if (quantity.Value.HasValue)
                values.Add(new IndexValue("value", new NumberValue(quantity.Value.Value)));

            if (values.Any())
                return new CompositeValue(values);

            return null;
        }
Exemple #12
0
 private IMongoQuery ParametersToQuery(IEnumerable<IParameter> parameters)
 {
     List<IMongoQuery> queries = new List<IMongoQuery>();
     queries.Add(M.Query.EQ(InternalField.LEVEL, 0)); // geindexeerde contained documents overslaan
     IEnumerable<IMongoQuery> q = parameters.Select(p => ParameterToQuery(p));
     queries.AddRange(q);
     return M.Query.And(queries);
 }
        private void genProfile(List<Row> rows, Profile profile, bool extensionsOnly)
        {
            if (!extensionsOnly)
            {
                var r = new  Row();
                rows.Add(r);
                r.setIcon("icon_profile.png");
                r.getCells().Add(new  Cell(null, null, profile.Name, null, null));
                r.getCells().Add(new  Cell());
                r.getCells().Add(new  Cell(null, null, "Profile", null, null));
                r.getCells().Add(new  Cell(null, null, profile.Description, null, null));

                foreach (var s in profile.Structure)
                {
                    var re = new  Row();
                    r.getSubRows().Add(re);
                    re.setIcon("icon_resource.png");
                    re.getCells().Add(new  Cell(null, null, s.Name, null, null));
                    re.getCells().Add(new  Cell(null, null, "", null, null));
                    re.getCells().Add(new  Cell(null, null, s.Type, null, null));

                    re.getCells().Add(new  Cell(null, null, s.Element[0].Definition.Short, null, null));     // DSTU1
                    //re.getCells().Add(new  Cell(null, null, s.Base, null, null));       // DSTU2
                }
            }

            if (profile.ExtensionDefn.Any() || extensionsOnly)
            {
                var re = new  Row();
                rows.Add(re);
                re.setIcon("icon_profile.png");
                re.getCells().Add(new  Cell(null, null, "Extensions", null, null));
                re.getCells().Add(new  Cell());
                re.getCells().Add(new  Cell());

                re.getCells().Add(new  Cell(null, null, "Extensions defined by this profile", null, null)); // DSTU1
                //re.getCells().Add(new  Cell(null, null, "Extensions defined by the URL \"" + profile.Url + "\"", null, null)); // DSTU2

                foreach (var ext in profile.ExtensionDefn)
                {
                    genExtension(re.getSubRows(), ext, true);
                }
            }

        }
        public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var result = new List<ValidationResult>();

            if (Id != null && !Id.IsAbsoluteUri)
                result.Add(FhirValidator.BuildResult(validationContext, "Entry id must be an absolute URI"));

            if (Bundle.UriHasValue(SelfLink) && !SelfLink.IsAbsoluteUri)
                result.Add(FhirValidator.BuildResult(validationContext, "Entry selflink must be an absolute URI"));

            if (Links.FirstLink != null || Links.LastLink != null || Links.PreviousLink != null || Links.NextLink != null)
                result.Add(FhirValidator.BuildResult(validationContext, "Paging links can only be used on feeds, not entries"));

            if (Tags != null && validationContext.ValidateRecursively())
                FhirValidator.TryValidate(Tags,result,true);

            return result;
        }
        public IEnumerable<Tuple<string, IFhirReader>> GetMembers()
        {
            if (_current is XElement)
            {
                var rootElem = (XElement)_current;
                var result = new List<Tuple<string, IFhirReader>>();

                // First, any attributes
                foreach(var attr in rootElem.Attributes()) //.Where(xattr => xattr.Name.LocalName != "xmlns"))
                {
                    if (attr.Name == XName.Get("xmlns", "")) continue;      // skip xmlns declarations
                    if (attr.Name == XName.Get("{http://www.w3.org/2000/xmlns/}xsi") && !SerializationConfig.EnforceNoXsiAttributesOnRoot ) continue;   // skip xmlns:xsi declaration
                    if (attr.Name == XName.Get("{http://www.w3.org/2001/XMLSchema-instance}schemaLocation") && !SerializationConfig.EnforceNoXsiAttributesOnRoot) continue;     // skip schemaLocation

                    if (attr.Name.NamespaceName == "")
                        result.Add(Tuple.Create(attr.Name.LocalName, (IFhirReader)new XmlDomFhirReader(attr)));
                    else
                        throw Error.Format("Encountered unsupported attribute {0}", this, attr.Name);
                }
                
                foreach(var node in rootElem.Nodes())
                {
                    if(node is XText)
                    {
                        // A nested text node (the content attribute of a Binary)
                        result.Add(Tuple.Create(SerializationConfig.BINARY_CONTENT_MEMBER_NAME, (IFhirReader)new XmlDomFhirReader(node)));
                    }
                    else if(node is XElement)
                    {
                        var elem = (XElement)node;
                        
                        // All normal elements
                        if(elem.Name.NamespaceName == SerializationUtil.FHIRNS)
                            result.Add(Tuple.Create(elem.Name.LocalName, (IFhirReader)new XmlDomFhirReader(elem)));

                        // The special xhtml div element
                        else if(elem.Name == XHTMLDIV)
                            result.Add(Tuple.Create(XHTMLDIV.LocalName,
                                (IFhirReader)new XmlDomFhirReader(buildDivXText(elem))));

                        else
                            throw Error.Format("Encountered element '{0}' from unsupported namespace '{1}'", this, elem.Name.LocalName, elem.Name.NamespaceName);
                    }
                    else if(node is XComment)
                    {
                        // nothing
                    }
                    else
                        throw Error.Format("Encountered unexpected element member of type {0}", this, node.GetType().Name);
                }

                return result;
            }
            else
                throw Error.Format("Cannot get members: reader not at an element", this);
            
        }
 public static IList<Interaction> GetInteractions(this ILocalhost localhost, Bundle bundle)
 {
     var interactions = new List<Interaction>();
     foreach(var entry in bundle.Entry)
     {
         Interaction interaction = localhost.ToInteraction(entry);
         interaction.SupplementBase(bundle.Base);
         interactions.Add(interaction);
     }
     return interactions;
 }
        public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            // TODO: Contained resources share the same internal id resolution space as the parent
            // resource -> verify id uniqueness
            var result = new List<ValidationResult>();
          
            if (Contained != null)
            {
                foreach (var contained in Contained)
                {
                    if (contained.Contained != null && contained.Contained.Any())
                        result.Add(new ValidationResult("Contained resources cannot contain nested contained resources"));

                    if (contained.Text != null)
                        result.Add(new ValidationResult("Contained resources should not contain narrative"));

                }
            }

            return result;
        }
Exemple #18
0
 private static IEnumerable<Type> LoadSupportedTypesFromAssembly(Assembly fhirAssembly)
 {
     var result = new List<Type>();
     foreach (Type fhirType in fhirAssembly.GetTypes())
     {
         if (typeof(Resource).IsAssignableFrom(fhirType) || typeof(Element).IsAssignableFrom(fhirType)) //It is derived of Resource or Element, so we should support it.
         {
             result.Add(fhirType);
         }
     }
     return result;
 }
        public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var result = new List<ValidationResult>();

            if (!Bundle.UriHasValue(Id))
                result.Add(new ValidationResult("Entry must have an id"));
            else
                if (!Id.IsAbsoluteUri)
                    result.Add(new ValidationResult("Entry id must be an absolute URI"));

            if (Bundle.UriHasValue(SelfLink) && !SelfLink.IsAbsoluteUri)
                result.Add(new ValidationResult("Entry selflink must be an absolute URI"));

            if (Links.FirstLink != null || Links.LastLink != null || Links.PreviousLink != null || Links.NextLink != null)
                result.Add(new ValidationResult("Paging links can only be used on feeds, not entries"));

            if (Tags != null)
                result.AddRange(new TagList(Tags).Validate(validationContext));

            return result;
        }
        public static void SetTextTag(this BundleEntry entry, string text)
        {
            var result = new List<Tag>();

            if (entry.Tags != null) result.AddRange(entry.Tags);

            result.RemoveAll(t => Equals(t.Scheme,Tag.FHIRTAGSCHEME_GENERAL) &&
                    (t.Term != null && t.Term.StartsWith(TAG_TERM_TEXT)));

            result.Add(new Tag(TAG_TERM_TEXT + Uri.EscapeUriString(text), Tag.FHIRTAGSCHEME_GENERAL, text));

            entry.Tags = result;
        }
Exemple #21
0
        public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            // TODO: Contained resources share the same internal id resolution space as the parent
            // resource -> verify id uniqueness
            var result = new List<ValidationResult>();

            // Validate specific invariants for contained items. The content of the contained
            // items is validated by the "normal" validation triggered by the FhirElement attribute
            if (Contained != null)
            {
                foreach (var contained in Contained)
                {
                    if (contained.Contained != null && contained.Contained.Any())
                        result.Add(FhirValidator.BuildResult(validationContext, "Contained resources cannot contain nested contained resources"));

                    if (contained.Text != null)
                        result.Add(FhirValidator.BuildResult(validationContext, "Contained resources should not contain narrative"));
                }
            }

            return result;
        }
Exemple #22
0
        internal static PropertyMapping Create(PropertyInfo prop, out IEnumerable<Type> referredTypes)        
        {
            if (prop == null) throw Error.ArgumentNull("prop");

            var foundTypes = new List<Type>();

            PropertyMapping result = new PropertyMapping();

#if PORTABLE45
			var elementAttr = prop.GetCustomAttribute<FhirElementAttribute>();
#else
			var elementAttr = (FhirElementAttribute)Attribute.GetCustomAttribute(prop, typeof(FhirElementAttribute));
#endif
       
            result.Name = determinePropertyName(prop);
            result.ReturnType = prop.PropertyType;
            result.ElementType = result.ReturnType;

            result.InSummary = elementAttr != null ? elementAttr.InSummary : false;            
            result.Choice = elementAttr != null ? elementAttr.Choice : ChoiceType.None;

            if (elementAttr != null)
            {
                result.SerializationHint = elementAttr.XmlSerialization;
                result.Order = elementAttr.Order;
            }

            foundTypes.Add(result.ElementType);

            result.IsCollection = ReflectionHelper.IsTypedCollection(prop.PropertyType) && !prop.PropertyType.IsArray;

            // Get to the actual (native) type representing this element
            if (result.IsCollection) result.ElementType = ReflectionHelper.GetCollectionItemType(prop.PropertyType);
            if (ReflectionHelper.IsNullableType(result.ElementType)) result.ElementType = ReflectionHelper.GetNullableArgument(result.ElementType);
            result.IsPrimitive = isAllowedNativeTypeForDataTypeValue(result.ElementType);

            // Check wether this property represents a native .NET type
            // marked to receive the class' primitive value in the fhir serialization
            // (e.g. the value from the Xml 'value' attribute or the Json primitive member value)
            if(result.IsPrimitive) result.RepresentsValueElement = isPrimitiveValueElement(prop);

            referredTypes = foundTypes;

            // May need to generate getters/setters using pre-compiled expression trees for performance.
            // See http://weblogs.asp.net/marianor/archive/2009/04/10/using-expression-trees-to-get-property-getter-and-setters.aspx
            result._getter = instance => prop.GetValue(instance, null);
            result._setter = (instance,value) => prop.SetValue(instance, value, null);
            
            return result;
        }
Exemple #23
0
        public FhirModel(Dictionary<Type, string> csTypeToFhirTypeNameMapping, IEnumerable<SearchParamDefinition> searchParameters, List<Type> enums)
        {
            LoadSearchParameters(searchParameters);
            _csTypeToFhirTypeName = csTypeToFhirTypeNameMapping;
            _fhirTypeNameToCsType = _csTypeToFhirTypeName.ToLookup(pair => pair.Value, pair => pair.Key).ToDictionary(group => group.Key, group => group.FirstOrDefault());

            _enumMappings = new List<EnumMapping>();
            foreach (var enumType in enums)
            {
                if (EnumMapping.IsMappableEnum(enumType))
                {
                    _enumMappings.Add(EnumMapping.Create(enumType));
                }
            }
        }
Exemple #24
0
        public static IEnumerable<Uri> GetReferences(this BundleEntry entry, string include)
        {
            Resource resource = (entry as ResourceEntry).Resource;
            ElementQuery query = new ElementQuery(include);
            var list = new List<Uri>();

            query.Visit(resource, element =>
            {
                if (element is ResourceReference)
                {
                    Uri uri = (element as ResourceReference).Url;
                    if (uri != null) list.Add(uri);
                }
            });
            return list.Where(u => u != null);
        }
        private static void ProcessAlerts(List<TimelineEntry> timeline, Bundle matchingAlerts)
        {
            foreach (var encounter in matchingAlerts.Entries.Select(x => (ResourceEntry<Alert>)x))
            {
                var startTime = encounter.Published;
                var endTime = encounter.Published;

                timeline.Add(new TimelineEntry
                {
                    StartTime = startTime,
                    EndTime = endTime,
                    TypeOfEntry = TimelineEntryType.Alert,
                    Summary = encounter.Resource.Note
                });
            }
        }
        /// <summary>
        /// Rewrites the Path's of the elements in a structure so they are based on the given path: the root
        /// of the given structure will become the given path, it's children will be relocated below that path
        /// </summary>
        /// <param name="root">The structure that will be rebased on the path</param>
        /// <param name="path">The path to rebase the structure on</param>
        public static void Rebase(this Profile.ProfileStructureComponent root, string path)
        {
            var nav = new ElementNavigator(root);

            if (nav.MoveToFirstChild())
            {
                var newPaths = new List<string>();
                newPaths.Add(path);

                rebaseChildren(nav, path, newPaths);

                // Can only change the paths after navigating the tree, otherwise the
                // navigation functions (which are based on the paths) won't function correctly
                for (var i = 0; i < root.Element.Count; i++)
                    root.Element[i].Path = newPaths[i];
            }
        }
        //internal static IList<Tag> ParseTags(XmlReader xr)
        //{
        //    xr.MoveToContent();

        //    var taglist = (XElement)XElement.ReadFrom(xr);

        //    if (taglist.Name == BundleXmlParser.XFHIRNS + TagListSerializer.TAGLIST_TYPE)
        //    {
        //        if (taglist.Elements().All(xe => xe.Name == BundleXmlParser.XFHIRNS + BundleXmlParser.XATOM_CATEGORY))
        //            return ParseTags(taglist.Elements());
        //        else
        //            throw Error.Format("TagList contains unexpected child elements");
        //    }
        //    else
        //        throw Error.Format("Unexpected element name {0} found at start of TagList", taglist.Name);
        //}

        //internal static IList<Tag> ParseTags(JsonReader xr)
        //{
        //    var tagObj = JObject.Load(xr);

        //    var tagType = tagObj[SerializationConfig.RESOURCETYPE_MEMBER_NAME];
        //    if(tagType == null || tagType.Value<string>() != TagListSerializer.TAGLIST_TYPE)
        //        throw Error.Format("TagList should start with a resourceType member TagList");

        //    var categoryArray = tagObj[BundleXmlParser.XATOM_CATEGORY] as JArray;
        //    if (categoryArray != null)
        //        return ParseTags(categoryArray);
        //    else
        //        return new List<Tag>();
        //}

        internal static IList<Tag> ParseTags(IEnumerable<XElement> tags)
        {
            var result = new List<Tag>();

            if (tags != null)
            {
                foreach (var tag in tags)
                {
                    var scheme = SerializationUtil.StringValueOrNull(tag.Attribute(BundleXmlParser.XATOM_CAT_SCHEME));
                    var term = SerializationUtil.StringValueOrNull(tag.Attribute(BundleXmlParser.XATOM_CAT_TERM));
                    var label = SerializationUtil.StringValueOrNull(tag.Attribute(BundleXmlParser.XATOM_CAT_LABEL));

                    result.Add(new Tag(term,scheme,label));
                }
            }

            return result;
        }
Exemple #28
0
        public List<Resource> GetExampleData()
        {
            var list = new List<Resource>();

            Bundle data = Examples.ImportEmbeddedZip().LimitPerType(5).ToBundle(localhost.Base);

            if (data.Entry != null && data.Entry.Count() != 0)
            {
                foreach (var entry in data.Entry)
                {
                    if (entry.Resource != null)
                    {
                        list.Add((Resource)entry.Resource);
                    }
                }
            }
            return list;
        }
        internal static IList<Tag> ParseTags(JToken token)
        {
            var result = new List<Tag>();
            var tags = token as JArray;

            if (tags != null)
            {
                foreach (var tag in tags)
                {
                    var scheme = tag.Value<string>(BundleXmlParser.XATOM_CAT_SCHEME);
                    var term = tag.Value<string>(BundleXmlParser.XATOM_CAT_TERM);
                    var label = tag.Value<string>(BundleXmlParser.XATOM_CAT_LABEL);
                    
                    result.Add(new Tag(term,scheme,label));
                }
            }

            return result;
        }
        private static void rebaseChildren(BaseElementNavigator nav, string path, List<string> newPaths)
        {
            var bm = nav.Bookmark();

            if (nav.MoveToFirstChild())
            {
                do
                {
                    var newPath = path + "." + nav.Current.GetNameFromPath();

                    newPaths.Add(newPath);

                    if(nav.HasChildren) 
                        rebaseChildren(nav, newPath, newPaths);
                }
                while (nav.MoveToNext());

                nav.ReturnToBookmark(bm);
            }
        }