예제 #1
0
        private void CreatePageClasses(string pageName, string pagesPath, string initialStateRequestsPath)
        {
            var sessionDictionary         = this.BuildSessionDictionary(pageName);
            var pageFilePath              = Path.Combine(pagesPath, $"{pageName}Page.cs");
            var viewModelFilePath         = Path.Combine(initialStateRequestsPath, $"{pageName}ViewModel.cs");
            var initialStateQueryFilePath = Path.Combine(initialStateRequestsPath, $"{pageName}InitialStateQuery.cs");

            if (!File.Exists(pageFilePath) &&
                !File.Exists(viewModelFilePath) &&
                !File.Exists(initialStateQueryFilePath))
            {
                if (!Directory.Exists(pagesPath))
                {
                    Directory.CreateDirectory(pagesPath);
                }

                File.WriteAllText(pageFilePath, TemplateRenderer.RenderTemplate(typeof(PageTemplate), sessionDictionary));

                if (!Directory.Exists(initialStateRequestsPath))
                {
                    Directory.CreateDirectory(initialStateRequestsPath);
                }

                File.WriteAllText(viewModelFilePath, TemplateRenderer.RenderTemplate(typeof(ViewModelTemplate), sessionDictionary));
                File.WriteAllText(initialStateQueryFilePath, TemplateRenderer.RenderTemplate(typeof(InitialStateQueryTemplate), sessionDictionary));

                Console.WriteLine(Messages.PageSuccessfullyCreated);
            }
            else
            {
                Console.WriteLine(Messages.FileExistMessage);
            }
        }
예제 #2
0
        public HtmlTagPlugin(TemplateRenderer renderer)
            : base(renderer)
        {
            Priority = TemplatePriority.Low;
            string tagNamePattern = "(?<tag>[a-zA-Z][a-zA-Z0-9_]*)";
            string attributes     = "(\\((?<attr>[a-zA-Z0-9_\\-]+([ ]?=[ ]?(\".*?\")))*[ ]*(,[ ]*(?<attr>[a-zA-Z0-9_\\-]+([ ]?=[ ]?(\".*?\")))*[ ]*)*\\))";
            string idPattern      = "(#(?<id>[a-zA-Z_][a-zA-Z_0-9]*))";
            string classPattern   = "(\\.(?<class>[a-zA-Z_][a-zA-Z_0-9]*))";
            string textPattern    = "( (?<text>[^\\(]*.*)|$)";
            string optional       = "?";

            base.RegularExpressionPatterns.Add("^" + tagNamePattern + idPattern + optional + classPattern + optional + textPattern + "$");
            base.RegularExpressionPatterns.Add("^" + tagNamePattern + classPattern + optional + idPattern + optional + textPattern + "$");
            base.RegularExpressionPatterns.Add("^" + tagNamePattern + idPattern + optional + classPattern + optional + attributes + textPattern + "$");
            base.RegularExpressionPatterns.Add("^" + tagNamePattern + classPattern + optional + idPattern + optional + attributes + textPattern + "$");
            base.RegularExpressionPatterns.Add("^" + tagNamePattern + classPattern + optional + idPattern + optional + attributes + optional + "\\.[w]*$");
            base.RegularExpressionPatterns.Add("^" + tagNamePattern + idPattern + optional + classPattern + optional + attributes + optional + "\\.[w]*$");
            base.RegularExpressionPatterns.Add("^" + idPattern + classPattern + optional + attributes + optional + textPattern + optional + "$");
            base.RegularExpressionPatterns.Add("^" + classPattern + idPattern + optional + attributes + optional + textPattern + optional + "$");
            base.RegularExpressionPatterns.Add("^" + idPattern + classPattern + optional + attributes + optional + textPattern + optional + "\\.[w]*$");
            base.RegularExpressionPatterns.Add("^" + classPattern + idPattern + optional + attributes + optional + textPattern + optional + "\\.[w]*$");
            nonEmptyTag.Add("script");
            nonEmptyTag.Add("style");
            nonEmptyTag.Add("title");
            nonEmptyTag.Add("textarea");
            textBlockTags.Add("script");
            textBlockTags.Add("style");
        }
예제 #3
0
        // A variant of TemplateRenderer.GetViewNames(). Main change relates to bool? handling.
        private static IEnumerable <string> GetInputTypeHints(ModelExplorer modelExplorer)
        {
            var inputTypeHints = new string[]
            {
                modelExplorer.Metadata.TemplateHint,
                modelExplorer.Metadata.DataTypeName,
            };

            foreach (string inputTypeHint in inputTypeHints.Where(s => !string.IsNullOrEmpty(s)))
            {
                yield return(inputTypeHint);
            }

            // In most cases, we don't want to search for Nullable<T>. We want to search for T, which should handle
            // both T and Nullable<T>. However we special-case bool? to avoid turning an <input/> into a <select/>.
            var fieldType = modelExplorer.ModelType;

            if (typeof(bool?) != fieldType)
            {
                fieldType = modelExplorer.Metadata.UnderlyingOrModelType;
            }

            foreach (string typeName in TemplateRenderer.GetTypeNames(modelExplorer.Metadata, fieldType))
            {
                yield return(typeName);
            }
        }
