Exemple #1
0
        public IEnumerable <SchemaNode> GetSchemaNodes(int implementationGuideId, string parentType = null, bool includeAttributes = true)
        {
            if (!CheckPoint.Instance.GrantViewImplementationGuide(implementationGuideId))
            {
                throw new AuthorizationException("You do not have permission to view this implementation guide");
            }

            ImplementationGuide ig     = this.tdb.ImplementationGuides.Single(y => y.Id == implementationGuideId);
            SimpleSchema        schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, ig.ImplementationGuideType);
            List <SimpleSchema.SchemaObject> children;

            if (!string.IsNullOrEmpty(parentType))
            {
                schema   = schema.GetSchemaFromContext(parentType);
                children = schema.Children;
            }
            else
            {
                children = schema.Children[0].Children;
            }

            var ret = (from s in children
                       where includeAttributes || !s.IsAttribute
                       select new SchemaNode()
            {
                Context = s.IsAttribute ? "@" + s.Name : s.Name,
                Conformance = s.Conformance,
                Cardinality = s.Cardinality,
                DataType = s.DataType,
                HasChildren = s.Children.Where(y => includeAttributes || !y.IsAttribute).Count() > 0
            });

            return(ret);
        }
Exemple #2
0
        public IHttpActionResult UpdateStructureDefinition(
            [FromBody] StructureDefinition strucDef,
            [FromUri] string bookmark)
        {
            Template existingTemplate = this.tdb.Templates.SingleOrDefault(y => y.Bookmark.ToLower().Trim() == bookmark.ToLower().Trim());

            // Make sure the profile exists
            if (existingTemplate == null)
            {
                return(CreateErrorResponse(App_GlobalResources.TrifoliaLang.TemplateNotFoundMessageFormat));
            }

            if (!CheckPoint.Instance.GrantEditTemplate(existingTemplate.Id))
            {
                throw new UnauthorizedAccessException();
            }

            var uri = HttpContext.Current != null && HttpContext.Current.Request != null ? HttpContext.Current.Request.Url : new Uri(AppSettings.DefaultBaseUrl);
            StructureDefinitionImporter importer = new StructureDefinitionImporter(this.tdb, uri.Scheme, uri.Authority);
            StructureDefinitionExporter exporter = new StructureDefinitionExporter(this.tdb, uri.Scheme, uri.Authority);

            Template updatedTemplate;

            try
            {
                User author = CheckPoint.Instance.GetUser(this.tdb);
                updatedTemplate = importer.Convert(strucDef, existingTemplate, author);
            }
            catch (Exception ex)
            {
                return(CreateErrorResponse(ex.Message, OperationOutcome.IssueType.Exception));
            }

            if (existingTemplate == null)
            {
                this.tdb.Templates.Add(updatedTemplate);
            }

            this.tdb.SaveChanges();

            string location = string.Format("{0}://{1}/api/FHIR3/StructureDefinition/{2}",
                                            this.Request.RequestUri.Scheme,
                                            this.Request.RequestUri.Authority,
                                            updatedTemplate.Id);

            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Location", location);

            SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current, updatedTemplate.ImplementationGuideType);

            schema = schema.GetSchemaFromContext(updatedTemplate.PrimaryContextType);

            StructureDefinition updatedStrucDef = exporter.Convert(updatedTemplate, schema);

            return(Content <Resource>((existingTemplate == null ? HttpStatusCode.Created : HttpStatusCode.OK), updatedStrucDef, headers));
        }
