/// <summary> /// 使用RazorEngine编译cshtml页面.返回静态内容 /// </summary> /// <param name="temps">temps是一个以路径为键,cshtml文件内容为值的字典.它包含了一个要被编译的cshtml主文件以及其引用的1个母板页和0~多个片段页.</param> /// <param name="mainCshtmlKey">要编译的主cshtml模板文件在temps中的key</param> /// <returns></returns> private static string RazorRun(Dictionary <string, string> temps, string mainCshtmlKey, object model = null) { // 添加要编译的cshtml文件,包括其引用的母板页和片段页 foreach (string key in temps.Keys) { // 如果文件有变化才重新添加模板和编译,因为编译时间比较长 if (!RazorCacheHelpers.IsChange(key, temps[key])) { continue; } // 键是文件的相对路径名,是固定的,每个cshtml的路径是唯一的. ITemplateKey k = serveice.GetKey(key); // 先删除这个键,再添加之.由于键固定,不删除的话,会报键重复. ((DelegateTemplateManager)config.TemplateManager).RemoveDynamic(k); // 添加模板,以键为模板名,以cshtml内容为模板内容 serveice.AddTemplate(k, temps[key]); // 编译之.由于键固定,如果不编译的话,就会使用上一次编译后的缓存(与这固定键对应的缓存).所以添加模板后,一定要重新编译. serveice.Compile(k); } // MainCshtmlKey是cshtml主页面,生成html时,必须以主cshtml模板的名. if (model == null) { return(serveice.Run(serveice.GetKey(mainCshtmlKey))); } return(serveice.Run(serveice.GetKey(mainCshtmlKey), null, model)); }
/// <summary> /// Создает зарегестрированного пользователя /// </summary> /// <param name="model">Модель для регистрации пользователя</param> /// <returns>ServiceResponce</returns> public ServiceResponce CreateSystemUser(RegisterUserModel model) { if (!model.GeneratePassword && !PasswordService.IsPasswordAcceptable(model.Password)) { return(ServiceResponce .FromFailed() .Add("error", "Password not acceptable")); } model.Phone = PhoneService.PhoneConvert(model.Phone); if (_userRep.CountByCredentails(model.Email, model.Phone) != 0) { return(ServiceResponce .FromFailed() .Add("error", "User with this Email or Phone already exist")); } // Генерируем и хэшируем пароль string UnHashedPassword = model.Password; if (model.GeneratePassword) { UnHashedPassword = PasswordService.GeneratePasswordString(); } model.Password = PasswordService.GeneratePasswordHash(UnHashedPassword); User user = RegisterUserModelHelper.CreateUser(model); _userRep.Save(user); ServiceResponce response = ServiceResponce .FromSuccess() .Result("User registered") .Add("UserId", user.Id); if (model.GeneratePassword) { response.Add("GeneratedPassword", UnHashedPassword); } if (model.NotSendWelcome == false) { // Создаем задачу отправки сообщения в фоне и запускаем ее new Thread(send => { RegisteredEmailModel RegisteredEmailModel = RegisteredEmailModelHelper.GetRegisteredEmailModel(model, UnHashedPassword); string RegisteredText = _templateServ .Run("Emails/Registered", typeof(RegisteredEmailModel), RegisteredEmailModel); EmailService.SendMail(RegisteredEmailModel, RegisteredText); }).Start(); } return(response); }
/// <summary> /// ユースケースカタログを出力する /// </summary> /// <param name="catalog">ユースケースカタログ</param> private void CreateUseCaseCatalog(UseCaseCatalog catalog) { Contract.Requires(catalog != null); var outputFilePath = Path.Combine(OutputDirectoryPath, Path.ChangeExtension(catalog.FileName, ".md")); Console.Error.WriteLine(Resources.Resources.Message_Format_WriteFileTo_UseCaseCatalog, outputFilePath); using (var writer = new StreamWriter(outputFilePath)) { writer.Write(razorEngineService.Run("UseCaseCatalogTemplateKey", typeof(UseCaseCatalog), catalog)); } }
public IHttpActionResult Test4() { string result1 = TemplateServ.Run("Emails/Invite", typeof(InviteEmailModel), new InviteEmailModel() { Link = "dsfdsgsdg" }); string result2 = TemplateServ.Run("Emails/Invite", typeof(InviteEmailModel), new InviteEmailModel() { Link = "qwertyu" }); return(Ok(result1 + " " + result2)); }
public string Render <TModel>(CompilerConfiguration configuration, FilePath templatePath, TModel model) where TModel : TemplateViewModel { lock (_lock) { var templateName = templatePath.FullPath; if (!_engine.IsTemplateCached(templateName, typeof(TModel))) { templatePath = configuration.Root.CombineWithFilePath(templatePath); // Make sure the template exist. if (!_fileSystem.Exist(templatePath)) { const string format = "The template '{0}' do not exist."; var message = string.Format(format, templatePath.FullPath); throw new InvalidOperationException(message); } using (var stream = _fileSystem.GetFile(templatePath).OpenRead()) using (var reader = new StreamReader(stream)) { // Read the template and compile it. var template = reader.ReadToEnd(); _engine.AddTemplate(templateName, template); _engine.Compile(templateName, typeof(TModel)); } } return(_engine.Run(templateName, typeof(TModel), model)); } }
private void GenerateHtml(IRazorEngineService service) { var SampleTemplate = File.ReadAllText("SampleTemplate.cshtml"); var SubSample = File.ReadAllText("SubSample.cshtml"); //service.AddTemplate("part", SubSample); // If you leave the second and third parameters out the current model will be used. // If you leave the third we assume the template can be used for multiple types and use "dynamic". // If the second parameter is null (which is default) the third parameter is ignored. // To workaround in the case you want to specify type "dynamic" without specifying a model use Include("p", new object(), null) //service.AddTemplate("template", SampleTemplate); service.Compile(SampleTemplate, "template", typeof(MyModel)); service.Compile(SubSample, "part", typeof(SubModel)); var result = service.Run("template", typeof(MyModel), new MyModel { SubModelTemplateName = "part", ModelProperty = "model1<@><b>rob</b></@>.com <", RawProperty = "model1<@><b>rob</b></@>.com <", SubModel = new SubModel { SubModelProperty = "submodel2" } }); Console.WriteLine("Result is: {0}", result); DisplayHtml(result); }
public void Save <TModel>(TModel model) where TModel : IRenderable { var html = _razor.Run(model.TemplateName, typeof(TModel), model); File.WriteAllText(Path.Combine(_outputDirectory, model.FileName + ".html"), html); }
public override IEnumerable <IRow> Operate(IEnumerable <IRow> rows) { var fileBasedTemplate = Context.Process.Templates.FirstOrDefault(t => t.Name == Context.Operation.Template); if (fileBasedTemplate != null) { Context.Operation.Template = fileBasedTemplate.Content; } var input = MultipleInput(); var matches = Context.Entity.GetFieldMatches(Context.Operation.Template); _input = input.Union(matches).ToArray(); if (!Run) { yield break; } var key = GetHashCode(Context.Operation.Template, _input); if (!Cache.TryGetValue(key, out _service)) { var config = new TemplateServiceConfiguration { DisableTempFileLocking = true, EncodedStringFactory = Context.Field.Raw ? (IEncodedStringFactory) new HtmlEncodedStringFactory() : new RawStringFactory(), Language = Language.CSharp, CachingProvider = new DefaultCachingProvider(t => { }) }; _service = RazorEngineService.Create(config); Cache.TryAdd(key, _service); } var first = true; foreach (var row in rows) { if (first) { try { var output = _service.RunCompile((string)Context.Operation.Template, (string)Context.Key, typeof(ExpandoObject), row.ToFriendlyExpandoObject(_input), null); row[Context.Field] = _convert(output); first = false; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) { Context.Error(ex.Message.Replace("{", "{{").Replace("}", "}}")); yield break; } catch (TemplateCompilationException ex) { Context.Error(ex.Message.Replace("{", "{{").Replace("}", "}}")); yield break; } yield return(row); } else { var output = _service.Run(Context.Key, typeof(ExpandoObject), row.ToFriendlyExpandoObject(_input)); row[Context.Field] = _convert(output); yield return(row); } } }
public override IRow Operate(IRow row) { var output = _service.Run(Context.Key, typeof(ExpandoObject), row.ToFriendlyExpandoObject(_input)); row[Context.Field] = Context.Field.Convert(output.Trim(' ', '\n', '\r')); return(row); }
public async Task <string> GetCompiledMessageAsync <T>(string templateKey, string messageTemplate, T model) { var res = _engineService.IsTemplateCached(templateKey, typeof(T)) ? _engineService.Run(templateKey, typeof(T), model) : _engineService.RunCompile(messageTemplate, templateKey, typeof(T), model); return(await Task.FromResult(res)); }
public string Render() { _result = _engine.Run(_templateKey, _modeldata.GetType(), _modeldata, _viewBag).Trim(); //put header for result code if (RazorTemplate.IsHeader) { _result = headerString + _result; } return(_result); }
public string Transform <T>(string template, T model) { var templateKey = template.GetHashCode().ToString(); if (!engine.IsTemplateCached(templateKey, typeof(T))) { engine.AddTemplate(templateKey, template); engine.Compile(templateKey, typeof(T)); } return(engine.Run(templateKey, typeof(T), model)); }
public static string RunTemplate(Type templateType, object model) { if (_razorService == null) { throw new RFSystemException(typeof(RFRazor), "Razor templates not initialized."); } lock (_sync) { var templateName = ParserHelpers.SanitizeClassName(templateType.FullName).ToLowerInvariant(); return(_razorService.Run(templateName, null, model)); } }
public string Generate(TModel model, TemplateContext templateContext) { if (!compiled) { razorEngineService.Compile(templateKey, typeof(TModel)); compiled = true; } var viewBag = new DynamicViewBag(); viewBag.AddValue("TemplateContext", templateContext); return(razorEngineService.Run(templateKey, typeof(TModel), model, viewBag)); }
public string Parse(string rootView, object model) { var config = new TemplateServiceConfiguration(); config.DisableTempFileLocking = true; config.CachingProvider = new DefaultCachingProvider(s => { }); using (engine = RazorEngineService.Create(config)) { LoadTemplates(); var result = engine.Run(rootView, null, model); return result; } }
/// <summary> /// 解析模板 /// </summary> /// <param name="sTemplateName">模板标识</param> /// <param name="Model">传入的对象</param> /// <returns></returns> public static string ParseString(string sTemplateName, object Model = null) { try { string str = service.Run(sTemplateName, null, Model); return(str); } catch (Exception ex) { logger.Info(ex.Message); logger.Fatal(ex); return(string.Empty); } }
/// <summary> /// 渲染数据 /// </summary> /// <param name="key">缓存键</param> /// <param name="template">模板</param> /// <param name="model">数据模型</param> /// <param name="tp">模板类型</param> /// <returns>返回渲染后的字符串</returns> public string Format(string key, string template, object model = null, Type tp = null) { var ret = ""; try { var keyString = key.Replace(Cache.runPath, ""); ITemplateKey km = razor.GetKey(keyString); var bl = razor.IsTemplateCached(km, tp); if (bl) { ret = razor.Run(km, tp, model, ViewBag); } else { ret = razor.RunCompile(template, km, tp, model, ViewBag); } } catch (Exception ex) { Ex = ex.ToString(); } return(ret); }
public RazorTemplateRenderResult Render([NotNull] IDictionary <string, object> settings) { try { var razorModel = new RazorModel(settings); var result = _razorEngineService.Run(_templateKey, null, razorModel); return(new RazorTemplateRenderResult( renderedResult: result, usedTokens: razorModel.AccessedTokens, unrecognisedTokens: razorModel.UnrecognisedTokens, appliedPreferences: razorModel.AppliedPreferences)); } catch (Exception ex) { return(new RazorTemplateRenderResult(error: $"Exception while rendering template: {ex}")); } }
/// <summary> /// Посылает приглашение на регистрацию указанному пользователю /// </summary> /// <param name="model"></param> /// <returns></returns> public ServiceResponce SendInvite(SendInviteModel model) { if (UserRep.CountByCredentails(model.Email, null) != 0) { return(ServiceResponce .FromFailed() .Add("error", "User with Email " + model.Email + " already exist in system")); } InviteCode Invite = SendInviteModelHelper.CreateInviteCode(model); if (InviteRep.Add(Invite)) { // Создаем задачу отправки сообщения в фоне и запускаем ее new Thread(send => { InviteEmailModel InviteEmailModel = InviteEmailModelHelper.GetInviteEmailModel(Invite); string inviteText = TemplateServ .Run("Emails/Invite", typeof(InviteEmailModel), InviteEmailModel); if (!EmailService.SendMail(InviteEmailModel, inviteText)) { StatusService.ChangeStatus(Invite.User, UserStatusType.Invite, null, "Invite Email was not delivered"); } else { StatusService.ChangeStatus(Invite.User, UserStatusType.Invite, null, "Invite Email was delivered"); } InviteRep.Update(Invite); }).Start(); return(ServiceResponce .FromSuccess() .Result("invite for user sended")); } else { return(ServiceResponce .FromFailed() .Add("error", "error saving invited user in DB")); } }
public string GenerateContent(string template, string name, object model) { var result = string.Empty; if (string.IsNullOrEmpty(name)) { Enforce.Throw(new Exception("模板名称不能为空")); } if (_razorEngineService.IsTemplateCached(name, null)) { result = _razorEngineService.Run(name, null, model); } else { if (string.IsNullOrEmpty(template)) { Enforce.Throw(new Exception("模板不能为空")); } result = _razorEngineService.RunCompile(template, name, null, model); } return(result); }
private static string Parse <T>(this IRazorEngineService item, bool shouldRefreshFileInfo, FileInfo fileInfo, T model = null, DynamicViewBag viewBag = null) where T : class { if (shouldRefreshFileInfo) { fileInfo.Refresh(); } // A bit of magic is required with how templates are complied and re-complied due to memory release issues // regarding assemblies - namely assemblies cannot be unloaded within an AppDomain. // // There are a few solutions here but I have opted to use the template file name and last write time as the // template key which pretty much solves the issue for the most part here (there is still technically // memory leaks between template changes but its not significant and edits will only happen when actively // developing). // // Note that when the Application Pool naturally refreshes all memory leaks will be taken care of. var templateKey = fileInfo.Name + fileInfo.LastWriteTimeUtc.ToBinary(); var modelType = typeof(T); return(item.IsTemplateCached(templateKey, modelType) ? item.Run(templateKey, modelType, model, viewBag) : item.RunCompile(File.ReadAllText(fileInfo.FullName), templateKey, modelType, model, viewBag)); }
public string Render(string key, Type modelType, object model) { TemplateState templateState; if (!_TemplateStates.TryGetValue(key, out templateState)) { throw new ApplicationException("Unable to find template in cache"); } var cacheFileInfo = templateState.FileInfo; string templatePath = cacheFileInfo.FullName; var fileInfo = new FileInfo(templatePath); if (!templateState.Compiled || fileInfo.LastWriteTimeUtc > cacheFileInfo.LastWriteTimeUtc) { try { Console.WriteLine("Recompiling {0}", templatePath); string source = File.ReadAllText(templatePath); var templateKey = _Engine.GetKey(key); _TemplateManager.RemoveDynamic(templateKey); _CachingProvider.InvalidateCache(templateKey); _Engine.Compile(source, key); templateState.FileInfo = fileInfo; templateState.Compiled = true; } catch (Exception exception) { templateState.Compiled = false; var errors = GetTemplateErrors(exception, templatePath); string message = string.Join("\n", errors); throw new ApplicationException(message); } } string markup = _Engine.Run(key, modelType, model); return(markup); }
public string GetResult([NotNull] HttpRequestMessage request, [CanBeNull] object model) { var lastWriteTimeUtc = File.GetLastWriteTimeUtc(templatePath); if (cachedLastWriteTimeUtc != lastWriteTimeUtc) { lock (locker) { if (cachedLastWriteTimeUtc != lastWriteTimeUtc) { var template = File.ReadAllText(templatePath); var templateSource = new LoadedTemplateSource(template, templatePath); templateKey = new NameOnlyTemplateKey(templatePath + Guid.NewGuid(), ResolveType.Global, null); razor.AddTemplate(templateKey, templateSource); razor.Compile(templateKey, modelType); cachedLastWriteTimeUtc = lastWriteTimeUtc; } } } var viewBag = new DynamicViewBag(); viewBag.AddValue("__request", request); return(razor.Run(templateKey, modelType, model, viewBag)); }
public override string Render(View view, object model) { return(_razor.Run(view.Hash, view.ModelType.Type, model)); }
/// <summary> /// See <see cref="RazorEngineService.Run"/>. /// Convenience method which creates a <see cref="TextWriter"/> and returns the result as string. /// </summary> /// <param name="service"></param> /// <param name="name"></param> /// <param name="modelType"></param> /// <param name="model"></param> /// <param name="viewBag"></param> /// <returns></returns> public static string Run(this IRazorEngineService service, string name, Type modelType = null, object model = null, DynamicViewBag viewBag = null) { return(WithWriter(writer => service.Run(name, writer, modelType, model, viewBag))); }
/// <summary> /// See <see cref="RazorEngineService.Run"/>. /// </summary> /// <param name="service"></param> /// <param name="name"></param> /// <param name="writer"></param> /// <param name="modelType"></param> /// <param name="model"></param> /// <param name="viewBag"></param> public static void Run(this IRazorEngineService service, string name, TextWriter writer, Type modelType = null, object model = null, DynamicViewBag viewBag = null) { service.Run(service.GetKey(name), writer, modelType, model, viewBag); }
/// <summary> /// Runs the given cached template. /// </summary> /// <param name="key"></param> /// <param name="writer"></param> /// <param name="modelType"></param> /// <param name="model"></param> /// <param name="viewBag"></param> public void Run(ITemplateKey key, System.IO.TextWriter writer, Type modelType = null, object model = null, DynamicViewBag viewBag = null) { _proxy.Run(key, writer, modelType, model, viewBag); }
public void Run(ITemplateKey key, TextWriter writer, Type modelType = null, object model = null, DynamicViewBag viewBag = null) { _razor.Run(key, writer, modelType, model, viewBag); }
/// <summary> /// Send email /// </summary> /// <param name="sender"></param> /// <param name="recipients"></param> /// <param name="subject"></param> /// <param name="templatePlain"></param> /// <param name="templateHtml"></param> /// <param name="model"></param> /// <param name="templateKey"></param> /// <param name="attachments"></param> /// <param name="customHeaders"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public async Task SendEmailAsync <T>(MailAddress sender, MailAddress[] recipients, string subject, string templatePlain, string templateHtml, T model, string templateKey, Attachment[] attachments = null, IDictionary <string, string> customHeaders = null) { if (string.IsNullOrEmpty(sender?.Address)) { throw new ArgumentNullException(nameof(sender)); } if (recipients == null || !recipients.Any()) { throw new ArgumentNullException(nameof(recipients)); } if (string.IsNullOrEmpty(subject)) { throw new ArgumentNullException(nameof(subject)); } if (string.IsNullOrEmpty(templatePlain)) { throw new ArgumentNullException(nameof(templatePlain)); } var modelType = typeof(T); var templateContentPlain = _engineService.IsTemplateCached(templateKey + "Plain", typeof(T)) ? _engineService.Run(templateKey + "Plain", typeof(T), model) : _engineService.RunCompile(templatePlain, templateKey + "Plain", typeof(T), model); var subjectProperty = modelType.GetProperties().SingleOrDefault(p => p.Name.ToLower() == "subject"); if (subjectProperty != null && subjectProperty.PropertyType == typeof(string)) { var sVal = subjectProperty.GetValue(model) as string; if (sVal != null) { subject = sVal; } } var message = new MailMessage { SubjectEncoding = Encoding.UTF8, BodyEncoding = Encoding.UTF8, From = sender, Subject = subject, Body = templateContentPlain, IsBodyHtml = false }; if (customHeaders != null) { foreach (var ch in customHeaders.Where(ch => !message.Headers.AllKeys.Contains(ch.Key))) { message.Headers.Add(ch.Key, ch.Value); } } if (!string.IsNullOrEmpty(templateHtml)) { var templateContentHtml = _engineService.IsTemplateCached(templateKey + "Html", typeof(T)) ? _engineService.Run(templateKey + "Html", typeof(T), model) : _engineService.RunCompile(templateHtml, templateKey + "Html", typeof(T), model); List <LinkedResource> embeddedImages; templateContentHtml = EmbedImages(templateContentHtml, out embeddedImages); var htmlView = AlternateView.CreateAlternateViewFromString(templateContentHtml); htmlView.ContentType = new ContentType("text/html") { CharSet = "utf8" }; foreach (var lr in embeddedImages) { htmlView.LinkedResources.Add(lr); } message.AlternateViews.Add(htmlView); } if (_emailSettings.TestMode) { message.To.Add(_emailSettings.TestRecipient); } else { foreach (var r in recipients) { message.To.Add(r); } } if (attachments != null) { foreach (var att in attachments) { message.Attachments.Add(att); } } if (_emailSettings.SaveCopy && !string.IsNullOrEmpty(_emailSettings.CopyLocation) && Directory.Exists(_emailSettings.CopyLocation)) { var client = new SmtpClient { DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory, PickupDirectoryLocation = _emailSettings.CopyLocation }; client.Send(message); } if (_emailSettings.Enabled) { await _mailProvider.SendAsync(message); } }
public void Run(ITemplateKey key, System.IO.TextWriter writer, Type modelType = null, object model = null, DynamicViewBag viewBag = null) { CheckModelType(modelType); _origin.Run(key, writer, modelType, GetDynamicModel(modelType, model, _allowMissingPropertiesOnDynamic), viewBag); }
/// <summary> /// Runs the template using the specified <paramref name="model"/>. /// </summary> /// <param name="model"></param> /// <param name="textWriter"></param> /// <param name="viewBag"></param> public void Run(TModel model, TextWriter textWriter, DynamicViewBag viewBag = null) { _service.Run(_key, textWriter, typeof(TModel), model, viewBag); }