コード例 #1
0
        public void TestSetup()
        {
            this.tdb = new MockObjectRepository();
            this.tdb.InitializeCDARepository();

            CodeSystem cs = tdb.FindOrCreateCodeSystem("LOINC", "1.2.3.4.5");

            this.vs1 = tdb.FindOrCreateValueSet("Test Valueset 1", "1.2.3.4");
            this.tdb.FindOrCreateValueSetMember(this.vs1, cs, "1", "One", "active", "1/1/2000");
            this.tdb.FindOrCreateValueSetMember(this.vs1, cs, "2", "Two", "active", "1/1/2000");
            this.tdb.FindOrCreateValueSetMember(this.vs1, cs, "1", "One", "inactive", "1/1/2001");
            this.tdb.FindOrCreateValueSetMember(this.vs1, cs, "3", "Three", "active", "1/1/2001");
            this.tdb.FindOrCreateValueSetMember(this.vs1, cs, "1", "One", "active", "1/1/2002");

            this.vs2 = tdb.FindOrCreateValueSet("Test Valueset 2", "4.3.2.1");
            this.tdb.FindOrCreateValueSetMember(this.vs2, cs, "1", "One");
            this.tdb.FindOrCreateValueSetMember(this.vs2, cs, "2", "Two");
            this.tdb.FindOrCreateValueSetMember(this.vs2, cs, "3", "Three", "inactive", "1/1/2000");
            this.tdb.FindOrCreateValueSetMember(this.vs2, cs, "4", "Four", "active", "1/1/2000");

            this.vs3 = tdb.FindOrCreateValueSet("Test Valueset 3", "1.4.2.3");
            this.tdb.FindOrCreateValueSetMember(this.vs3, cs, "1", "One");
            this.tdb.FindOrCreateValueSetMember(this.vs3, cs, "2", "Two");
            this.tdb.FindOrCreateValueSetMember(this.vs3, cs, "3", "Three", valueSetStatus: "inactive", dateOfValueSetStatus: "08/05/2013");
            this.tdb.FindOrCreateValueSetMember(this.vs3, cs, "4", "Four", valueSetStatus: "active");
            this.tdb.FindOrCreateValueSetMember(this.vs3, cs, "5", "Five");

            this.ig = this.tdb.FindOrCreateImplementationGuide(Constants.IGTypeNames.CDA, "Test IG");
        }
コード例 #2
0
        public HttpResponseMessage ExportMSWord(MSWordSettingsModel exportSettings)
        {
            if (exportSettings == null)
            {
                throw new ArgumentNullException("model");
            }

            ImplementationGuide          ig        = this.tdb.ImplementationGuides.Single(y => y.Id == exportSettings.ImplementationGuideId);
            ImplementationGuideGenerator generator = new ImplementationGuideGenerator(this.tdb, exportSettings.ImplementationGuideId, exportSettings.TemplateIds);
            string fileName = string.Format("{0}.docx", ig.GetDisplayName(true));

            ExportSettings lConfig = new ExportSettings();

            lConfig.Use(c =>
            {
                c.GenerateTemplateConstraintTable = exportSettings.TemplateTables == TemplateTableOptions.ConstraintOverview || exportSettings.TemplateTables == TemplateTableOptions.Both;
                c.GenerateTemplateContextTable    = exportSettings.TemplateTables == TemplateTableOptions.Context || exportSettings.TemplateTables == TemplateTableOptions.Both;
                c.GenerateDocTemplateListTable    = exportSettings.DocumentTables == DocumentTableOptions.List || exportSettings.DocumentTables == DocumentTableOptions.Both;
                c.GenerateDocContainmentTable     = exportSettings.DocumentTables == DocumentTableOptions.Containment || exportSettings.DocumentTables == DocumentTableOptions.Both;
                c.AlphaHierarchicalOrder          = exportSettings.TemplateSortOrder == TemplateSortOrderOptions.AlphaHierarchically;
                c.DefaultValueSetMaxMembers       = exportSettings.GenerateValuesets ? exportSettings.MaximumValuesetMembers : 0;
                c.GenerateValueSetAppendix        = exportSettings.ValuesetAppendix;
                c.IncludeXmlSamples     = exportSettings.IncludeXmlSample;
                c.IncludeChangeList     = exportSettings.IncludeChangeList;
                c.IncludeTemplateStatus = exportSettings.IncludeTemplateStatus;
                c.IncludeNotes          = exportSettings.IncludeNotes;
                c.SelectedCategories    = exportSettings.SelectedCategories;
            });

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

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

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

                lConfig.ValueSetMaxMembers = valueSetMemberMaximums;
            }

            // Save the export settings as the default settings
            if (exportSettings.SaveAsDefaultSettings)
            {
                IGSettingsManager settingsManager = new IGSettingsManager(this.tdb, exportSettings.ImplementationGuideId);
                var settingsJson = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(exportSettings);
                settingsManager.SaveSetting(MSWordExportSettingsPropertyName, settingsJson);
            }

            generator.BuildImplementationGuide(lConfig);

            byte[] data = generator.GetDocument();

            return(GetExportResponse(fileName, DOCX_MIME_TYPE, data));
        }