Exemple #3
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));
        }
        public IHttpActionResult CreateStructureDefinition(
            [FromBody] StructureDefinition strucDef)
        {
            if (!string.IsNullOrEmpty(strucDef.Id))
            {
                OperationOutcome error = new OperationOutcome();
                error.Issue.Add(new OperationOutcome.IssueComponent()
                {
                    Severity    = OperationOutcome.IssueSeverity.Error,
                    Diagnostics = App_GlobalResources.TrifoliaLang.CreateFHIR2TemplateFailedDuplicateId
                });
                return(Content <OperationOutcome>(HttpStatusCode.BadRequest, error));
            }

            var foundProfile = this.tdb.Templates.SingleOrDefault(y => y.Oid == strucDef.Url);

            if (foundProfile != null)
            {
                OperationOutcome oo = new OperationOutcome()
                {
                    Issue = new List <OperationOutcome.IssueComponent> {
                        new OperationOutcome.IssueComponent()
                        {
                            Severity    = OperationOutcome.IssueSeverity.Error,
                            Code        = OperationOutcome.IssueType.Duplicate,
                            Diagnostics = "A StructureDefinition with the same url already exists. To update, use PUT."
                        }
                    }
                };

                return(Content <OperationOutcome>(HttpStatusCode.Created, oo));
            }

            var template = CreateTemplate(strucDef);

            this.tdb.SaveChanges();

            string location = string.Format("{0}://{1}/api/FHIR3/StructureDefinition/{2}",
                                            this.Request.RequestUri.Scheme,
                                            this.Request.RequestUri.Authority,
                                            template.Id);

            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Location", location);

            var uri = HttpContext.Current != null && HttpContext.Current.Request != null ? HttpContext.Current.Request.Url : new Uri(AppSettings.DefaultBaseUrl);
            StructureDefinitionExporter exporter = new StructureDefinitionExporter(this.tdb, uri.Scheme, uri.Authority);
            SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current, template.ImplementationGuideType);

            schema = schema.GetSchemaFromContext(template.PrimaryContextType);

            StructureDefinition newStrucDef = exporter.Convert(template, schema);

            return(Content <StructureDefinition>(HttpStatusCode.Created, newStrucDef, headers));
        }
        public IHttpActionResult GetTemplate(
            [FromUri] string templateId,
            [FromUri(Name = "_summary")] SummaryType?summary = null)
        {
            Template template = this.tdb.Templates.SingleOrDefault(y => y.Oid == this.Request.RequestUri.AbsoluteUri || y.Id.ToString() == templateId);

            // Return an operation outcome indicating that the profile was not found
            if (template == null)
            {
                OperationOutcome oo = new OperationOutcome();
                oo.Issue.Add(new OperationOutcome.OperationOutcomeIssueComponent()
                {
                    Severity    = OperationOutcome.IssueSeverity.Fatal,
                    Diagnostics = "Profile was not found"
                });

                return(Content <OperationOutcome>(HttpStatusCode.NotFound, oo));
            }

            // Redirect the user to the Trifolia web interface if an acceptable format is text/html, and no format or summary was specified
            if (Request.Headers.Accept.Any(y => y.MediaType == "text/html") && summary == null)
            {
                Dictionary <string, string> headers = new Dictionary <string, string>();
                headers.Add("Location", Request.RequestUri.Scheme + "://" + Request.RequestUri.Authority + "/TemplateManagement/View/Id/" + template.Id);

                OperationOutcome redirectOutcome = new OperationOutcome();
                redirectOutcome.Issue.Add(new OperationOutcome.OperationOutcomeIssueComponent()
                {
                    Severity    = OperationOutcome.IssueSeverity.Information,
                    Diagnostics = "Detecting browser-based request, redirecting to Trifolia web interface."
                });

                return(Content <OperationOutcome>(HttpStatusCode.Redirect, redirectOutcome, headers));
            }

            if (template.TemplateType.ImplementationGuideType != this.implementationGuideType)
            {
                throw new FormatException(App_GlobalResources.TrifoliaLang.TemplateNotFHIRSTU3);
            }

            if (!CheckPoint.Instance.GrantViewTemplate(template.Id))
            {
                throw new UnauthorizedAccessException();
            }

            var uri = HttpContext.Current != null && HttpContext.Current.Request != null ? HttpContext.Current.Request.Url : new Uri(AppSettings.DefaultBaseUrl);
            StructureDefinitionExporter exporter = new StructureDefinitionExporter(this.tdb, uri.Scheme, uri.Authority);
            SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current, template.ImplementationGuideType);

            schema = schema.GetSchemaFromContext(template.PrimaryContextType);

            StructureDefinition strucDef = exporter.Convert(template, schema, summary);

            return(Content <StructureDefinition>(HttpStatusCode.OK, strucDef));
        }