예제 #4
0
        protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody)
        {
            testFactCodeLines = new StringBuilder();
            var canonicalDataCase = testMethodBody.CanonicalDataCase;
            var input             = canonicalDataCase.Properties["input"] as System.Collections.Generic.Dictionary <string, object>;
            var constructorData   = input["treeData"] as string[];

            if (constructorData.Length == 1)
            {
                addCodeLine($"var tree = new BinarySearchTree({constructorData[0]});");
            }
            else
            {
                string constructorDataString = string.Join(", ", constructorData);
                addCodeLine($"var tree = new BinarySearchTree(new[] {{ {constructorDataString} }});");
            }

            var expected = canonicalDataCase.Properties["expected"] as System.Collections.Generic.Dictionary <string, object>;

            if (expected != null)
            {
                var tree = new ExpectedDataBinaryTree(expected as System.Collections.Generic.Dictionary <string, object>);
                foreach (var assert in tree.TestAsserts())
                {
                    addCodeLine(assert);
                }
            }
            else
            {
                string expectedArrayString = string.Join(", ", canonicalDataCase.Properties["expected"] as string[]);
                addCodeLine($"Assert.Equal(new[] {{ {expectedArrayString} }}, tree.AsEnumerable());");
            }

            return(TemplateRenderer.RenderInline(testFactCodeLines.ToString(), testMethodBody.AssertTemplateParameters));
        }
        public void Can_Render_Html_Template()
        {
            var renderer = new TemplateRenderer(new ReportModel
            {
                Error = new Error
                {
                    Exception = new TestException()
                },
                App = new App
                {
                    Title        = "Error Report",
                    Name         = TestApp,
                    Version      = Version,
                    AssemblyRefs = new List <AssemblyRef>
                    {
                        new AssemblyRef
                        {
                            Name    = AssemblyName,
                            Version = AssemblyVersion
                        }
                    }
                }
            });

            var result = renderer.RenderPreset(TemplateFormat.Html);

            Assert.That(result, Does.Contain("<title> Error Report </title>"));
            Assert.That(result, Does.Contain("<td> Application: </td>"));
            Assert.That(result, Does.Contain(string.Format("<td> {0} </td>", TestApp)));
        }
예제 #6
0
        public virtual async Task SendPasswordResetLinkAsync(
            IdentityUser user,
            string resetToken,
            string appName,
            string returnUrl     = null,
            string returnUrlHash = null)
        {
            Debug.Assert(CurrentTenant.Id == user.TenantId, "This method can only work for current tenant!");

            var url = await AppUrlProvider.GetResetPasswordUrlAsync(appName);

            var link = $"{url}?userId={user.Id}&tenantId={user.TenantId}&resetToken={UrlEncoder.Default.Encode(resetToken)}";

            if (!returnUrl.IsNullOrEmpty())
            {
                link += "&returnUrl=" + NormalizeReturnUrl(returnUrl);
            }

            if (!returnUrlHash.IsNullOrEmpty())
            {
                link += "&returnUrlHash=" + returnUrlHash;
            }

            var emailContent = await TemplateRenderer.RenderAsync(
                AccountEmailTemplates.PasswordResetLink,
                new { link = link }
                );

            await EmailSender.SendAsync(
                user.Email,
                StringLocalizer["PasswordReset"],
                emailContent
                );
        }
        //TODO: this method is doing way too much - Pawel
        public void GenerateFullReport(string codeMetricsDataFile, string reportOutputFolder)
        {
            reportOutputFolder = Path.GetFullPath(reportOutputFolder);
            codeMetricsDataFile = Path.GetFullPath(codeMetricsDataFile);

            CopyTemplatesToTheOutputFolder(reportOutputFolder);

            var parser = new CodeMetricsParser();
            var data = parser.Parse(GetContent(codeMetricsDataFile));

            var templateFinder = new TemplateFinder(reportOutputFolder);
            var summaryTemplate = templateFinder.FindTemplateFor("Summary");

            var summaryTemplateContent = GetContent(summaryTemplate.FullPath);
            var renderer = new TemplateRenderer();
            var summaryView = renderer.Render(summaryTemplateContent, data);
            SaveContent(reportOutputFolder, summaryTemplate.Name + summaryTemplate.Extension, summaryView);

            var moduleTemplate = templateFinder.FindTemplateFor("Module");

            foreach (var module in data.Targets.SelectMany(t => t.Modules))
            {
                var moduleTemplateContent = GetContent(moduleTemplate.FullPath);
                var moduleView = renderer.Render(moduleTemplateContent, module);
                SaveContent(reportOutputFolder, module.Name + moduleTemplate.Extension, moduleView);
            }

            DeleteAllTemplateFiles(reportOutputFolder);
        }
