public ApiDocGenerator(IDocumentGenerator documentGenerator, DocumentTemplate template, DoxygenModel model)
 {
     this.dg = documentGenerator;
     this.sectionLevel = 0;
     this.Template = template;
     this.Model = model;
 }
Ejemplo n.º 2
0
        public List<IResource> GetResources(int folderId)
        {
            IResource docTemplate1 = new DocumentTemplate { Name = "Doc template 1", Description = "Doc template 1 description" };
            IResource docTemplate2 = new DocumentTemplate { Name = "Doc template 2", Description = "Doc template 2 description" };

            // Just return a List of simple concepts for now
            return new List<IResource> { docTemplate1, docTemplate2 };
        }
Ejemplo n.º 3
0
 public async Task<ActionResult> ModifyAsync(DocumentTemplate item)
 {
     var dbItem = await _dbContext.DocumentTemplates.FirstOrDefaultAsync(d => d.Id == item.Id);
     if (item == null)
     {
         return ActionResult.Failed("Item not found");
     }
     dbItem.Body = item.Body;
     dbItem.Name = item.Name;
     await _dbContext.SaveChangesAsync();
     return ActionResult<DocumentTemplate>.Success(item);
 }
Ejemplo n.º 4
0
 public async Task<ActionResult> CreateAsync(DocumentTemplate item)
 {
     try
     {
         _dbContext.DocumentTemplates.Add(item);
         await _dbContext.SaveChangesAsync();
         return ActionResult<DocumentTemplate>.Success(item);
     }
     catch (Exception ex)
     {
         return ActionResult.Failed(ex);
     }
 }
Ejemplo n.º 5
0
        public void GenerateContext_SingleChildElement_2Levels()
        {
            var administrativeCodeElement = new DocumentTemplateElement("administrativeGenderCode");

            administrativeCodeElement.AddAttribute(new DocumentTemplateElementAttribute("code", "20", string.Empty, "MMG-GENDER-CODE-OID"));
            var cdaDocumentTemplate = new DocumentTemplate("urn:hl7-org:v3");

            cdaDocumentTemplate.AddElement(new DocumentTemplateElement("recordTarget")
                                           .AddElement(administrativeCodeElement));
            var contextBuilder = new ContextBuilder(administrativeCodeElement, "cda");
            var context        = contextBuilder.GetFullyQualifiedContextString();
            var expected       = "cda:recordTarget/cda:administrativeGenderCode[@code='20']";

            Assert.IsFalse(string.IsNullOrEmpty(context), "Null or empty string returned by context builder");
            Assert.IsTrue(context == expected, "Context string was not correct, expected '{0}', actual '{1}'", expected, context);
        }
Ejemplo n.º 6
0
        public void GenerateContext_SingleElementChildElement_2Levels_SingleAttribute()
        {
            var element   = new DocumentTemplateElement("assignedPerson");
            var attribute = new DocumentTemplateElementAttribute("classCode", "ASSIGNED");

            element.AddAttribute(attribute);
            var cdaDocumentTemplate = new DocumentTemplate("urn:hl7-org:v3");

            cdaDocumentTemplate.AddElement(new DocumentTemplateElement("custodian")
                                           .AddElement(element));
            var contextBuilder = new ContextBuilder(attribute, "cda");
            var context        = contextBuilder.GetRelativeContextString();
            var expected       = "cda:assignedPerson[@classCode='ASSIGNED']";

            Assert.IsFalse(string.IsNullOrEmpty(context), "Null or empty string returned by context builder");
            Assert.IsTrue(context == expected, "Context string was not correct, expected '{0}', actual '{1}'", expected, context);
        }
Ejemplo n.º 7
0
        public string GenerateHtmlDocument(int documentID, string unitnum, int apptid, string configFile)
        {
            RiskApps3.Utilities.Configurator.configFilePath = configFile;
            SessionManager.Instance.SetCoreConfigPath(configFile);

            SessionManager.Instance.SetActivePatientNoCallback(unitnum, apptid);

            DocumentTemplate dt = new DocumentTemplate();

            dt.documentTemplateID = documentID;
            dt.BackgroundLoadWork();
            dt.OpenHTML();
            dt.ProcessDocument();

            SessionManager.Instance.Shutdown();
            return(dt.htmlText);
        }
        public override void CreatePackage(string fileName)
        {
            var document = DocumentModel.Load(DocumentTemplate.ExtractDoc("ExaminationStatementMiddleEducation"));

            // Подготовка стилей
            var underlinedText = new CharacterFormat
            {
                FontName       = "Times New Roman",
                Size           = 12,
                UnderlineColor = Color.Black,
                UnderlineStyle = UnderlineType.Single
            };
            var underlinedBoldText = new CharacterFormat
            {
                FontName       = "Times New Roman",
                Size           = 12,
                UnderlineColor = Color.Black,
                UnderlineStyle = UnderlineType.Single,
                Bold           = true
            };

            document.InsertToBookmark("ClaimNumber", _claim.Number, underlinedText);

            document.InsertToBookmark("CurrentUser",
                                      string.Format("{0} {1}.{2}.", Session.CurrentUser.LastName,
                                                    Session.CurrentUser.FirstName[0], Session.CurrentUser.Patronymic[0]));

            document.InsertToBookmark("Date",
                                      DateTime.Now.ToString("«dd» MMMM yyyy г."), underlinedText);

            document.InsertToBookmark("EntrantName",
                                      _claim.Person.FullName);

            string middleMark = string.Format("{0}({1} балла)",
                                              _claim.MiddleMark,
                                              RusCurrency.Str(_claim.MiddleMark, true, "целый", "целых", "целых", "сотый", "сотых", "сотых"));

            document.InsertToBookmark("MiddleMark", middleMark);
            document.InsertToBookmark("ProtocolInfo",
                                      string.Format("{0} №{1}",
                                                    ((DateTime)_claim.SchoolCertificateDocuments.First().EntranceExaminationsCheckProtocol.Date).ToString("dd.MM.yyyy г."),
                                                    _claim.SchoolCertificateDocuments.First().EntranceExaminationsCheckProtocol.Number), underlinedBoldText);

            document.Save(fileName, SaveOptions.DocxDefault);
        }
Ejemplo n.º 9
0
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            winFormHtmlEditor1.Focus();
            winFormHtmlEditor1.DocumentHtml = "";
            progressBar1.Enabled            = true;
            progressBar1.Visible            = true;
            winFormHtmlEditor1.Enabled      = false;
            label5.Visible = true;
            reportTemplate = (DocumentTemplate)ReportCombo.SelectedItem;
            clinicId       = ((Clinic)(ClinicCombo.SelectedItem)).clinicID;
            clinicName     = ((Clinic)(ClinicCombo.SelectedItem)).clinicName;
            StartTime      = dateTimePicker1.Value;
            EndTime        = dateTimePicker2.Value;


            backgroundWorker1.RunWorkerAsync();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Create Invoice action
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreateInvoice_Click(object sender, EventArgs e)
        {
            DocumentTemplate template = new DocumentTemplate();

            template.HeaderCsHtml = txbHeader.Text;
            template.BodyCsHtml   = txbBody.Text;
            template.FooterCsHtml = txbFooter.Text;

            string templateOptionsJson = txbTemplateOption.Text;
            List <TemplateOption> templateOptionsList = new JavaScriptSerializer().Deserialize <List <TemplateOption> >(templateOptionsJson);
            TemplateOption        templateOptions     = templateOptionsList[0];

            CreatePDFBasedOnCsHtmlTemplate(template, txbOutput.Text, templateOptions);



            MessageBox.Show(txbOutput.Text + " was created successfully.");
        }
