public void RenderLocalizedTemplate_RendersInSpecifiedCulture() { var template = _templateEngine.Render("Test.cshtml", null, new CultureInfo("ru-RU")); Assert.IsNotNull(template); Debug.WriteLine(template); Assert.IsTrue(!string.IsNullOrEmpty(template)); }
public void TemplateEngine_RenderTemplateWithCommonLayout_Executes() { var templateInvariant = _embeddedResourceTemplateEngine.Render("WithLayout.cshtml", null, CultureInfo.InvariantCulture); var templateRu = _embeddedResourceTemplateEngine.Render("WithLayout.cshtml", null, new CultureInfo("ru-RU")); Assert.IsNotNull(templateInvariant); Assert.IsNotNull(templateRu); Assert.IsTrue(templateInvariant.Contains("Layout")); Assert.IsTrue(templateRu.Contains("Layout")); Assert.IsTrue(templateInvariant.Contains("English")); Assert.IsTrue(templateRu.Contains("русском")); }
private static string Render(ITemplateEngine templateEngine, string templateFile, object values) { using (var writer = new StringWriter()) { templateEngine.Render(templateFile, values, writer); return(writer.GetStringBuilder().ToString()); } }
private string RenderTemplate(string template, MessageContext ctx, bool required = true) { if (!required && template.IsEmpty()) { return(null); } return(_templateEngine.Render(template, ctx.Model, ctx.FormatProvider)); }
public static MailMessage RenderEmail(this ITemplateEngine templateEngine, string path, object viewBag = null, CultureInfo culture = null) { Contract.Requires <ArgumentNullException>(templateEngine != null); Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(path)); Contract.Requires <NotSupportedException>(templateEngine.GetType() == typeof(RazorTemplateEngine), "Only razor engine is supported."); return(templateEngine.Render(path, renderer: new EmailRenderer(), viewBag: viewBag, culture: culture)); }
public ActionResponse Execute() { var response = new ActionResponse(_engine.Render()); foreach (var action in _template.Actions) { action.Content = response.Content; } return(response); }
private string ApplyVariablesToTemplate(ITemplateEngine engine, string template, IEnumerable <IQueryTemplateVariable> variables) { var valuePairs = new List <KeyValuePair <string, object> >(); foreach (var variable in variables) { valuePairs.Add(new KeyValuePair <string, object>(variable.Name, variable.Value)); } return(engine.Render(template, valuePairs)); }
public ActionResponse Execute() { var response = new ActionResponse(_engine.Render()); foreach (var action in _template.Actions) { action.Body = response.Message; } return(response); }
private Email EmailTemplateAndDataMerge(EmailTemplate emailTemplateAndData) { // translations done on templates and data // use template engine to render variables with values within email templates var appTemplate = templateEngine.Render(emailTemplateAndData.ApplicationTemplateBodyHtml, emailTemplateAndData.ApplicationTemplateText); var emailTemplate = templateEngine.Render(emailTemplateAndData.EmailTemplateBodyHtml, emailTemplateAndData.EmailTemplateText); var body = appTemplate.Replace("<email-template/>", emailTemplate); var mergedEmail = new Email { Subject = emailTemplateAndData.Subject, Body = body }; return(mergedEmail); }
private async Task CreateServiceInterfaceFile() { _viewFileModel.TemplateFolderNames = "/Application/IAppServiceTemplate.cshtml"; string content = await _templateEngine.Render(_viewFileModel); var fileName = _parameter.ServiceInterfaceName + ".cs"; FileHelper.CreateFile(_baseUrl + _parameter.ServiceFolder, fileName, content); }
public virtual string FormatAddress(object address, string template = null, IFormatProvider formatProvider = null) { Guard.NotNull(address, nameof(address)); template = template.NullEmpty() ?? Address.DefaultAddressFormat; var result = _templateEngine .Render(template, address, formatProvider ?? CultureInfo.CurrentCulture) .Compact(true); return(result); }
public async Task <ActionResult> Get() { ViewFileModel viewFileModel = new ViewFileModel() { TemplateFolderNames = "/Application/Dto/ListDtoTemplate.cshtml", CreateTime = DateTime.Now, EmailAddress = Project.EmailAddress, Author = Project.Author, TableName = "WebInfos", ProjectName = "SJNScaffolding", IdType = IdType.Long, TemplateFolder = @"..\..\..\SJNScaffolding.WPF\Templates", OutputFolder = Project.OutputPath, TypeColumnNames = TestHelper.GetColunmsList() }; foreach (var itemFolder in new[] { "Views", "JS" }) { foreach (var templateName in new[] { "IndexTemplate", "CreateOrUpdateModalTemplate" }) { viewFileModel.TemplateFolderNames = "/Views/" + itemFolder + "-" + templateName + ".cshtml"; string content = await _templateEngine.Render(viewFileModel); string fileName = templateName.Replace("JS", "").Replace("Template", ".").Replace("Views", "."); if (itemFolder.Equals("JS")) { fileName += "js"; } else { fileName += "cshtml"; } // FileHelper.CreateFile(_baseUrl + _parameter.ViewFolder, fileName, content); } } //await _addNewBussinessHelper.Execute(new ViewFileModel() //{ // TemplateFolderNames = "/Application/Dto/ListDtoTemplate.cshtml", // CreateTime = DateTime.Now, // EmailAddress = _project.EmailAddress, // Author = _project.Author, // TableName = "WebInfos", // ProjectName = "SJNScaffolding", // IdType = IdType.Long, // TemplateFolder = @"..\..\..\SJNScaffolding.WPF\Templates", // OutputFolder = _project.OutputPath, // TypeColumnNames = TestHelper.GetColunmsList() //}); return(Content("OJBK")); }
public string CreateBody(string confirmationUrl) { TemplateData templateData = new TemplateData { Template = "Please confirm your registration: {{ConfirmationUrl}}.", Parameters = new { ConfirmationUrl = confirmationUrl } }; return(engine.Render(templateData)); }
public async Task Build(List <TypeColumnName> typeColumnNames) { try { Template[] templates = _project.BuildTasks.Templates; bool isWebUpload = typeColumnNames.Exists(u => u.WebuploadColunm.IsWebUpload); foreach (var buildKv in templates) { if (buildKv.IsExcute == false) { continue; } //此模板是ViewModel,只有有上传控件时才生成模板 if (buildKv.Key == "/ViewModel/EntityViewModel.cshtml" && isWebUpload == false) { continue; } var output = buildKv.Output; var addViewModel = new ViewFileModel() { TemplateFolderNames = buildKv.Key, CreateTime = DateTime.Now, EmailAddress = _project.EmailAddress, Author = _project.Author, TableName = _project.TableName, ProjectName = _project.ProjectName, IdType = _project.IdType, OutputFolder = _project.OutputPath, TypeColumnNames = typeColumnNames }; string content = await _templateEngine.Render(addViewModel); var fileName = Handlebars.Compile(buildKv.Output.Name)(addViewModel) ?? ""; string folder = Handlebars.Compile(buildKv.Output.Folder)(addViewModel) ?? ""; FileHelper.CreateFile(_project.OutputPath + folder, fileName, content); } } catch (Exception e) { Console.WriteLine(e); throw; } }
/// <summary> /// <inheritdoc cref="IDynamicViewPresenter.GetView(IDynamicViewModel)"/> /// </summary> /// <param name="vm"></param> /// <returns></returns> public IView GetView(IDynamicViewModel vm) { string template = vm.Template; logger.Debug($"Try to parse template {template}"); // Get template, check if template is not null. if (!File.Exists(template)) { logger.Error("Template does not exist is null"); return(null); } // Render xaml content string xaml = templateEngine.Render(template, vm.DataSource); try { // https://github.com/verybadcat/CSharpMath/pull/149 // moved into the separate package: Avalonia.Markup.Xaml.Loader // dynamically load xaml object view = AvaloniaRuntimeXamlLoader.Parse(xaml); if (view is IView control) { // binding datacontext control.DataContext = vm; return(control); } logger.Error($"Dynamic view must be a instance of {typeof(DynamicViewBase).FullName}"); } catch (Exception e) { logger.Error($"Could not parse xaml template dynamically, {e.StackTrace}"); } return(null); }
/// <summary> /// Asynchronously sending of notification /// </summary> /// <param name="notificationTemplateName"></param> /// <param name="endpoints"></param> /// <param name="type"></param> /// <param name="url"></param> /// <param name="variables"></param> /// <returns></returns> public bool Send(string notificationTemplateName, IList <SNSEndpoint> endpoints, SNSType type, string url = null, Dictionary <string, string> variables = null) { NotificationTemplate template = _notificationTemplateService.GetTemplate(notificationTemplateName, MessageType.Notification, FormatType.Text); var freshTemplate = new NotificationTemplate() { DateCreated = template.DateCreated, TemplateName = template.TemplateName, Description = template.Description, TemplateBody = template.TemplateBody, MessageType = template.MessageType, MessageTypeInternal = template.MessageTypeInternal, FormatType = template.FormatType, FormatTypeInternal = template.FormatTypeInternal, TemplatePlaceholderStrategy = template.TemplatePlaceholderStrategy, TemplatePlaceholderStrategyEnum = template.TemplatePlaceholderStrategyEnum, SubjectTitle = template.SubjectTitle }; if (variables != null) { Hashtable vars = new Hashtable(); foreach (string index in variables.Keys) { vars[(object)index] = (object)variables[index]; } freshTemplate.TemplateBody = _templateEngine.Render(template.TemplateBody, vars); } else { freshTemplate.TemplateBody = notificationTemplateName; } SendNotificationAsync(freshTemplate, endpoints.Where(_ => _.IsActive && _.IsLoggedIn).ToList(), type, url); return(true); }
protected virtual object CreateModelPart(Campaign part, MessageContext messageContext) { Guard.NotNull(messageContext, nameof(messageContext)); Guard.NotNull(part, nameof(part)); var protocol = messageContext.BaseUri.Scheme; var host = messageContext.BaseUri.Authority + messageContext.BaseUri.AbsolutePath; var body = HtmlUtils.RelativizeFontSizes(part.Body.EmptyNull()); // We must render the body separately body = _templateEngine.Render(body, messageContext.Model, messageContext.FormatProvider); var m = new Dictionary <string, object> { { "Id", part.Id }, { "Subject", part.Subject.NullEmpty() }, { "Body", WebHelper.MakeAllUrlsAbsolute(body, protocol, host).NullEmpty() }, { "CreatedOn", ToUserDate(part.CreatedOnUtc, messageContext) } }; PublishModelPartCreatedEvent <Campaign>(part, m); return(m); }
public string Render(string template, dynamic model) { return(contentFilter.Filter(markupLanguage.Render(templateEngine.Render(template, model)))); }
public async Task <string> Build(List <TypeColumnName> typeColumnNames, bool download = false) { try { Template[] templates = _project.BuildTasks.Templates; bool isWebUpload = typeColumnNames.Exists(u => u.WebuploadColunm.IsWebUpload); foreach (var buildKv in templates) { if (buildKv.IsExcute == false) { continue; } //此模板是ViewModel,只有有上传控件时才生成模板 if (buildKv.Key == "/ViewModel/EntityViewModel.cshtml" && isWebUpload == false) { continue; } var addViewModel = new ViewFileModel() { TemplateFolderNames = buildKv.Key, CreateTime = DateTime.Now, EmailAddress = _project.EmailAddress, Author = _project.Author, TableName = _project.TableName, ProjectName = _project.ProjectName, IdType = _project.IdType, OutputFolder = _project.OutputPath, TypeColumnNames = typeColumnNames }; string content = await _templateEngine.Render(addViewModel); var fileName = Handlebars.Compile(buildKv.Output.Name)(addViewModel) ?? ""; string folder = Handlebars.Compile(buildKv.Output.Folder)(addViewModel) ?? ""; FileHelper.CreateFile(_project.OutputPath + folder, fileName, content); } } catch (Exception e) { Console.WriteLine(e); _logger.LogError(e.Message); throw; } if (download) { string outputUrl = FileHelper.GetCompressDirPath(_project.OutputPath, new List <string>() { _project.OutputPath }); string relaName = outputUrl.Substring(outputUrl.LastIndexOf("/", StringComparison.Ordinal) + 1); string path = Directory.GetCurrentDirectory() + "/wwwroot/file/" + relaName; byte[] fileBuffer = FileHelper.File2Bytes(outputUrl); FileHelper.Bytes2File(fileBuffer, path); FileHelper.DeletePath(_project.OutputPath); return("/file/" + relaName); } return(string.Empty); }
public ActionResponse Execute() { _context.Warn("Initializing"); List <CoreResult> cores = null; try { cores = _admin.Status(); } catch (Exception ex) { return(new ActionResponse() { Code = 500, Message = $"Count not access {_context.Connection.Url}: {ex.Message}" }); } var coreFolder = new DirectoryInfo(Path.Combine(_context.Connection.Folder, _context.Connection.Core)); if (!coreFolder.Exists) { coreFolder.Create(); // https://stackoverflow.com/questions/58744/copy-the-entire-contents-of-a-directory-in-c-sharp var sourceFolder = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files\\solr")); foreach (string d in Directory.GetDirectories(sourceFolder.FullName, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(d.Replace(sourceFolder.FullName, coreFolder.FullName)); } foreach (string f in Directory.GetFiles(sourceFolder.FullName, "*.*", SearchOption.AllDirectories)) { File.Copy(f, f.Replace(sourceFolder.FullName, coreFolder.FullName), true); } } File.WriteAllText(Path.Combine(Path.Combine(coreFolder.FullName, "conf"), "schema.xml"), _engine.Render()); if (cores.Any(c => c.Name == _context.Connection.Core)) { _admin.Reload(_context.Connection.Core); } else { _admin.Create(_context.Connection.Core, _context.Connection.Core); } _solr.Delete(SolrQuery.All); _solr.Commit(); return(new ActionResponse()); }
public ActionResponse Execute() { _context.Warn("Initializing"); List <CoreResult> cores = null; try { cores = _admin.Status(); } catch (SolrConnectionException ex) { return(new ActionResponse { Code = 500, Message = $"Count not access {_context.Connection.Url}: {ex.Message}" }); } var coreFolder = new DirectoryInfo(Path.Combine(_context.Connection.Folder, _context.Connection.Core)); if (!coreFolder.Exists) { try { coreFolder.Create(); } catch (UnauthorizedAccessException ex) { _context.Warn("Unable to create core folder: {0}", ex.Message); } } // https://stackoverflow.com/questions/58744/copy-the-entire-contents-of-a-directory-in-c-sharp var sourceFolder = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "files\\solr")); try { foreach (var d in Directory.GetDirectories(sourceFolder.FullName, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(d.Replace(sourceFolder.FullName, coreFolder.FullName)); } var fileCount = 0; _context.Debug(() => $"Copying SOLR files to {coreFolder.FullName}."); foreach (var f in Directory.GetFiles(sourceFolder.FullName, "*.*", SearchOption.AllDirectories)) { var solrFileInfo = new FileInfo(f.Replace(sourceFolder.FullName, coreFolder.FullName)); File.Copy(f, solrFileInfo.FullName, true); _context.Debug(() => $"Copied {solrFileInfo.Name}."); fileCount++; } _context.Info($"Copied {fileCount} SOLR file{fileCount.Plural()}."); File.WriteAllText(Path.Combine(Path.Combine(coreFolder.FullName, "conf"), "schema.xml"), _schemaEngine.Render()); File.WriteAllText(Path.Combine(Path.Combine(coreFolder.FullName, "conf"), "solrconfig.xml"), _configEngine.Render()); } catch (UnauthorizedAccessException ex) { _context.Warn("Unable to transfer configuration files to core folder: {0}", ex.Message); } if (cores.Any(c => c.Name == _context.Connection.Core)) { try { _admin.Reload(_context.Connection.Core); } catch (SolrConnectionException ex) { _context.Warn("Unable to reload core"); _context.Warn(ex.Message); } } else { try { _admin.Create(_context.Connection.Core, _context.Connection.Core); } catch (SolrConnectionException ex) { _context.Warn("Unable to create core"); _context.Error(ex, ex.Message); } } _solr.Delete(SolrQuery.All); // _solr.Commit(); /* wait until after writing the new records */ return(new ActionResponse()); }