Example #1
0
        public async Task Ensure_Content_Added_To_DynamicTemplates_When_RazorLightProject_Set_Explicitly_And_Options_Not_Set_Explicitly()
        {
            const string key     = "key";
            const string content = "content";

            var engine = new RazorLightEngineBuilder()
#if NETFRAMEWORK
                         .SetOperatingAssembly(typeof(Root).Assembly)
#endif
                         .UseNoProject()
                         .Build();

            var actual = await engine.CompileRenderStringAsync(key, content, new object(), new ExpandoObject());

            Assert.NotEmpty(engine.Options.DynamicTemplates);
            Assert.Contains(engine.Options.DynamicTemplates, t => t.Key == key && t.Value == content);
            Assert.Equal(typeof(NoRazorProject), (engine.Handler.Compiler as RazorTemplateCompiler)?.ProjectType);
            Assert.Equal(content, actual);
        }
Example #2
0
        public void Respects_DisabledEncoding_On_CachedTemplates()
        {
            string templateKey = "Assets.Embedded.Empty.cshtml";

            var engine = new RazorLightEngineBuilder()
                         .DisableEncoding()
                         .UseMemoryCachingProvider()
                         .SetOperatingAssembly(typeof(Root).Assembly)
                         .UseEmbeddedResourcesProject(typeof(Root))

                         .Build();
            var testCompileToCache = engine.CompileTemplateAsync(templateKey).Result;

            Assert.True(testCompileToCache.DisableEncoding);

            var cachedCompile = engine.CompileTemplateAsync(templateKey).Result;

            Assert.True(cachedCompile.DisableEncoding);
        }
        public async Task Template_Shares_Model_With_Layout()
        {
            var engine = new RazorLightEngineBuilder()
                         .UseEmbeddedResourcesProject(typeof(Root).Assembly, "RazorLight.Tests.Assets.Embedded")
                         .Build();

            var model = new TestModel()
            {
                Value = "123"
            };

            string expected = $"Layout: {model.Value}_body: {model.Value}";

            string result = await engine.CompileRenderAsync("WithModelAndLayout", model);

            result = result.Replace(Environment.NewLine, "");

            Assert.Equal(expected, result);
        }
        public Task SendConfirmationEmailAsync(ApplicationUser user, string callback_url)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseMemoryCachingProvider()
                         .Build();


            string template = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "wwwroot", "Templates", "Emails", "Account", "ConfirmationEmail.cshtml"));
            EmailConfirmationViewModel model = new EmailConfirmationViewModel()
            {
                FirstName       = user.FirstName,
                CallbackLink    = callback_url,
                UnsubscribeLink = "www.google.com"
            };

            string result = engine.CompileRenderAsync("Confirmation", template, model).Result;

            return(Execute(Options.SendGridKey, "Confirm Your Account", result, user.Email));
        }
Example #5
0
        public async Task Templates_Supports_Local_Functions_Using_Helper()
        {
            // See https://github.com/aspnet/Razor/issues/715

            var engine = new RazorLightEngineBuilder()
#if NETFRAMEWORK
                         .SetOperatingAssembly(typeof(Root).Assembly)
#endif
                         .UseEmbeddedResourcesProject(typeof(Root).Assembly, "RazorLight.Tests.Assets.Embedded")
                         .Build();

            string expected = "<strong>LocalFunctionUsingHelper</strong>";

            string result = await engine.CompileRenderAsync("LocalFunctionUsingHelper", (object)null);

            result = result.Replace(Environment.NewLine, "");

            Assert.Equal(expected, result);
        }
Example #6
0
        private static string GenerateHtml(CharacterSheet sheet, string template, Assembly operatingAssembly = null)
        {
            try
            {
                var engine = new RazorLightEngineBuilder()
                             .SetOperatingAssembly(Assembly.GetCallingAssembly())
                             .UseCachingProvider(new MemoryCachingProvider())
                             .Build();

                var result = engine.CompileRenderAsync("CharacterSheet", template, new CharacterSheetViewModel(sheet))
                             .Result;

                return(result);
            }
            catch (AggregateException e)
            {
                throw new InvalidOperationException("Unable to create PrintView.", e);
            }
        }