Ejemplo n.º 11
0
        private void SetViewBag(DocumentTemplate model)
        {
            ViewBag.DocumentKindId_ddl          = nomService.GetDDL_DocumentKind(DocumentConstants.DocumentDirection.OutGoing);
            ViewBag.DocumentTemplateStateId_ddl = nomService.GetDropDownList <DocumentTemplateState>();
            ViewBag.breadcrumbs = commonService.Breadcrumbs_GetForDocumentTemplate(model.SourceType, model.SourceId);
            if (model.DocumentId > 0)
            {
                ViewBag.docNumber = docService.Document_GetById(model.DocumentId.Value).Result.RegNumber;
            }

            if ((model.CaseId ?? 0) > 0)
            {
                ViewBag.haveCasePersonIds = nomService.GetHtmlTemplateForCasePerson();
                ViewBag.CasePersonId_ddl  = casePersonService.CasePerson_SelectForDropDownList(model.CaseId ?? 0, null, "", "Изберете");
            }

            SetHelpFileBySourceType(model.SourceType);
        }
        public async Task Can_Get_Template_By_Id()
        {
            var template         = new DocumentTemplate();
            var dbContextOptions = CreateNewContextOptions();

            using (var context = new ApplicationDbContext(dbContextOptions))
            {
                context.DocumentTemplates.Add(template);
                await context.SaveChangesAsync();
            }

            using (var context = new ApplicationDbContext(dbContextOptions))
            {
                var service = new DocumentsTemplateService(context);
                var result  = await service.GetTemplateById(template.IdDocumentTemplate);

                Assert.NotNull(result);
            }
        }
Ejemplo n.º 13
0
        /**********************************************************************/
        private void GetDataAndReplaceTag(HtmlTextNode tableNode)
        {
            int pos       = 0;
            int suffixPos = -1;

            while (pos < tableNode.Text.Length && pos >= 0)
            {
                pos = tableNode.Text.IndexOf(HraTagText, pos);
                if (pos >= 0)
                {
                    suffixPos = tableNode.Text.IndexOf(HraTagSuffix, pos);
                    if (pos >= 0 && suffixPos > pos)
                    {
                        string tag        = tableNode.Text.Substring(pos, suffixPos + HraTagSuffix.Length - pos);
                        string args       = tableNode.Text.Substring(pos + HraTagText.Length, suffixPos - pos - HraTagText.Length);
                        int    templateId = -1;
                        int.TryParse(args, out templateId);

                        string value = "";

                        if (templateId > 0)
                        {
                            DocumentTemplate dt = new DocumentTemplate();
                            dt.documentTemplateID = templateId;
                            dt.SetPatient(proband);
                            dt.BackgroundLoadWork();
                            dt.OpenHTML();
                            dt.UseDocArgs = UseDocArgs;
                            dt.ProcessDocument();
                            value = dt.htmlText;
                            HtmlNode body = dt.FindNodeByName(dt.doc.DocumentNode, "body");
                            StripNonInsertNodes(body);
                            if (body != null)
                            {
                                value = body.InnerHtml;
                            }

                            tableNode.Text = tableNode.Text.Replace(tag, value);
                        }
                    }
                }
            }
        }
Ejemplo n.º 14
0
 public IActionResult Edit(DocumentTemplate model)
 {
     if (!ModelState.IsValid)
     {
         SetViewBag(model);
         return(View(nameof(Edit), model));
     }
     if (service.DocumentTemplate_SaveData(model))
     {
         SetSuccessMessage(MessageConstant.Values.SaveOK);
         return(RedirectToAction(nameof(Edit), new { id = model.Id }));
     }
     else
     {
         SetErrorMessage(MessageConstant.Values.SaveFailed);
     }
     SetViewBag(model);
     return(View(nameof(Edit), model));
 }
Ejemplo n.º 15
0
        public AboutForm(AboutTextFormatter aboutTextFormatter, DocumentTemplate <object> aboutDocumentTemplate, Size size)
        {
            InitializeComponent();

            AboutTextFormatter    = aboutTextFormatter;
            AboutDocumentTemplate = aboutDocumentTemplate;

            if (!size.IsEmpty)
            {
                Size        = size;
                MinimumSize = size;
            }

            backgoundWorker = new BackgroundWorker();

            backgoundWorker.WorkerSupportsCancellation = true;
            backgoundWorker.DoWork             += BackgoundWorker_DoWork;
            backgoundWorker.RunWorkerCompleted += BackgoundWorker_RunWorkerCompleted;
        }
Ejemplo n.º 16
0
        private void LoadTreeDocuments(TreeNode root, List <DocumentTemplateFlow> documentTemplateFlowList)
        {
            foreach (DocumentTemplateFlow documentTemplateFlow in documentTemplateFlowList)
            {
                TreeNode tnDocumentTemplateFlow = new TreeNode(documentTemplateFlow.DocumentTemplateFlowName);
                tnDocumentTemplateFlow.Name = documentTemplateFlow.DocumentTemplateFlowGUID;

                if (documentTemplateFlow.DocumentTemplateFlowType == "S"
                    ) //Standard approach
                {
                    ContextMenu cm = new ContextMenu();
                    MenuItem    mi = new MenuItem("Nowa seria dokumentów");
                    mi.Name = documentTemplateFlow.DocumentTemplateFlowGUID;
                    cm.MenuItems.Add(mi);
                    mi.Click += Mi_Click;
                    tnDocumentTemplateFlow.ContextMenu = cm;
                }
                foreach (DocumentTemplateFlowAssignment dtfa
                         in documentTemplateFlowAssignmentList.Where(t => t.DocumentTemplateFlowGUID == documentTemplateFlow.DocumentTemplateFlowGUID).OrderBy(t => t.DocumentPosition))
                {
                    TreeNode tnDT = new TreeNode(documentTemplateList.Where(t => t.DocumentTemplateGUID == dtfa.DocumentTemplateGUID).First().DocumentName);

                    DocumentTemplate dt = documentTemplateList.Where(t => t.DocumentTemplateGUID == dtfa.DocumentTemplateGUID).First();
                    tnDT.Name = dt.DocumentTemplateGUID;

                    if (!String.IsNullOrEmpty(dt.DocumentHint))
                    {
                        tnDT.ToolTipText = dt.DocumentHint;
                    }

                    ContextMenu cmm = new ContextMenu();
                    MenuItem    mii = dt.DocumentType == "L" || dt.DocumentType == "N" ? new MenuItem("Otwórz link") : new MenuItem("Nowy dokument");
                    mii.Name   = tnDT.Name;
                    mii.Click += Mii_Click;
                    cmm.MenuItems.Add(mii);
                    tnDT.ContextMenu = cmm;

                    tnDocumentTemplateFlow.Nodes.Add(tnDT);
                }

                root.Nodes.Add(tnDocumentTemplateFlow);
            }
        }