コード例 #3
0
        public static void Setup(TestContext context)
        {
            ExportTests.tdb = new MockObjectRepository();
            TrifoliaImporter importer = new TrifoliaImporter(ExportTests.tdb);

            ExportTests.tdb.InitializeFHIR3Repository();
            ExportTests.tdb.InitializeLCGAndLogin();

            string importContent = Helper.GetSampleContents(IMPORT_XML);
            var    importModel   = ImportModel.Deserialize(importContent);

            var importStatus = importer.Import(importModel);

            Assert.IsTrue(importStatus.Success, "Expected import to succeed");
            Assert.AreNotEqual(importStatus.ImplementationGuides.Count, 0, "Expected import to include implementation guides");

            ImplementationGuide ig = ExportTests.tdb.ImplementationGuides.SingleOrDefault(y => y.Id == importStatus.ImplementationGuides.First().InternalId);
            var schema             = ig.ImplementationGuideType.GetSimpleSchema();
            ImplementationGuideExporter exporter = new ImplementationGuideExporter(ExportTests.tdb, schema, "localhost", "http");

            ExportTests.exportedBundle = exporter.GetImplementationGuides(implementationGuideId: ig.Id, include: "ImplementationGuide:resource");

            ExportTests.exportedXml = FhirSerializer.SerializeResourceToXml(ExportTests.exportedBundle);

            Assert.IsNotNull(ExportTests.exportedXml);
        }
コード例 #4
0
        public string GetImplementationGuideVocabulary(int implementationGuideId, int maxValueSetMembers, int vocabOutputType, string encoding)
        {
            try
            {
                TDBImplementationGuide ig = tdb.ImplementationGuides.SingleOrDefault(y => y.Id == implementationGuideId);

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

                bool?onlyStatic = VocabularyOutputTypeTranslator.FromInt(vocabOutputType) != VocabularyOutputType.FHIR ? (bool?)true : null;
                List <ImplementationGuideValueSet> valueSets = ig.GetValueSets(tdb, onlyStatic);
                List <VocabularySystem>            systems   = new List <VocabularySystem>();

                foreach (ImplementationGuideValueSet cValueSet in valueSets)
                {
                    VocabularySystem newSystem = this.GetSystem(tdb, cValueSet.ValueSet, cValueSet.BindingDate);
                    systems.Add(newSystem);
                }

                VocabularySystems schema = new VocabularySystems();
                schema.Systems = systems.ToArray();
                VocabularyOutputTypeAdapter adapter = new VocabularyOutputTypeAdapter(schema, VocabularyOutputTypeTranslator.FromInt(vocabOutputType), Encoding.GetEncoding(encoding));
                return(adapter.AsXML());
            }
            catch (Exception ex)
            {
                Log.For(this).Critical("Error occurred while retrieving vocabulary for an implementation guide.", ex);
                throw;
            }
        }
コード例 #5
0
        public Trifolia.Shared.ImportExport.Model.Trifolia ExportTrifoliaModel(XMLSettingsModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (model.ImplementationGuideId == 0)
            {
                throw new ArgumentNullException("model.ImplementationGuideId");
            }

            ImplementationGuide ig = this.tdb.ImplementationGuides.SingleOrDefault(y => y.Id == model.ImplementationGuideId);

            if (ig == null)
            {
                throw new Exception("Implementation guide with id " + model.ImplementationGuideId + " was not found");
            }

            List <Template>   templates  = this.tdb.Templates.Where(y => model.TemplateIds.Contains(y.Id)).ToList();
            IGSettingsManager igSettings = new IGSettingsManager(this.tdb, model.ImplementationGuideId);
            string            fileName   = string.Format("{0}.xml", ig.GetDisplayName(true));
            string            export     = string.Empty;

            try
            {
                NativeExporter exporter = new NativeExporter(this.tdb, templates, igSettings, categories: model.SelectedCategories);
                return(exporter.GenerateExport());
            }
            catch (Exception ex)
            {
                Log.For(this).Error("Error creating Trifolia export", ex);
                throw;
            }
        }
