static void StronglyTypedModel() { var welcomeEmailTemplatePath = Path.Combine(TemplateFolderPath, "WelcomeEmailStronglyTyped.cshtml"); // Generate the email body from our email template var stronglyTypedModel = new UserModel() { Name = "Sarah", Email = "*****@*****.**", IsPremiumUser = false }; var templateService = new TemplateService(); var emailHtmlBody = templateService.Parse(File.ReadAllText(welcomeEmailTemplatePath), stronglyTypedModel, null, null); // Send the email var email = new MailMessage() { Body = emailHtmlBody, IsBodyHtml = true, Subject = "Welcome (generated from strongly-typed model)" }; email.To.Add(new MailAddress(stronglyTypedModel.Email, stronglyTypedModel.Name)); // The From field will be populated from the app.config value by default var smtpClient = new SmtpClient(); smtpClient.Send(email); // In the real world, you'll probably want to use async version instead: // await smtpClient.SendMailAsync(email); }
static void Main(string[] args) { /* * Quick benchmark demonstrating the effect of using RazorEngine's caching functionality. * * We'll generate the same email 3 times in a row - first without caching and then with caching. * We'll measure and print how long each try takes. * * Also demonstrates how to retrieve the list of default namespaces to use when generating the template class * from the ASP.NET MVC configuration section in the web.config file. */ var welcomeEmailTemplate = File.ReadAllText(Path.Combine(TemplateFolderPath, "WelcomeEmail.cshtml")); var model = new UserModel() { Name = "Sarah", Email = "*****@*****.**", IsPremiumUser = false }; var templateService = new TemplateService(); // Add the default namespaces that will be automatically imported in all template classes AddDefaultNamespacesFromWebConfig(templateService); //-- Warm-up var emailHtmlBody = templateService.Parse(welcomeEmailTemplate, model, null, null); Stopwatch watch = new Stopwatch(); //-- Without cache Console.WriteLine("Without cache: "); for (int i = 1; i < 4; i++) { watch.Start(); emailHtmlBody = templateService.Parse(welcomeEmailTemplate, model, null, null); watch.Stop(); Console.WriteLine("Try #{0}: {1}ms", i, watch.ElapsedMilliseconds); watch.Reset(); } //-- With cache Console.WriteLine("With cache: "); for (int i = 1; i < 4; i++) { watch.Start(); emailHtmlBody = templateService.Parse(welcomeEmailTemplate, model, null, "Welcome"); watch.Stop(); Console.WriteLine("Try #{0}: {1}ms", i, watch.ElapsedMilliseconds); watch.Reset(); } Console.ReadLine(); /* * Example output: * Without cache: Try #1: 116ms Try #2: 114ms Try #3: 118ms With cache: Try #1: 114ms Try #2: 0ms Try #3: 0ms * */ }