Example #7
0
        public RazorRenderer(Assembly operatingAssembly, IHttpContextAccessor httpContextAccessor, RazorRendererOptions options = null)
        {
            options ??= new RazorRendererOptions();
            Options = options;

            var rootDir = GetApplicationRoot();

            var engine = new RazorLightEngineBuilder()
                         .SetOperatingAssembly(operatingAssembly)
                         .UseFileSystemProject(Path.Combine(rootDir, options.PageRoot))
                         .UseMemoryCachingProvider()
                         .Build();

            Engine              = engine;
            ImageRoot           = Path.Combine(rootDir, options.ImageRoot);
            StyleRoot           = Path.Combine(rootDir, options.StyleRoot);
            ScriptRoot          = Path.Combine(rootDir, options.ScriptRoot);
            HttpContextAccessor = httpContextAccessor;
        }
Example #8
0
        public async Task ProcessAsync()
        {
            Require.NonNullNonEmpty(SonarUrl, "SonarUrl");
            Require.NonNullNonEmpty(Token, "Token");
            Require.NonNullNonEmpty(SmtpServer, "SmtpServer");
            Require.NonNullNonEmpty(SmtpSenderAddress, "SmtpServerAddress");
            if (SmtpUsername != null && SmtpPassword != null)
            {
                Require.NonNullNonEmpty(SmtpUsername, "SmtpUsername");
                Require.NonNullNonEmpty(SmtpPassword, "SmtpPassword");
            }

            Logger.Info($"Sonar URL: {SonarUrl}");
            Logger.Info($"Max Issue Date: {MaxCreationDate}");
            Logger.Info($"Project filter: {ProjectFilter.ToPrettyString()}, ignored projects: {IgnoredProjects.ToPrettyString()}");
            Logger.Info($"User filter: {UserFilter.ToPrettyString()}, ignored users: {IgnoredUsers.ToPrettyString()}");
            Logger.Info($"SMTP server: {SmtpServer} ({(SmtpSslEnabled ? "SSL enabled" : "SSL disabled")})");
            Logger.Info($"SMTP sender address: {SmtpSenderAddress}");
            Logger.Info($"SMTP authentication: {(SmtpUsername != null && SmtpPassword != null ? $"Yes (username: {SmtpUsername})" : "None")}");
            Logger.Info($"Recipient filter: {RecipientFilter.ToPrettyString()}, ignored recipients: {IgnoredRecipients.ToPrettyString()}");
            Logger.Info($"Summary recipients: {SummaryRecipients.ToPrettyString()}");

            SummaryViewModel summary = await GenerateSummary().OnAnyThread();

            Logger.Info($"Processing complete, {summary.NumberOfOverdueIssues} issues overdue, {summary.NumberOfUnassignedIssues} issues unassigned, {summary.Users.Count} users to notify, {summary.Projects.Count} projects to notify");

            RazorLightEngine razor = new RazorLightEngineBuilder()
                                     .UseEmbeddedResourcesProject(typeof(Startup)) // exception without this (or another project type)
                                     .UseMemoryCachingProvider()
                                     .Build();

            SmtpClient smtpClient = new SmtpClient(SmtpServer !);

            smtpClient.EnableSsl = SmtpSslEnabled;
            if (SmtpUsername != null && SmtpPassword != null)
            {
                smtpClient.Credentials = new NetworkCredential(SmtpUsername, SmtpPassword);
            }

            await NotifyUser(summary, razor, smtpClient).OnAnyThread();
            await NotifySummary(summary, razor, smtpClient).OnAnyThread();
        }
