private PublishStatus GetImportStatus(ImportImplementationGuide importIg)
        {
            switch (importIg.status)
            {
            case Shared.ImportExport.Model.ImplementationGuideStatus.Ballot:
                return(PublishStatus.GetBallotStatus(this.tdb));

            case Shared.ImportExport.Model.ImplementationGuideStatus.Published:
                return(PublishStatus.GetPublishedStatus(this.tdb));

            case Shared.ImportExport.Model.ImplementationGuideStatus.Deprecated:
                return(PublishStatus.GetDeprecatedStatus(this.tdb));

            case Shared.ImportExport.Model.ImplementationGuideStatus.Retired:
                return(PublishStatus.GetRetiredStatus(this.tdb));

            default:
                return(PublishStatus.GetDraftStatus(this.tdb));
            }
        }
        public FhirImplementationGuide Convert(ImplementationGuide ig, SummaryType?summaryType = null, bool includeVocabulary = true)
        {
            var parserSettings = new fhir_latest.Hl7.Fhir.Serialization.ParserSettings();

            parserSettings.AcceptUnknownMembers        = true;
            parserSettings.AllowUnrecognizedEnums      = true;
            parserSettings.DisallowXsiAttributesOnRoot = false;
            var fhirXmlParser  = new FhirXmlParser(parserSettings);
            var fhirJsonParser = new FhirJsonParser(parserSettings);

            string url = string.Format("ImplementationGuide/{0}", ig.Id);

            if (!string.IsNullOrEmpty(ig.Identifier) && (ig.Identifier.StartsWith("http://") || ig.Identifier.StartsWith("https://")))
            {
                url = ig.Identifier.TrimEnd('/') + "/" + url.TrimStart('/');
            }

            var fhirImplementationGuide = new FhirImplementationGuide()
            {
                Id   = ig.Id.ToString(),
                Name = ig.Name,
                Url  = url
            };

            // Status
            if (ig.PublishStatus == PublishStatus.GetPublishedStatus(this.tdb))
            {
                fhirImplementationGuide.Status = PublicationStatus.Active;
            }
            else if (ig.PublishStatus == PublishStatus.GetRetiredStatus(this.tdb) || ig.PublishStatus == PublishStatus.GetDeprecatedStatus(this.tdb))
            {
                fhirImplementationGuide.Status = PublicationStatus.Retired;
            }
            else
            {
                fhirImplementationGuide.Status = PublicationStatus.Draft;
            }

            if (summaryType == null || summaryType == SummaryType.Data)
            {
                // Package
                FhirImplementationGuide.PackageComponent package = new FhirImplementationGuide.PackageComponent();
                package.Name = "Profiles in this Implementation Guide";
                fhirImplementationGuide.Package.Add(package);

                // Page: Create a page for the implementation guide. This is required by the fhir ig publisher
                fhirImplementationGuide.Page        = new FhirImplementationGuide.PageComponent();
                fhirImplementationGuide.Page.Kind   = FhirImplementationGuide.GuidePageKind.Page;
                fhirImplementationGuide.Page.Title  = ig.GetDisplayName();
                fhirImplementationGuide.Page.Source = string.Format("{0}://{1}/IG/View/{2}", this.scheme, this.authority, ig.Id);

                // Add profiles to the implementation guide
                List <Template> templates        = ig.GetRecursiveTemplates(this.tdb, inferred: false);
                var             profileResources = (from t in templates.OrderBy(y => y.ImpliedTemplateId)
                                                    select new FhirImplementationGuide.ResourceComponent()
                {
                    Example = false,
                    Source = new ResourceReference()
                    {
                        Reference = string.Format("StructureDefinition/{0}", t.FhirId()),
                        Display = t.Name
                    }
                });
                package.Resource.AddRange(profileResources);

                if (includeVocabulary)
                {
                    // Add value sets to the implementation guide
                    var valueSetsIds = (from t in templates
                                        join tc in this.tdb.TemplateConstraints.AsNoTracking() on t.Id equals tc.TemplateId
                                        where tc.ValueSetId != null
                                        select tc.ValueSetId)
                                       .Distinct()
                                       .ToList();
                    var valueSets = (from vs in this.tdb.ValueSets
                                     join vsi in valueSetsIds on vs.Id equals vsi
                                     select vs).ToList();
                    var valueSetResources = (from vs in valueSets
                                             where vs.GetIdentifier() != null && !vs.GetIdentifier().StartsWith("http://hl7.org/fhir/ValueSet/")    // Ignore value sets in the base spec
                                             select new FhirImplementationGuide.ResourceComponent()
                    {
                        Example = false,
                        Source = new ResourceReference()
                        {
                            Reference = string.Format("ValueSet/{0}", vs.GetFhirId()),
                            Display = vs.Name
                        }
                    });
                    package.Resource.AddRange(valueSetResources);
                }

                // Add each of the individual FHIR resources added as files to the IG
                foreach (var file in ig.Files)
                {
                    var      fileData = file.GetLatestData();
                    Resource resource = null;

                    try
                    {
                        string fileContent = System.Text.Encoding.UTF8.GetString(fileData.Data);

                        if (file.MimeType == "application/xml" || file.MimeType == "text/xml")
                        {
                            resource = fhirXmlParser.Parse <Resource>(fileContent);
                        }
                        else if (file.MimeType == "application/json")
                        {
                            resource = fhirJsonParser.Parse <Resource>(fileContent);
                        }
                    }
                    catch
                    {
                    }

                    if (resource == null || string.IsNullOrEmpty(resource.Id))
                    {
                        continue;
                    }

                    var packageFile = new FhirImplementationGuide.ResourceComponent()
                    {
                        Example = false,
                        Source  = new ResourceReference()
                        {
                            Reference = string.Format("{0}/{1}", resource.ResourceType, resource.Id),
                            Display   = GetResourceName(resource, file.FileName)
                        }
                    };

                    package.Resource.Add(packageFile);
                }

                // Add each of the samples generated for the template/profile
                var templateExamples = (from t in templates
                                        join ts in this.tdb.TemplateSamples on t.Id equals ts.TemplateId
                                        select new { Template = t, Sample = ts });

                foreach (var templateExample in templateExamples)
                {
                    Resource resource = null;

                    try
                    {
                        resource = fhirXmlParser.Parse <Resource>(templateExample.Sample.XmlSample);
                    }
                    catch
                    {
                    }

                    try
                    {
                        if (resource == null)
                        {
                            resource = fhirJsonParser.Parse <Resource>(templateExample.Sample.XmlSample);
                        }
                    }
                    catch
                    {
                    }

                    if (resource == null || string.IsNullOrEmpty(resource.Id))
                    {
                        continue;
                    }

                    var packageExample = new FhirImplementationGuide.ResourceComponent()
                    {
                        Example = true,
                        Source  = new ResourceReference()
                        {
                            Reference = string.Format("{0}/{1}", resource.ResourceType, resource.Id),
                            Display   = GetResourceName(resource, templateExample.Sample.Name)
                        },
                        ExampleFor = new ResourceReference()
                        {
                            Reference = string.Format("StructureDefinition/{0}", templateExample.Template.Bookmark),
                            Display   = templateExample.Template.Name
                        }
                    };

                    package.Resource.Add(packageExample);
                }
            }

            return(fhirImplementationGuide);
        }
        public FhirImplementationGuide Convert(ImplementationGuide ig, SummaryType?summaryType = null)
        {
            var fhirImplementationGuide = new FhirImplementationGuide()
            {
                Id   = ig.Id.ToString(),
                Name = ig.Name,
                Url  = string.Format("ImplementationGuide/{0}", ig.Id)
            };

            // Status
            if (ig.PublishStatus == PublishStatus.GetPublishedStatus(this.tdb))
            {
                fhirImplementationGuide.Status = ConformanceResourceStatus.Active;
            }
            else if (ig.PublishStatus == PublishStatus.GetRetiredStatus(this.tdb) || ig.PublishStatus == PublishStatus.GetDeprecatedStatus(this.tdb))
            {
                fhirImplementationGuide.Status = ConformanceResourceStatus.Retired;
            }
            else
            {
                fhirImplementationGuide.Status = ConformanceResourceStatus.Draft;
            }

            // Package
            FhirImplementationGuide.ImplementationGuidePackageComponent package = new FhirImplementationGuide.ImplementationGuidePackageComponent();
            package.Name = "Profiles in this Implementation Guide";
            fhirImplementationGuide.Package.Add(package);

            if (summaryType == null || summaryType == SummaryType.Data)
            {
                List <Template> templates        = ig.GetRecursiveTemplates(this.tdb, inferred: false);
                var             packageResources = (from t in templates
                                                    select new FhirImplementationGuide.ImplementationGuidePackageResourceComponent()
                {
                    Purpose = FhirImplementationGuide.GuideResourcePurpose.Profile,
                    Source = new ResourceReference()
                    {
                        Reference = string.Format("StructureDefinition/{0}", t.Id),
                        Display = t.Name
                    }
                });

                package.Resource.AddRange(packageResources);
            }

            // Page
            fhirImplementationGuide.Page        = new FhirImplementationGuide.ImplementationGuidePageComponent();
            fhirImplementationGuide.Page.Kind   = FhirImplementationGuide.GuidePageKind.Page;
            fhirImplementationGuide.Page.Name   = ig.GetDisplayName();
            fhirImplementationGuide.Page.Source = string.Format("{0}://{1}/IG/View/{2}", this.scheme, this.authority, ig.Id);

            return(fhirImplementationGuide);
        }