Exemple #6
0
        public string GetConstraintDataType(DB.TemplateConstraint aConstraint, string aConstraintXpath)
        {
            var    templateType = aConstraint.Template.TemplateType;
            string context      = !string.IsNullOrEmpty(aConstraint.Template.PrimaryContextType) ?
                                  aConstraint.Template.PrimaryContextType : templateType.RootContextType;

            var schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, templateType.ImplementationGuideType);

            schema = schema.GetSchemaFromContext(context);

            SimpleSchema.SchemaObject lSchemaObject = schema.FindFromPath(aConstraintXpath);
            return(lSchemaObject.DataType);
        }
        public HttpResponseMessage GetImplementationGuide(
            int implementationGuideId,
            [FromUri(Name = "_format")] string format = null,
            [FromUri(Name = "_summary")] fhir_stu3.Hl7.Fhir.Rest.SummaryType?summary = null)
        {
            var          uri = HttpContext.Current != null && HttpContext.Current.Request != null ? HttpContext.Current.Request.Url : new Uri(AppSettings.DefaultBaseUrl);
            var          implementationGuide = this.tdb.ImplementationGuides.Single(y => y.Id == implementationGuideId);
            SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, implementationGuide.ImplementationGuideType);
            ImplementationGuideExporter exporter = new ImplementationGuideExporter(this.tdb, schema, uri.Scheme, uri.Authority);
            FhirImplementationGuide     response = exporter.Convert(implementationGuide, summary);

            return(Shared.GetResponseMessage(this.Request, format, response));
        }
        public HttpResponseMessage GetImplementationGuides(
            [FromUri(Name = "_format")] string format = null,
            [FromUri(Name = "_summary")] fhir_stu3.Hl7.Fhir.Rest.SummaryType?summary = null,
            [FromUri(Name = "_include")] string include       = null,
            [FromUri(Name = "_id")] int?implementationGuideId = null,
            [FromUri(Name = "name")] string name = null)
        {
            var          uri    = HttpContext.Current != null && HttpContext.Current.Request != null ? HttpContext.Current.Request.Url : new Uri(AppSettings.DefaultBaseUrl);
            SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, this.implementationGuideType);
            ImplementationGuideExporter exporter = new ImplementationGuideExporter(this.tdb, schema, uri.Scheme, uri.Authority);
            var bundle = exporter.GetImplementationGuides(summary, include, implementationGuideId, name);

            return(Shared.GetResponseMessage(this.Request, format, bundle));
        }
        public IEnumerable <string> GetDerivedTypes(int implementationGuideId, string dataType)
        {
            if (!CheckPoint.Instance.GrantViewImplementationGuide(implementationGuideId))
            {
                throw new AuthorizationException("You do not have permission to view this implementation guide");
            }

            ImplementationGuide ig     = this.tdb.ImplementationGuides.Single(y => y.Id == implementationGuideId);
            SimpleSchema        schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, ig.ImplementationGuideType);
            var derivedTypes           = schema.GetDerivedTypes(dataType);

            if (derivedTypes != null)
            {
                return(derivedTypes.Where(y => y.Name != dataType).Select(y => y.Name));
            }

            return(null);
        }