Ejemplo n.º 17
0
        private void SetUpNewDocument(DocumentTemplate template)
        {
            TimetableDocument newDocument = new TimetableDocument();

            if (template != null)
            {
                newDocument.LocationList.Overwrite(template.Locations);
                newDocument.Options       = template.DocumentOptions;
                newDocument.ExportOptions = template.ExportOptions;
                newDocument.NoteDefinitions.Overwrite(template.NoteDefinitions);
                newDocument.TrainClassList.Overwrite(template.TrainClasses);
                newDocument.Signalboxes.Overwrite(template.Signalboxes);
            }
            Model = newDocument;
            UpdateTrainGraphLocationModel();
            UpdateFields();
            Model.UpdateTrainDisplays();
            UpdateSignalboxHours();
            _documentChanged = false;
        }
Ejemplo n.º 18
0
        public bool savePdfDoc(int apptID, string unitnum, int templateID, string directory)
        {
            try
            {
                SessionManager.Instance.SetActivePatient(unitnum, apptID);
                directory = Configurator.GetDocumentStorage();   // override save location with config.xml
                if (directory.Substring(directory.Length - 1) != "\\")
                {
                    directory = directory + "\\";
                }
                string templateDirectory = Configurator.GetDocumentTemplateStorage();   // override save location with config.xml
                if (templateDirectory.Substring(templateDirectory.Length - 1) != "\\")
                {
                    templateDirectory = templateDirectory + "\\";
                }

                HraHtmlDocument hdoc = new HraHtmlDocument(templateID, unitnum, apptID);
                if (hdoc == null)
                {
                    Logger.Instance.WriteToLog("RiskApps3Automation.HtmlDocument(" + templateID.ToString() + ", " + apptID.ToString() + ", \"" + unitnum + "\") returned null");
                    return(false);
                }
                hdoc.apptid = apptID;

                FileInfo fInfo = hdoc.template.CalculateFileName(SessionManager.Instance.GetActivePatient().name,
                                                                 SessionManager.Instance.GetActivePatient().apptdatetime.ToShortDateString().Replace("/", "-"),
                                                                 SessionManager.Instance.GetActivePatient().apptid,
                                                                 SessionManager.Instance.GetActivePatient().unitnum,
                                                                 "pdf", directory);

                string PdfFileName = fInfo.FullName;

                DocumentTemplate.ConvertToPdf(hdoc.template.htmlText, PdfFileName);
            }
            catch (Exception e)
            {
                Logger.Instance.WriteToLog("saveHtmlDoc(" + apptID.ToString() + ", \"" + unitnum + "\", " + templateID.ToString() + ", \"" + directory + "\") " + e.ToString());
                return(false);
            }
            return(true);
        }
Ejemplo n.º 19
0
        public void LoadDocument(List <DocumentTemplate> _documentTemplateList,
                                 List <DocumentTemplateFlow> _documentTemplateFlowList,
                                 List <DocumentTemplateFlowAssignment> _documentTemplateFlowAssignmentList,
                                 string documentGUID
                                 )
        {
            try
            {
                CurrentDocumentTemplateGUID        = documentGUID;
                CurrentDocumentGUID                = GlobalVariables.GetNewGUID();
                documentTemplateList               = _documentTemplateList;
                documentTemplateFlowList           = _documentTemplateFlowList;
                documentTemplateFlowAssignmentList = _documentTemplateFlowAssignmentList;

                DocumentTemplate dt = documentTemplateList.Where(t => t.DocumentTemplateGUID == documentGUID).First();

                if (dt.DocumentType == "L")
                {
                    webBrowser.Navigate(dt.DocumentText);
                }
                else if (dt.DocumentType == "N")
                {
                    htmlDoc.LoadHtml(dt.DocumentText);
                    LoadDictionaryWithInputFields();
                    LoadDocumentDefaultFieldValues();

                    webBrowser.DocumentText = htmlDoc.DocumentNode.OuterHtml.Replace("<head>", "<head><style>body { height:297mm; width:210mm; margin-left:auto; margin-right:auto; }</style>");
                }
                else
                {
                    htmlDoc.LoadHtml(dt.DocumentText);
                    LoadDictionaryWithInputFields();
                    LoadDocumentDefaultFieldValues();

                    webBrowser.DocumentText = htmlDoc.DocumentNode.OuterHtml.Replace("<head>", "<head><style>body { height:297mm; width:210mm; margin-left:auto; margin-right:auto; }</style>");
                }
            }catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 20
0
        public IEnumerable <LabelValueVM> DocumentTemplate_LoadBreadCrumbs(DocumentTemplate model)
        {
            var result = new List <LabelValueVM>();

            switch (model.SourceType)
            {
            case SourceTypeSelectVM.CaseSessionAct:
                var actModel = repo.AllReadonly <CaseSessionAct>()
                               .Include(x => x.ActType)
                               .FirstOrDefault(x => x.Id == model.SourceId);

                var sessionModel = repo.AllReadonly <CaseSession>()
                                   .Include(x => x.SessionType)
                                   .Include(x => x.Case)
                                   .FirstOrDefault(x => x.Id == actModel.CaseSessionId);


                result.Add(new LabelValueVM
                {
                    Value = urlHelper.Action("CasePreview", "Case", new { id = sessionModel.CaseId }),
                    Label = $"Дело {sessionModel.Case.RegNumber}"
                });
                result.Add(new LabelValueVM
                {
                    Value = urlHelper.Action("Preview", "CaseSession", new { id = actModel.Id }),
                    Label = $"{sessionModel.SessionType.Label} {sessionModel.DateFrom:dd.MM.yyyy}"
                });
                result.Add(new LabelValueVM
                {
                    Value = urlHelper.Action("Edit", "CaseSessionAct", new { id = actModel.Id }),
                    Label = $"{actModel.ActType.Label} {actModel.RegNumber} / {actModel.RegDate:dd.MM.yyyy}"
                });

                break;

            default:
                return(null);
            }
            ;
            return(result);
        }
Ejemplo n.º 21
0
        /**************************************************************************************************/

        private void activePatientLoaded(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                baseOutputPath          = DocumentTemplate.getLetterDirectory(proband.apptid, proband.unitnum, proband.name);
                fileSystemWatcher1.Path = baseOutputPath;

                linkLabel1.Text = baseOutputPath.TrimEnd(trimchars);

                backgroundWorker1.RunWorkerAsync();
            }
            catch (Exception exc)
            {
                Logger.Instance.WriteToLog(exc.ToString());
            }


            Enabled = true;
            proband.Tasks.AddHandlersWithLoad(TaskListChanged,
                                              TaskListLoaded,
                                              TaskChanged);
        }