Example #4
0
        public FhirImplementationGuide Convert(ImplementationGuide ig, SummaryType?summaryType = null, bool includeVocabulary = true)
        {
            var fhirImplementationGuide = new FhirImplementationGuide()
            {
                Id   = ig.Id.ToString(),
                Name = ig.Name,
                Url  = string.Format("ImplementationGuide/{0}", ig.Id)
            };

            // Status
            if (ig.PublishStatus == PublishStatus.GetPublishedStatus(this.tdb))
            {
                fhirImplementationGuide.Status = ConformanceResourceStatus.Active;
            }
            else if (ig.PublishStatus == PublishStatus.GetRetiredStatus(this.tdb) || ig.PublishStatus == PublishStatus.GetDeprecatedStatus(this.tdb))
            {
                fhirImplementationGuide.Status = ConformanceResourceStatus.Retired;
            }
            else
            {
                fhirImplementationGuide.Status = ConformanceResourceStatus.Draft;
            }

            if (summaryType == null || summaryType == SummaryType.Data)
            {
                // Package
                FhirImplementationGuide.PackageComponent package = new FhirImplementationGuide.PackageComponent();
                package.Name = "Profiles in this Implementation Guide";
                fhirImplementationGuide.Package.Add(package);

                // Page: Create a page for the implementation guide. This is required by the fhir ig publisher
                fhirImplementationGuide.Page        = new FhirImplementationGuide.PageComponent();
                fhirImplementationGuide.Page.Kind   = FhirImplementationGuide.GuidePageKind.Page;
                fhirImplementationGuide.Page.Title  = ig.GetDisplayName();
                fhirImplementationGuide.Page.Source = string.Format("{0}://{1}/IG/View/{2}", this.scheme, this.authority, ig.Id);

                // Add profiles to the implementation guide
                List <Template> templates        = ig.GetRecursiveTemplates(this.tdb, inferred: false);
                var             profileResources = (from t in templates
                                                    select new FhirImplementationGuide.ResourceComponent()
                {
                    Example = false,
                    Source = new ResourceReference()
                    {
                        Reference = string.Format("StructureDefinition/{0}", t.FhirId()),
                        Display = t.Name
                    }
                });
                package.Resource.AddRange(profileResources);

                if (includeVocabulary)
                {
                    // Add value sets to the implementation guide
                    var valueSets = (from t in templates
                                     join tc in this.tdb.TemplateConstraints on t.Id equals tc.TemplateId
                                     where tc.ValueSet != null
                                     select tc.ValueSet).Distinct().ToList();
                    var valueSetResources = (from vs in valueSets
                                             select new FhirImplementationGuide.ResourceComponent()
                    {
                        Example = false,
                        Source = new ResourceReference()
                        {
                            Reference = string.Format("ValueSet/{0}", vs.Id.ToString()),
                            Display = vs.Name
                        }
                    });
                    package.Resource.AddRange(valueSetResources);
                }

                // Add each of the individual FHIR resources added as files to the IG
                foreach (var file in ig.Files)
                {
                    var      fileData = file.GetLatestData();
                    Resource resource = null;

                    try
                    {
                        string fileContent = System.Text.Encoding.UTF8.GetString(fileData.Data);

                        if (file.MimeType == "application/xml" || file.MimeType == "text/xml")
                        {
                            resource = FhirParser.ParseResourceFromXml(fileContent);
                        }
                        else if (file.MimeType == "application/json")
                        {
                            resource = FhirParser.ParseResourceFromJson(fileContent);
                        }
                    }
                    catch
                    {
                    }

                    if (resource == null || string.IsNullOrEmpty(resource.Id))
                    {
                        continue;
                    }

                    var packageFile = new FhirImplementationGuide.ResourceComponent()
                    {
                        Example = false,
                        Source  = new ResourceReference()
                        {
                            Reference = string.Format("{0}/{1}", resource.ResourceType, resource.Id),
                            Display   = GetResourceName(resource, file.FileName)
                        }
                    };

                    package.Resource.Add(packageFile);
                }

                // Add each of the samples generated for the template/profile
                var templateExamples = (from t in templates
                                        join ts in this.tdb.TemplateSamples on t.Id equals ts.TemplateId
                                        select new { Template = t, Sample = ts });

                foreach (var templateExample in templateExamples)
                {
                    Resource resource = null;

                    try
                    {
                        resource = FhirParser.ParseResourceFromXml(templateExample.Sample.XmlSample);
                    }
                    catch
                    {
                    }

                    try
                    {
                        if (resource == null)
                        {
                            resource = FhirParser.ParseResourceFromJson(templateExample.Sample.XmlSample);
                        }
                    }
                    catch
                    {
                    }

                    if (resource == null || string.IsNullOrEmpty(resource.Id))
                    {
                        continue;
                    }

                    var packageExample = new FhirImplementationGuide.ResourceComponent()
                    {
                        Example = true,
                        Source  = new ResourceReference()
                        {
                            Reference = string.Format("{0}/{1}", resource.ResourceType, resource.Id),
                            Display   = GetResourceName(resource, templateExample.Sample.Name)
                        }
                    };

                    package.Resource.Add(packageExample);
                }
            }

            return(fhirImplementationGuide);
        }