예제 #8
0
        public override byte[] GenerateReport(ReportCardsInputModel settings)
        {
            Trace.Assert(ServiceLocator.Context.SchoolLocalId.HasValue);
            var inowReportCardTask = Task.Run(() => GetInowReportData(settings));

            var logo = ServiceLocator.ReportService.GetLogoBySchoolId(ServiceLocator.Context.SchoolLocalId.Value)
                       ?? ServiceLocator.ReportService.GetDistrictLogo();
            var            template = ServiceLocator.ServiceLocatorMaster.CustomReportTemplateService.GetById(settings.CustomReportTemplateId);
            var            templateRenderer = new TemplateRenderer(settings.DefaultDataPath);
            var            listOfReportCards = BuildReportCardsData(inowReportCardTask.Result, logo?.LogoAddress, settings);
            IList <byte[]> listOfpdf = new List <byte[]>();
            string         headerTpl = null, footerTpl = null;

            foreach (var data in listOfReportCards)
            {
                var bodyTpl = templateRenderer.Render(template.Layout, data);
                if (template.Header != null)
                {
                    headerTpl = templateRenderer.Render(template.Header.Layout, data);
                }
                if (template.Footer != null)
                {
                    footerTpl = templateRenderer.Render(template.Footer.Layout, data);
                }
                var report = DocumentRenderer.RenderToPdf(settings.DefaultDataPath, settings.ContentUrl, bodyTpl, template.Style, headerTpl,
                                                          template.Header?.Style, footerTpl, template.Footer?.Style);
                listOfpdf.Add(report);
            }
            return(DocumentRenderer.MergePdfDocuments(listOfpdf));
        }
        public virtual async Task SendResetPasswordLink(IdentityUser user, string resetToken, string appName,
                                                        string?returnUrl, string?returnUrlHash, CancellationToken ct)
        {
            Debug.Assert(CurrentTenant.Id == user.TenantId, "This method can only work for current tenant!");

            var url = await GetResetPasswordUrlAsync(AppUrlProvider, appName);

            var link = $"{url}?userId={user.Id}&tenantId={user.TenantId}&resetToken={UrlEncoder.Default.Encode(resetToken)}";

            if (!returnUrl.IsNullOrEmpty())
            {
                link += "&returnUrl=" + NormalizeReturnUrl(returnUrl);
            }

            if (!returnUrlHash.IsNullOrEmpty())
            {
                link += "&returnUrlHash=" + returnUrlHash;
            }

            var emailContent = await TemplateRenderer.RenderAsync(EmailingTemplates.ResetPasswordLink,
                                                                  model : new ResetPasswordEmailVm
            {
                Username           = user.Name,
                ConfirmActionTitle = StringLocalizer["ResetPassword:ConfirmAction"],
                ConfirmActionUrl   = link
            },
                                                                  globalContext : new EmailLayoutVm(StringLocalizer["ResetPassword:Title"]));

            await EmailSender.SendAsync(user.Email, StringLocalizer["ResetPassword:Title"], emailContent);
        }
예제 #10
0
        protected override string RenderTestMethodBodyAct(TestMethodBody testMethodBody)
        {
            var template =
                @"DoRoll(previousRolls, sut);
";

            if (testMethodBody.CanonicalDataCase.ExceptionThrown != null)
            {
                return(template);
            }

            if (testMethodBody.CanonicalDataCase.Input.ContainsKey("roll"))
            {
                template +=
                    @"sut.Roll({{RolVal}});
var actual = sut.Score();
";
                var templateParameters = new
                {
                    RolVal = testMethodBody.CanonicalDataCase.Input["roll"]
                };
                return(TemplateRenderer.RenderInline(template, templateParameters));
            }

            template += "var actual = sut.Score();";
            return(template);
        }
예제 #11
0
        public async Task Ensure_PrerenderCallbacks_Are_Invoked()
        {
            //Assign
            var page = TemplatePageTest.CreatePage(t => t.Write("test"));

            bool triggered1 = false, triggered2 = false;
            var  callbacks = new List <Action <ITemplatePage> >
            {
                t => triggered1 = true,
                t => triggered2 = true
            };

            var options = new RazorLightOptions {
                PreRenderCallbacks = callbacks
            };
            var engineMock = new Mock <IEngineHandler>();

            engineMock.SetupGet(e => e.Options).Returns(options);

            //Act
            var templateRenderer = new TemplateRenderer(engineMock.Object, HtmlEncoder.Default, new MemoryPoolViewBufferScope());
            await templateRenderer.RenderAsync(page);

            //Assert
            Assert.True(triggered1);
            Assert.True(triggered2);
        }
예제 #12
0
        public void Render_TemplateWithForeach_RenderIEnumerableOfAddresses()
        {
            //for this potentially can extract whole section and then render it and re-insert
            var message = new ComplexModel
            {
                SomeText         = "Bob",
                BunchOfAddresses = new List <Address>()
                {
                    new Address {
                        StreetNumber = 5, StreetName = "Main"
                    },
                    new Address {
                        StreetNumber = 10, StreetName = "Main"
                    }
                }
            };

            string templateText = @"{{SomeText}} <<foreach:BunchOfAddresses>>{{StreetNumber}} {{StreetName}} <</foreach:BunchOfAddresses>>";
            var    template     = new Template <ComplexModel>(templateText);
            var    content      = new TemplateRenderer <ComplexModel>(template);
            var    text         = content.Render(message);

            Assert.Contains("5 Main", text);
            Assert.Contains("10 Main", text);
            Assert.Contains("Bob", text);
        }
예제 #13
0
        static TemplateRenderer LoadFile(string filename, out Type templateType)
        {
            var fileInfo = new FileInfo(filename);

            // Use the absolute file path to make sure files are only cached once even if different relative paths are used
            var normalizedFilename = fileInfo.FullName;

            if (TemplateRendererFileCache.ContainsKey(normalizedFilename))
            {
                templateType = TemplateTypeFileCache[normalizedFilename];
                return(TemplateRendererFileCache[normalizedFilename]);
            }
            else
            {
                if (!File.Exists(normalizedFilename))
                {
                    throw new System.IO.FileNotFoundException(filename);
                }

                string           templateText = File.ReadAllText(normalizedFilename);
                Type             type;
                TemplateRenderer templateRenderer = CompileTemplateString(templateText, out type);
                TemplateRendererFileCache[normalizedFilename] = templateRenderer;
                TemplateTypeFileCache[normalizedFilename]     = type;
                templateType = type;
                return(templateRenderer);
            }
        }