Exemple #10
0
        public IHttpActionResult CreateStructureDefinition(
            [FromBody] StructureDefinition strucDef)
        {
            var foundProfile = this.tdb.Templates.SingleOrDefault(y => y.Oid == strucDef.Url);

            if (foundProfile != null)
            {
                return(CreateErrorResponse(App_GlobalResources.TrifoliaLang.StructureDefinitionSameUrlExists, OperationOutcome.IssueType.Duplicate));
            }

            Template template;

            try
            {
                User author = CheckPoint.Instance.GetUser(this.tdb);

                template = CreateTemplate(strucDef, author);
                this.tdb.SaveChanges();
            }
            catch (Exception ex)
            {
                return(CreateErrorResponse(ex.Message, OperationOutcome.IssueType.Exception));
            }

            string location = string.Format("{0}://{1}/api/FHIR3/StructureDefinition/{2}",
                                            this.Request.RequestUri.Scheme,
                                            this.Request.RequestUri.Authority,
                                            template.Id);

            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Location", location);

            var uri = HttpContext.Current != null && HttpContext.Current.Request != null ? HttpContext.Current.Request.Url : new Uri(AppSettings.DefaultBaseUrl);
            StructureDefinitionExporter exporter = new StructureDefinitionExporter(this.tdb, uri.Scheme, uri.Authority);
            SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current, template.ImplementationGuideType);

            schema = schema.GetSchemaFromContext(template.PrimaryContextType);

            StructureDefinition newStrucDef = exporter.Convert(template, schema);

            return(Content <StructureDefinition>(HttpStatusCode.Created, newStrucDef, headers));
        }
        public IHttpActionResult UpdateStructureDefinition(
            [FromBody] StructureDefinition strucDef,
            [FromUri] int templateId)
        {
            Template existingTemplate = this.tdb.Templates.SingleOrDefault(y => y.Id == templateId);

            if (!CheckPoint.Instance.GrantEditTemplate(templateId))
            {
                throw new UnauthorizedAccessException();
            }

            var uri = HttpContext.Current != null && HttpContext.Current.Request != null ? HttpContext.Current.Request.Url : new Uri(AppSettings.DefaultBaseUrl);
            StructureDefinitionImporter importer = new StructureDefinitionImporter(this.tdb, uri.Scheme, uri.Authority);
            StructureDefinitionExporter exporter = new StructureDefinitionExporter(this.tdb, uri.Scheme, uri.Authority);

            Template updatedTemplate = importer.Convert(strucDef, existingTemplate);

            if (existingTemplate == null)
            {
                this.tdb.Templates.AddObject(updatedTemplate);
            }

            this.tdb.SaveChanges();

            string location = string.Format("{0}://{1}/api/FHIR2/StructureDefinition/{2}",
                                            this.Request.RequestUri.Scheme,
                                            this.Request.RequestUri.Authority,
                                            updatedTemplate.Id);

            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Location", location);

            SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current, updatedTemplate.ImplementationGuideType);

            schema = schema.GetSchemaFromContext(updatedTemplate.PrimaryContextType);

            StructureDefinition updatedStrucDef = exporter.Convert(updatedTemplate, schema);

            return(Content <Resource>((existingTemplate == null ? HttpStatusCode.Created : HttpStatusCode.OK), updatedStrucDef, headers));
        }
        public IEnumerable <SchemaNode> GetSchemaNodesByType(int implementationGuideId, string parentType = null, string path = null, bool includeAttributes = true)
        {
            if (!CheckPoint.Instance.GrantViewImplementationGuide(implementationGuideId))
            {
                throw new AuthorizationException("You do not have permission to view this implementation guide");
            }

            ImplementationGuide ig     = this.tdb.ImplementationGuides.Single(y => y.Id == implementationGuideId);
            SimpleSchema        schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, ig.ImplementationGuideType);
            List <SimpleSchema.SchemaObject> children = null;

            if (schema == null)
            {
                Logging.Log.For(this).Error("Request for schema nodes by type did not find a schema for implementation guide id " + implementationGuideId);
                return(new List <SchemaNode>());
            }

            if (!string.IsNullOrEmpty(parentType))
            {
                schema = schema.GetSchemaFromContext(parentType);

                if (schema != null)
                {
                    children = schema.Children;
                }
                else
                {
                    Logging.Log.For(this).Warn("Schema for implementation guide type " + ig.ImplementationGuideType.Name + " did not find a parent type of " + parentType);
                }
            }
            else
            {
                children = schema.Children[0].Children;
            }

            if (children == null)
            {
                return(new List <SchemaNode>());
            }

            if (!string.IsNullOrEmpty(path))
            {
                string[] pathSplit = path.Split('/');

                foreach (string nextPath in pathSplit)
                {
                    var child = children.SingleOrDefault(y => y.Name == nextPath);

                    if (child == null)
                    {
                        throw new ArgumentException("Path specified could not be found within type");
                    }

                    children = child.Children;
                }
            }

            var ret = (from s in children
                       where includeAttributes || !s.IsAttribute
                       select new SchemaNode()
            {
                Context = s.IsAttribute ? "@" + s.Name : s.Name,
                Conformance = s.Conformance,
                Cardinality = s.Cardinality,
                DataType = s.DataType,
                IsChoice = s.IsChoice,
                HasChildren = s.Children.Where(y => includeAttributes || !y.IsAttribute).Count() > 0
            });

            return(ret);
        }
        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));
        }
        public SaveResponse Save(SaveModel model)
        {
            SaveResponse response   = new SaveResponse();
            int?         templateId = null;

            using (IObjectRepository tdb = DBContext.CreateAuditable(CheckPoint.Instance.UserName, CheckPoint.Instance.HostAddress))
            {
                if (!CheckPoint.Instance.GrantEditImplementationGuide(model.Template.OwningImplementationGuideId))
                {
                    throw new AuthorizationException("You do not have authorization to edit templates associated with the selected implementation guide");
                }

                if (model.Template.Id != null && !CheckPoint.Instance.GrantEditTemplate(model.Template.Id.Value))
                {
                    throw new AuthorizationException("You do not have permission to edit this template");
                }

                Template template = SaveTemplate(tdb, model.Template);

                // Remove the specified constraints before creating/updating the other constraints
                this.RemoveConstraints(tdb, model.RemovedConstraints);

                // Create/update constraints
                this.SaveConstraints(tdb, template, model.Constraints);

                var allNumbers = (from t in tdb.Templates
                                  join tc in tdb.TemplateConstraints on t.Id equals tc.TemplateId
                                  where t.OwningImplementationGuideId == template.OwningImplementationGuideId
                                  select new { tc.Id, tc.Number });
                var duplicateNumbers = (from tcc in template.ChildConstraints
                                        join an in allNumbers on tcc.Number equals an.Number
                                        where tcc.Id != an.Id
                                        select tcc.Number);

                if (duplicateNumbers.Count() > 0)
                {
                    response.Error = string.Format("The following constraints have duplicate numbers: {0}", string.Join(", ", duplicateNumbers));
                }
                else
                {
                    tdb.SaveChanges();
                    templateId = template.Id;
                }
            }

            if (templateId != null)
            {
                using (IObjectRepository tdb = DBContext.Create())
                {
                    var template = tdb.Templates.Single(y => y.Id == templateId);

                    response.TemplateId  = template.Id;
                    response.AuthorId    = template.AuthorId;
                    response.Constraints = GetConstraints(tdb, template);

                    SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, template.ImplementationGuideType);
                    schema = schema.GetSchemaFromContext(template.PrimaryContextType);

                    var validator = new RIMValidator(tdb);

                    response.ValidationResults = (from vr in validator.ValidateTemplate(template, schema)
                                                  select new
                    {
                        ConstraintNumber = vr.ConstraintNumber,
                        Level = vr.Level.ToString(),
                        Message = vr.Message
                    });
                }
            }

            return(response);
        }
        public IHttpActionResult GetTemplates(
            [FromUri(Name = "_id")] int?templateId           = null,
            [FromUri(Name = "name")] string name             = null,
            [FromUri(Name = "_summary")] SummaryType?summary = null)
        {
            var uri       = HttpContext.Current != null && HttpContext.Current.Request != null ? HttpContext.Current.Request.Url : new Uri(AppSettings.DefaultBaseUrl);
            var templates = this.tdb.Templates.Where(y => y.TemplateType.ImplementationGuideType == this.implementationGuideType);
            StructureDefinitionExporter exporter = new StructureDefinitionExporter(this.tdb, uri.Scheme, uri.Authority);

            if (!CheckPoint.Instance.IsDataAdmin)
            {
                User currentUser = CheckPoint.Instance.GetUser(this.tdb);
                templates = (from t in templates
                             join vtp in this.tdb.ViewTemplatePermissions on t.Id equals vtp.TemplateId
                             where vtp.UserId == currentUser.Id
                             select t);
            }

            if (templateId != null)
            {
                templates = templates.Where(y => y.Id == templateId);
            }

            if (!string.IsNullOrEmpty(name))
            {
                templates = templates.Where(y => y.Name.ToLower().Contains(name.ToLower()));
            }

            Bundle bundle = new Bundle()
            {
                Type = Bundle.BundleType.BatchResponse
            };

            foreach (var template in templates)
            {
                SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current, template.ImplementationGuideType);
                schema = schema.GetSchemaFromContext(template.PrimaryContextType);

                bool isMatch = true;
                StructureDefinition strucDef = exporter.Convert(template, schema, summary);
                var fullUrl = string.Format("{0}://{1}/api/FHIR2/StructureDefinition/{2}",
                                            this.Request.RequestUri.Scheme,
                                            this.Request.RequestUri.Authority,
                                            template.Id);

                // Skip adding the structure definition to the response if a criteria rules it out
                foreach (var queryParam in this.Request.GetQueryNameValuePairs())
                {
                    if (queryParam.Key == "_id" || queryParam.Key == "name" || queryParam.Key == "_format" || queryParam.Key == "_summary")
                    {
                        continue;
                    }

                    if (queryParam.Key.Contains("."))
                    {
                        throw new NotSupportedException(App_GlobalResources.TrifoliaLang.FHIRSearchCriteriaNotSupported);
                    }

                    var propertyDef = strucDef.GetType().GetProperty(queryParam.Key, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

                    if (propertyDef == null)
                    {
                        continue;
                    }

                    var value       = propertyDef.GetValue(strucDef);
                    var valueString = value != null?value.ToString() : string.Empty;

                    if (valueString != queryParam.Value)
                    {
                        isMatch = false;
                    }
                }

                if (isMatch)
                {
                    bundle.AddResourceEntry(strucDef, fullUrl);
                }
            }

            return(Content <Bundle>(HttpStatusCode.OK, bundle));
        }
        public TemplateMetaDataModel GetMetaData(int templateId)
        {
            if (!CheckPoint.Instance.GrantEditTemplate(templateId))
            {
                throw new AuthorizationException("You do not have permission to edit this template");
            }

            DB.Template lTemplate = tdb.Templates.Single(t => t.Id == templateId);

            SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, lTemplate.ImplementationGuideType);

            schema = schema.GetSchemaFromContext(lTemplate.PrimaryContextType);

            var plugin    = lTemplate.OwningImplementationGuide.ImplementationGuideType.GetPlugin();
            var validator = plugin.GetValidator(this.tdb);

            TemplateMetaDataModel lViewModel = new TemplateMetaDataModel()
            {
                Bookmark           = lTemplate.Bookmark,
                PrimaryContext     = lTemplate.PrimaryContext,
                PrimaryContextType = lTemplate.PrimaryContextType,
                Description        = lTemplate.Description,
                Notes = lTemplate.Notes,
                Id    = lTemplate.Id,
                OwningImplementationGuideId = lTemplate.OwningImplementationGuideId,
                ImpliedTemplateId           = lTemplate.ImpliedTemplateId,
                IsOpen                   = lTemplate.IsOpen,
                Name                     = lTemplate.Name,
                Oid                      = lTemplate.Oid,
                StatusId                 = lTemplate.StatusId,
                TemplateTypeId           = lTemplate.TemplateTypeId,
                AuthorId                 = lTemplate.AuthorId,
                Author                   = string.Format("{0} {1}", lTemplate.Author.FirstName, lTemplate.Author.LastName),
                OrganizationName         = lTemplate.OrganizationName,
                MoveUrl                  = lTemplate.GetMoveUrl(),
                TemplateTypeAbbreviation = lTemplate.TemplateType.GetAbbreviation(),
                Locked                   = lTemplate.OwningImplementationGuide.IsPublished()
            };

            // Parse the validation results for the template
            lViewModel.ValidationResults = (from vr in validator.ValidateTemplate(lTemplate, schema)
                                            select new
            {
                ConstraintNumber = vr.ConstraintNumber,
                Level = vr.Level.ToString(),
                Message = vr.Message
            });

            lViewModel.Extensions = (from te in lTemplate.Extensions
                                     select new TemplateMetaDataModel.TemplateExtension()
            {
                Identifier = te.Identifier,
                Type = te.Type,
                Value = te.Value
            });

            if (lTemplate.PreviousVersion != null)
            {
                lViewModel.PreviousVersionLink = "/TemplateManagement/View/" + lTemplate.PreviousVersion.Oid;
                lViewModel.PreviousVersionName = lTemplate.PreviousVersion.Name;
                lViewModel.PreviousVersionOid  = lTemplate.PreviousVersion.Oid;
            }

            // Contained By Templates
            List <TemplateMetaDataModel.TemplateReference> containedByTemplates = new List <TemplateMetaDataModel.TemplateReference>();

            lViewModel.ContainedByTemplates = containedByTemplates;

            var containingConstraints = (from tcr in this.tdb.TemplateConstraintReferences
                                         join tc in this.tdb.TemplateConstraints on tcr.TemplateConstraintId equals tc.Id
                                         where tcr.ReferenceIdentifier == lTemplate.Oid && tcr.ReferenceType == ConstraintReferenceTypes.Template
                                         select tc);

            foreach (var containingConstraint in containingConstraints)
            {
                TemplateMetaDataModel.TemplateReference newReference = new TemplateMetaDataModel.TemplateReference()
                {
                    EditUrl             = containingConstraint.Template.GetEditUrl(),
                    ViewUrl             = containingConstraint.Template.GetViewUrl(),
                    Name                = containingConstraint.Template.Name,
                    ImplementationGuide = containingConstraint.Template.OwningImplementationGuide.GetDisplayName()
                };

                containedByTemplates.Add(newReference);
            }

            // Implied By Templates
            List <TemplateMetaDataModel.TemplateReference> impliedByTemplates = new List <TemplateMetaDataModel.TemplateReference>();

            lViewModel.ImpliedByTemplates = impliedByTemplates;

            foreach (Template implyingTemplate in this.tdb.Templates.Where(y => y.ImpliedTemplateId == templateId))
            {
                TemplateMetaDataModel.TemplateReference newReference = new TemplateMetaDataModel.TemplateReference()
                {
                    EditUrl             = implyingTemplate.GetEditUrl(),
                    ViewUrl             = implyingTemplate.GetViewUrl(),
                    Name                = implyingTemplate.Name,
                    ImplementationGuide = implyingTemplate.OwningImplementationGuide.GetDisplayName()
                };

                impliedByTemplates.Add(newReference);
            }

            return(lViewModel);
        }