Ejemplo n.º 22
0
        public bool DocumentTemplate_SaveData(DocumentTemplate model)
        {
            try
            {
                model.HtmlTemplateId      = model.HtmlTemplateId.EmptyToNull();
                model.CasePersonId        = model.CasePersonId.EmptyToNull();
                model.CasePersonAddressId = model.CasePersonAddressId.EmptyToNull();

                if (model.Id > 0)
                {
                    var saved = repo.GetById <DocumentTemplate>(model.Id);
                    saved.DocumentKindId          = model.DocumentKindId;
                    saved.DocumentGroupId         = model.DocumentGroupId;
                    saved.DocumentTypeId          = model.DocumentTypeId;
                    saved.HtmlTemplateId          = model.HtmlTemplateId;
                    saved.AuthorId                = model.AuthorId;
                    saved.Description             = model.Description;
                    saved.DocumentTemplateStateId = model.DocumentTemplateStateId;
                    saved.CasePersonId            = model.CasePersonId;
                    saved.CasePersonAddressId     = model.CasePersonAddressId;
                    repo.Update(saved);
                    repo.SaveChanges();
                }
                else
                {
                    model.CourtId = userContext.CourtId;
                    model.UserId  = userContext.UserId;
                    model.DateWrt = DateTime.Now;
                    repo.Add(model);
                    repo.SaveChanges();
                }
                return(true);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"Грешка при DocumentTemplate_SaveData Id={ model.Id }");
            }
            return(false);
        }
Ejemplo n.º 23
0
    private void ExportDocumentTemplate(string fileName, DocumentTemplate documentTemplate)
    {
        var purchaseOrderManager = new PurchaseOrderManager(this);

        //
        // Limpa os buffers de resposta, para não enviar os cabeçalhos da página ASPX
        //
        Response.Clear();
        Response.ContentType = "text/doc";
        //
        // Seta o cabeçalho que irá dizer ao navegador que é para fazer download, ao invés de apresentar na tela.
        //
        Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".htm");
        //
        // Indica que o formato do arquivo será o mesmo do modelo
        //
        Response.ContentEncoding = Encoding.Default;

        //
        // Busca a localização do modelo no servidor e retorna seu conteúdo
        //
        string contentFile = File.ReadAllText(Server.MapPath(documentTemplate.FileUrl));

        //
        // Aplica as trocas das máscaras no modelo, ou seja, substitui os []'s pelo conteúdo e retorna
        //
        contentFile = purchaseOrderManager.ApplyPurchaseOrderInDocumentTemplate(Page.PurchaseOrder, contentFile);
        //
        // Envia o arquivo para o cliente
        //
        Response.Write(contentFile);

        //
        // Interrompe o processamento da página para que o conteúdo do modelo não se misture
        // ao HTML da página PurchaseOrder.aspx
        //
        Response.End();
    }
        protected override void OnLoad()
        {
            base.OnLoad();

            DocumentTemplate documentTemplate = (DocumentTemplate)this.Tag;

            TitleTextBox.Text       = documentTemplate.Title;
            DescriptionTextBox.Text = documentTemplate.Description;
            pictureSelection.Initialize(documentTemplate.ImageID);
            TemplatePath = documentTemplate.TemplatePath;
            if (documentTemplate.ApplicationType == ApplicationTypes.Word)
            {
                WordTemplateApplicationRadioButton.IsChecked = true;
            }
            else if (documentTemplate.ApplicationType == ApplicationTypes.Outlook)
            {
                OutlookTemplateApplicationRadioButton.IsChecked = true;
            }
            else
            {
                ExcelTemplateApplicationRadioButton.IsChecked = true;
            }
        }
        public void GenerateSchematronAssertion_Element_With_Value_ConformanceSHALL_CardinalityOneToOne()
        {
            //create cda doc
            var cdaDocumentTemplate = new DocumentTemplate("urn:hl7-org:v3");
            //create code element
            var element = new DocumentTemplateElement("code", "Test");

            //add element to doc
            cdaDocumentTemplate.AddElement(element);
            //create schematron assertion line builder
            var builder = new AssertionLineBuilder(this.tdb, element, this.igType, this.igTypeSchema);
            //define cardinality and conformance
            var cardinality = CardinalityParser.Parse("1..1");
            var conformance = ConformanceParser.Parse("SHALL");

            //add element (context comes from doc), conformance, cardinality through fluent interface
            builder.ConformsTo(conformance).WithCardinality(cardinality);
            //generate string
            string assertion = builder.ToString();

            //did we generate the correct string?
            Assert.IsTrue(assertion == @"count(cda:code[text()='Test'])=1", "The generated assertion was not correct. Expected 'count(cda:code[text()='Test'])=1', Actual '{0}'.", assertion);
        }