コード例 #6
0
        public HttpResponseMessage ExportVocabulary(VocabularySettingsModel model)
        {
            ImplementationGuide ig = this.tdb.ImplementationGuides.Single(y => y.Id == model.ImplementationGuideId);

            byte[] data        = new byte[0];
            string fileType    = string.Empty;
            string contentType = string.Empty;

            VocabularyService service = new VocabularyService(this.tdb, ig.ImplementationGuideType.SchemaURI == "urn:hl7-org:v3");

            switch (model.ExportFormat)
            {
            case VocabularySettingsModel.ExportFormatTypes.Standard:
            case VocabularySettingsModel.ExportFormatTypes.SVS:
            case VocabularySettingsModel.ExportFormatTypes.FHIR:
                fileType    = "xml";
                contentType = XML_MIME_TYPE;
                string   vocXml   = service.GetImplementationGuideVocabulary(model.ImplementationGuideId, model.MaximumMembers, (int)model.ExportFormat, model.Encoding);
                Encoding encoding = Encoding.GetEncoding(model.Encoding);
                data = encoding.GetBytes(vocXml);
                break;

            case VocabularySettingsModel.ExportFormatTypes.Excel:
                fileType    = "xlsx";
                contentType = XLSX_MIME_TYPE;
                data        = service.GetImplementationGuideVocabularySpreadsheet(model.ImplementationGuideId, model.MaximumMembers);
                break;
            }

            string fileName = string.Format("{0}.{1}", ig.GetDisplayName(true), fileType);

            return(GetExportResponse(fileName, contentType, data));
        }
コード例 #7
0
        public XMLModel Xml(int implementationGuideId)
        {
            if (!CheckPoint.Instance.GrantViewImplementationGuide(implementationGuideId))
            {
                throw new AuthorizationException("You do not have permissions to this implementation guide.");
            }

            ImplementationGuide ig         = this.tdb.ImplementationGuides.Single(y => y.Id == implementationGuideId);
            IGSettingsManager   igSettings = new IGSettingsManager(this.tdb, implementationGuideId);

            XMLModel model = new XMLModel()
            {
                ImplementationGuideId = implementationGuideId,
                Name      = ig.GetDisplayName(),
                CancelUrl = GetCancelUrl(implementationGuideId),
                ImplementationGuideType = ig.ImplementationGuideType.Name
            };

            // Get categories from the IG's settings
            string categories = igSettings.GetSetting(IGSettingsManager.SettingProperty.Categories);

            if (!string.IsNullOrEmpty(categories))
            {
                string[] categoriesSplit = categories.Split(',');

                foreach (string category in categoriesSplit)
                {
                    model.Categories.Add(category.Replace("###", ","));
                }
            }

            return(model);
        }
コード例 #8
0
            public AuditEntry CreateAuditEntry(string auditUserName, string auditIP)
            {
                if (this.fieldChanges.Count == 0)
                {
                    return(null);
                }

                AuditEntry          newAuditEntry = new AuditEntry();
                ImplementationGuide ig            = this.entity as ImplementationGuide;
                Template            template      = this.entity as Template;
                TemplateConstraint  constraint    = this.entity as TemplateConstraint;

                if (this.changeState != EntityState.Deleted)
                {
                    this.SetIds();
                }

                string note = string.Format("{0}: {1} ({2})",
                                            this.changeState,
                                            this.GetUniqueId(this.entity),
                                            String.Join(", ", this.fieldChanges));

                newAuditEntry.ImplementationGuideId = this.implementationGuideId;
                newAuditEntry.TemplateId            = this.templateId;
                newAuditEntry.TemplateConstraintId  = this.constraintId;
                newAuditEntry.Note      = note;
                newAuditEntry.IP        = auditIP;
                newAuditEntry.Username  = auditUserName;
                newAuditEntry.AuditDate = DateTime.Now;
                newAuditEntry.Type      = this.entity.GetType().Name;

                return(newAuditEntry);
            }
コード例 #9
0
        public static string GetFullUrl(this ImplementationGuide implementationGuide, string scheme, string authority)
        {
            var url = string.Format("{0}://{1}/api/FHIR2/ImplementationGuide/{2}",
                                    scheme,
                                    authority,
                                    implementationGuide.Id);

            return(url);
        }
コード例 #10
0
        private string GetFullUrl(ImplementationGuide implementationGuide)
        {
            var url = string.Format("{0}://{1}/api/FHIRLatest/ImplementationGuide/{2}",
                                    this.scheme,
                                    this.authority,
                                    implementationGuide.Id);

            return(url);
        }
