public static GreenTemplateViewModel AdaptFromGreenTemplate(GreenTemplate g)
 {
     return(new GreenTemplateViewModel()
     {
         Id = g.Id,
         Name = g.Name,
         Oid = g.Template.Oid,
         TemplateName = g.Template.Name,
         TemplateType = g.Template.TemplateType.Name
     });
 }
示例#2
0
        /// <summary>
        /// Used to test green artifact generation.
        /// </summary>
        /// <returns></returns>
        public static MockObjectRepository GenerateGreenMockDataset1()
        {
            MockObjectRepository mockRepo = new MockObjectRepository();

            mockRepo.FindOrCreateCodeSystem("SNOMED CT", "6.96");
            mockRepo.FindOrCreateCodeSystem("HL7ActStatus", "113883.5.14");
            mockRepo.FindOrCreateValueSet("GenderCode", "11.1");

            ImplementationGuideType igType      = mockRepo.FindOrCreateImplementationGuideType("CDA", "CDA.xsd", "cda", "urn:hl7-org:v3");
            TemplateType            docType     = mockRepo.FindOrCreateTemplateType(igType, "Document", "ClinicalDocument", "ClinicalDocument", 1);
            TemplateType            sectionType = mockRepo.FindOrCreateTemplateType(igType, "Section", "section", "Section", 2);

            mockRepo.GenerateDataType(igType, "II");
            mockRepo.GenerateDataType(igType, "INT");
            mockRepo.GenerateDataType(igType, "TS");
            mockRepo.GenerateDataType(igType, "CE");

            ImplementationGuide ig1 = mockRepo.FindOrAddImplementationGuide(igType, "Test IG 1");
            Template            t1  = mockRepo.GenerateTemplate("urn:oid:1.2.3.4", docType, "Test Template 1", ig1, null, null, null);

            TemplateConstraint tc1       = mockRepo.GenerateConstraint(t1, null, null, "code", "SHALL", "1..1", "CE");
            TemplateConstraint tc1_1     = mockRepo.GenerateConstraint(t1, tc1, null, "@code", "SHALL", "1..1", null, "SHALL", "1234-x", "Test Doc Code", null, null);
            TemplateConstraint tc1_2     = mockRepo.GenerateConstraint(t1, tc1, null, "@codeSystem", "SHALL", "1..1", null, "SHALL", "1.5.4.2.3", "Test Code System OID", null, null);
            TemplateConstraint tc2       = mockRepo.GenerateConstraint(t1, null, null, "setId", "SHALL", "1..1", "II");
            TemplateConstraint tc3       = mockRepo.GenerateConstraint(t1, null, null, "versionNumber", "SHALL", "1..1", "INT");
            TemplateConstraint tc4       = mockRepo.GenerateConstraint(t1, null, null, "recordTarget", "SHALL", "1..*", null);
            TemplateConstraint tc4_1     = mockRepo.GenerateConstraint(t1, tc4, null, "patientRole", "SHALL", "1..1", null);
            TemplateConstraint tc4_1_1   = mockRepo.GenerateConstraint(t1, tc4_1, null, "id", "SHALL", "1..1", "II");
            TemplateConstraint tc4_1_2   = mockRepo.GenerateConstraint(t1, tc4_1, null, "patient", "SHALL", "1..1", null);
            TemplateConstraint tc4_1_2_1 = mockRepo.GenerateConstraint(t1, tc4_1_2, null, "birthTime", "SHALL", "1..1", "TS");
            TemplateConstraint tc4_1_2_2 = mockRepo.GenerateConstraint(t1, tc4_1_2, null, "administrativeGenderCode", "SHALL", "1..1", "CE");

            // Green Info

            GreenTemplate gt1 = new GreenTemplate()
            {
                Id         = 1,
                Template   = t1,
                TemplateId = t1.Id,
                Name       = "Test Green Template 1"
            };

            mockRepo.GreenTemplates.AddObject(gt1);
            t1.GreenTemplates.Add(gt1);

            GreenConstraint gc1 = mockRepo.GenerateGreenConstraint(gt1, tc2, null, 1, "VersionSet", true);
            GreenConstraint gc2 = mockRepo.GenerateGreenConstraint(gt1, tc3, null, 2, "VersionNumber", true);
            GreenConstraint gc3 = mockRepo.GenerateGreenConstraint(gt1, tc4, null, 3, "Patient", false);
            GreenConstraint gc4 = mockRepo.GenerateGreenConstraint(gt1, tc4_1_1, gc3, 1, "Id", true);
            GreenConstraint gc5 = mockRepo.GenerateGreenConstraint(gt1, tc4_1_2_1, gc3, 2, "BirthDate", true);
            GreenConstraint gc6 = mockRepo.GenerateGreenConstraint(gt1, tc4_1_2_2, gc3, 3, "Gender", true);

            return(mockRepo);
        }
        private GreenTemplate CreateGreenTemplate(Template template, string name)
        {
            GreenTemplate newGreenTemplate = new GreenTemplate()
            {
                Template   = template,
                TemplateId = template.Id,
                Name       = name
            };

            template.GreenTemplates.Add(newGreenTemplate);
            this.mockRepo.GreenTemplates.AddObject(newGreenTemplate);

            return(newGreenTemplate);
        }