예제 #14
0
        protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody)
        {
            var expected = testMethodBody.CanonicalDataCase.Expected as Dictionary <string, dynamic>;

            expected.TryGetValue("position", out dynamic position);
            expected.TryGetValue("direction", out dynamic direction);

            StringBuilder template = new StringBuilder();

            if (direction != null)
            {
                template.AppendLine("Assert.Equal({{Direction}}, sut.Direction);");
            }

            if (position != null)
            {
                template.AppendLine("Assert.Equal({{X}}, sut.Coordinate.X);");
                template.AppendLine("Assert.Equal({{Y}}, sut.Coordinate.Y);");
            }

            var templateParameters = new
            {
                Direction = !string.IsNullOrEmpty(direction) ? GetDirectionEnum(direction) : null,
                X         = position?["x"],
                Y         = position?["y"]
            };

            return(TemplateRenderer.RenderInline(template.ToString(), templateParameters));
        }
예제 #15
0
 /// <summary>
 /// Adds a new URL pattern with a regex pattern that responds to requests with a template.
 /// </summary>
 /// <param name="pattern">A string in .NET Regex Syntax, specifying the URL pattern.</param>
 /// <param name="template">The TemplateRenderer that is used to render the response.</param>
 /// <param name="contentType">The optional HTTP content-type. Default is "text/html".</param>
 public void AddUrlPattern(string pattern, TemplateRenderer template, string contentType = "text/html")
 {
     AddUrlPattern(pattern, (request) =>
     {
         return(new HttpResponse(template(null), contentType: contentType));
     });
 }
예제 #16
0
        private UnescapedValue ToMultiLineString(string[] input)
        {
            const string template = @"{% if input.size == 0 %}string.Empty{% else %}{% for item in {{input}} %}{% if forloop.length == 1 %}""{{item}}""{% break %}{% endif %}""{{item}}""{% if forloop.last == false %} + Environment.NewLine +{% endif %}
               {% endfor %}.Trim(){% endif %}";

            return(new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })));
        }
예제 #17
0
        private UnescapedValue ToDigitStringRepresentation(string[] input)
        {
            const string template = @" {% for item in {{input}} %}{% if forloop.first == true %}""{{item}}"" + ""\n"" +{% continue %}{% endif %}
             ""{{item}}""{% if forloop.last == false %} + ""\n"" +{% endif %}{% endfor %}";

            return(new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })));
        }
예제 #18
0
        private static async Task DoFile(DocumentContext context, RelativeFile file)
        {
            if (file.Source.Extension != "md")
            {
                return;
            }
            Console.Error.WriteLine($"Working on {file.Source.FullPath}");

            var text = await file.Read();

            var doc = MarkdownFactory.Parse(text);

            doc.ApplyD2LTweaks();
            var html = MarkdownFactory.RenderToString(doc, context);

            var renderer  = TemplateRenderer.CreateFromResource("Templates.page.html");
            var formatted = await renderer.RenderAsync(
                title : GetTitle(doc),
                content : html,
                editLink : file.EditSourceLink
                );

            await file.Write(formatted);

            CopyAssociatedFiles(doc, context, file.Source.Path);
        }
예제 #19
0
        /// <summary>
        /// 入力するデータの型のヒントリストを取得する
        /// 基本的に「InputTagHelper」の実装をそのまま利用している
        /// </summary>
        /// <returns>バインドしているデータ型のヒントリスト</returns>
        protected IEnumerable <string> GetInputValueTypeHints()
        {
            var modelExplorer = For.ModelExplorer;

            // テンプレートヒントが有ればそれをリストにして返す
            if (!string.IsNullOrEmpty(modelExplorer.Metadata.TemplateHint))
            {
                yield return(modelExplorer.Metadata.TemplateHint);
            }

            // データタイプ名が有ればそれをそれをリストにして返す
            if (!string.IsNullOrEmpty(modelExplorer.Metadata.DataTypeName))
            {
                yield return(modelExplorer.Metadata.DataTypeName);
            }

            // In most cases, we don't want to search for Nullable<T>. We want to search for T, which should handle
            // both T and Nullable<T>. However we special-case bool? to avoid turning an <input/> into a <select/>.
            var fieldType = modelExplorer.ModelType;

            if (typeof(bool?) != fieldType)
            {
                fieldType = modelExplorer.Metadata.UnderlyingOrModelType;
            }

            foreach (var typeName in TemplateRenderer.GetTypeNames(modelExplorer.Metadata, fieldType))
            {
                yield return(typeName);
            }
        }