コード例 #11
0
        public HttpResponseMessage ExportXML(XMLSettingsModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (model.ImplementationGuideId == 0)
            {
                throw new ArgumentNullException("model.ImplementationGuideId");
            }

            ImplementationGuide ig = this.tdb.ImplementationGuides.SingleOrDefault(y => y.Id == model.ImplementationGuideId);

            if (ig == null)
            {
                throw new Exception("Implementation guide with id " + model.ImplementationGuideId + " was not found");
            }

            List <Template>   templates  = this.tdb.Templates.Where(y => model.TemplateIds.Contains(y.Id)).ToList();
            IGSettingsManager igSettings = new IGSettingsManager(this.tdb, model.ImplementationGuideId);
            string            fileName   = string.Format("{0}.xml", ig.GetDisplayName(true));
            string            export     = string.Empty;
            bool returnJson        = Request.Headers.Accept.Count(y => y.MediaType == "application/json") == 1;
            bool includeVocabulary = model.IncludeVocabulary == true;
            var  igTypePlugin      = IGTypePluginFactory.GetPlugin(ig.ImplementationGuideType);
            var  schema            = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, ig.ImplementationGuideType);

            if (model.XmlType == XMLSettingsModel.ExportTypes.Proprietary)
            {
                export = igTypePlugin.Export(tdb, schema, ExportFormats.Proprietary, igSettings, model.SelectedCategories, templates, includeVocabulary, returnJson);
            }
            else if (model.XmlType == XMLSettingsModel.ExportTypes.DSTU)
            {
                export = igTypePlugin.Export(tdb, schema, ExportFormats.TemplatesDSTU, igSettings, model.SelectedCategories, templates, includeVocabulary, returnJson);
            }
            else if (model.XmlType == XMLSettingsModel.ExportTypes.FHIR)
            {
                export = igTypePlugin.Export(this.tdb, schema, ExportFormats.FHIR, igSettings, model.SelectedCategories, templates, includeVocabulary, returnJson);
            }
            else if (model.XmlType == XMLSettingsModel.ExportTypes.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 = jsonSerializer.Serialize(dataModel);

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

            byte[] data = System.Text.ASCIIEncoding.UTF8.GetBytes(export);
            return(GetExportResponse(fileName, data));
        }
コード例 #12
0
ファイル: ExportController.cs プロジェクト: BOBO41/trifolia
        public ActionResult Schematron(int implementationGuideId)
        {
            if (!CheckPoint.Instance.GrantViewImplementationGuide(implementationGuideId))
            {
                throw new AuthorizationException("You do not have permissions to this implementation guide.");
            }

            ImplementationGuide ig = this.tdb.ImplementationGuides.Single(y => y.Id == implementationGuideId);

            return(View("Schematron", implementationGuideId));
        }
コード例 #13
0
        public Bundle GetImplementationGuideValueSets(Trifolia.DB.ImplementationGuide ig)
        {
            var    igValueSets = ig.GetValueSets(this.tdb, readOnly: true);
            Bundle bundle      = new Bundle();

            foreach (var igValueSet in igValueSets)
            {
                bundle.AddResourceEntry(this.Convert(igValueSet.ValueSet), igValueSet.ValueSet.GetIdentifier(ValueSetIdentifierTypes.HTTP));
            }

            return(bundle);
        }
コード例 #14
0
        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);
        }
コード例 #15
0
ファイル: BuildExporter.cs プロジェクト: yasir2000/trifolia
        public BuildExporter(IObjectRepository tdb, int implementationGuideId, IEnumerable <Template> templates = null, bool jsonFormat = false)
        {
            this.tdb = tdb;

            this.ig           = this.tdb.ImplementationGuides.SingleOrDefault(y => y.Id == implementationGuideId);
            this.igTypePlugin = this.ig.ImplementationGuideType.GetPlugin();
            this.templates    = templates ?? this.ig.GetRecursiveTemplates(this.tdb);

            this.schema          = this.ig.ImplementationGuideType.GetSimpleSchema();
            this.igName          = this.ig.Name.Replace(" ", "_");
            this.controlFileName = "ig.json";
            this.JsonFormat      = jsonFormat;

            this.dataExamples = new DataExamples();
        }
コード例 #16
0
        public List <VocabularyItemModel> GetValueSets(int implementationGuideId, int?exportFormat = 0)
        {
            ImplementationGuide ig = this.tdb.ImplementationGuides.Single(y => y.Id == implementationGuideId);

            switch (exportFormat)
            {
            case 0:
            case 1:
            case 2:
                return(ConvertVocabularyItems(ig.GetValueSets(this.tdb, true)));

            default:
                return(ConvertVocabularyItems(ig.GetValueSets(this.tdb)));
            }
        }