Exemple #17
0
        public SaveResponse Save(SaveModel model)
        {
            SaveResponse response = new SaveResponse();

            using (IObjectRepository tdb = DBContext.Create())
            {
                if (!CheckPoint.Instance.GrantEditImplementationGuide(model.Template.OwningImplementationGuideId))
                {
                    throw new AuthorizationException("You do not have authorization to edit templates associated with the selected implementation guide");
                }

                if (model.Template.Id != null && !CheckPoint.Instance.GrantEditTemplate(model.Template.Id.Value))
                {
                    throw new AuthorizationException("You do not have permission to edit this template");
                }

                // Audit all changes to template and constraints
                tdb.AuditChanges(CheckPoint.Instance.UserName, CheckPoint.Instance.OrganizationName, CheckPoint.Instance.HostAddress);

                Template template = SaveTemplate(tdb, model.Template);

                // Remove the specified constraints before creating/updating the other constraints
                this.RemoveConstraints(tdb, model.RemovedConstraints);

                // Create/update constraints
                this.SaveConstraints(tdb, template, model.Constraints);

                var duplicateNumbers = (from tcc in template.ChildConstraints
                                        join tc in tdb.TemplateConstraints on tcc.Number equals tc.Number
                                        join t in tdb.Templates on tc.TemplateId equals t.Id
                                        where tcc.Id != tc.Id && t.OwningImplementationGuideId == template.OwningImplementationGuideId
                                        select tcc.Number).ToList();

                if (duplicateNumbers.Count > 0)
                {
                    response.Error = string.Format("The following constraints have duplicate numbers: {0}", string.Join(", ", duplicateNumbers));
                }
                else
                {
                    tdb.SaveChanges();

                    tdb.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, template);

                    foreach (var constraint in template.ChildConstraints)
                    {
                        tdb.Refresh(System.Data.Entity.Core.Objects.RefreshMode.StoreWins, constraint);
                    }

                    response.TemplateId  = template.Id;
                    response.Constraints = GetConstraints(tdb, template);

                    SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, template.ImplementationGuideType);
                    schema = schema.GetSchemaFromContext(template.PrimaryContextType);

                    response.ValidationResults = (from vr in template.ValidateTemplate(schema)
                                                  select new
                    {
                        ConstraintNumber = vr.ConstraintNumber,
                        Level = vr.Level.ToString(),
                        Message = vr.Message
                    });
                }
            }

            return(response);
        }