Example #9
0
        private async void OnExecute()
        {
            try
            {
                Console.WriteLine($"Building {Project}...");
                // make sure the project is built
                var buildProc = System.Diagnostics.Process.Start("dotnet", $"build {Project}");
                buildProc.WaitForExit();

                Console.WriteLine($"Loading class {ContextClass} from {Project}");
                var contextType = LoadContextClass();

                // We're calling ISchemaProvider schema = SchemaBuilder.FromObject<TContext>();
                // let's us do it with type safety
                Expression <Func <ISchemaProvider> > call = () => SchemaBuilder.FromObject <object>(true, true, null);
                var method = ((MethodCallExpression)call.Body).Method;
                method = method.GetGenericMethodDefinition().MakeGenericMethod(contextType);
                var schema = method.Invoke(null, new object[] { true }) as ISchemaProvider;

                Console.WriteLine($"Generating {Namespace}.{OutputClassName}, outputting to {OutputFilename}");

                // pass the schema to the template
                var engine = new RazorLightEngineBuilder()
                             .UseEmbeddedResourcesProject(typeof(Program))
                             .UseMemoryCachingProvider()
                             .Build();

                string result = await engine.CompileRenderAsync("template.cshtml", new
                {
                    Namespace       = Namespace,
                    OutputClassName = OutputClassName,
                    ContextClass    = ContextClass,
                    Schema          = schema
                });

                File.WriteAllText(OutputFilename, result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }
        }
Example #10
0
        public async Task Should_Render_IncludeAsync()
        {
            var path = DirectoryUtils.RootDirectory;

            var engine = new RazorLightEngineBuilder()
#if NETFRAMEWORK
                         .SetOperatingAssembly(typeof(Root).Assembly)
#endif
                         .UseFileSystemProject(Path.Combine(path, "Assets", "Files"))
                         .Build();

            var model = new TestViewModel
            {
                Name          = "RazorLight",
                NumberOfItems = 400
            };
            var renderedResult = await engine.CompileRenderAsync("template7.cshtml", model);

            await Verifier.Verify(renderedResult);
        }
        public async Task Ensure_Option_DisablEncoding_Renders_Models_Raw()
        {
            //Assing
            var engine = new RazorLightEngineBuilder()
                         .UseMemoryCachingProvider()
                         .UseFileSystemProject(DirectoryUtils.RootDirectory)
                         .DisableEncoding()
                         .Build();

            string key     = "key";
            string content = "@Model.Entity";

            var model = new { Entity = "<pre></pre>" };

            // act
            var result = await engine.CompileRenderStringAsync(key, content, model);

            // assert
            Assert.Contains("<pre></pre>", result);
        }
Example #12
0
        public Task Should_Fail_When_Required_Section_Is_Missing()
        {
            var path = DirectoryUtils.RootDirectory;

            var engine = new RazorLightEngineBuilder()
#if NETFRAMEWORK
                         .SetOperatingAssembly(typeof(Root).Assembly)
#endif
                         .UseFileSystemProject(Path.Combine(path, "Assets", "Files"))
                         .Build();

            var model = new TestViewModel
            {
                Name          = "RazorLight",
                NumberOfItems = 300
            };

            return(Verifier.ThrowsTask(() => engine.CompileRenderAsync("template6.cshtml", model))
                   .ModifySerialization(_ => _.IgnoreMember <Exception>(exception => exception.StackTrace)));
        }
Example #13
0
        public async Task SendEmailsWithTemplate(string title, Subscriber model, string template)
        {
            var path = Path.Combine(
                _env.WebRootPath, "Templates/");

            var engine = new RazorLightEngineBuilder()
                         .UseFilesystemProject(path)
                         .UseMemoryCachingProvider()
                         .Build();
            string body = "";

            if (model.Email != string.Empty)
            {
                // send to subscriber email with template

                body = await engine.CompileRenderAsync(template, model);

                Execute(Regex.Replace(model.Email, "%40", "@"), title, body).Wait();
            }
        }
Example #14
0
        public async Task OutputRedisHelperAsync(string filename)
        {
            var engine = new RazorLightEngineBuilder()
                         .DisableEncoding()
                         .UseFileSystemProject(Directory.GetCurrentDirectory())
                         .UseMemoryCachingProvider()
                         .Build();

            var model = new TemplateClass(methods.Select(_method => _method.ToMethod()).ToList());

            #region Build Interface
            var result = await engine.CompileRenderAsync("Template/Helper.cshtml", model);

            using (var writeStream = File.OpenWrite(filename))
            {
                using (var streamWrite = new StreamWriter(writeStream, Encoding.UTF8))
                    await streamWrite.WriteLineAsync(result);
            }
            #endregion
        }
Example #15
0
        public Task <Result <byte[]> > GenerateProductPdfReport(ProductReportModel model) =>
        Result <byte[]> .TryAsync(async() =>
        {
            Result <IList <ProductModel> > result = await GetProductListFromDB(model);
            if (!result.Success)
            {
                return(Result <byte[]> .Failed(Error.WithCode(ErrorCodes.ErrorInProductReport)));
            }
            var productModels = result.Data;

            //Initialize HTML to PDF converter
            HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter()
            {
                //Assign WebKit settings to HTML converter
                ConverterSettings = new WebKitConverterSettings
                {
                    //Set WebKit path
                    WebKitPath = $"{Directory.GetCurrentDirectory()}" +
                                 $"{Path.DirectorySeparatorChar}bin" +
                                 $"{Path.DirectorySeparatorChar}Debug" +
                                 $"{Path.DirectorySeparatorChar}netcoreapp3.1" +
                                 $"{Path.DirectorySeparatorChar}QtBinariesWindows"
                }
            };

            string templatesPath = $"{Directory.GetCurrentDirectory()}" +
                                   $"{Path.DirectorySeparatorChar}wwwroot" +
                                   $"{Path.DirectorySeparatorChar}Resources" +
                                   $"{Path.DirectorySeparatorChar}ReportTemplates";

            RazorLightEngine engine = new RazorLightEngineBuilder().UseFileSystemProject(templatesPath)
                                      .UseMemoryCachingProvider().Build();
            string resultt = await engine.CompileRenderAsync("ProductPdfReport.cshtml", productModels);

            var pdfDocument     = htmlToPdfConverter.Convert(resultt, $"www.google.com");
            MemoryStream stream = new MemoryStream();
            pdfDocument.Save(stream);

            _logger.Info("Product pdf report generated");
            return(Result <byte[]> .Successful(stream.ToArray()));
        });
Example #16
0
        public async Task UseRazorLightDirect()
        {
            //Test. Exist error for:
            //GetEntryAssembly returns null?
            var nulo = Assembly.GetEntryAssembly();


            var engine = new RazorLightEngineBuilder()
                         //.UseMemoryCachingProvider()
                         .Build();

            string    template = "Hello, @Model.Name. Welcome to RazorLight repository";
            ViewModel model    = new ViewModel()
            {
                Name = "John Doe"
            };

            string result = await engine.CompileRenderAsync("templateKey", template, model);

            TestContext.WriteLine(result);
        }
Example #17
0
        private async Task <string> Template(MutationProjectReportModel model)
        {
            var currentAssembly = Assembly.GetExecutingAssembly();
            var resourceName    = currentAssembly
                                  .GetManifestResourceNames()
                                  .Single(str => str.EndsWith("HTML.cshtml"));

            using var streamReader = new StreamReader(currentAssembly.GetManifestResourceStream(resourceName));
            var template = await streamReader.ReadToEndAsync();

            var engine = new RazorLightEngineBuilder()
                         // required to have a default RazorLightProject type,
                         // but not required to create a template from string.
                         .UseEmbeddedResourcesProject(typeof(HtmlReporter))
                         .UseMemoryCachingProvider()
                         .Build();

            var result = await engine.CompileRenderStringAsync("templateKey", template, model);

            return(result);
        }
Example #18
0
    public async Task Simple()
    {
        #region Simple
        var engine = new RazorLightEngineBuilder()
                     // required to have a default RazorLightProject type,
                     // but not required to create a template from string.
                     .UseEmbeddedResourcesProject(typeof(Program))
                     .UseMemoryCachingProvider()
                     .Build();

        string    template = "Hello, @Model.Name. Welcome to RazorLight repository";
        ViewModel model    = new ViewModel {
            Name = "John Doe"
        };

        string result = await engine.CompileRenderStringAsync("templateKey", template, model);

        #endregion

        Assert.NotNull(result);
    }
Example #19
0
        public static void GenerateSeleniumTestListHtml(List <SingleTestStats> testStatsList)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseFileSystemProject(Program.TEMPLATE_FOLDER)
                         .UseMemoryCachingProvider()
                         .Build();

            var viewModel = new SeleniumTestsViewModel(testStatsList);

            string result = engine.CompileRenderAsync("seleniumTests.cshtml", viewModel).Result;

            //Console.WriteLine(result);
            File.WriteAllText(Path.Combine(Program.WEB_REPORT_FOLDER, "seleniumTests.html"), result);

            testStatsList.ForEach(testStats =>
            {
                var testViewModel = new SeleniumTestViewModel(testStats);
                result            = engine.CompileRenderAsync("seleniumTest.cshtml", testViewModel).Result;
                File.WriteAllText(Path.Combine(Program.WEB_REPORT_FOLDER, $"testPages/{testStats.Name}.html"), result);
            });
        }
        public async Task Multiple_Simultaneous_Compilations_RaceCondition_Test()
        {
            var path = DirectoryUtils.RootDirectory;


            for (int i = 0; i < 100; i++)
            {
                var engine = new RazorLightEngineBuilder()
#if NETFRAMEWORK
                             .SetOperatingAssembly(typeof(Root).Assembly)
#endif
                             .UseFileSystemProject(Path.Combine(path, "Assets", "Files"))
                             .Build();

                var model = new { };
                var t1    = Task.Run(async() => await engine.CompileRenderAsync("template1.cshtml", model));
                var t2    = Task.Run(async() => await engine.CompileRenderAsync("template2.cshtml", model));

                var result = await Task.WhenAll(t1, t2);
            }
        }