예제 #20
0
 public HtmlTagPlugin(TemplateRenderer renderer)
     : base(renderer)
 {
     Priority = TemplatePriority.Low;
     string tagNamePattern = "(?<tag>[a-zA-Z][a-zA-Z0-9_]*)";
     string attributes = "(\\((?<attr>[a-zA-Z0-9_\\-]+([ ]?=[ ]?(\".*?\")))*[ ]*(,[ ]*(?<attr>[a-zA-Z0-9_\\-]+([ ]?=[ ]?(\".*?\")))*[ ]*)*\\))";
     string idPattern = "(#(?<id>[a-zA-Z_][a-zA-Z_0-9]*))";
     string classPattern = "(\\.(?<class>[a-zA-Z_][a-zA-Z_0-9]*))";
     string textPattern = "( (?<text>[^\\(]*.*)|$)";
     string optional = "?";
     base.RegularExpressionPatterns.Add("^" + tagNamePattern + idPattern + optional + classPattern + optional + textPattern + "$");
     base.RegularExpressionPatterns.Add("^" + tagNamePattern + classPattern + optional + idPattern + optional + textPattern + "$");
     base.RegularExpressionPatterns.Add("^" + tagNamePattern + idPattern + optional + classPattern + optional + attributes + textPattern + "$");
     base.RegularExpressionPatterns.Add("^" + tagNamePattern + classPattern + optional + idPattern + optional + attributes + textPattern + "$");
     base.RegularExpressionPatterns.Add("^" + tagNamePattern + classPattern + optional + idPattern + optional + attributes + optional + "\\.[w]*$");
     base.RegularExpressionPatterns.Add("^" + tagNamePattern + idPattern + optional + classPattern + optional + attributes + optional + "\\.[w]*$");
     base.RegularExpressionPatterns.Add("^" + idPattern + classPattern + optional + attributes + optional + textPattern + optional + "$");
     base.RegularExpressionPatterns.Add("^" + classPattern + idPattern + optional + attributes + optional + textPattern + optional + "$");
     base.RegularExpressionPatterns.Add("^" + idPattern + classPattern + optional + attributes + optional + textPattern + optional + "\\.[w]*$");
     base.RegularExpressionPatterns.Add("^" + classPattern + idPattern + optional + attributes + optional + textPattern + optional + "\\.[w]*$");
     nonEmptyTag.Add("script");
     nonEmptyTag.Add("style");
     nonEmptyTag.Add("title");
     nonEmptyTag.Add("textarea");
     textBlockTags.Add("script");
     textBlockTags.Add("style");
 }
예제 #21
0
        public void Render_FourMergeOptions2500TimesTwice_InUnderOneSecond()
        {
            int occurances = 2500;

            string templateText = "Hello {{FullName}} from {{Address.StreetNumber}} {{Address.StreetName}}! on {{JoinDate}}";
            var    template     = BuildTemplate(occurances, templateText);

            DateTime date    = DateTime.Parse("2014-08-30");
            var      message = new WelcomeMessage()
            {
                FullName = "Devon", JoinDate = date, Address = new Address {
                    StreetNumber = 5, StreetName = "Main"
                }
            };

            var content = new TemplateRenderer <WelcomeMessage>(template);

            var before = DateTime.Now.Ticks;

            var text1 = content.Render(message);
            var text2 = content.Render(message);

            var after       = DateTime.Now.Ticks;
            var elapsedSpan = new TimeSpan(after - before);

            Assert.True(elapsedSpan.TotalSeconds < 1);
        }
예제 #22
0
        protected override async Task SendErrorNotifierAsync(ExceptionSendNotifierContext context)
        {
            // 需不需要用 SettingProvider 来获取?
            var receivedUsers = EmailOptions.GetReceivedEmailOrDefault(context.Exception.GetType());

            if (!receivedUsers.IsNullOrWhiteSpace())
            {
                var emailTitle      = EmailOptions.DefaultTitle ?? L("SendEmailTitle");
                var templateContent = await TemplateRenderer
                                      .RenderAsync(ExceptionHandlingTemplates.SendEmail,
                                                   new
                {
                    title          = emailTitle,
                    header         = EmailOptions.DefaultContentHeader ?? L("SendEmailHeader"),
                    type           = context.Exception.GetType().FullName,
                    message        = context.Exception.Message,
                    loglevel       = context.LogLevel.ToString(),
                    triggertime    = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
                    sendstacktrace = EmailOptions.SendStackTrace,
                    stacktrace     = context.Exception.ToString(),
                    footer         = EmailOptions.DefaultContentFooter ?? "Copyright to LINGYUN © 2020"
                });

                await EmailSender.SendAsync(receivedUsers,
                                            emailTitle,
                                            templateContent);
            }
        }
예제 #23
0
 protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody)
 {
     if (testMethodBody.CanonicalDataCase.Properties["input"]["strings"] as string[] == null)
     {
         return(TemplateRenderer.RenderInline("Assert.Empty(Proverb.Recite(new string[] { }));", new { }));
     }
     return(base.RenderTestMethodBodyAssert(testMethodBody));
 }
        public string Report()
        {
            var renderer = new TemplateRenderer(this.ReportModel());

            return(_info.ReportCustomTemplate.IsEmpty()
                                ? renderer.RenderPreset(_info.ReportTemplateFormat)
                                : renderer.RenderCustom(_info.ReportCustomTemplate));
        }
        public void Renders_SimpleTemplate()
        {
            var result = TemplateRenderer.RenderTemplate("blah $var$ blah2", new TemplateConfiguration(new List <string>()),
                                                         new Dictionary <string, string> {
                { "var", "value1" }
            });

            Assert.Equal(result, "blah value1 blah2");
        }
        public void Renderer_Uses_MagicCharacter()
        {
            var result = TemplateRenderer.RenderTemplate("blah #var# blah2", new TemplateConfiguration(new List <string>(), magicCharacter: '#'),
                                                         new Dictionary <string, string> {
                { "var", "value1" }
            });

            Assert.Equal(result, "blah value1 blah2");
        }
 public static async Task RenderIncludedTemplateAsync <T>(ITemplatePage parentPage, BasePage <T> includedTemplatePage, T model)
 {
     using (var scope = new MemoryPoolViewBufferScope())
     {
         var renderer = new TemplateRenderer(Handler, HtmlEncoder.Default, scope);
         SetModelContext(includedTemplatePage, parentPage.PageContext.Writer, model, parentPage.PageContext.ViewBag);
         await renderer.RenderAsync(includedTemplatePage).ConfigureAwait(false);
     }
 }
