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);
        }
Esempio n. 2
0
        public string[] GetValueSetOidsForImplementationGuide(int implementationGuideId)
        {
            try
            {
                TDBImplementationGuide ig = tdb.ImplementationGuides.SingleOrDefault(y => y.Id == implementationGuideId);

                if (ig == null)
                {
                    throw new Exception("Could not find ImplementationGuide specified.");
                }

                List <Template> templates = ig.GetRecursiveTemplates(tdb);
                return((from t in templates
                        join tc in tdb.TemplateConstraints on t.Id equals tc.TemplateId
                        join vs in tdb.ValueSets on tc.ValueSetId equals vs.Id
                        where tc.ValueSetId != null
                        select vs).Distinct().Select(vs => vs.Oid).ToArray());
            }
            catch (Exception ex)
            {
                Log.For(this).Critical("Error occurred while retrieving valueset oids for an implementation guide.", ex);
                throw;
            }
        }
        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);
        }
Esempio n. 4
0
        public HttpResponseMessage Export(ExportSettingsModel model)
        {
            ImplementationGuide ig = this.tdb.ImplementationGuides.SingleOrDefault(y => y.Id == model.ImplementationGuideId);

            if (model.TemplateIds == null)
            {
                model.TemplateIds = ig.GetRecursiveTemplates(this.tdb, categories: model.SelectedCategories.ToArray()).Select(y => y.Id).ToList();
            }

            List <Template>   templates    = this.tdb.Templates.Where(y => model.TemplateIds.Contains(y.Id)).ToList();
            SimpleSchema      schema       = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, ig.ImplementationGuideType);
            IIGTypePlugin     igTypePlugin = IGTypePluginFactory.GetPlugin(ig.ImplementationGuideType);
            IGSettingsManager igSettings   = new IGSettingsManager(this.tdb, model.ImplementationGuideId);
            bool   isCDA = ig.ImplementationGuideType.SchemaURI == "urn:hl7-org:v3";
            string fileName;

            byte[] export;
            string contentType = null;

            switch (model.ExportFormat)
            {
            case ExportFormats.FHIR_Build_Package:
            case ExportFormats.FHIR_Bundle:
            case ExportFormats.Native_XML:
            case ExportFormats.Templates_DSTU_XML:
                string fileExtension = model.ReturnJson ? "json" : "xml";
                contentType = model.ReturnJson ? JSON_MIME_TYPE : XML_MIME_TYPE;

                if (model.ExportFormat == ExportFormats.FHIR_Build_Package)
                {
                    fileExtension = "zip";
                    contentType   = ZIP_MIME_TYPE;
                }

                fileName = string.Format("{0}.{1}", ig.GetDisplayName(true), fileExtension);
                var pluginExporter = igTypePlugin.GetExporter();
                export = pluginExporter.Export(this.tdb, schema, model.ExportFormat, igSettings, model.SelectedCategories, templates, model.IncludeVocabulary, model.ReturnJson);
                break;

            case ExportFormats.Snapshot_JSON:
                ImplementationGuideController ctrl = new ImplementationGuideController(this.tdb);
                var dataModel = ctrl.GetViewData(model.ImplementationGuideId, null, null, true);

                // Serialize the data to JSON
                var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                jsonSerializer.MaxJsonLength = Int32.MaxValue;
                export = System.Text.Encoding.UTF8.GetBytes(jsonSerializer.Serialize(dataModel));

                // Set the filename to JSON
                fileName    = string.Format("{0}.json", ig.GetDisplayName(true));
                contentType = JSON_MIME_TYPE;
                break;

            case ExportFormats.Microsoft_Word_DOCX:
                ImplementationGuideGenerator generator = new ImplementationGuideGenerator(this.tdb, model.ImplementationGuideId, model.TemplateIds);
                fileName = string.Format("{0}.docx", ig.GetDisplayName(true));

                ExportSettings lConfig = new ExportSettings();
                lConfig.Use(c =>
                {
                    c.GenerateTemplateConstraintTable = model.TemplateTables == TemplateTableOptions.ConstraintOverview || model.TemplateTables == TemplateTableOptions.Both;
                    c.GenerateTemplateContextTable    = model.TemplateTables == TemplateTableOptions.Context || model.TemplateTables == TemplateTableOptions.Both;
                    c.GenerateDocTemplateListTable    = model.DocumentTables == DocumentTableOptions.List || model.DocumentTables == DocumentTableOptions.Both;
                    c.GenerateDocContainmentTable     = model.DocumentTables == DocumentTableOptions.Containment || model.DocumentTables == DocumentTableOptions.Both;
                    c.AlphaHierarchicalOrder          = model.TemplateSortOrder == TemplateSortOrderOptions.AlphaHierarchically;
                    c.DefaultValueSetMaxMembers       = model.ValueSetTables ? model.MaximumValueSetMembers : 0;
                    c.GenerateValueSetAppendix        = model.ValueSetAppendix;
                    c.IncludeXmlSamples     = model.IncludeXmlSample;
                    c.IncludeChangeList     = model.IncludeChangeList;
                    c.IncludeTemplateStatus = model.IncludeTemplateStatus;
                    c.IncludeNotes          = model.IncludeNotes;
                    c.IncludeVolume1        = model.IncludeVolume1;
                    c.SelectedCategories    = model.SelectedCategories;
                    c.GenerateRequiredAndOptionalSectionsTable = model.GenerateRequiredAndOptionalSectionsTable;
                    c.DocumentTemplateTypeId = model.DocumentTemplateTypeId;
                    c.SectionTemplateTypeId  = model.SectionTemplateTypeId;
                });

                if (model.ValueSetOid != null && model.ValueSetOid.Count > 0)
                {
                    Dictionary <string, int> valueSetMemberMaximums = new Dictionary <string, int>();

                    for (int i = 0; i < model.ValueSetOid.Count; i++)
                    {
                        if (valueSetMemberMaximums.ContainsKey(model.ValueSetOid[i]))
                        {
                            continue;
                        }

                        valueSetMemberMaximums.Add(model.ValueSetOid[i], model.ValueSetMaxMembers[i]);
                    }

                    lConfig.ValueSetMaxMembers = valueSetMemberMaximums;
                }

                generator.BuildImplementationGuide(lConfig, ig.ImplementationGuideType.GetPlugin());
                export      = generator.GetDocument();
                contentType = DOCX_MIME_TYPE;
                break;

            case ExportFormats.Schematron_SCH:
                string schematronResult = SchematronGenerator.Generate(tdb, ig, model.IncludeCustomSchematron, VocabularyOutputType.Default, model.VocabularyFileName, templates, model.SelectedCategories, model.DefaultSchematron);
                export      = ASCIIEncoding.UTF8.GetBytes(schematronResult);
                fileName    = string.Format("{0}.sch", ig.GetDisplayName(true));
                contentType = XML_MIME_TYPE;

                if (model.IncludeVocabulary)
                {
                    using (ZipFile zip = new ZipFile())
                    {
                        zip.AddEntry(fileName, export);

                        NativeTerminologyExporter nativeTermExporter = new NativeTerminologyExporter(this.tdb);
                        byte[] vocData     = nativeTermExporter.GetExport(ig.Id, model.MaximumValueSetMembers, this.GetExportEncoding(model));
                        string vocFileName = string.Format("{0}", model.VocabularyFileName);

                        //Ensuring the extension is present in case input doesn't have it
                        if (vocFileName.IndexOf(".xml") == -1)
                        {
                            vocFileName += ".xml";
                        }

                        zip.AddEntry(vocFileName, vocData);

                        using (MemoryStream ms = new MemoryStream())
                        {
                            zip.Save(ms);

                            fileName    = string.Format("{0}.zip", ig.GetDisplayName(true));
                            contentType = ZIP_MIME_TYPE;
                            export      = ms.ToArray();
                        }
                    }
                }
                break;

            case ExportFormats.Vocabulary_XLSX:
                fileName    = string.Format("{0}.xlsx", ig.GetDisplayName(true));
                contentType = XLSX_MIME_TYPE;

                ExcelExporter excelExporter = new ExcelExporter(this.tdb);
                export = excelExporter.GetSpreadsheet(ig.Id, model.MaximumValueSetMembers);

                break;

            case ExportFormats.Vocbulary_Single_SVS_XML:
                fileName    = string.Format("{0}_SingleSVS.xml", ig.GetDisplayName(true));
                contentType = XML_MIME_TYPE;

                SingleSVSExporter ssvsExporter = new SingleSVSExporter(this.tdb);
                export = ssvsExporter.GetExport(ig.Id, model.MaximumValueSetMembers, this.GetExportEncoding(model));

                break;

            case ExportFormats.Vocabulary_Multiple_SVS_XML:
                fileName    = string.Format("{0}_MultipleSVS.xml", ig.GetDisplayName(true));
                contentType = XML_MIME_TYPE;

                MultipleSVSExporter msvsExporter = new MultipleSVSExporter(this.tdb);
                export = msvsExporter.GetExport(ig.Id, model.MaximumValueSetMembers, this.GetExportEncoding(model));

                break;

            case ExportFormats.Vocabulary_Native_XML:
                fileName    = string.Format("{0}_MultipleSVS.xml", ig.GetDisplayName(true));
                contentType = XML_MIME_TYPE;

                NativeTerminologyExporter nativeExporter = new NativeTerminologyExporter(this.tdb);
                export = nativeExporter.GetExport(ig.Id, model.MaximumValueSetMembers, this.GetExportEncoding(model));

                break;

            case ExportFormats.Web_HTML:
                // Get the data from the API controller
                HtmlExporter exporter      = new HtmlExporter(this.tdb);
                var          templateIds   = templates.Select(y => y.Id).ToArray();
                var          htmlDataModel = exporter.GetExportData(ig.Id, null, templateIds, model.IncludeInferred);

                IGController igController    = new IGController(this.tdb);
                var          downloadPackage = igController.GetDownloadPackage(ig, JsonConvert.SerializeObject(htmlDataModel));

                export      = downloadPackage.Content;
                fileName    = downloadPackage.FileName;
                contentType = ZIP_MIME_TYPE;
                break;

            case ExportFormats.Vocbulary_Bundle_FHIR_XML:
                ValueSetExporter vsExporter = new ValueSetExporter(this.tdb);
                var bundle = vsExporter.GetImplementationGuideValueSets(ig);

                if (model.ReturnJson)
                {
                    export      = fhir_stu3.Hl7.Fhir.Serialization.FhirSerializer.SerializeResourceToJsonBytes(bundle);
                    fileName    = string.Format("{0}_fhir_voc.json", ig.GetDisplayName(true));
                    contentType = JSON_MIME_TYPE;
                }
                else
                {
                    export      = fhir_stu3.Hl7.Fhir.Serialization.FhirSerializer.SerializeResourceToXmlBytes(bundle);
                    fileName    = string.Format("{0}_fhir_voc.xml", ig.GetDisplayName(true));
                    contentType = XML_MIME_TYPE;
                }

                break;

            default:
                throw new NotSupportedException();
            }

            return(GetExportResponse(fileName, contentType, export));
        }
Esempio n. 5
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);
        }