コード例 #17
0
        public HttpResponseMessage ExportSchematron(SchematronSettingsModel model)
        {
            ImplementationGuide  ig            = this.tdb.ImplementationGuides.Single(y => y.Id == model.ImplementationGuideId);
            VocabularyOutputType vocOutputType = GetVocOutputType(model.ValueSetOutputFormat);

            var templates = (from t in this.tdb.Templates
                             where model.TemplateIds.Contains(t.Id)
                             select t).ToList();

            string schematronResult = SchematronGenerator.Generate(tdb, ig, model.IncludeCustomSchematron, vocOutputType, model.VocabularyFileName, templates, model.SelectedCategories, model.DefaultSchematron);

            byte[] data     = ASCIIEncoding.UTF8.GetBytes(schematronResult);
            string fileName = string.Format("{0}.sch", ig.GetDisplayName(true));

            return(GetExportResponse(fileName, XML_MIME_TYPE, data));
        }
コード例 #18
0
        public GreenModel Green(int implementationGuideId)
        {
            ImplementationGuide ig = this.tdb.ImplementationGuides.Single(y => y.Id == implementationGuideId);

            GreenModel model = new GreenModel()
            {
                ImplementationGuideId = implementationGuideId,
                Name = ig.GetDisplayName()
            };

            List <TemplateType> rootTemplateTypes = ig.ImplementationGuideType.GetRootTemplateTypes();

            model.Templates = (from t in ig.ChildTemplates
                               join rtt in rootTemplateTypes on t.TemplateTypeId equals rtt.Id
                               where t.GreenTemplates.Count > 0
                               select LookupTemplate.ConvertTemplate(t)).ToList();

            return(model);
        }
コード例 #19
0
        public ActionResult Vocabulary(int implementationGuideId)
        {
            if (!CheckPoint.Instance.GrantViewImplementationGuide(implementationGuideId))
            {
                throw new AuthorizationException("You do not have permissions to this implementation guide.");
            }

            ImplementationGuide ig = this.tdb.ImplementationGuides.Single(y => y.Id == implementationGuideId);

            // Check if we need to rediret the user first
            ActionResult redirect = this.BeforeExport(ig, "Vocabulary");

            if (redirect != null)
            {
                return(redirect);
            }

            return(View("Vocabulary", implementationGuideId));
        }
コード例 #20
0
        /// <summary>
        /// Checks if the authenticated user is from the HL7 organization.
        /// If yes, a redirect ActionResult is returned that forwards the user to the HL7 disclaimer page.
        /// The action result includes a redirectUrl parameter that tells HL7 to redirect the user back to trifolia.
        /// The redirectUrl parameter of the returned ActionResult includes the retAction passed to this method
        /// and an implementationGuideId param for the ig.
        /// </summary>
        private ActionResult BeforeExport(ImplementationGuide ig, string retAction)
        {
            bool dy = false;

            bool.TryParse(Request.Params["dy"], out dy);

            // If the user is HL7 authenticated, they must sign a disclaimer before generating the IG
            if (CheckPoint.Instance.OrganizationName == "HL7" && !dy)
            {
                Dictionary <string, string> authData = CheckPoint.Instance.GetAuthenticatedData();

                string userId = authData["UserId"];

                string url = HL7AuthHelper.GetComplianceUrl(
                    Url.Action(retAction, "Export", new { implementationGuideId = ig.Id, dy = true }, Request.Url.Scheme),
                    userId,
                    ig.Name);

                return(Redirect(url));
            }

            return(null);
        }
コード例 #21
0
        public HttpResponseMessage ExportGreen(GreenSettingsModel model)
        {
            if (!CheckPoint.Instance.GrantViewImplementationGuide(model.ImplementationGuideId))
            {
                throw new AuthorizationException("You do not have permissions to this implementation guide.");
            }

            ImplementationGuide ig           = this.tdb.ImplementationGuides.Single(y => y.Id == model.ImplementationGuideId);
            Template            rootTemplate = this.tdb.Templates.Single(y => y.Id == model.RootTemplateId);

            // Generate the schema
            GreenSchemaPackage package = GreenSchemaGenerator.Generate(this.tdb, rootTemplate, model.SeparateDataTypes);

            using (ZipFile zip = new ZipFile())
            {
                byte[] schemaContentBytes = ASCIIEncoding.UTF8.GetBytes(package.GreenSchemaContent);
                zip.AddEntry(package.GreenSchemaFileName, schemaContentBytes);

                // If the datatypes were separated into another schema
                if (!string.IsNullOrEmpty(package.DataTypesFileName))
                {
                    byte[] dataTypesContentBytes = ASCIIEncoding.UTF8.GetBytes(package.DataTypesContent);
                    zip.AddEntry(package.DataTypesFileName, dataTypesContentBytes);
                }

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

                    string packageFileName = string.Format("{0}_green.zip", ig.GetDisplayName(true));
                    byte[] data            = ms.ToArray();

                    return(GetExportResponse(packageFileName, ZIP_MIME_TYPE, data));
                }
            }
        }