Example #21
0
                /// <summary>
                /// テンプレートファイル展開を行う
                /// </summary>
                /// <param name="TemplateString"></param>
                /// <param name="info"></param>
                /// <returns></returns>
                public static string TemplateExpansion(
                    string TemplateKey,
                    string TemplateString,
                    SiteInfos info)
                {
                    // NetCoreへの対応状況により
                    // 以下ライブラリに差し替えする
                    // https://github.com/toddams/RazorLight


                    // ToDo
                    // 暫定で一番簡単な方法で実装する。
                    // 別途パフォーマンス調整の方法があるハズ
                    var engine = new RazorLightEngineBuilder()
                                 // required to have a default RazorLightProject type,
                                 // but not required to create a template from string.
                                 .UseEmbeddedResourcesProject(typeof(Program))
                                 .UseMemoryCachingProvider()
                                 .Build();

                    var result = engine.CompileRenderStringAsync(TemplateKey, TemplateString, info);

                    result.Wait();

                    var cacheResult = engine.Handler.Cache.RetrieveTemplate(TemplateKey);

                    if (cacheResult.Success)
                    {
                        var templatePage = cacheResult.Template.TemplatePageFactory();
                        var tresult      = engine.RenderTemplateAsync(templatePage, info);

                        tresult.Wait();

                        var v = tresult.Result;

                        return(v);
                    }

                    return("");
                }