示例#4
0
        public static void Delete(LookupGreenTemplate lookupGreenTemplate)
        {
            using (IObjectRepository tdb = DBContext.Create())
            {
                GreenTemplate greenTemplate = tdb.GreenTemplates.Single(y => y.Id == lookupGreenTemplate.Id);

                // Remove all green constraints associated with the green template
                greenTemplate.ChildGreenConstraints.ToList().ForEach(y => tdb.GreenConstraints.DeleteObject(y));

                // Remove the green template
                tdb.GreenTemplates.DeleteObject(greenTemplate);

                tdb.SaveChanges();
            }
        }
示例#5
0
        public static void Delete(LookupGreenTemplate lookupGreenTemplate)
        {
            using (TemplateDatabaseDataSource tdb = new TemplateDatabaseDataSource())
            {
                GreenTemplate greenTemplate = tdb.GreenTemplates.Single(y => y.Id == lookupGreenTemplate.Id);

                // Remove all green constraints associated with the green template
                greenTemplate.ChildGreenConstraints.ToList().ForEach(y => tdb.GreenConstraints.DeleteObject(y));

                // Remove the green template
                tdb.GreenTemplates.DeleteObject(greenTemplate);

                tdb.SaveChanges();
            }
        }
        private void CreateTemplate(GreenTemplate greenTemplate)
        {
            // Create the xsl:template for the green template and add it to the document
            string     name            = Helper.NormalizeName(greenTemplate.Name);
            XmlElement templateElement = TransformHelper.CreateXslTemplate(this.transformDoc, name, Helper.NormalizeName(greenTemplate.Name));

            this.transformDoc.DocumentElement.AppendChild(templateElement);

            // Identify all the root-level constraints within the template
            List <TemplateConstraint> rootTemplateConstraints = (from tc in tdb.TemplateConstraints
                                                                 where tc.TemplateId == greenTemplate.TemplateId &&
                                                                 tc.ParentConstraintId == null
                                                                 select tc).ToList();

            if (!string.IsNullOrEmpty(greenTemplate.Template.TemplateType.RootContext))
            {
                // Create top-level context element
                XmlElement contextElement = this.transformDoc.CreateElement(TransformHelper.IgNamespacePrefix, greenTemplate.Template.TemplateType.RootContext, this.schemaNamespace);
                templateElement.AppendChild(contextElement);

                // TODO: This should be replaced with more generic code for IG types in the future
                // TODO: This should be put in the right location in the output. If there is an ID constraint, the order of elements won't match CDA.xsd
                TemplateConstraint foundTemplateId = (from tc in rootTemplateConstraints
                                                      join tcc in tdb.TemplateConstraints on tc.Id equals tcc.ParentConstraintId
                                                      where tc.Context == "templateId" &&
                                                      tcc.Context == "@root" &&
                                                      tcc.Value == greenTemplate.Template.Oid
                                                      select tc).FirstOrDefault();

                // If a templateId constraint has not been defined at the top level for this template, then we should create
                // a templateId element for it, and add it to the output
                if (foundTemplateId == null)
                {
                    XmlElement templateIdElement = this.transformDoc.CreateElement(TransformHelper.IgNamespacePrefix, "templateId", this.schemaNamespace);
                    templateIdElement.Attributes.Append(
                        TransformHelper.CreateXsltAttribute(this.transformDoc, "root", greenTemplate.Template.Oid));
                    contextElement.AppendChild(templateIdElement);
                }

                rootTemplateConstraints.ForEach(y => CreateTemplateConstraint(contextElement, y));
            }
            else
            {
                rootTemplateConstraints.ForEach(y => CreateTemplateConstraint(templateElement, y));
            }
        }
        private GreenConstraint CreateGreenConstraint(GreenTemplate greenTemplate, TemplateConstraint constraint, GreenConstraint parent, string businessName = null, string elementName = null, string xpath = null, ImplementationGuideTypeDataType dataType = null)
        {
            if (string.IsNullOrEmpty(constraint.Context))
            {
                throw new ArgumentException(constraint.Context);
            }

            if (string.IsNullOrEmpty(elementName))
            {
                elementName = constraint.Context;
            }

            if (string.IsNullOrEmpty(businessName))
            {
                businessName = constraint.Context;
            }

            GreenConstraint newGreenConstraint = new GreenConstraint()
            {
                GreenTemplate        = greenTemplate,
                GreenTemplateId      = greenTemplate.Id,
                TemplateConstraint   = constraint,
                TemplateConstraintId = constraint.Id,
                Description          = businessName,
                Name      = elementName,
                RootXpath = xpath,
                ImplementationGuideTypeDataType   = dataType,
                ImplementationGuideTypeDataTypeId = dataType != null ? (int?)dataType.Id : null
            };

            if (parent != null)
            {
                newGreenConstraint.ParentGreenConstraint   = parent;
                newGreenConstraint.ParentGreenConstraintId = parent.Id;
                parent.ChildGreenConstraints.Add(newGreenConstraint);
            }

            constraint.GreenConstraints.Add(newGreenConstraint);
            greenTemplate.ChildGreenConstraints.Add(newGreenConstraint);

            this.mockRepo.GreenConstraints.AddObject(newGreenConstraint);

            return(newGreenConstraint);
        }
        public void BuildGreenSchemaTest_SeparatedDataTypes()
        {
            Template docTemplate         = this.mockRepo.Templates.Single(y => y.Oid == "urn:oid:1.2.3.4");
            Template baseSectionTemplate = this.mockRepo.Templates.Single(y => y.Oid == "urn:oid:1.2.3.4.1");
            Template sectionTemplateReq  = this.mockRepo.Templates.Single(y => y.Oid == "urn:oid:1.2.3.4.1.1");
            Template sectionTemplateOpt  = this.mockRepo.Templates.Single(y => y.Oid == "urn:oid:1.2.3.4.1.2");
            Template entryTemplate       = this.mockRepo.Templates.Single(y => y.Oid == "urn:oid:1.2.3.4.1.3");

            GreenTemplate greenDocTemplate = CreateGreenTemplate(docTemplate, "myGreenDoc");
            string        sectionXpath     = "component/structuredBody/component/section";
            var           greenDoc         = CreateGreenConstraint(greenDocTemplate, this.mockRepo.TemplateConstraints.Single(y => y.Number == 39704), null, "My Section", "mySection", sectionXpath);

            GreenTemplate greenSectionTemplateReq = CreateGreenTemplate(sectionTemplateReq, "myGreenSection");
            string        entryXpath   = "entry/observation";
            var           greenSection = CreateGreenConstraint(greenSectionTemplateReq, this.mockRepo.TemplateConstraints.Single(y => y.Number == 39712), null, "My Entry", "myEntry", entryXpath);

            GreenTemplate greenEntryTemplate = CreateGreenTemplate(entryTemplate, "myEntry");
            string        hemoglobinXpath    = "value";
            var           cdDataType         = this.mockRepo.FindOrAddDataType(MockObjectRepository.DEFAULT_CDA_IG_TYPE_NAME, "CD");
            var           greenEntry         = CreateGreenConstraint(greenEntryTemplate, this.mockRepo.TemplateConstraints.Single(y => y.Number == 39714), null, "Hemoglobin", "hemoglobin", hemoglobinXpath, cdDataType);

            GreenSchemaPackage package = GreenSchemaGenerator.Generate(mockRepo, docTemplate, true);

            Assert.IsNotNull(package);

            Assert.IsNotNull(package.GreenSchemaContent);
            Assert.AreNotEqual(0, package.GreenSchemaContent.Length);
            Assert.IsNotNull(package.GreenSchemaFileName);
            Assert.AreNotEqual(0, package.GreenSchemaFileName.Length);

            bool foundImport = package.GreenSchemaContent.IndexOf("<xs:import") > 0;

            Assert.IsTrue(foundImport, "Could not find <xs:import> in green schema content");

            Assert.IsNotNull(package.DataTypesContent);
            Assert.AreNotEqual(0, package.DataTypesContent.Length);
            Assert.IsNotNull(package.DataTypesFileName);
            Assert.AreNotEqual(0, package.DataTypesFileName.Length);
        }
        /// <summary>
        /// Creates the transform for the green template and all data types found/used within the green template
        /// and the contained templates
        /// </summary>
        public void BuildTransform()
        {
            if (!this.greenTemplates.ContainsKey(this.rootTemplate.Id))
            {
                return;
            }

            long          rootGreenTemplateId = this.greenTemplates[this.rootTemplate.Id];
            GreenTemplate rootGreenTemplate   = this.rootTemplate.GreenTemplates.SingleOrDefault(y => y.Id == rootGreenTemplateId);

            if (rootGreenTemplate == null)
            {
                return;
            }

            // Create the transform for the root template
            CreateTemplate(rootGreenTemplate);

            // Add the templates to the transform for the data types
            foreach (XmlElement cDataTypeTemplate in this.dataTypeTemplates.Values)
            {
                this.transformDoc.DocumentElement.AppendChild(cDataTypeTemplate);
            }
        }