Ejemplo n.º 26
0
        public void GenerateSchematronAssertion_Element_With_Value_ConformanceSHALL_CardinalityOneToOne()
        {
            //create cda doc
            var cdaDocumentTemplate = new DocumentTemplate("urn:hl7-org:v3");
            //create code element
            var element = new DocumentTemplateElement("code", "Test");

            //add element to doc
            cdaDocumentTemplate.AddElement(element);
            //create schematron assertion line builder
            var builder = new AssertionLineBuilder(element, templateIdentifierXpath, templateVersionIdentifierXpath, "cda");
            //define cardinality and conformance
            var cardinality = CardinalityParser.Parse("1..1");
            var conformance = ConformanceParser.Parse("SHALL");

            //add element (context comes from doc), conformance, cardinality through fluent interface
            builder.ConformsTo(conformance).WithCardinality(cardinality);
            //generate string
            string assertion = builder.ToString();

            //did we generate the correct string?
            Assert.IsTrue(assertion == @"count(cda:code[translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')='test'])=1", "The generated assertion was not correct. Expected 'count(cda:code[text()='Test'])=1', Actual '{0}'.", assertion);
        }
        public void GenerateSchematronAssertion_NamespaceEMA_Element_Template_ConformanceSHALL_CardinalityOneToOne()
        {
            //create cda doc
            var cdaDocumentTemplate = new DocumentTemplate("urn:hl7-org:v3");
            //create code element
            var element = new DocumentTemplateElement("encounter");

            //add element to doc
            cdaDocumentTemplate.AddElement(element);
            //create schematron assertion line builder
            var builder = new AssertionLineBuilder(this.tdb, element, this.igType, this.igTypeSchema, "ema");
            //define cardinality and conformance
            var cardinality = CardinalityParser.Parse("1..1");
            var conformance = ConformanceParser.Parse("SHALL");

            //add element (context comes from doc), conformance, cardinality through fluent interface
            builder.ConformsTo(conformance).WithCardinality(cardinality).ContainsTemplate("urn:oid:4.3.2.1", "Section");
            //generate string
            string assertion = builder.ToString();
            string expected  = @"count(ema:encounter[ema:templateId[@root='4.3.2.1']])=1";

            //did we generate the correct string?
            Assert.IsTrue(assertion == expected, "The generated assertion was not correct. Expected '{0}', Actual '{1}'.", expected, assertion);
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> GenerateDocument(Guid selectedTemplate)
        {
            try
            {
                DocumentTemplate documentTemplate = await _dbService.GetTemplate(selectedTemplate);

                if (documentTemplate != null)
                {
                    string filledTemplatePath = _apiService.FillTemplate(documentTemplate);
                    if (filledTemplatePath != null)
                    {
                        var provider = new FileExtensionContentTypeProvider();
                        if (!provider.TryGetContentType(filledTemplatePath, out var contentType))
                        {
                            contentType = "application/octet-stream";
                        }

                        var    fileBytes = System.IO.File.ReadAllBytes(filledTemplatePath);
                        string filename  = documentTemplate.TemplateName + "Describing text.pdf";
                        return(File(fileBytes, contentType, Path.GetFileName(filename)));
                    }
                    else
                    {
                        return(StatusCode(500));
                    }
                }
                else
                {
                    return(StatusCode(404));
                }
            }
            catch
            {
                return(StatusCode(500));
            }
        }
Ejemplo n.º 29
0
        public void GenerateSchematronAssertion_Element_ConformanceSHALL_CardinalityZeroToMany()
        {
            //create cda doc
            var cdaDocumentTemplate = new DocumentTemplate("urn:hl7-org:v3");
            //create code element
            var element = new DocumentTemplateElement("code");

            //add element to doc
            cdaDocumentTemplate.AddElement(element);
            //create schematron assertion line builder
            var builder = new AssertionLineBuilder(element, templateIdentifierXpath, templateVersionIdentifierXpath);
            //define cardinality and conformance
            var cardinality = CardinalityParser.Parse("0..*");
            var conformance = ConformanceParser.Parse("SHALL");

            //add element (context comes from doc), conformance, cardinality through fluent interface
            builder.ConformsTo(conformance).WithCardinality(cardinality);
            //generate string
            string assertion = builder.ToString();
            string expected  = "not(code) or code";

            //did we generate the correct string?
            Assert.IsTrue(assertion == expected, "The generated assertion was not correct. Expected '{0}', Actual '{1}'.", expected, assertion);
        }
 void IApiDocTemplateProcessor.Process(DocumentTemplate template)
 {
     template.ProcessItems(this);
 }
Ejemplo n.º 31
0
        /**********************************************************************/
        private void GetDataAndReplaceTag(HtmlTextNode tableNode)
        {
            int pos = 0;
            int suffixPos = -1;

            while (pos < tableNode.Text.Length && pos >= 0)
            {
                pos = tableNode.Text.IndexOf(HraTagText, pos);
                if (pos >= 0)
                {
                    suffixPos = tableNode.Text.IndexOf(HraTagSuffix, pos);
                    if (pos >= 0 && suffixPos > pos)
                    {
                        string tag = tableNode.Text.Substring(pos, suffixPos + HraTagSuffix.Length - pos);
                        string args = tableNode.Text.Substring(pos + HraTagText.Length, suffixPos - pos - HraTagText.Length);
                        int templateId = -1;
                        int.TryParse(args, out templateId);

                        string value = "";

                        if (templateId > 0)
                        {
                            DocumentTemplate dt = new DocumentTemplate();
                            dt.documentTemplateID = templateId;
                            dt.SetPatient(proband);
                            dt.BackgroundLoadWork();
                            dt.OpenHTML();
                            dt.UseDocArgs = UseDocArgs;
                            dt.ProcessDocument();
                            value = dt.htmlText;
                            HtmlNode body = dt.FindNodeByName(dt.doc.DocumentNode, "body");
                            StripNonInsertNodes(body);
                            if (body != null)
                            {
                                value = body.InnerHtml;
                            }

                            tableNode.Text = tableNode.Text.Replace(tag, value);
                        }
                    }
                }
            }
        }
Ejemplo n.º 32
0
        public GalleryBrowserView(GalleryBrowserFilter galleryBrowserFilter, GalleryModel galleryModel, DocumentTemplate <ISearchProgressArg> searchCovergridTemplate, DocumentTemplate <ISearchArg> searchPreloadTemplate, IPathFormatter pathFormatter
                                  , Configuration.ConfigGalleryBrowserView galleryBrowserSettings
                                  , PageDownloader pageDownloader
                                  , CoverDownloader coverDownloader
                                  , MetadataKeywordLists metadataKeywordLists
                                  , TagsModel tagsModel
                                  , SearchHandler searchHandler)
        {
            InitializeComponent();

            GalleryBrowserFilter    = galleryBrowserFilter;
            GalleryModel            = galleryModel;
            PathFormatter           = pathFormatter;
            SearchCovergridTemplate = searchCovergridTemplate;
            SearchPreloadTemplate   = searchPreloadTemplate;
            GalleryBrowserSettings  = galleryBrowserSettings;
            PageDownloader          = pageDownloader;
            CoverDownloader         = coverDownloader;
            MetadataKeywordLists    = metadataKeywordLists;
            TagsModel     = tagsModel;
            SearchHandler = searchHandler;

            webBrowser           = new WebBrowserEx();
            listBackgroundWorker = new BackgroundWorker();

            SuspendLayout();

            webBrowser.AllowWebBrowserDrop = false;
            webBrowser.Dock = DockStyle.Fill;
            webBrowser.Name = "galleryWebBrowser";
            webBrowser.BeforeDocumentCompleted += WebBrowser_BeforeDocumentCompleted;
            webBrowser.DocumentCompleted       += WebBrowser_DocumentCompleted;

            listBackgroundWorker.WorkerReportsProgress      = true;
            listBackgroundWorker.WorkerSupportsCancellation = true;

            listBackgroundWorker.DoWork             += ListBackgroundWorker_DoWork;
            listBackgroundWorker.ProgressChanged    += ListBackgroundWorker_ProgressChanged;
            listBackgroundWorker.RunWorkerCompleted += ListBackgroundWorker_RunWorkerCompleted;

            PageDownloader.PageDownloadReportProgress += PageDownloader_PageDownloadReportProgress;
            PageDownloader.PagesDownloadStarted       += PageDownloader_PagesDownloadStarted;
            PageDownloader.PagesDownloadCancelled     += PageDownloader_PagesDownloadCancelled;
            PageDownloader.PagesDownloadCompleted     += PageDownloader_PagesDownloadCompleted;

            CoverDownloader.CoverDownloadReportProgress += CoverDownloader_CoverDownloadReportProgress;
            CoverDownloader.CoversDownloadStarted       += CoverDownloader_CoversDownloadStarted;
            CoverDownloader.CoversDownloadCancelled     += CoverDownloader_CoversDownloadCancelled;
            CoverDownloader.CoversDownloadCompleted     += CoverDownloader_CoversDownloadCompleted;

            MetadataKeywordLists.WhitelistChanged  += Form_WhiteListChanged;
            MetadataKeywordLists.BlacklistChanged  += Form_BlackListChanged;
            MetadataKeywordLists.IgnorelistChanged += Form_IgnoreListChanged;
            MetadataKeywordLists.HidelistChanged   += Form_HideListChanged;

            GalleryModel.SearchArgChanged         += GalleryModel_SearchArgChanged;
            GalleryModel.SearchProgressArgChanged += GalleryModel_SearchProgressArgChanged;

            galleryBrowserFilter.TextChanged += GalleryBrowserFilter_TextChanged;

            Controls.Add(webBrowser);

            ResumeLayout(false);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Fills selected template with selected datasource.
        /// </summary>
        /// <param name="selectedTemplate"></param>
        /// <returns></returns>
        //Todo: Add data-source as indata aswell.
        public string FillTemplate(DocumentTemplate selectedTemplate)
        {
            string sourceFile      = selectedTemplate.FilePath;
            string destinationFile = $@"C:\Users\Gustav\source\repos\Doctrim\Doctrim.API\FilledTemplates\DatasourceName_{selectedTemplate.TemplateName}_{DateTime.Now.ToString("yyMMddhhmmssffff")}.docx";



            try
            {
                //Makes a copy of template, that gets filled.
                File.Copy(sourceFile, destinationFile, true);
                using (WordprocessingDocument doc = WordprocessingDocument.Open(destinationFile, true))
                {
                    var body = doc.MainDocumentPart.Document.Body;

                    foreach (var text in body.Descendants <Text>())
                    {
                        if (text.Text.Contains("<#name>"))
                        {
                            text.Text = text.Text.Replace("<#name>", "Gustav");
                        }

                        if (text.Text.Contains("<#lastname>"))
                        {
                            text.Text = text.Text.Replace("<#lastname>", "Falk");
                        }

                        if (text.Text.Contains("<#food>"))
                        {
                            text.Text = text.Text.Replace("<#food>", "Tacos");
                        }

                        if (text.Text.Contains("<#animal>"))
                        {
                            text.Text = text.Text.Replace("<#animal>", "Dog");
                        }
                    }
                }

                Credentials credentials = Credentials.ServiceAccountCredentialsBuilder()
                                          .FromFile("Insert path to pdf-apitools-credentials.json inside of CreatePdfFromDocx") //TODO: Fill in credential path here
                                          .Build();

                //Create an ExecutionContext using credentials and create a new operation instance.
                ExecutionContext   executionContext   = ExecutionContext.Create(credentials);
                CreatePDFOperation createPdfOperation = CreatePDFOperation.CreateNew();

                // Set operation input from a source file.
                FileRef source = FileRef.CreateFromLocalFile(destinationFile);
                createPdfOperation.SetInput(source);

                // Execute the operation.
                FileRef result = createPdfOperation.Execute(executionContext);

                string savedPdf = $"{_env.ContentRootPath}\\FilledTemplates\\{Path.GetFileNameWithoutExtension(destinationFile)}.pdf";
                // Save the result to the specified location.
                result.SaveAs(savedPdf);


                return(savedPdf);
            }

            catch
            {
                return(null);
            }
        }
 public ApiDocTemplateProcessor(DocumentTemplate template, DoxygenModel model, ApiDocGenerator generator)
 {
     this.model = model;
     this.generator = generator;
     this.template = template;
 }
Ejemplo n.º 35
0
        public override void CreatePackage(string fileName)
        {
            // Извлекаем шаблон из вспомогательной сборки и создаем объект экселя
            var ef = ExcelFile.Load(DocumentTemplate.ExtractXls("AdmissionStatistic"));
            var ws = ef.Worksheets[0];

            // готовим шляпу
            string reportTitle = string.Empty;

            if (_isTodayStatistic)
            {
                reportTitle = string.Format("Статистика приёма за {0}",
                                            DateTime.Now.ToString("dd.MM.yyyy г."));
            }
            else
            {
                reportTitle = string.Format("Статистика приёма на {0}",
                                            DateTime.Now.ToString("dd.MM.yyyy г."));
            }
            ws.FindAndReplaceText("ReportTitle", reportTitle);

            ws.FindAndReplaceText("EducationForm",
                                  _educationForm.Name.BeginWithUpper() + " форма обучения");

            /****************************************************************************
             * ПОДГОТОВКА ДАННЫХ
             ***************************************************************************/
            // Копируем 7-ю строку как шаблон
            int i           = 7;
            var templateRow = ws.Rows[i];


            // Получить направления из конкурсных групп по по форме обучения
            var directions = (from compGroup in Session.DataModel.CompetitiveGroups
                              where compGroup.EducationForm.Id == _educationForm.Id &&
                              compGroup.Campaign.CampaignStatus.Id == 2
                              select compGroup.Direction).ToList();

            // Удалить дубликаты из коллекции, отсортировать по коду
            directions = directions.DistinctBy(d => d.Code).ToList();
            directions = directions.OrderBy(d => d.Code).ToList();

            int kcpBudgetTotal = 0, kcpExtrabudgetTotal = 0, kcpQuotaTotal = 0,
                kcpTotalTotal = 0, countBudgetFactTotal = 0, countBudgetOriginalTotal = 0,
                countExtrabudgetFactTotal = 0, countExtrabudgetOriginalTotal = 0,
                countQuotaFactTotal = 0, countQuotaOriginalTotal = 0,
                countTotalFactTotal = 0, countTotalOriginalTotal = 0;

            foreach (var direction in directions)
            {
                string directionName = string.Format("{0} {1}",
                                                     direction.Code, direction.Name);
                int kcpBudget = 0, kcpExtrabudget = 0, kcpQuota = 0,
                    kcpTotal = 0, countBudgetFact = 0, countBudgetOriginal = 0,
                    countExtrabudgetFact = 0, countExtrabudgetOriginal = 0,
                    countQuotaFact = 0, countQuotaOriginal = 0,
                    countTotalFact = 0, countTotalOriginal = 0;

                // Выбрать конкурсные группы по бюджету, направлению и форме обучения
                var competitiveGroupCollection = (from compGroup in direction.CompetitiveGroups
                                                  where compGroup.EducationForm.Id == _educationForm.Id &&
                                                  compGroup.FinanceSource.Id == 1 &&
                                                  compGroup.Campaign.CampaignStatus.Id == 2
                                                  select compGroup);
                // Если есть хоть одна такая, выдираем данные
                if (competitiveGroupCollection.Count() > 0)
                {
                    var currentCompetitiveGroup = competitiveGroupCollection.First();

                    // Заполняем КЦП
                    kcpBudget = currentCompetitiveGroup.PlaceCount ?? 0;
                    CalculateClaimCountInCompetitiveGroup(currentCompetitiveGroup,
                                                          out countBudgetFact, out countBudgetOriginal);
                }

                // Выбрать конкурсные группы по внебюджету, направлению и форме обучения
                competitiveGroupCollection = (from compGroup in direction.CompetitiveGroups
                                              where compGroup.EducationForm.Id == _educationForm.Id &&
                                              compGroup.FinanceSource.Id == 2 &&
                                              compGroup.Campaign.CampaignStatus.Id == 2
                                              select compGroup);
                // Если есть хоть одна такая, выдираем данные
                if (competitiveGroupCollection.Count() > 0)
                {
                    var currentCompetitiveGroup = competitiveGroupCollection.First();

                    // Заполняем КЦП
                    kcpExtrabudget = currentCompetitiveGroup.PlaceCount ?? 0;
                    CalculateClaimCountInCompetitiveGroup(currentCompetitiveGroup,
                                                          out countExtrabudgetFact, out countExtrabudgetOriginal);
                }

                // Выбрать конкурсные группы по льготе, направлению и форме обучения
                competitiveGroupCollection = (from compGroup in direction.CompetitiveGroups
                                              where compGroup.EducationForm.Id == _educationForm.Id &&
                                              compGroup.FinanceSource.Id == 3 &&
                                              compGroup.Campaign.CampaignStatus.Id == 2
                                              select compGroup);
                // Если есть хоть одна такая, выдираем данные
                if (competitiveGroupCollection.Count() > 0)
                {
                    var currentCompetitiveGroup = competitiveGroupCollection.First();

                    // Заполняем КЦП
                    kcpQuota = currentCompetitiveGroup.PlaceCount ?? 0;
                    CalculateClaimCountInCompetitiveGroup(currentCompetitiveGroup,
                                                          out countQuotaFact, out countQuotaOriginal);
                }

                // Считаем итоговые значения
                kcpTotal       = kcpBudget + kcpExtrabudget;
                countTotalFact = countBudgetFact + countExtrabudgetFact +
                                 countQuotaFact;
                countTotalOriginal = countBudgetOriginal + countExtrabudgetOriginal +
                                     countQuotaOriginal;

                // Совсем итоговые
                kcpBudgetTotal                += kcpBudget;
                kcpExtrabudgetTotal           += kcpExtrabudget;
                kcpQuotaTotal                 += kcpQuota;
                kcpTotalTotal                 += kcpTotal;
                countBudgetFactTotal          += countBudgetFact;
                countBudgetOriginalTotal      += countBudgetOriginal;
                countExtrabudgetFactTotal     += countExtrabudgetFact;
                countExtrabudgetOriginalTotal += countExtrabudgetOriginal;
                countQuotaFactTotal           += countQuotaFact;
                countQuotaOriginalTotal       += countQuotaOriginal;
                countTotalFactTotal           += countTotalFact;
                countTotalOriginalTotal       += countTotalOriginal;


                /***************************************************************************
                 * ДАННЫЕ ЗАГРУЖЕНЫ, ЗАНИМАЕМСЯ ЗАГРУЗКОЙ В ДОКУМЕНТ
                 **************************************************************************/

                // Подготовка строки
                ws.Rows.InsertCopy(i, templateRow);
                var currentRow = ws.Rows[i];
                i++;

                // Вставляем данные
                currentRow.Cells[0].Value  = directionName;
                currentRow.Cells[1].Value  = kcpBudget;
                currentRow.Cells[2].Value  = kcpQuota;
                currentRow.Cells[3].Value  = kcpExtrabudget;
                currentRow.Cells[4].Value  = kcpTotal;
                currentRow.Cells[5].Value  = countBudgetFact;
                currentRow.Cells[6].Value  = countBudgetOriginal;
                currentRow.Cells[7].Value  = countQuotaFact;
                currentRow.Cells[8].Value  = countQuotaOriginal;
                currentRow.Cells[9].Value  = countExtrabudgetFact;
                currentRow.Cells[10].Value = countExtrabudgetOriginal;
                currentRow.Cells[11].Value = countTotalFact;
                currentRow.Cells[12].Value = countTotalOriginal;
            }

            // Вставляем самые итоговые итоги
            ws.Rows.InsertCopy(i, templateRow);
            var totalRow = ws.Rows[i];

            totalRow.Cells[0].Value  = "ИТОГО";
            totalRow.Cells[1].Value  = kcpBudgetTotal;
            totalRow.Cells[2].Value  = kcpQuotaTotal;
            totalRow.Cells[3].Value  = kcpExtrabudgetTotal;
            totalRow.Cells[4].Value  = kcpTotalTotal;
            totalRow.Cells[5].Value  = countBudgetFactTotal;
            totalRow.Cells[6].Value  = countBudgetOriginalTotal;
            totalRow.Cells[7].Value  = countQuotaFactTotal;
            totalRow.Cells[8].Value  = countQuotaOriginalTotal;
            totalRow.Cells[9].Value  = countExtrabudgetFactTotal;
            totalRow.Cells[10].Value = countExtrabudgetOriginalTotal;
            totalRow.Cells[11].Value = countTotalFactTotal;
            totalRow.Cells[12].Value = countTotalOriginalTotal;

            ef.Save(fileName);
        }
        /// <summary>
        /// Convert a <see cref="DocumentTemplate" /> instance to a <see cref="TimetableDocumentTemplateModel" /> instance.
        /// </summary>
        /// <param name="template">The object to be converted.</param>
        /// <returns>A <see cref="TimetableDocumentTemplateModel" /> instance containing the same data as the original object in serialisable form.</returns>
        /// <exception cref="NullReferenceException">Thrown if the parameter is null.</exception>
        public static TimetableDocumentTemplateModel ToYamlTimetableDocumentTemplateModel(this DocumentTemplate template)
        {
            if (template is null)
            {
                throw new NullReferenceException();
            }

            TimetableDocumentTemplateModel tdtm = new TimetableDocumentTemplateModel
            {
                DefaultExportOptions = template.ExportOptions.ToYamlExportOptionsModel(),
                DefaultOptions       = template.DocumentOptions.ToYamlDocumentOptionsModel(),
            };
            NetworkMapModel nmm = new NetworkMapModel();

            nmm.LocationList.AddRange(template.Locations.Select(c => c.ToYamlLocationModel()));
            nmm.Signalboxes.AddRange(template.Signalboxes.Select(b => b.ToYamlSignalboxModel()));
            tdtm.Maps.Add(nmm);
            tdtm.NoteDefinitions.AddRange(template.NoteDefinitions.Select(n => n.ToYamlNoteModel()));
            tdtm.TrainClasses.AddRange(template.TrainClasses.Select(c => c.ToYamlTrainClassModel()));
            return(tdtm);
        }
Ejemplo n.º 37
0
        public void BuildAdvanceDirectiveObservationDocument_1stLevelOnly()
        {
            var sectionCount = 1;
            var phase        = new Phase();

            phase.ID = "error";
            var document = new SchematronDocument();

            document.Phases.Add(phase);


            var doc = new DocumentTemplate("cda");

            doc.AddElement(new DocumentTemplateElement("observation"));
            doc.ChildElements[0].AddAttribute(new DocumentTemplateElementAttribute("classCode", "OBS"));
            doc.ChildElements[0].AddAttribute(new DocumentTemplateElementAttribute("moodCode", "EVN"));
            doc.AddElement(new DocumentTemplateElement("templateId"));
            doc.ChildElements[1].AddAttribute(new DocumentTemplateElementAttribute("root", "2.16.840.1.113883.10.20.22.4.48"));
            doc.AddElement(new DocumentTemplateElement("id"));
            doc.AddElement(new DocumentTemplateElement("code"));
            doc.ChildElements[doc.ChildElements.Count - 1].AddAttribute(new DocumentTemplateElementAttribute("xsi-type", "CE", "2.16.840.1.113883.1.11.20.2"));
            doc.AddElement(new DocumentTemplateElement("statusCode"));
            doc.ChildElements[doc.ChildElements.Count - 1].AddAttribute(new DocumentTemplateElementAttribute("code", "completed", "2.16.840.1.113883.5.14"));
            var participantElement = new DocumentTemplateElement("participant");

            doc.ChildElements[0].AddElement(participantElement);
            participantElement.AddAttribute(new DocumentTemplateElementAttribute("typeCode", "VRF"));
            var templateIdElement = new DocumentTemplateElement("templateId");

            templateIdElement.AddAttribute(new DocumentTemplateElementAttribute("root", "2.16.840.1.113883.10.20.1.58"));
            participantElement.AddElement(templateIdElement);
            var timeElement = new DocumentTemplateElement("time");

            timeElement.AddAttribute(new DocumentTemplateElementAttribute("xsi:type", "TS"));
            participantElement.AddElement(timeElement);
            var participantRoleElement = new DocumentTemplateElement("participantRole");

            participantElement.AddElement(participantRoleElement);


            var contextBuilder = new ContextBuilder(doc.ChildElements[0], "cda");
            var rule           = new Rule();

            rule.Context = contextBuilder.GetFullyQualifiedContextString();

            var assertionBuilder = new AssertionLineBuilder(doc.ChildElements[0].Attributes[0], templateIdentifierXpath, templateVersionIdentifierXpath);  //"OBS"

            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..1 @classCode='OBS' Observation (CodeSystem: HL7ActClass 2.16.840.1.113883.5.6) (CONF:8648).",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..1")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });

            assertionBuilder = new AssertionLineBuilder(doc.ChildElements[0].Attributes[1], templateIdentifierXpath, templateVersionIdentifierXpath);  //"EVN"
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..1 @moodCode='EVN' Event (CodeSystem: ActMood 2.16.840.1.113883.5.1001) (CONF:8649).",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..1")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });
            var pattern = new Pattern();

            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            rule             = new Rule();
            contextBuilder   = new ContextBuilder(doc.ChildElements[1], "cda");
            rule.Context     = contextBuilder.GetFullyQualifiedContextString();
            assertionBuilder = new AssertionLineBuilder(doc.ChildElements[1], templateIdentifierXpath, templateVersionIdentifierXpath);  //"templateId[@rootCode]"
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..1 @root='2.16.840.1.113883.10.20.22.4.48' (CONF:10485).",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..1")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });

            sectionCount++;
            pattern      = new Pattern();
            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            rule             = new Rule();
            contextBuilder   = new ContextBuilder(doc.ChildElements[2], "cda");
            rule.Context     = contextBuilder.GetFullyQualifiedContextString();
            assertionBuilder = new AssertionLineBuilder(doc.ChildElements[2], templateIdentifierXpath, templateVersionIdentifierXpath);  //"1..* id"
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..* id (CONF:8654)",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..*")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });

            sectionCount++;
            pattern      = new Pattern();
            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            rule             = new Rule();
            contextBuilder   = new ContextBuilder(doc.ChildElements[3], "cda");
            rule.Context     = contextBuilder.GetFullyQualifiedContextString();
            assertionBuilder = new AssertionLineBuilder(doc.ChildElements[3], templateIdentifierXpath, templateVersionIdentifierXpath);  //"1..1 code @xsi:type='CE' valueset = 2.16.840.1.113883.1.11.20.2"
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..1 code with @xsi:type='CE', where the @code SHOULD be selected from ValueSet AdvanceDirectiveTypeCode 2.16.840.1.113883.1.11.20.2 STATIC 2006-10-17 (CONF:8651).",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..1")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });

            sectionCount++;
            pattern      = new Pattern();
            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            rule             = new Rule();
            contextBuilder   = new ContextBuilder(doc.ChildElements[3], "cda");
            rule.Context     = contextBuilder.GetFullyQualifiedContextString();
            assertionBuilder = new AssertionLineBuilder(doc.ChildElements[3], templateIdentifierXpath, templateVersionIdentifierXpath);  //"1..1 statusCode @code='completed' valueset = 2.16.840.1.113883.1.11.20.2"
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "SHALL contain 1..1 code with @xsi:type='CE', where the @code SHOULD be selected from ValueSet AdvanceDirectiveTypeCode 2.16.840.1.113883.1.11.20.2 STATIC 2006-10-17 (CONF:8651).",
                Test             = assertionBuilder.WithCardinality(CardinalityParser.Parse("1..1")).WithinContext(contextBuilder.GetRelativeContextString()).ConformsTo(Conformance.SHALL).ToString()
            });

            sectionCount++;
            pattern      = new Pattern();
            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            rule           = new Rule();
            contextBuilder = new ContextBuilder(doc.ChildElements[1].Attributes[0], "cda");
            rule.Context   = contextBuilder.GetFullyQualifiedContextString();
            var childtemplateIdElementAssertionBuilder = new AssertionLineBuilder(templateIdElement.Attributes[0], templateIdentifierXpath, templateVersionIdentifierXpath)  //templateId/@root
                                                         .WithCardinality(CardinalityParser.Parse("1..1"))
                                                         .ConformsTo(Conformance.SHALL)
                                                         .WithinContext("cda:");
            var childParticipantElementAssertionBuilder = new AssertionLineBuilder(participantRoleElement, templateIdentifierXpath, templateVersionIdentifierXpath)
                                                          .WithCardinality(CardinalityParser.Parse("1..*"))
                                                          .ConformsTo(Conformance.SHALL)
                                                          .WithinContext("cda:");
            var childTimeElementAssertionBuilder = new AssertionLineBuilder(timeElement, templateIdentifierXpath, templateVersionIdentifierXpath)
                                                   .WithCardinality(CardinalityParser.Parse("0..1"))
                                                   .ConformsTo(Conformance.SHOULD)
                                                   .WithinContext("cda:");

            assertionBuilder = new AssertionLineBuilder(participantElement, templateIdentifierXpath, templateVersionIdentifierXpath);  //participant
            rule.Assertions.Add(new Assertion()
            {
                AssertionMessage = "should contain 1..* participant (CONF:8662), participant should contain 0..1 time (CONF:8665), the data type of Observation/participant/time in a verification SHALL be TS (time stamp) (CONF:8666), participant shall contain 1..1 participantRole (CONF:8825), participant shall contain 1..1 @typeCode=VRF 'Verifier' (CodeSystem: 2.16.840.1.113883.5.90) (CONF:8663), participant shall contain 1..1 templateId (CONF:8664), templateId shall contain 1..1 @root=2.16.840.1.113883.10.20.1.58 (CONF:10486)",
                Test             = assertionBuilder
                                   .WithCardinality(CardinalityParser.Parse("1..*"))
                                   .WithinContext("cda:")
                                   .ConformsTo(Conformance.SHALL)
                                   .WithChildElementBuilder(childTimeElementAssertionBuilder)
                                   .WithChildElementBuilder(childParticipantElementAssertionBuilder)
                                   .WithChildElementBuilder(childtemplateIdElementAssertionBuilder)
                                   .ToString()
            });

            sectionCount++;
            pattern      = new Pattern();
            pattern.ID   = sectionCount.ToString();
            pattern.Name = string.Format("pattern-{0}-errors", pattern.ID);
            pattern.Rules.Add(rule);
            phase.ActivePatterns.Add(pattern);

            var    builder         = new SchematronDocumentSerializer();
            string serializedModel = builder.SerializeDocument(document);

            Assert.IsFalse(string.IsNullOrEmpty(serializedModel), "No string returned from serialize document");

            string[] lModelLines = serializedModel.Split('\n');
            Assert.IsNotNull(lModelLines, "The generated string was not split on lines");
            Assert.IsTrue(lModelLines.Length > 1, "The generated string was not split on lines");
        }