Example #5
0
        /// <summary>
        /// Adds a single template to the implementation guide document.
        /// </summary>
        /// <param name="template">The template to add to the document</param>
        private void AddTemplate(Template template)
        {
            Log.For(this).Trace("BEGIN: Adding template '{0}'.", template.Oid);

            List <TemplateConstraint> templateConstraints = (from tc in this._tdb.TemplateConstraints
                                                             where tc.TemplateId == template.Id
                                                             select tc).ToList();
            List <TemplateConstraint> rootConstraints = templateConstraints
                                                        .Where(y => y.ParentConstraintId == null)
                                                        .OrderBy(y => y.Order)
                                                        .ToList();
            GreenTemplate greenTemplate      = template.GreenTemplates.FirstOrDefault();
            string        bookmarkId         = template.Bookmark;
            string        templateIdentifier = string.Format("identifier: {0}", template.Oid);

            if (!string.IsNullOrEmpty(template.PrimaryContext))
            {
                templateIdentifier = string.Format("{0} (identifier: {1})", template.PrimaryContext, template.Oid);
            }

            this.templateCount++;

            string headingLevel = Properties.Settings.Default.TemplateHeaderStyle;

            if (_exportSettings.AlphaHierarchicalOrder && template.ImpliedTemplateId != null && this._templates.Exists(y => y.Id == template.ImpliedTemplateId))
            {
                headingLevel = Properties.Settings.Default.TemplateHeaderSecondLevelStyle;
            }

            StringBuilder lTitleBuilder = new StringBuilder(string.Format("{0}", template.Name.Substring(1)));

            bool   lDirectlyOwnedTemplate = template.OwningImplementationGuideId == this.implementationGuide.Id;
            bool   lStatusMatches         = template.StatusId == template.OwningImplementationGuide.PublishStatusId;
            string status = "Draft";

            if (_exportSettings.IncludeTemplateStatus || !lDirectlyOwnedTemplate || !lStatusMatches || template.Status == PublishStatus.GetDeprecatedStatus(this._tdb))
            {
                status = template.Status != null ? template.Status.Status : status;
            }

            string lTemplateTitle = lTitleBuilder.ToString();

            // Output the title of the template
            Paragraph pHeading = new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId()
            {
                Val = headingLevel
            }),
                new Run(
                    new Text(template.Name.Substring(0, 1))),
                new Run(
                    new RunProperties(
                        new BookmarkStart()
            {
                Id = bookmarkId, Name = bookmarkId
            },
                        new BookmarkEnd()
            {
                Id = bookmarkId
            }),
                    new Text(lTemplateTitle)));

            if (!string.IsNullOrEmpty(template.Notes) && this._exportSettings.IncludeNotes)
            {
                this._commentManager.AddCommentRange(pHeading, template.Notes);
            }

            this._document.MainDocumentPart.Document.Body.AppendChild(pHeading);

            // Output the "bracket data" for the template
            string detailsText = string.Format("identifier: {0} ({1})", template.Oid, template.IsOpen == true ? "open" : "closed");

            if (!string.IsNullOrEmpty(template.PrimaryContext))
            {
                detailsText = string.Format("[{0}: identifier {1} ({2})]",
                                            template.PrimaryContext,
                                            template.Oid,
                                            template.IsOpen == true ? "open" : "closed");
            }

            Paragraph pDetails = new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId()
            {
                Val = Properties.Settings.Default.TemplateLocationStyle
            }),
                DocHelper.CreateRun(detailsText));

            this._document.MainDocumentPart.Document.Body.AppendChild(pDetails);

            //Output IG publish/draft info with "bracket data" format
            string igText = string.Format("{0} as part of {1}", status, template.OwningImplementationGuide.GetDisplayName());

            Paragraph igDetails = new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId()
            {
                Val = Properties.Settings.Default.TemplateLocationStyle
            }),
                DocHelper.CreateRun(igText));

            this._document.MainDocumentPart.Document.Body.AppendChild(igDetails);

            // If we were told to generate context tables for the template...
            if (_exportSettings.GenerateTemplateContextTable)
            {
                TemplateContextTable.AddTable(this._tdb, this.tables, this._document.MainDocumentPart.Document.Body, template, this._templates);
            }

            // Output the template's description
            if (!string.IsNullOrEmpty(template.Description))
            {
                this.wikiParser.ParseAndAppend(template.Description, this._document.MainDocumentPart.Document.Body);
            }

            // If we were told to generate tables for the template...
            if (_exportSettings.GenerateTemplateConstraintTable)
            {
                this.constraintTableGenerator.AddTemplateConstraintTable(template, this._document.MainDocumentPart.Document.Body, templateIdentifier);
            }

            if (templateConstraints.Count(y => y.IsHeading) > 0)
            {
                Paragraph propertiesHeading = new Paragraph(
                    new ParagraphProperties(
                        new ParagraphStyleId()
                {
                    Val = Properties.Settings.Default.PropertiesHeadingStyle
                }),
                    DocHelper.CreateRun("Properties"));
                this._document.MainDocumentPart.Document.Body.AppendChild(propertiesHeading);
            }

            // Output the implied template conformance line
            if (template.ImpliedTemplate != null)
            {
                OpenXmlElement templateReference = !this._templates.Contains(template.ImpliedTemplate) ?
                                                   (OpenXmlElement)DocHelper.CreateRun(template.ImpliedTemplate.Name) :
                                                   (OpenXmlElement)DocHelper.CreateAnchorHyperlink(template.ImpliedTemplate.Name, template.ImpliedTemplate.Bookmark, Properties.Settings.Default.LinkStyle);

                Paragraph impliedConstraint = new Paragraph(
                    new ParagraphProperties(
                        new NumberingProperties(
                            new NumberingLevelReference()
                {
                    Val = 0
                },
                            new NumberingId()
                {
                    Val = GenerationConstants.BASE_TEMPLATE_INDEX + (int)template.Id
                })),
                    DocHelper.CreateRun("Conforms to "),
                    templateReference,
                    DocHelper.CreateRun(" template "),
                    DocHelper.CreateRun("(identifier: " + template.ImpliedTemplate.Oid + ")", style: Properties.Settings.Default.TemplateOidStyle),
                    DocHelper.CreateRun("."));
                this._document.MainDocumentPart.Document.Body.Append(impliedConstraint);
            }

            bool lCreateValueSetTables = _exportSettings.DefaultValueSetMaxMembers > 0;

            IConstraintGenerator constraintGenerator = ConstraintGenerationFactory.NewConstraintGenerator(
                this._settings,
                this._document.MainDocumentPart.Document.Body,
                this._commentManager,
                this.figures,
                this.wikiParser,
                _exportSettings.IncludeXmlSamples,
                _tdb,
                rootConstraints,
                templateConstraints,
                template,
                this._templates,
                Properties.Settings.Default.ConstraintHeadingStyle,
                _exportSettings.SelectedCategories);

            constraintGenerator.GenerateConstraints(lCreateValueSetTables, this._exportSettings.IncludeNotes);

            // Add value-set tables
            if (lCreateValueSetTables)
            {
                var constraintValueSets = (from c in templateConstraints
                                           where c.ValueSet != null
                                           select new { ValueSet = c.ValueSet, ValueSetDate = c.ValueSetDate })
                                          .Distinct();

                foreach (var cConstraintValueSet in constraintValueSets)
                {
                    DateTime?bindingDate = cConstraintValueSet.ValueSetDate != null ? cConstraintValueSet.ValueSetDate : this.implementationGuide.PublishDate;

                    if (bindingDate == null)
                    {
                        bindingDate = DateTime.Now;
                    }

                    this.valueSetsExport.AddValueSet(cConstraintValueSet.ValueSet, bindingDate.Value);
                }
            }

            if (_exportSettings.IncludeXmlSamples)
            {
                foreach (var lSample in template.TemplateSamples.OrderBy(y => y.Id))
                {
                    this.figures.AddSample(lSample.Name, lSample.XmlSample);
                }
            }

            Log.For(this).Trace("END: Adding template '{0}' with {1} constraints.", template.Oid, templateConstraints.Count);
        }