コード例 #22
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;
            }
        }
コード例 #23
0
        public ImplementationGuide Convert(FhirImplementationGuide fhirImplementationGuide, ImplementationGuide implementationGuide)
        {
            if (implementationGuide == null)
            {
                implementationGuide = new ImplementationGuide()
                {
                    ImplementationGuideType = this.implementationGuideType
                }
            }
            ;

            if (implementationGuide.Name != fhirImplementationGuide.Name)
            {
                implementationGuide.Name = fhirImplementationGuide.Name;
            }

            if (fhirImplementationGuide.Package != null)
            {
                foreach (var package in fhirImplementationGuide.Package)
                {
                    foreach (var resource in package.Resource)
                    {
                        if (resource.Source is ResourceReference)
                        {
                        }
                        else
                        {
                            throw new Exception("Only resource references are supported by ImplementationGuide.resource");
                        }
                    }
                }
            }

            return(implementationGuide);
        }
    }
コード例 #24
0
        public Template Convert(StructureDefinition strucDef, Template template = null)
        {
            if (string.IsNullOrEmpty(strucDef.ConstrainedType))
            {
                throw new Exception("StructureDefinition.constrainedType is required");
            }

            if (template == null)
            {
                ImplementationGuide unassignedImplementationGuide = this.tdb.ImplementationGuides.SingleOrDefault(y =>
                                                                                                                  y.Name == DSTU2Helper.DEFAULT_IG_NAME &&
                                                                                                                  y.ImplementationGuideTypeId == this.implementationGuideType.Id);

                if (unassignedImplementationGuide == null)
                {
                    unassignedImplementationGuide = new ImplementationGuide()
                    {
                        Name = DSTU2Helper.DEFAULT_IG_NAME,
                        ImplementationGuideType = this.implementationGuideType
                    };
                    this.tdb.ImplementationGuides.Add(unassignedImplementationGuide);
                }

                template = new Template()
                {
                    OwningImplementationGuide = unassignedImplementationGuide,
                    ImplementationGuideType   = this.implementationGuideType,
                    Author = this.tdb.Users.Single(y => y.UserName == DSTU2Helper.DEFAULT_USER_NAME),
                    IsOpen = true
                };
            }

            // Name
            if (template.Name != strucDef.Name)
            {
                template.Name = strucDef.Name;
            }

            // Descrition
            if (template.Description != strucDef.Description)
            {
                template.Description = strucDef.Description;
            }

            // Identifier -> Oid
            string identifier = strucDef.Url;

            if (string.IsNullOrEmpty(identifier))
            {
                identifier = string.Format(DSTU2Helper.STRUCDEF_NEW_IDENTIFIER_FORMAT, Guid.NewGuid());
            }

            if (template.Oid != identifier)
            {
                template.Oid = identifier;
            }

            // ConstrainedType -> Template Type
            TemplateType templateType = this.tdb.TemplateTypes.SingleOrDefault(y =>
                                                                               y.ImplementationGuideTypeId == this.implementationGuideType.Id &&
                                                                               y.RootContextType == strucDef.ConstrainedType);

            if (templateType == null)
            {
                throw new Exception("Could not find Template Type for " + strucDef.ConstrainedType);
            }

            if (template.TemplateType != templateType)
            {
                template.TemplateType = templateType;
            }

            if (template.PrimaryContext != template.TemplateType.RootContext)
            {
                template.PrimaryContext = template.TemplateType.RootContext;
            }

            if (template.PrimaryContextType != template.TemplateType.RootContextType)
            {
                template.PrimaryContextType = template.TemplateType.RootContextType;
            }

            // Bookmark
            template.Bookmark = Template.GenerateBookmark(template.Name, template.TemplateType.Name.ToUpper());

            if (strucDef.Snapshot != null && strucDef.Differential == null)
            {
                throw new Exception("Trifolia does not support snapshots for DSTU2, yet");
            }

            // Differential.Element -> Constraint
            if (strucDef.Differential != null)
            {
                // Remove all current constraints from the template so that we re-create
                foreach (var cc in template.ChildConstraints.ToList())
                {
                    this.tdb.TemplateConstraints.Remove(cc);
                }

                ElementNavigator   navigator = new ElementNavigator(strucDef.Differential.Element);
                TemplateConstraint current   = null;

                if (navigator.MoveToFirstChild() && navigator.MoveToFirstChild())
                {
                    while (true)
                    {
                        if (navigator.Current.Slicing != null)
                        {
                            if (!navigator.MoveToNext())
                            {
                                if (current != null && current.ParentConstraint != null && navigator.MoveToParent())
                                {
                                    current = current.ParentConstraint;
                                }
                                else
                                {
                                    break;
                                }
                            }
                            continue;
                        }

                        TemplateConstraint next = new TemplateConstraint();
                        next.Context          = navigator.PathName;
                        next.ParentConstraint = current;
                        next.Order            = current != null?current.ChildConstraints.Count() : template.ChildConstraints.Count(y => y.ParentConstraint == null);

                        if (navigator.Elements.Any(y => y.Path == navigator.Path && y.Slicing != null))
                        {
                            next.IsBranch = true;
                        }

                        template.ChildConstraints.Add(next);

                        string cardinality = string.Format("{0}..{1}",
                                                           navigator.Current.Min == null ? 0 : navigator.Current.Min,
                                                           string.IsNullOrEmpty(navigator.Current.Max) ? "*" : navigator.Current.Max);

                        if (next.Cardinality != cardinality)
                        {
                            next.Cardinality = cardinality;
                        }

                        string conformance = cardinality.StartsWith("1") ? "SHALL" : "SHOULD";

                        if (next.Conformance != conformance)
                        {
                            next.Conformance = conformance;
                        }

                        if (navigator.MoveToFirstChild())
                        {
                            current = next;
                            continue;
                        }
                        else if (navigator.MoveToNext())
                        {
                            continue;
                        }
                        else if (navigator.MoveToParent() && navigator.MoveToNext())
                        {
                            current = current.ParentConstraint;
                            continue;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            return(template);
        }
コード例 #25
0
        public byte[] GetImplementationGuideVocabularySpreadsheet(int implementationGuideId, int maxValueSetMembers)
        {
            try
            {
                TDBImplementationGuide ig = tdb.ImplementationGuides.SingleOrDefault(y => y.Id == implementationGuideId);

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

                List <ImplementationGuideValueSet> valueSets = ig.GetValueSets(tdb);

                using (MemoryStream ms = new MemoryStream())
                {
                    SpreadsheetDocument spreadsheet = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook, true);

                    WorkbookPart workbookpart = spreadsheet.AddWorkbookPart();
                    workbookpart.Workbook = new Workbook();
                    workbookpart.Workbook.AppendChild <Sheets>(new Sheets());

                    Worksheet sheet1      = CreateWorksheet(workbookpart.Workbook, "Affected Value Sets");
                    SheetData sheet1Data  = sheet1.GetFirstChild <SheetData>();
                    Worksheet sheet2      = CreateWorksheet(workbookpart.Workbook, "Value Set Members");
                    SheetData sheet2Data  = sheet2.GetFirstChild <SheetData>();
                    int       sheet1Count = 2;
                    int       sheet2Count = 2;

                    // Sheet 1 column widths
                    Columns sheet1Cols = new Columns(
                        new Column()
                    {
                        Min         = 1,
                        Max         = 1,
                        Width       = 56,
                        BestFit     = BooleanValue.FromBoolean(true),
                        CustomWidth = BooleanValue.FromBoolean(true)
                    },
                        new Column()
                    {
                        Min         = 2,
                        Max         = 2,
                        Width       = 38,
                        BestFit     = BooleanValue.FromBoolean(true),
                        CustomWidth = BooleanValue.FromBoolean(true)
                    });
                    sheet1.InsertBefore <Columns>(sheet1Cols, sheet1Data);

                    // Sheet 2 column widths
                    Columns sheet2Cols = new Columns(
                        new Column()
                    {
                        Min         = 1,
                        Max         = 1,
                        Width       = 32,
                        BestFit     = BooleanValue.FromBoolean(true),
                        CustomWidth = BooleanValue.FromBoolean(true)
                    },
                        new Column()
                    {
                        Min         = 2,
                        Max         = 2,
                        Width       = 51,
                        BestFit     = BooleanValue.FromBoolean(true),
                        CustomWidth = BooleanValue.FromBoolean(true)
                    },
                        new Column()
                    {
                        Min         = 3,
                        Max         = 3,
                        Width       = 26,
                        BestFit     = BooleanValue.FromBoolean(true),
                        CustomWidth = BooleanValue.FromBoolean(true)
                    },
                        new Column()
                    {
                        Min         = 4,
                        Max         = 4,
                        Width       = 39,
                        BestFit     = BooleanValue.FromBoolean(true),
                        CustomWidth = BooleanValue.FromBoolean(true)
                    },
                        new Column()
                    {
                        Min         = 5,
                        Max         = 5,
                        Width       = 23,
                        BestFit     = BooleanValue.FromBoolean(true),
                        CustomWidth = BooleanValue.FromBoolean(true)
                    });
                    sheet2.InsertBefore <Columns>(sheet2Cols, sheet2Data);

                    // Add headers
                    sheet1Data.AppendChild(
                        new Row(
                            new Cell(
                                new CellValue("Value Set Name"))
                    {
                        CellReference = "A1",
                        DataType      = CellValues.String
                    },
                            new Cell(
                                new CellValue("Value Set OID"))
                    {
                        CellReference = "B1",
                        DataType      = CellValues.String
                    })
                    {
                        RowIndex = 1
                    });
                    sheet2Data.AppendChild(
                        new Row(
                            new Cell(
                                new CellValue("Value Set OID"))
                    {
                        CellReference = "A1",
                        DataType      = CellValues.String
                    },
                            new Cell(
                                new CellValue("Value Set Name"))
                    {
                        CellReference = "B1",
                        DataType      = CellValues.String
                    },
                            new Cell(
                                new CellValue("Code"))
                    {
                        CellReference = "C1",
                        DataType      = CellValues.String
                    },
                            new Cell(
                                new CellValue("Display Name"))
                    {
                        CellReference = "D1",
                        DataType      = CellValues.String
                    },
                            new Cell(
                                new CellValue("Code System Name"))
                    {
                        CellReference = "E1",
                        DataType      = CellValues.String
                    })
                    {
                        RowIndex = 1
                    });

                    for (int x = 0; x < valueSets.Count; x++)
                    {
                        var    cValueSet  = valueSets[x];
                        string summaryXml = string.Format(
                            "<row r=\"{0}\" xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">" +
                            "  <c r=\"A{0}\" t=\"str\"><v>{1}</v></c>" +
                            "  <c r=\"B{0}\" t=\"str\"><v>{2}</v></c>" +
                            "</row>",
                            sheet1Count++,
                            XmlEncodeText(cValueSet.ValueSet.Name),
                            XmlEncodeText(cValueSet.ValueSet.Oid));

                        Row newSummaryRow = new Row(summaryXml);
                        sheet1Data.AppendChild(newSummaryRow);

                        List <ValueSetMember> members = cValueSet.ValueSet.GetActiveMembers(cValueSet.BindingDate);

                        for (int i = 0; i < members.Count && (maxValueSetMembers == 0 || i < maxValueSetMembers); i++)
                        {
                            var cMember = members[i];

                            string memberXml = string.Format(
                                "<row r=\"{0}\" xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">" +
                                "  <c r=\"A{0}\" t=\"str\"><v>{1}</v></c>" +
                                "  <c r=\"B{0}\" t=\"str\"><v>{2}</v></c>" +
                                "  <c r=\"C{0}\" t=\"str\"><v>{3}</v></c>" +
                                "  <c r=\"D{0}\" t=\"str\"><v>{4}</v></c>" +
                                "  <c r=\"E{0}\" t=\"str\"><v>{5}</v></c>" +
                                "</row>",
                                sheet2Count++,
                                XmlEncodeText(cValueSet.ValueSet.Oid),
                                XmlEncodeText(cValueSet.ValueSet.Name),
                                XmlEncodeText(cMember.Code),
                                XmlEncodeText(cMember.DisplayName),
                                XmlEncodeText(cMember.CodeSystem.Name));

                            Row newMemberRow = new Row(memberXml);
                            sheet2Data.AppendChild(newMemberRow);
                        }
                    }

                    workbookpart.Workbook.Save();
                    spreadsheet.Close();

                    ms.Position = 0;
                    byte[] buffer = new byte[ms.Length];
                    ms.Read(buffer, 0, (int)ms.Length);
                    return(buffer);
                }
            }
            catch (Exception ex)
            {
                Log.For(this).Critical("Error occurred while generating spreadsheet for IG vocabulary", ex);
                throw;
            }
        }
コード例 #26
0
        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);
        }
コード例 #27
0
ファイル: AuditExtension.cs プロジェクト: yasir2000/trifolia
 private void SetProperties(ImplementationGuide ig)
 {
 }
コード例 #28
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));
        }
コード例 #29
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);
        }
コード例 #30
0
 public static void SetPreviousVersion(this ImplementationGuide ig, ImplementationGuide previousVersion)
 {
     ig.PreviousVersion.Add(previousVersion);
     ig.PreviousVersionImplementationGuideId = previousVersion.Id;
 }