Example #22
0
        private RazorLightEngine CreateRazorLightEngine()
        {
            if (string.IsNullOrEmpty(appPath))
            {
                appPath = GetApplicationRoot();
            }

            var templatePath = System.IO.Path.Combine(appPath, "App_Data\\EmailTemplates");

            RazorLightEngine engine;

            try {
                engine = new RazorLightEngineBuilder()
                         .UseFilesystemProject(templatePath)
                         .UseMemoryCachingProvider()
                         .Build();
            } catch (Exception ex) {
                throw new Exception("Error reading email templates from " + templatePath + "\n" + ex.Message);
            }

            return(engine);
        }
Example #23
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            var engine = new RazorLightEngineBuilder()
                         .SetOperatingAssembly(Assembly.GetExecutingAssembly())
                         .UseEmbeddedResourcesProject(typeof(RenderTemplate))
                         .UseMemoryCachingProvider()
                         .Build();

            string template = "Hello, @Model.Name. Welcome to RazorLight repository at @Model.Time";
            var    model    = new { Name = "John Doe", Time = DateTime.UtcNow };

            string result = await engine.CompileRenderStringAsync("templateKey", template, model);


            return(new OkObjectResult(result));
        }
Example #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // DI
            services.AddScoped <IPDFService, PDFService>();


            var processSufix = "32bit";

            if (Environment.Is64BitProcess && IntPtr.Size == 8)
            {
                processSufix = "64bit";
            }

            var pdfcontext = new CustomPdfContext();

            // pdfcontext.LoadUnmanagedLibrary(Path.Combine(Directory.GetCurrentDirectory(), $"libwkhtmltox.dll"));
            pdfcontext.LoadUnmanagedLibrary(Path.Combine(Directory.GetCurrentDirectory(), $"PDFNative/{processSufix}/libwkhtmltox.dll"));

            services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));

            // razon services
            services.AddScoped <IRazorLightEngine>(sp =>
            {
                var engine = new RazorLightEngineBuilder()
                             .UseFilesystemProject(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
                             .UseMemoryCachingProvider()
                             .Build();
                return(engine);
            });


            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
Example #25
0
        public async Task <EmailMessage> PrepareEmailMessage(string base64Json)
        {
            var engine = new RazorLightEngineBuilder()
                         .UseEmbeddedResourcesProject(typeof(EmailMessageBuilder))
                         .UseMemoryCachingProvider()
                         .Build();

            var template = Encoding.UTF8.GetString(EmailTemplates.Hello);

            var jsonString = base64Json.Base64Decode();

            using var input = new StringReader(jsonString);

            var model = JSON.Deserialize <CustomViewModel>(input);

            var result = await engine.CompileRenderStringAsync("templateKey", template, model);

            return(new EmailMessage
            {
                Content = result
            });
        }
Example #26
0
        public override async Task <IDataToSent> TransformData(IDataToSent receiveData)
        {
            receiveData ??= new DataToSentTable();

            var engine = new RazorLightEngineBuilder()
                         .UseEmbeddedResourcesProject(this.GetType())
                         .UseMemoryCachingProvider()
                         .Build();


            var key = Guid.NewGuid().ToString();

            var found = await engine.CompileRenderStringAsync(key, InputTemplate, receiveData);

            base.CreateOutputIfNotExists(receiveData);

            base.OutputString.Rows.Add(null, key, found);



            return(receiveData);
        }
Example #27
0
        public async Task <ServiceResult <string> > ForgotPassword(ForgotPasswordDto model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            var notif = new ServiceResult <string>();

            if (user == null)
            {
                notif.AddError("Error", "Su correo no se encuentra registrado.");
                return(notif);
            }

            var code = await _userManager.GeneratePasswordResetTokenAsync(user);

            var codeScaped = Uri.EscapeDataString(code);

            //var callbackUrl = string.Format(_configuration["AppSettings:"]+"/CambiarPassword/{0}/{1}", Uri.EscapeDataString(code), user.Id);
            var callbackUrl =
                string.Format(_configuration["AppSettings:baseUrl"] + "/CambiarPassword?code={0}&userId={1}", codeScaped,
                              user.Id);
            UserRecoveryPassword userRecoveryPasswordModel = new UserRecoveryPassword()
            {
                LastName    = user.LastName,
                FirstName   = user.FirstName,
                UrlCallBack = callbackUrl
            };
            string template = Path.Combine(StaticFilesDirectory, "Templates");
            var    engine   = new RazorLightEngineBuilder()
                              .UseFilesystemProject(template)
                              .UseMemoryCachingProvider()
                              .Build();

            string result = await engine.CompileRenderAsync("Email/recoveryPassword.cshtml", userRecoveryPasswordModel);

            await _emailSender.SendEmail(model.Email, "Reset Password", result);

            return(new ServiceResult <string>(model.Email));
        }
Example #28
0
        public async static Task <IRestResponse> SendReceipt(string email, Receipt receipt)
        {
            string       template = File.ReadAllText("Utils/Receipt_template.html", System.Text.Encoding.UTF8);
            const string key      = "templateKey";

            // mock model for testing
            //var receipt1 = new Receipt
            //{
            //    OrderId = "fj32lkj322443sd",
            //    ReceiptItems = new List<ReceiptItem>
            //                        {
            //                            new ReceiptItem
            //                            {
            //                                ProductName = "Valheim",
            //                                ActivationCodes = new List<string> { "1234dsdf45", "231984u", "3209ufsldifj"},
            //                                UnitPrice = 18,
            //                                Qty = 3
            //                            },

            //                            new ReceiptItem
            //                            {
            //                                ProductName = "Three Kingdom",
            //                                ActivationCodes = new List<string> { "1dfdsf45", "32ds546di65fj"},
            //                                UnitPrice = 38,
            //                                Qty = 2
            //                            }
            //                        }
            //};

            var engine = new RazorLightEngineBuilder()
                         .UseEmbeddedResourcesProject(typeof(Receipt))
                         .SetOperatingAssembly(typeof(Receipt).Assembly)
                         .Build();

            string msg = await engine.CompileRenderStringAsync(key, template, receipt);

            return(await SendEmail(msg, email));
        }
        public async Task Ensure_Registered_Properties_Are_Injected()
        {
            var    collection    = new ServiceCollection();
            string expectedValue = "TestValue";
            string templateKey   = "key";

            collection.AddSingleton(new TestViewModel()
            {
                Title = expectedValue
            });
            var propertyInjector = new PropertyInjector(collection.BuildServiceProvider());

            var builder = new StringBuilder();

            builder.AppendLine("@model object");
            builder.AppendLine("@inject RazorLight.Tests.Models.TestViewModel test");
            builder.AppendLine("Hello @test");

            var engine = new RazorLightEngineBuilder()
                         .UseEmbeddedResourcesProject(typeof(Root))
                         .AddDynamicTemplates(new Dictionary <string, string>()
            {
                { templateKey, builder.ToString() }
            })
                         .Build();

            ITemplatePage templatePage = await engine.CompileTemplateAsync(templateKey);

            //Act
            propertyInjector.Inject(templatePage);

            //Assert
            var prop = templatePage.GetType().GetProperty("test").GetValue(templatePage);

            Assert.NotNull(prop);
            Assert.IsAssignableFrom <TestViewModel>(prop);
            Assert.Equal((prop as TestViewModel).Title, expectedValue);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "dafunction")] HttpRequest req)
        {
            string name = req.Query["name"];

            if (string.IsNullOrWhiteSpace(name))
            {
                return(new BadRequestObjectResult("Please pass a name on the query string or in the request body"));
            }

            var engine = new RazorLightEngineBuilder()
                         .SetOperatingAssembly(typeof(DaFunction).Assembly)
                         .Build();

            const string Template = "Hello, @Model.Name. Welcome to RazorLight repository";
            var          model    = new ViewModel {
                Name = name
            };

            var result = await engine.CompileRenderAsync("templateKey", Template, model);

            return(new OkObjectResult(result));
        }