示例#10
0
        /// <summary>
        /// Adds a single template to the implementation guide document.
        /// </summary>
        /// <param name="template">The template to add to the document</param>
        private void AddTemplate(Template template)
        {
            Log.For(this).Trace("BEGIN: Adding template '{0}'.", template.Oid);

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

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

            this.templateCount++;

            string headingLevel = Properties.Settings.Default.TemplateHeaderStyle;

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

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

            bool lDirectlyOwnedTemplate = template.OwningImplementationGuideId == this.implementationGuide.Id;
            bool lStatusMatches         = template.StatusId == template.OwningImplementationGuide.PublishStatusId;

            string lTemplateTitle = lTitleBuilder.ToString();

            // Output the title of the template
            Paragraph pHeading = new Paragraph(
                new ParagraphProperties(
                    new ParagraphStyleId()
            {
                Val = headingLevel
            }));

            this.hyperlinkTracker.AddAnchorAround(pHeading, bookmarkId,
                                                  new Run(
                                                      new Text(template.Name.Substring(0, 1))),
                                                  new Run(
                                                      new Text(lTemplateTitle)));

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

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

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

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

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

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

            //Output IG publish/draft info with "bracket data" format
            if (exportSettings.IncludeTemplateStatus)
            {
                string status = template.Status != null ? template.Status.Status : "Draft";
                string igText = string.Format("{0} as part of {1}", status, template.OwningImplementationGuide.GetDisplayName());

                Paragraph igDetails = new Paragraph(
                    new ParagraphProperties(
                        new ParagraphStyleId()
                {
                    Val = Properties.Settings.Default.TemplateLocationStyle
                }),
                    DocHelper.CreateRun(igText));
                this.document.MainDocumentPart.Document.Body.AppendChild(igDetails);
            }

            // If we were told to generate context tables for the template...
            if (exportSettings.GenerateTemplateContextTable)
            {
                TemplateContextTable.AddTable(this._tdb, this.templateRelationships, this.tables, this.document.MainDocumentPart.Document.Body, template, this.templates, this.hyperlinkTracker);
            }

            // Output the template's descriptionz
            if (!string.IsNullOrEmpty(template.Description))
            {
                OpenXmlElement element = template.Description.MarkdownToOpenXml(this._tdb, this.document.MainDocumentPart);
                OpenXmlHelper.Append(element, this.document.MainDocumentPart.Document.Body);
            }

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

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

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

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

            bool lCreateValueSetTables = exportSettings.DefaultValueSetMaxMembers > 0;

            IConstraintGenerator constraintGenerator = ConstraintGenerationFactory.NewConstraintGenerator(
                this.igSettings,
                this.document.MainDocumentPart,
                this.commentManager,
                this.figures,
                exportSettings.IncludeXmlSamples,
                _tdb,
                rootConstraints,
                templateConstraints,
                template,
                this.templates,
                Properties.Settings.Default.ConstraintHeadingStyle,
                exportSettings.SelectedCategories,
                this.hyperlinkTracker);

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

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

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

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

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

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

            Log.For(this).Trace("END: Adding template '{0}' with {1} constraints.", template.Oid, templateConstraints.Count);
        }