예제 #28
0
        public void ListRenderTest()
        {
            var list1 = new List <string> {
                "item1", "item2", "item3"
            };
            var list2 = new List <string> {
                "thing one", "thing two", "thing three"
            };


            var templateBody =
                @"List Test

list1=[lst:item1,item2, item3 ]
list2=[lst:thing one, thing two, thing three]
";


            var validator = new TemplateValidator(new MockRandomTableService(), new MockTemplateService());

            var template = new Template
            {
                Id           = Guid.Empty,
                Name         = "List Test",
                Category     = "Test",
                Description  = "Description here",
                Enabled      = true,
                TemplateBody = templateBody
            };

            var result = validator.ValidateTemplate(template).Result;

            var outTemplate = result.Template;
            var errors      = result.ValidationErrors;

            Assert.AreEqual(0, errors.Count, $"Validation errors incorrect : {errors.Count}");
            Assert.AreEqual(2, outTemplate.Fields.Count, $"Fields incorrect : {outTemplate.Fields.Count}");
            Assert.AreEqual(0, outTemplate.TemplateVariables.Count,
                            $"Variable count incorrect : {outTemplate.TemplateVariables.Count}");

            var renderer = new TemplateRenderer(new MockRandomTableService(), new MockTemplateService());

            var render = renderer.RenderTemplateToMarkDown(outTemplate).Result;

            var regex1 = new Regex(@"^list1=([\d\w\s]+)[\r]", RegexOptions.Multiline);
            var regex2 = new Regex(@"^list2=([\d\w\s]+)[\r]", RegexOptions.Multiline);

            var match1 = regex1.Match(render);
            var match2 = regex2.Match(render);


            Assert.IsTrue(match1.Success, "list1 was not found");
            Assert.IsTrue(list1.Contains(match1.Groups[1].Value), "list1 not valid");
            Assert.IsTrue(match2.Success, "list2 was not found");
            Assert.IsTrue(list2.Contains(match2.Groups[1].Value), "list2 not valid");
        }
        public void Render_when_non_default_magic_char_replace_value()
        {
            var result = TemplateRenderer.RenderTemplate("blah #var# blah2",
                                                         new TemplateConfiguration(new List <string>(), magicCharacter: '#'),
                                                         new Dictionary <string, string> {
                { "var", "value1" }
            });

            Assert.Equal("blah value1 blah2", result);
        }
예제 #30
0
        private async Task <Attachment> BuildAttach()
        {
            if (_Attachment != null)
            {
                return(await TemplateRenderer.RenderAttachmentToAttachAsync(_Attachment)
                       .ConfigureAwait(false));
            }

            return(_Attachment);
        }
예제 #31
0
        private void CreateRequest(string requestName, string requestType, string requestPath)
        {
            var sessionDictionary = this.BuildSessionDictionary(requestName, requestType);
            var resultFilePath    = Path.Combine(requestPath, $"{requestName}Result.cs");

            if (File.Exists(resultFilePath))
            {
                Console.WriteLine(Messages.FileExistMessage);
                return;
            }

            if (!Directory.Exists(requestPath))
            {
                Directory.CreateDirectory(requestPath);
            }

            if (requestType == QueryRequestType)
            {
                var queryFilePath = Path.Combine(requestPath, $"{requestName}Query.cs");

                if (File.Exists(queryFilePath))
                {
                    Console.WriteLine(Messages.FileExistMessage);
                    return;
                }

                File.WriteAllText(queryFilePath, TemplateRenderer.RenderTemplate(typeof(QueryTemplate), sessionDictionary));
                File.WriteAllText(resultFilePath, TemplateRenderer.RenderTemplate(typeof(ResultTemplate), sessionDictionary));

                Console.WriteLine(Messages.QuerySuccessfullyCreated);
            }
            else if (requestType == CommandRequestType)
            {
                var requestFilePath          = Path.Combine(requestPath, $"{requestName}Request.cs");
                var commandFilePath          = Path.Combine(requestPath, $"{requestName}Command.cs");
                var commandValidatorFilePath = Path.Combine(requestPath, $"{requestName}CommandValidator.cs");

                if (File.Exists(requestFilePath) || File.Exists(commandFilePath) || File.Exists(commandValidatorFilePath))
                {
                    Console.WriteLine(Messages.FileExistMessage);
                    return;
                }

                File.WriteAllText(requestFilePath, TemplateRenderer.RenderTemplate(typeof(RequestTemplate), sessionDictionary));
                File.WriteAllText(commandFilePath, TemplateRenderer.RenderTemplate(typeof(CommandTemplate), sessionDictionary));
                File.WriteAllText(commandValidatorFilePath, TemplateRenderer.RenderTemplate(typeof(CommandValidatorTemplate), sessionDictionary));
                File.WriteAllText(resultFilePath, TemplateRenderer.RenderTemplate(typeof(ResultTemplate), sessionDictionary));

                Console.WriteLine(Messages.CommandSuccessfullyCreated);
            }
            else
            {
                Console.WriteLine(Messages.RequestCannotBeCreated);
            }
        }
예제 #32
0
        private static string RenderIsAllergicToAssert(TestMethodBody testMethodBody)
        {
            const string template =
                @"{%- for allergy in Allergies -%}
Assert.{% if allergy.result %}True{% else %}False{% endif %}(sut.IsAllergicTo(""{{ allergy.substance }}""));
{%- endfor -%}";

            var templateParameters = new { Allergies = testMethodBody.CanonicalDataCase.Expected };

            return(TemplateRenderer.RenderInline(template, templateParameters));
        }
