public async Task <string> Process(string keyTemplate, string template, object model) { var cacheResult = engine.TemplateCache.RetrieveTemplate(keyTemplate); if (cacheResult.Success) { return(await engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), model)); } return(await engine.CompileRenderAsync(keyTemplate, template, model)); }
public async Task <string> Render <T>(string folder, string file, T model) { var path = string.IsNullOrWhiteSpace(folder) ? file : Path.Combine(folder, file); if (!path.EndsWith(".cshtml") && !path.EndsWith(".html")) { path += ".cshtml"; } return(await _engine.CompileRenderAsync <T>(path, model)); }
public async Task <string> ParseFile(string key, string template, Dictionary <string, string> model) { try { return(await _engine.CompileRenderAsync($"{key}", $"/{template}", model)); } catch (Exception ex) { throw ex; } }
public async Task <ServiceResult <string> > CompileHtmlAsync <T> (string templateName, T model) { try { string htmlResult = await engine.CompileRenderAsync <T>(templateName + "/view.cshtml", model); string htmlFilePath = SaveHtmlDocument(templateName, htmlResult); return(new ServiceResult <string> (htmlFilePath, true, "")); } catch (Exception ex) { return(new ServiceResult <string> ("", false, ex.ToString())); } }
public async Task <byte[]> GetByteArray <T>(string View, T model, ExpandoObject viewBag = null) { try { var html = await _engine.CompileRenderAsync(View, model, viewBag); return(base.GetPDF(html)); } catch (System.Exception ex) { throw ex; } }
public string CreateReport(string report, object model) { var result = _engine.CompileRenderAsync($"{report}.cshtml", model); var html = result.Result; var filename = Guid.NewGuid() + ".pdf"; var path = Path.Combine(_environment.WebRootPath, "reports", filename); var doc = new HtmlToPdfDocument { GlobalSettings = { ColorMode = ColorMode.Color, Orientation = Orientation.Landscape, PaperSize = PaperKind.A4Plus, Out = path, }, Objects = { new ObjectSettings { PagesCount = true, HtmlContent = html, WebSettings = { DefaultEncoding = "utf-8" }, HeaderSettings ={ FontSize =9, Right = "Page [page] of [toPage]", Line = true, Spacing = 2.812 }, } } }; _converter.Convert(doc); return(filename); }
public async Task SignUp(SignUpVm model) { var existingUser = await _userRepository.GetUserByEmail(model.Email); if (existingUser != null) { throw new BadRequestException("User with this email is already exists"); } var signUpDto = _mapper.Map <SignUpDto>(model); var id = await _userRepository.SignUp(signUpDto); //create user root folder await _foldersRepository.CreateFolder(new CreateFolderDto { Name = $"User {id} root folder", UserId = id, FolderType = FolderType.Private }); var body = await _razorLightEngine.CompileRenderAsync("UserInvitationTemplate.cshtml", new UserInvitationVm { ActivationUrl = $"{_commonSettings.ApplicationUrl}/activate_user", ActivationToken = signUpDto.ActivationToken, FirstName = model.FirstName, LastName = model.LastName }); _emailService.SendEmail(signUpDto.Email, $"Welcome to Video", body).Forget(); }
/// <summary> /// Compiles and renders a razor view and returns the rendered SSML string /// </summary> /// <param name="parsableTemplate">The razor template to be compiled and rendered</param> /// <param name="templateKey">The template key, that is used cache the compiled view with</param> /// <param name="model">The model you want to give your razor view</param> /// <returns>The rendered razor view</returns> public static async Task <string> BuildFromAsync(string parsableTemplate, string templateKey, object model = null) { var result = await m_engine.CompileRenderAsync(templateKey, parsableTemplate, model) .ConfigureAwait(false); return(result); }
public async Task <IActionResult> Download([FromServices] INodeServices nodeServices) { var model = new ResultsPdf { Title = "Hello World", Description = "This PDF is generated from a Razor view.", Results = new List <string> { "List Item 1", "List Item 2", "List Item 3" } }; var pdfHtml = await _razorEngine.CompileRenderAsync("Results.cshtml", model); var result = await nodeServices.InvokeAsync <byte[]>("./pdf", pdfHtml); HttpContext.Response.ContentType = "application/pdf"; string filename = @"results.pdf"; HttpContext.Response.Headers.Add("x-filename", filename); HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "x-filename"); HttpContext.Response.Body.Write(result, 0, result.Length); return(new ContentResult()); }
public async Task Run(Database dc, Workflow wf, ActivityInWorkflow activity, ActivityInWorkflow preActivity) { var template = activity.GetOptionValue("Template"); if (engine == null) { engine = new RazorLightEngineBuilder() .UseFilesystemProject(AppDomain.CurrentDomain.GetData("ContentRootPath").ToString() + "\\App_Data") .UseMemoryCachingProvider() .Build(); } var model = CleanJObject(activity); string result = ""; var cacheResult = engine.TemplateCache.RetrieveTemplate(template); if (cacheResult.Success) { result = await engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), model); } else { result = await engine.CompileRenderAsync(template, model); } activity.Output.Data = JObject.Parse(result); }
/// <summary> /// create or over write html file /// </summary> /// <param name="engine">RazorLightEngin Instance</param> /// <param name="cshtmlPath">cshtml template file</param> /// <param name="outputDir">out put directory</param> public async Task CreateOrOverWrite(RazorLightEngine engine, string cshtmlPath, string outputDir) { string result = await engine.CompileRenderAsync(cshtmlPath, new { title = fileName, articleText = convertHtml }); string htmlFilePath = HtmlFilePath(outputDir); Console.WriteLine($"[Generate] : {htmlFilePath}"); // create directory if not exist string htmlFileDir = Path.GetDirectoryName(htmlFilePath); if (!Directory.Exists(htmlFileDir)) { Directory.CreateDirectory(htmlFileDir); } // over write or create file if (File.Exists(htmlFilePath)) { File.WriteAllText(htmlFilePath, result); } else { using (FileStream fs = File.Create(htmlFilePath)) using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(result); } } }
public async static Task Main(string[] args) { string view = "Views.EmbedEmail.cshtml"; EmailModel model = GetModel(); RazorViewToStringRenderer razor = GetRazorRenderer(); RazorLightEngine razorLight = GetRazorLightRenderer(); Stopwatch razorStopwatch = new Stopwatch(); Stopwatch razorLightStopwatch = new Stopwatch(); IEnumerable <Task <string> > tasks; for (int i = 0; i < Batches; i++) { razorStopwatch.Start(); tasks = Enumerable.Range(0, NumberOfEmails / Batches) .Select(_ => razor.Render(view, model)); await Task.WhenAll(tasks); razorStopwatch.Stop(); razorLightStopwatch.Start(); tasks = Enumerable.Range(0, NumberOfEmails / Batches) .Select(_ => razorLight.CompileRenderAsync(view, model)); await Task.WhenAll(tasks); razorLightStopwatch.Stop(); } }
public async Task SendEmail(Form from) { string html = await _razorLightEngine.CompileRenderAsync <object>(Template, from); User user = await repository.GetUserById(from.SenderId); SmtpConfiguration configuration = await service.GetConfiguration(); Email.DefaultSender = new SmtpSender(new SmtpClient { Host = configuration.Host, Port = int.Parse(configuration.Port), Credentials = new NetworkCredential(configuration.Username, configuration.Password) }); SendResponse sendResponse = await Email .From(configuration.From) .To(configuration.To) .Subject($"New Message from: {user.Username}") .Body(html, true) .SendAsync(); if (!sendResponse.Successful) { //Todo log } }
/// <summary> /// Fetches embedded Razor views for more complex HTML code from the dll (requires to set "build" to "embedded ressource" in the propertys of the cshtml file) /// </summary> string GetEmbeddRazorTemplate(string name, BBCodeNode node) { string key = $"Html.Templates.{name}.cshtml"; string template = razor.CompileRenderAsync(key, node).Result; return(template); }
public bool SendEmail(string templatePath, object model) { var templateTask = _razorLightEngine.CompileRenderAsync(templatePath, model); var html = templateTask.Result; // TODO: send email return(!string.IsNullOrEmpty(html)); }
private async Task <string> CreateActivationEmailBody(User user) { var language = user.PreferredLanguage ?? "en"; var translationDefinition = LoadTranslationDefinition(language, "Activation"); var model = new { user.Username }; var translatedModel = await _emailTranslator.Translate(_templateEngine, translationDefinition, model, language, "activation"); translatedModel.Add(new KeyValuePair <string, object>("url", $"{_configuration.ActivationURL}/{user.ActivationToken}")); var result = await _templateEngine.CompileRenderAsync("template.cshtml", translatedModel); return(result); }
public async Task <string> GetWebPage(ExecutionContext executionContext, Constants.Pages webpage, object model) { if (_engine is null) { BuildEngine(executionContext); } return(await _engine.CompileRenderAsync(Constants.Templates[webpage], model)); }
public async Task <string> Render <TData>(string className, TData data) { var relativeClassName = className; if (!string.IsNullOrEmpty(_rootNamespace)) { relativeClassName = className.Replace(_rootNamespace + ".", ""); } return(await _razor.CompileRenderAsync(relativeClassName, data)); }
/// <summary> /// Handler that is registered within the <see cref="IRouter"/> that returns /// all registered routes in a nice view. /// </summary> /// <param name="request">HttpRequest.</param> /// <param name="response">HttpResponse.</param> /// <param name="data">RouteData (unused).</param> /// <returns>A task that is resolved when all routes are collected and rendered into html.</returns> public async Task Handler(HttpRequest request, HttpResponse response, RouteData data) { response.ContentType = ContentType; await response.WriteAsync( await _viewEngine.CompileRenderAsync( "Routes", _provider.ActionDescriptors.Items .Select(descriptor => new RouteInformation(descriptor)) .OrderBy(info => info.Template) .ToImmutableList())); }
/// <inheritdoc /> public Task <string> RenderAsync <T>(MessageTemplate template, T model) { template.ThrowIfNull(nameof(template)); if (template.EngineType != Engines.Razor) { throw new ArgumentException($"Type template engine is not {Engines.Razor:G}"); } ReplaceRenderBodyIfIsParentTemplateNull(template); return(engine?.CompileRenderAsync(template.Name, template.Body, model)); }
public async Task <bool> SendRegisterConfirmationEmailAsync(string email, string firstName, string lastName, string confirmationToken) { try { bool result = false; int attempts = 0; IUrlHelper urlHelper = (IUrlHelper)_httpContextAccessor.HttpContext.Items[BaseController.URLHELPER]; string toName = $"{firstName} {lastName}"; string subject = "Account Email Confirmation"; var model = new ConfirmEmailModel { Name = firstName, ConfirmationUrl = urlHelper.Link("ConfirmEmail", new { token = confirmationToken }) }; string htmlContent = await _engine.CompileRenderAsync("ConfirmationEmail.cshtml", model); string plainTextContent = htmlContent; while (!result && attempts < _maxEmailAttempts) { result = await SendEmailAsync(email, toName, subject, plainTextContent, htmlContent); attempts++; } if (!result) { throw new Exception("Maxium number of attempts reached"); } return(true); } catch (Exception ex) { _logger.LogError(ex, ex.Message); } return(false); }
public async Task Send(Order order, string shopEmail, string shopPhoneNumber, string templatePath) { var conf = this.configuration.Value; var model = new NewOrderViewModel { Id = order.Id, PaymentMethod = order.Payment, Email = shopEmail, DeliveryMethod = order.Delivery, CustomerName = order.CustomerName, PhoneNumber = shopPhoneNumber, Created = order.Timestamp, Total = order.OrderItems.Sum(x => x.Count * x.Price), CustomerPhoneNumber = order.PhoneNumber, CustomerAddress = order.Address, Items = order.OrderItems.Select(x => new NewOrderItemViewModel { Name = x.Product.Title, Color = x.Color, Size = x.Size, Id = x.Product.Id, Price = x.Price, Count = x.Count }).ToList() }; var letter = await engine.CompileRenderAsync(templatePath, model).ConfigureAwait(false); var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress(conf.From.Name, conf.From.Address)); emailMessage.To.Add(new MailboxAddress(order.CustomerName, order.Email)); emailMessage.Subject = $"Оформлен новый заказ № {order.Id} на сайте Piligrim"; emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = letter }; using (var client = new SmtpClient()) { await client.ConnectAsync(conf.Smtp.Host, conf.Smtp.Port, conf.Smtp.UseSsl); await client.AuthenticateAsync(conf.Smtp.Login, conf.Smtp.Password); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); } }
/// <summary> /// Renders "cshtml" email template to string. /// </summary> /// <param name="assembly">Assembly where the embedded resource resides.</param> /// <param name="embeddedResourceName"></param> /// <param name="model">The model to pass to the view.</param> private async Task <string> RenderPartialView <T>(Assembly assembly, string embeddedResourceName, T model) { var modelType = typeof(T); var cache = engine.TemplateCache.RetrieveTemplate(modelType.FullName); if (!cache.Success) { var source = assembly.GetEmbeddedResourceText(embeddedResourceName); return(await engine.CompileRenderAsync(modelType.FullName, source, model)); } return(await engine.RenderTemplateAsync(cache.Template.TemplatePageFactory(), model)); }
public async Task <string> EmbeddedViews(string viewName, object viewModel) { if (!_hostFileSystemStorage.ExistFile(EmbeddedViewsPath.GetViewFullPath(viewName))) { Console.WriteLine("View Not Exist " + EmbeddedViewsPath.GetViewFullPath(viewName)); } else { // has an dependency on the filesystem by _engine.CompileRenderAsync return(await _engine.CompileRenderAsync("WebHtmlPublish/EmbeddedViews/" + viewName, viewModel)); } return(string.Empty); }
public async Task <string> RenderAsync <T>( string templateKey, string templateContent, T model, bool isHtml = true) { var cacheResult = _engine.TemplateCache.RetrieveTemplate(templateKey); if (cacheResult.Success) { string result = await _engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), model); return(result); } return(await _engine .CompileRenderAsync(templateKey, templateContent, model)); }
private async static Task <string> ParseAsync(string templateKey, string template, TemplateModel model) { string result = null; var cacheResult = _engine.TemplateCache.RetrieveTemplate(templateKey); if (cacheResult.Success) { result = await _engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), model); } else { result = await _engine.CompileRenderAsync(templateKey, template, model); } return(result); }
private async Task <string> ProcessTemplate(string template, string outPath, object?model) { var html = await razorEngine.CompileRenderAsync(template, model); if (!Directory.Exists(outPath)) { Directory.CreateDirectory(outPath); } var dest = Path.Combine(outPath, "index.htm"); File.WriteAllText(dest, html); return(dest); }
public string Render(string template, ViewInfoWapper model) { var result = string.Empty; var cacheResult = _engine.TemplateCache.RetrieveTemplate(template); if (cacheResult.Success) { result = _engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), model).Result; } else { result = _engine.CompileRenderAsync(template, model).Result; } return(result); }
public async Task <string> GetCompiledMessageAsync <T>(string templateKey, string messageTemplate, T model) { string retVal; var cacheResult = _razorEngine.TemplateCache.RetrieveTemplate(templateKey); if (cacheResult.Success) { retVal = await _razorEngine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), model); } else { retVal = await _razorEngine.CompileRenderAsync(templateKey, messageTemplate, model); } return(retVal); }
public async Task <IActionResult> Add([FromBody] VmSubscription sub) { if (!dc.Table <Subscription>().Any(x => x.Email == sub.Email.ToLower())) { dc.DbTran(() => { dc.Table <Subscription>().Add(new Subscription() { Email = sub.Email.ToLower(), IsActive = true }); }); EmailRequestModel model = new EmailRequestModel(); model.Subject = Database.Configuration.GetSection("UserSubscriptionEmail:Subject").Value; model.ToAddresses = sub.Email; model.Template = Database.Configuration.GetSection("UserSubscriptionEmail:Template").Value; if (engine == null) { engine = new RazorLightEngineBuilder() .UseFilesystemProject(Database.ContentRootPath + "\\App_Data") .UseMemoryCachingProvider() .Build(); } var cacheResult = engine.TemplateCache.RetrieveTemplate(model.Template); var emailModel = new { Host = Database.Configuration.GetSection("clientHost").Value, Email = sub.Email }; if (cacheResult.Success) { model.Body = await engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), emailModel); } else { model.Body = await engine.CompileRenderAsync(model.Template, emailModel); } var ses = new AwsSesHelper(Database.Configuration); string emailId = await ses.Send(model, Database.Configuration); } return(Ok()); }