示例#11
0
 public HtmlTag Green(GreenTemplate input)
 {
     return new HtmlTag("div").Text("Green: " + Thread.CurrentThread.CurrentCulture.Name);
 }
示例#12
0
 public HtmlTag Green(GreenTemplate input)
 {
     return(new HtmlTag("div").Text("Green: " + Thread.CurrentThread.CurrentCulture.Name));
 }
示例#13
0
        /// <summary>
        /// Creates a schema complexType out of the green template and inserts it at the top of the schemas items
        /// </summary>
        /// <remarks>
        /// Adds an annotation that indicates what canonical template it represents
        /// If the template implies another template, the implied template is build if it has
        ///   a green template definition, and this template's complexType extends its parent
        /// Calls BuildConstraint for each root constraint within the green template (root
        ///   constraints don't have a ParentGreenConstraint)
        /// </remarks>
        private void BuildTemplate(GreenTemplate greenTemplate)
        {
            if (FindTemplateComplexType(greenTemplate.Name) != null)
            {
                return;
            }

            XmlSchemaSequence    sequence       = new XmlSchemaSequence();
            XmlSchemaComplexType newComplexType = new XmlSchemaComplexType()
            {
                Name = greenTemplate.Name
            };

            // Create an annotation telling the implementers what canonical template this complex type represents
            string annotationText = string.Format("Template \"{0}\" ({1}) from implementation guide \"{2}\"",
                                                  greenTemplate.Template.Name,
                                                  greenTemplate.Template.Oid,
                                                  greenTemplate.Template.OwningImplementationGuide.Name);

            newComplexType.Annotation = CreateAnnotation(annotationText);

            // If this template inherits from another, build the parent and have this complex type extend its base
            if (greenTemplate.Template.ImpliedTemplate != null)
            {
                var impliedTemplate = greenTemplate.Template.ImpliedTemplate;

                if (impliedTemplate.GreenTemplates.Count > 0)
                {
                    var impliedGreenTemplate = greenTemplate.Template.ImpliedTemplate.GreenTemplates.First();
                    BuildTemplate(impliedGreenTemplate);

                    XmlSchemaComplexContent newComplexContent = new XmlSchemaComplexContent();
                    newComplexType.ContentModel = newComplexContent;

                    XmlSchemaComplexContentExtension newExtension = new XmlSchemaComplexContentExtension();
                    newExtension.BaseTypeName = new XmlQualifiedName(impliedGreenTemplate.Name);
                }
            }

            if (newComplexType.ContentModel == null && newComplexType.Particle == null)
            {
                newComplexType.Particle = sequence;
            }

            // Green Constraints
            var rootGreenConstraints = greenTemplate.ChildGreenConstraints.Where(y => y.ParentGreenConstraint == null);

            if (rootGreenConstraints.Count() > 0)
            {
                foreach (var currentRootGreenConstraint in rootGreenConstraints)
                {
                    XmlSchemaObject newConstraintElement = BuildConstraint(currentRootGreenConstraint);

                    if (newConstraintElement != null)
                    {
                        sequence.Items.Add(newConstraintElement);
                    }
                }
            }

            this.schema.Items.Insert(0, newComplexType);
        }
        public void BuildGreenSchemaTest_Basic()
        {
            var ivlts_dt = this.mockRepo.FindOrAddDataType(MockObjectRepository.DEFAULT_CDA_IG_TYPE_NAME, "IVL_TS");

            Template docTemplate         = this.mockRepo.Templates.Single(y => y.Oid == "urn:oid:1.2.3.4");
            Template baseSectionTemplate = this.mockRepo.Templates.Single(y => y.Oid == "urn:oid:1.2.3.4.1");
            Template sectionTemplateReq  = this.mockRepo.Templates.Single(y => y.Oid == "urn:oid:1.2.3.4.1.1");
            Template sectionTemplateOpt  = this.mockRepo.Templates.Single(y => y.Oid == "urn:oid:1.2.3.4.1.2");
            Template entryTemplate       = this.mockRepo.Templates.Single(y => y.Oid == "urn:oid:1.2.3.4.1.3");

            GreenTemplate greenDocTemplate = CreateGreenTemplate(docTemplate, "myGreenDoc");
            string        sectionXpath     = "component/structuredBody/component/section";
            var           greenDoc         = CreateGreenConstraint(greenDocTemplate, this.mockRepo.TemplateConstraints.Single(y => y.Number == 39704), null, "My Section", "mySection", sectionXpath);

            CreateGreenConstraint(greenDocTemplate, this.mockRepo.TemplateConstraints.Single(y => y.Number == 98023), null, "MyCode", "myCode", "code", ivlts_dt);

            GreenTemplate greenSectionTemplateReq = CreateGreenTemplate(sectionTemplateReq, "myGreenSection");
            string        entryXpath   = "entry/observation";
            var           greenSection = CreateGreenConstraint(greenSectionTemplateReq, this.mockRepo.TemplateConstraints.Single(y => y.Number == 39712), null, "My Entry", "myEntry", entryXpath);

            GreenTemplate greenEntryTemplate = CreateGreenTemplate(entryTemplate, "myEntry");
            string        hemoglobinXpath    = "value";
            var           cdDataType         = this.mockRepo.FindOrAddDataType(MockObjectRepository.DEFAULT_CDA_IG_TYPE_NAME, "CD");
            var           greenEntry         = CreateGreenConstraint(greenEntryTemplate, this.mockRepo.TemplateConstraints.Single(y => y.Number == 39714), null, "Hemoglobin", "hemoglobin", hemoglobinXpath, cdDataType);

            GreenSchemaPackage package = GreenSchemaGenerator.Generate(mockRepo, docTemplate);

            // Is the schema content a valid schema?
            AssertSchemaValid(package.GreenSchemaContent);

            // Load the schema into an XmlDocument so we can assert XPATH against it
            XmlDocument schemaDoc = new XmlDocument();

            schemaDoc.LoadXml(package.GreenSchemaContent);

            XmlNamespaceManager nsManager = new XmlNamespaceManager(schemaDoc.NameTable);

            nsManager.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

            ///////////
            // Test the schema generation results
            ///////////

            // XPATH = /xs:schema/xs:element[@name='myGreenDoc']
            var rootElementDocTemplate = schemaDoc.SelectSingleNode(
                "/xs:schema/xs:element[@name='" + greenDocTemplate.Name + "']", nsManager);

            Assert.IsNotNull(rootElementDocTemplate, "Could not find correct root element for document template");

            // XPATH = //xs:complexType[@name='myGreenDoc']
            var docTemplateComplexType = schemaDoc.SelectSingleNode(
                "//xs:complexType[@name='" + greenDocTemplate.Name + "']", nsManager);

            Assert.IsNotNull(docTemplateComplexType, "Could not find complex type for document template");

            // XPATH = xs:sequence/xs:choice/xs:element[@name='myGreenSection' and @type='myGreenSection']
            var docTemplateElement = docTemplateComplexType.SelectSingleNode(
                "xs:sequence/xs:choice/xs:element[@name='" + greenSectionTemplateReq.Name + "' and @type='" + greenSectionTemplateReq.Name + "']", nsManager);

            Assert.IsNotNull(docTemplateElement, "Could not find section element within doc template");

            // XPATH = //xs:complexType[@name='myGreenSection']
            var sectionComplexType = schemaDoc.SelectSingleNode(
                "//xs:complexType[@name='" + greenSectionTemplateReq.Name + "']", nsManager);

            Assert.IsNotNull(sectionComplexType, "Could not find complex type for green section template");

            // XPATH = xs:sequence/xs:element[@name='myEntry' and @type='myEntry']
            var sectionTemplateElement = sectionComplexType.SelectSingleNode(
                "xs:sequence/xs:element[@name='" + greenEntryTemplate.Name + "' and @type='" + greenEntryTemplate.Name + "']", nsManager);

            Assert.IsNotNull(sectionTemplateElement, "Could not find entry element within section template");

            // XPATH = //xs:complexType[@name='myEntry']
            var entryComplexType = schemaDoc.SelectSingleNode(
                "//xs:complexType[@name='" + greenEntryTemplate.Name + "']", nsManager);

            Assert.IsNotNull(entryComplexType, "Could not find complex type for green entry template");

            // XPATH = xs:sequence/xs:element[@name='hemoglobin']
            var hemoglobinElement = entryComplexType.SelectSingleNode(
                "xs:sequence/xs:element[@name='hemoglobin']", nsManager);

            Assert.IsNotNull(hemoglobinElement, "Could not find element in entry for hemoglobin constraint.");
            Assert.IsNotNull(hemoglobinElement.Attributes["type"], "Hemoglobin element does not have a data-type specified.");
            Assert.AreEqual("CD", hemoglobinElement.Attributes["type"].Value, "Hemoglobin element's data type is not 'CD'.");

            // XPATH = //xs:complexType[@name='CD']
            var dataTypeCDComplexType = schemaDoc.SelectSingleNode(
                "//xs:complexType[@name='CD']", nsManager);

            Assert.IsNotNull(dataTypeCDComplexType, "Could not find complex type 'CD' copied from base schema.");

            // XPATH = //xs:complexType[@name='ANY']
            var dataTypeANYComplexType = schemaDoc.SelectSingleNode(
                "//xs:complexType[@name='ANY']", nsManager);

            Assert.IsNotNull(dataTypeANYComplexType, "Could not find complex type 'ANY' (referenced from 'CD') copied from base schema.");
        }
        public void BuildGreenSchemaTest_CollapsedConstraint2()
        {
            ImplementationGuide ig          = this.mockRepo.FindOrAddImplementationGuide(MockObjectRepository.DEFAULT_CDA_IG_TYPE_NAME, "Testing");
            Template            docTemplate = this.mockRepo.GenerateTemplate("5.4.3.2.1", "Document", "Testing Collapsed", ig, "ClinicalDocument", "ClinicalDocument");
            var recordTarget     = this.mockRepo.GenerateConstraint(docTemplate, null, null, "recordTarget", "SHALL", "1..*");
            var patientRole      = this.mockRepo.GenerateConstraint(docTemplate, recordTarget, null, "patientRole", "SHALL", "1..1");
            var patient          = this.mockRepo.GenerateConstraint(docTemplate, patientRole, null, "patient", "SHALL", "1..1");
            var patientGender    = this.mockRepo.GenerateConstraint(docTemplate, patient, null, "administrativeGenderCode", "SHALL", "1..1");
            var patientName      = this.mockRepo.GenerateConstraint(docTemplate, patient, null, "name", "SHALL", "1..1");
            var patientFirstName = this.mockRepo.GenerateConstraint(docTemplate, patientName, null, "given", "SHALL", "1..1");
            var patientLastName  = this.mockRepo.GenerateConstraint(docTemplate, patientName, null, "family", "SHALL", "1..1");

            GreenTemplate greenDocTemplate  = CreateGreenTemplate(docTemplate, "myGreenDoc");
            string        recordTargetXpath = "recordTarget";
            var           greenRecordTarget = CreateGreenConstraint(greenDocTemplate, recordTarget, null, "Patient", "patient", recordTargetXpath);

            string genderXpath        = "recordTarget/patientRole/patient/administrativeGenderCode";
            var    ceDataType         = this.mockRepo.FindOrAddDataType(MockObjectRepository.DEFAULT_CDA_IG_TYPE_NAME, "CE");
            var    greenPatientGender = CreateGreenConstraint(greenDocTemplate, patientGender, greenRecordTarget, "Gender", "gender", genderXpath, ceDataType);

            string nameXpath        = "recordTarget/patientRole/patient/name";
            var    greenPatientName = CreateGreenConstraint(greenDocTemplate, patientName, greenRecordTarget, "Name", "name", nameXpath);

            string firstNameXpath        = "recordTarget/patientRole/patient/name/given";
            var    stDataType            = this.mockRepo.FindOrAddDataType(MockObjectRepository.DEFAULT_CDA_IG_TYPE_NAME, "ST");
            var    greenPatientFirstName = CreateGreenConstraint(greenDocTemplate, patientFirstName, greenPatientName, "First", "first", firstNameXpath, stDataType);

            string lastNameXpath        = "recordTarget/patientRole/patient/name/family";
            var    greenPatientLastName = CreateGreenConstraint(greenDocTemplate, patientLastName, greenPatientName, "Last", "last", lastNameXpath, stDataType);

            GreenSchemaPackage package = GreenSchemaGenerator.Generate(mockRepo, docTemplate);

            // Is the schema content a valid schema?
            AssertSchemaValid(package.GreenSchemaContent);

            // Load the schema into an XmlDocument so we can assert XPATH against it
            XmlDocument schemaDoc = new XmlDocument();

            schemaDoc.LoadXml(package.GreenSchemaContent);

            XmlNamespaceManager nsManager = new XmlNamespaceManager(schemaDoc.NameTable);

            nsManager.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

            ///////////
            // Test the schema generation results
            ///////////

            // XPATH = /xs:schema/xs:element[@name='myGreenDoc']
            var rootElementDocTemplate = schemaDoc.SelectSingleNode(
                "/xs:schema/xs:element[@name='" + greenDocTemplate.Name + "' and @type='" + greenDocTemplate.Name + "']", nsManager);

            Assert.IsNotNull(rootElementDocTemplate, "Could not find correct root element for document template");

            // XPATH = /xs:schema/xs:complexType[@name='myGreenDoc']
            var rootComplexTypeDocTemplate = schemaDoc.SelectSingleNode(
                "/xs:schema/xs:complexType[@name='" + greenDocTemplate.Name + "']", nsManager);

            Assert.IsNotNull(rootComplexTypeDocTemplate, "Could not find complex type for document template");

            // XPATH = xs:sequence/xs:element[@name='patient' and @minOccurs='1' and @maxOccurs='unbounded']
            var patientNode = rootComplexTypeDocTemplate.SelectSingleNode(
                "xs:sequence/xs:element[@name='patient' and @minOccurs='1' and @maxOccurs='unbounded']", nsManager);

            Assert.IsNotNull(patientNode, "Could not find patient element within myGreenDoc that has min and max occurs set correctly.");

            // XPATH = xs:complexType/xs:sequence/xs:element[@name='gender' and @minOccurs='1' and @maxOccurs='1']
            var patientGenderNode = patientNode.SelectSingleNode(
                "xs:complexType/xs:sequence/xs:element[@name='gender' and @minOccurs='1' and @maxOccurs='1']", nsManager);

            Assert.IsNotNull(patientGenderNode, "Could not find gender element with correct min and max occurs within patient element.");

            // XPATH = xs:complexType/xs:sequence/xs:element[@name='name' and @minOccurs='1' and @maxOccurs='1']
            var patientNameNode = patientNode.SelectSingleNode(
                "xs:complexType/xs:sequence/xs:element[@name='name' and @minOccurs='1' and @maxOccurs='1']", nsManager);

            Assert.IsNotNull(patientGenderNode, "Could not find name element with correct min and max occurs within patient element.");

            // XPATH = xs:complexType/xs:sequence/xs:element[@name='first' and @minOccurs='1' and @maxOccurs='1' and @type='ST']
            var patientFirstNameNode = patientNameNode.SelectSingleNode(
                "xs:complexType/xs:sequence/xs:element[@name='first' and @minOccurs='1' and @maxOccurs='1' and @type='ST']", nsManager);

            Assert.IsNotNull(patientFirstNameNode, "Could not find name element with correct min and max occurs within patient element.");

            // XPATH = xs:complexType/xs:sequence/xs:element[@name='last' and @minOccurs='1' and @maxOccurs='1' and @type='ST']
            var patientLastNameNode = patientNameNode.SelectSingleNode(
                "xs:complexType/xs:sequence/xs:element[@name='last' and @minOccurs='1' and @maxOccurs='1' and @type='ST']", nsManager);

            Assert.IsNotNull(patientLastNameNode, "Could not find name element with correct min and max occurs within patient element.");
        }