예제 #33
0
        public MixinPlugin(TemplateRenderer renderer)
            : base(renderer)
        {
            // string oneOrZeroAttribute = "\\((" + attributeName + optional + ")\\)";
            string lp = "\\(";
            string rp = "\\)";
            string emptyAttributes = "(" + lp + "[ ]*" + rp + ")";
            string oneOrMoreAttributes = "(" + lp + attributeName + "(," + attributeName + ")*" + rp + ")";
            string parameters = "(" + lp + "(?<param>[^,]*)(,(?<param>[^,]*))*" + rp + ")";
            RegularExpressionPatterns.Add("^mixin[ ]+" + namePattern + "[ ]*$");
            RegularExpressionPatterns.Add("^mixin[ ]+" + namePattern + emptyAttributes + "$");
            RegularExpressionPatterns.Add("^mixin[ ]+" + namePattern + oneOrMoreAttributes + "$");

            RegularExpressionPatterns.Add("^\\+" + namePattern + emptyAttributes + "$");
            RegularExpressionPatterns.Add("^\\+" + namePattern + parameters + "$");
        }
예제 #34
0
        public void Render_FullName10000Times_InUnderHalfSecond()
        {
            int occurances = 10000;

            string templateText = "{{FullName}}";
            var template = BuildTemplate(occurances, templateText);
            var message = new WelcomeMessage() { FullName = "Devon" };

            var content = new TemplateRenderer<WelcomeMessage>(template);
            var before = DateTime.Now.Ticks;

            var text = content.Render(message);

            var after = DateTime.Now.Ticks;
            var elapsedSpan = new TimeSpan(after - before);

            Assert.True(elapsedSpan.TotalSeconds < 0.5);
        }
예제 #35
0
        public void Render_FourMergeOptions2500Times_InUnderHalfSecond()
        {
            int occurances = 2500;

            string templateText = "Hello {{FullName}} from {{Address.StreetNumber}} {{Address.StreetName}}! on {{JoinDate}}";
            var template = BuildTemplate(occurances, templateText);

            DateTime date = DateTime.Parse("2014-08-30");
            var message = new WelcomeMessage(){ FullName = "Devon", JoinDate = date, Address = new Address{ StreetNumber = 5, StreetName = "Main"} };

            var content = new TemplateRenderer<WelcomeMessage>(template);

            var before = DateTime.Now.Ticks;

            var text = content.Render(message);

            var after = DateTime.Now.Ticks;
            var elapsedSpan = new TimeSpan(after - before);

            Assert.True(elapsedSpan.TotalSeconds < 0.5);
        }
예제 #36
0
 public DoctypePlugin(TemplateRenderer renderer)
     : base(renderer)
 {
     RegularExpressionPatterns.Add("^(doctype[ ]+)(?<statment>.*)[ ]*$");
 }
예제 #37
0
 public TemplatePlugin(TemplateRenderer renderer)
 {
     this.Priority = TemplatePriority.Medium;
     this.renderer=renderer;
 }
예제 #38
0
        public void Render_WithX_ReturnsString()
        {
            var message = new WelcomeMessage(){ FullName = "Devon" };
            var template = new Template<WelcomeMessage>("Hello {{FullName}}!");
            var content = new TemplateRenderer<WelcomeMessage>(template);
            var text = content.Render(message);

            Assert.False(string.IsNullOrEmpty(text));
        }
예제 #39
0
 public TextPlugin(TemplateRenderer renderer)
     : base(renderer)
 {
     Priority = TemplatePriority.Low;
     RegularExpressionPatterns.Add("^(\\|)(?<text>.*)$");
 }
예제 #40
0
 public BlockPlugin(TemplateRenderer renderer)
     : base(renderer)
 {
     RegularExpressionPatterns.Add("^(block[ ]+)(?<statment>.*)[ ]*$");
 }
예제 #41
0
        public void Render_TemplateWithIEnumerable_RenderIEnumerableOfString()
        {
            var message = new ComplexModel
            {
                BunchOfStrings = new List<string>() { "ONE", "TWO"}
            };

            var template = new Template<ComplexModel>("{{BunchOfStrings}}");
            var content = new TemplateRenderer<ComplexModel>(template);
            var text = content.Render(message);

            Assert.Contains("ONE, TWO", text);
        }
예제 #42
0
        public IHtmlContent Build()
        {
            if (_metadata.ConvertEmptyStringToNull && string.Empty.Equals(_model))
            {
                _model = null;
            }

            var formattedModelValue = _model;
            if (_model == null && _readOnly)
            {
                formattedModelValue = _metadata.NullDisplayText;
            }

            var formatString = _readOnly ? _metadata.DisplayFormatString : _metadata.EditFormatString;

            if (_model != null && !string.IsNullOrEmpty(formatString))
            {
                formattedModelValue = string.Format(CultureInfo.CurrentCulture, formatString, _model);
            }

            // Normally this shouldn't happen, unless someone writes their own custom Object templates which
            // don't check to make sure that the object hasn't already been displayed
            if (_viewData.TemplateInfo.Visited(_modelExplorer))
            {
                return HtmlString.Empty;
            }

            // We need to copy the ModelExplorer to copy the model metadata. Otherwise we might
            // lose track of the model type/property. Passing null here explicitly, because
            // this might be a typed VDD, and the model value might not be compatible.
            // Create VDD of type object so it retains the correct metadata when the model type is not known.
            var viewData = new ViewDataDictionary<object>(_viewData, model: null);

            // We're setting ModelExplorer in order to preserve the model metadata of the original
            // _viewData even though _model may be null.
            viewData.ModelExplorer = _modelExplorer.GetExplorerForModel(_model);

            viewData.TemplateInfo.FormattedModelValue = formattedModelValue;
            viewData.TemplateInfo.HtmlFieldPrefix = _viewData.TemplateInfo.GetFullHtmlFieldName(_htmlFieldName);

            if (_additionalViewData != null)
            {
                foreach (var kvp in HtmlHelper.ObjectToDictionary(_additionalViewData))
                {
                    viewData[kvp.Key] = kvp.Value;
                }
            }

            var visitedObjectsKey = _model ?? _modelExplorer.ModelType;
            viewData.TemplateInfo.AddVisited(visitedObjectsKey);

            var templateRenderer = new TemplateRenderer(
                _viewEngine,
                _bufferScope,
                _viewContext,
                viewData,
                _templateName,
                _readOnly);

            return templateRenderer.Render();
        }
예제 #43
0
 public ExtendsPlugin(TemplateRenderer renderer)
     : base(renderer)
 {
     RegularExpressionPatterns.Add("^(extends[ ]+)(?<statment>.*)[ ]*$");
 }
예제 #44
0
        public void Render_WithTemplateForNullable_ReturnsValueIs5()
        {
            var message = new ComplexModel(){ NullIntProp = 5 };
            var template = new Template<ComplexModel>("Value is {{NullIntProp}}");
            var content = new TemplateRenderer<ComplexModel>(template);
            var text = content.Render(message);

            Assert.Equal("Value is 5", text);
        }
예제 #45
0
        public void Render_TemplateWithForeach_RenderIEnumerableOfAddresses()
        {
            //for this potentially can extract whole section and then render it and re-insert
            var message = new ComplexModel
            {
                SomeText = "Bob",
                BunchOfAddresses = new List<Address>() {
                new Address{ StreetNumber = 5, StreetName = "Main"},
                new Address{ StreetNumber = 10, StreetName = "Main"}
                }
            };

            string templateText = @"{{SomeText}} <<foreach:BunchOfAddresses>>{{StreetNumber}} {{StreetName}} <</foreach:BunchOfAddresses>>";
            var template = new Template<ComplexModel>(templateText);
            var content = new TemplateRenderer<ComplexModel>(template);
            var text = content.Render(message);

            Assert.Contains("5 Main", text);
            Assert.Contains("10 Main", text);
            Assert.Contains("Bob", text);
        }
예제 #46
0
 public ForeachPlugin(TemplateRenderer renderer)
     : base(renderer)
 {
     RegularExpressionPatterns.Add("^(each[ ]+)(?<statment>.*)$");
 }
예제 #47
0
        public void Render_WithNullProperty_ReturnsEmptyString()
        {
            var message = new WelcomeMessage(){ FullName = null };
            var template = new Template<WelcomeMessage>("Hello {{FullName}}!");
            var content = new TemplateRenderer<WelcomeMessage>(template);
            var text = content.Render(message);

            Assert.Contains("Hello !", text);
        }
예제 #48
0
        public void Render_WithHelloWorldTemplate_ReturnsHelloDevon()
        {
            var message = new WelcomeMessage(){ FullName = "Devon" };
            var template = new Template<WelcomeMessage>("Hello {{FullName}}!");
            var content = new TemplateRenderer<WelcomeMessage>(template);
            var text = content.Render(message);

            Assert.Equal("Hello Devon!", text);
        }
예제 #49
0
        public void Render_TemplateWithForeach_RenderIEnumerableOfString()
        {
            var message = new ComplexModel
            {
                BunchOfStrings = new List<string>() { "ONE", "TWO"}
            };

            string templateText = @"<<foreach:BunchOfStrings>>{{value}} <</foreach:BunchOfStrings>>";
            var template = new Template<ComplexModel>(templateText);
            var content = new TemplateRenderer<ComplexModel>(template);
            var text = content.Render(message);

            Assert.Contains("ONE", text);
            Assert.Contains("TWO", text);
        }
 public ConditionalStatmentPlugin(TemplateRenderer renderer)
     : base(renderer)
 {
     RegularExpressionPatterns.Add("^(if[ ]+)(?<condition>.*)$");
 }
예제 #51
0
 protected void initialze()
 {
     renderer = new TemplateRenderer(sourceCode, parameters);
 }
예제 #52
0
        public void Render_TemplateWithDate_TransformsNestedProperties()
        {
            string myFormat = "yyyy-MM-dd";
            DateTime date = DateTime.Parse("2014-08-30");
            var message = new WelcomeMessage(){ FullName = "Devon", JoinDate = date, Address = new Address{ StreetNumber = 5, StreetName = "Main"} };
            var template = new Template<WelcomeMessage>("Hello {{FullName}} from {{Address.StreetNumber}} {{Address.StreetName}}! on {{JoinDate}}");
            var content = new TemplateRenderer<WelcomeMessage>(template)
            {
                RenderSettings = new RenderSettings
                {
                    DateTimeFormat = myFormat
                }
            };
            var text = content.Render(message);

            Assert.Contains("Hello Devon from 5 Main! on ", text);
            Assert.Contains("on 2014-08-30", text);
        }
예제 #53
0
        public void Render_TemplateWithNavigationalProperties_TransformsNestedProperties()
        {
            var message = new WelcomeMessage(){ FullName = "Devon", Address = new Address{ StreetName = "Main"} };
            var template = new Template<WelcomeMessage>("Hello {{FullName}} from {{Address.StreetName}}!");
            var content = new TemplateRenderer<WelcomeMessage>(template);
            var text = content.Render(message);

            Assert.Contains("Main", text);
        }