public string GenerateBody()
    {
        var layout = RazorEngine.RunCompile("_Layout", model: null);
        var body   = RazorEngine.RunCompile(TemplateName, Model.GetType(), Model);

        return(layout.Replace("{{BODY}}", body));
    }
        public string Render(string viewPath)
        {
            var template = _viewFileReader.Read(viewPath);
            var view     = _razorEngine.RunCompile(template, viewPath);

            return(view);
        }
Exemple #3
0
        /// <summary>
        ///     Notifies the user that an observation they submitted has been approved by a moderator.
        /// </summary>
        /// <param name="observation">The observation that has been approved.</param>
        /// <returns>An awaitable Task.</returns>
        public async Task ObservationApproved(Observation observation)
        {
            Log.Info($"Notifying user {observation.UserId} of observation approval for observation ID {observation.Id}");
            var model = new ModerationEmailModel
            {
                ChallengeName  = observation.Challenge.Name,
                Points         = observation.Challenge.Points,
                InformationUrl = HomePage,
                Recipient      = observation.User.Email
            };
            var emailBody = razor.RunCompile("ObservationApproved.cshtml", typeof(ModerationEmailModel), model);
            await userManager.SendEmailAsync(observation.UserId, "Observation approved", emailBody);

            Log.Info($"Successfully notified user {observation.UserId} of observation approval");
        }
Exemple #4
0
        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 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));
        }
Exemple #6
0
        private void GenerateTeams(IRazorEngineService razor)
        {
            var teams = GetTeamInfo(_leagueData);

            using (var writer = new StreamWriter(_root + "teams.htm"))
            {
                razor.RunCompile("team-list", writer, null, teams.OrderBy(t => t.Name).ToList());
            }

            foreach (var team in teams)
            {
                using (var writer = new StreamWriter(_root + team.Filename))
                {
                    razor.RunCompile("team-info", writer, null, team);
                }
            }
        }
Exemple #7
0
 private void GenerateHome(IRazorEngineService razor, List <object> providers)
 {
     using (var writer = new StreamWriter(_root + "index.htm"))
     {
         object model = providers.Select(p => p.GetType()).OrderBy(t => t.Name).ToList();
         razor.RunCompile("home", writer, null, model);
     }
 }
Exemple #8
0
        static void runTemplate(string destFolder, string fileName, string template, object model)
        {
            string path = Path.Combine(destFolder, fileName);

            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                using (StreamWriter writer = new StreamWriter(fs, System.Text.Encoding.UTF8, 1024, true))
                    service.RunCompile(template, writer, model.GetType(), model);
        }
Exemple #9
0
        private Task PrepareAndSendMailAsync <TMessage>(MessageData data, string templateName, string subject) where TMessage : MessageModel
        {
            string template = ReadEmailTemplate(templateName);
            string body     = _engineService.RunCompile(template, templateName, null, data.Model as TMessage);

            AlternateView alternateView = CreateAlternateView(body, data.Model.ContentId);

            return(SendMailAsync(subject, body, data.Destination, alternateView));
        }
        public IPartialMailIIII AndTemplate <T>(string templateFileName, T templateData)
        {
            _templateService.If("_templateService").IsNull.ThenThrow();
            var body = _templateService.RunCompile(templateFileName, null, templateData);

            _mail.Body = body;

            return(this);
        }
        /// <summary>
        /// Renders the view into the given <see cref="TextWriter"/>.
        /// </summary>
        /// <param name="viewContext">Contains the view data model.</param>
        /// <param name="writer">The <see cref="TextWriter"/> used to write the rendered output.</param>
        public async Task RenderAsync(ViewContext viewContext)
        {
            var            writer  = viewContext.Writer;
            DynamicViewBag viewBag = new DynamicViewBag(viewContext.ViewData);
            string         content = "";

            if (razorEngine != null)
            {
                content = razorEngine.RunCompile(template, resourcePath + GetMd5Hash(template), viewContext.ViewData.ModelMetadata.ModelType, viewContext.ViewData.Model, viewBag);
            }
            else
            {
                content = Engine.Razor.RunCompile(template, resourcePath + GetMd5Hash(template), viewContext.ViewData.ModelMetadata.ModelType, viewContext.ViewData.Model, viewBag);
            }
            await writer.WriteAsync(content);

            await writer.FlushAsync();
        }
Exemple #12
0
        /// <summary>
        /// Tries to compile a template, from cache or build from scratch.
        /// </summary>
        /// <param name="template"></param>
        /// <param name="model"></param>
        /// <param name="cache"></param>
        /// <returns></returns>
        public static string Compile(this string template, object model, string cache)
        {
            if (template.IsNullOrEmpty())
            {
                throw new Exception("Template cannot be null or empty.");
            }

            return(_engine.RunCompile(template, cache, null, model)); //Razor.Parse(template, model, cache);
        }
        public string GetMailMessage <T>(T model, string emailTemplateName)
        {
            var templateFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MailTemplates");
            var mailTemplate       = Path.Combine(templateFolderPath, emailTemplateName);
            var template           = File.ReadAllText(mailTemplate);

            var emailHtmlBody = _engineService.RunCompile(template, "Mail", typeof(T), model);

            return(emailHtmlBody);
        }
Exemple #14
0
        private static string Render(Type rootType, string templateName, object model)
        {
            var config = new TemplateServiceConfiguration
            {
                TemplateManager = new EmbeddedResourceTemplateManager(rootType)
            };

            IRazorEngineService service = RazorEngineService.Create(config);

            return(service.RunCompile(templateName, model: model));
        }
        static void Main(string[] args)
        {
            string template = "Hello @Model.Name, welcome to RazorEngine!";
            var    result   = Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });

            Console.WriteLine(result);

            string templateFilePath   = "HelloWorld.cshtml";
            var    templateFile       = File.ReadAllText(templateFilePath);
            string templateFileResult = Engine.Razor.RunCompile(templateFile, Guid.NewGuid().ToString(), null, new
            {
                Name = "World"
            });

            Console.WriteLine(templateFileResult);

            string copyRightTemplatePath = "CopyRightTemplate.cshtml";
            var    copyRightTemplate     = File.ReadAllText(copyRightTemplatePath);
            string copyRightResult       = Engine.Razor.RunCompile(copyRightTemplate, Guid.NewGuid().ToString(), typeof(CopyRightUserInfo), new CopyRightUserInfo
            {
                CreateTime   = DateTime.Now,
                EmailAddress = "*****@*****.**",
                UserName     = "******"
            });

            Console.WriteLine(copyRightResult);

            ITemplateServiceConfiguration configuration = new TemplateServiceConfiguration()
            {
                Language             = Language.CSharp,
                EncodedStringFactory = new RawStringFactory(),
                Debug = true
            };

            configuration.Namespaces.Add("Helpers");

            IRazorEngineService service = RazorEngineService.Create(configuration);

            string template2 = @"Hello @Model.Name, @TextHelper.Decorate(Model.Name)";
            string result2   = service.RunCompile(template2, "templateKey", null, new { Name = "World" });

            Console.WriteLine(result2);

            Engine.Razor = service;

            string template3     = "Hello @Model.Name, welcome to RazorEngine!";
            string templateFile3 = "C:/mytemplate.cshtml";
            var    result3       =
                Engine.Razor.RunCompile(new LoadedTemplateSource(template3, templateFile3), "templateKey3", null, new { Name = "World" });

            Console.WriteLine(result3);

            Console.ReadKey();
        }
 public virtual string CreateEmail <T>(string templateName, T model)
 {
     try
     {
         var key = _service.GetKey(templateName);
         return(_service.RunCompile(key, typeof(T), model));
     }
     finally
     {
         _service.Dispose();
     }
 }
Exemple #17
0
        /// <summary>
        /// 得到模版
        /// </summary>
        /// <param name="metadata"></param>
        /// <param name="codeType"></param>
        /// <returns></returns>
        private string GetTemplateCode(ProjectMetadata metadata, CodeType codeType)
        {
            string template = GetInternalTemplate(codeType);
            var    key      = GetKey(codeType, template);
            ITemplateServiceConfiguration configuration = new TemplateServiceConfiguration()
            {
                Language = Language.CSharp,
                //EncodedStringFactory = new RawStringFactory(),
                Debug = true
            };
            IRazorEngineService service = RazorEngineService.Create(configuration);

            return(service.RunCompile(template, key, metadata.GetType(), metadata));
        }
Exemple #18
0
        public string Render()
        {
            var p = new Dictionary <string, string>();
            var l = new Cfg.Net.Loggers.MemoryLogger();

            // get template
            _context.Debug(() => $"Reading {_template.File}");
            var templateContent = _templateReader.Read(_template.File, p, l);

            if (l.Errors().Any())
            {
                foreach (var error in l.Errors())
                {
                    _context.Error(error);
                }
                return(string.Empty);
            }

            // get parameters (other than process)
            var parameters = new ExpandoObject();

            foreach (var parameter in _template.Parameters)
            {
                ((IDictionary <string, object>)parameters).Add(parameter.Name, parameter.Value);
            }
            if (p.Any())
            {
                foreach (var parameter in p)
                {
                    ((IDictionary <string, object>)parameters)[parameter.Key] = parameter.Value;
                }
            }

            try {
                _context.Debug(() => $"Compiling {_template.Name}.");
                return(_service.RunCompile(templateContent, _template.Name, null, new {
                    _context.Process,
                    Parameters = parameters
                }));
            } catch (TemplateCompilationException ex) {
                _context.Error($"Error parsing template {_template.Name}.");
                _context.Error($"There are {ex.CompilerErrors.Count} errors.");
                foreach (var error in ex.CompilerErrors)
                {
                    _context.Error(error.ErrorText);
                }
                Utility.CodeToError(_context, ex.SourceCode);
                return(string.Empty);
            }
        }
Exemple #19
0
        /// <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);
        }
Exemple #20
0
        public static void Multiple(
            [Required(Description = "Имя Angular модуля")]
            string appModule,
            [Required(Description = "Путь до библиотеки")]
            string dllPath,
            [Required(Description = "Сгенерированный файл сервисов")]
            string outputFile
            )
        {
            //пишем в дебаг параметрах: "DemoModule" "Core.Web.dll" "Services.js"
            //var stream = typeof(Program).Assembly.GetManifestResourceStream("ServiceGenConsole.Templates.NoModel.cshtml");
            //appModule = "DemoModule";
            //dllName = "Core.Web.dll";
            //outputFile = @"c:\Projects\TestT4Template\TestT4Template\Content\Services\Services.js";

            //Подключаем библиотеку
            Assembly.LoadFrom(dllPath);

            //Получаем файл для записи
            FileInfo file = new FileInfo(outputFile);

            var gen   = new AngularWebApiMethodGenerator();
            var model = new AppDomainModel
            {
                AppModule = appModule,
                Data      = gen.GetData()
            };

            var rootType = typeof(Program);
            var template = "Templates.ServiceTemplate";

            var config = new TemplateServiceConfiguration
            {
                TemplateManager = new EmbeddedResourceTemplateManager(rootType),

                //http://antaris.github.io/RazorEngine/#Temporary-files
                CachingProvider = new DefaultCachingProvider(t => { })
            };

            IRazorEngineService service = RazorEngineService.Create(config);

            string result = service.RunCompile(template, model: model);

            using (var sw = new StreamWriter(file.FullName, false, System.Text.Encoding.UTF8))
            {
                sw.Write(result);
            }
        }
Exemple #21
0
        private void GenerateRecords <T>(IRazorEngineService razor, string template, List <object> providers, Func <T, object> modelResolver)
        {
            foreach (var recordProvider in providers.OfType <T>())
            {
                using (var writer = new StreamWriter(_root + recordProvider.GetType().Name + ".htm"))
                {
                    object model = modelResolver(recordProvider);

                    var viewBag = new DynamicViewBag();
                    viewBag.AddValue("Title", TitleAttribute.GetTitleText(recordProvider));
                    viewBag.AddValue("Summary", SummaryAttribute.GetSummaryText(recordProvider));

                    razor.RunCompile(template, writer, null, model, viewBag);
                }
            }
        }
Exemple #22
0
        public void ProcessRequest(HttpContext context)
        {
            var stringBuilder = new StringBuilder();
            var path          = context.Request.PhysicalPath;

            using (var fs = File.Open(path, FileMode.Open))
            {
                using (var sr = new StreamReader(fs))
                {
                    string csjsFile = sr.ReadToEnd();

                    // Compile the .csjs file into javascript using RazorEngine
                    var result = service.RunCompile(csjsFile, csjsFile, null, HttpContext.Current.Request.QueryString);
                    context.Response.Write(result);
                }
            }
        }
Exemple #23
0
        public virtual void SendThresholdCalculationMail(string subjectTemplate, string criteria, int count, Type type, ThresholdSeverity severity, string to)
        {
            var model = new {
                Criteria = criteria,
                Count    = count,
                DataType = CaptionHelper.GetClassCaption(type.FullName),
                Severity = severity
            };
            MailMessage mail = new MailMessage();

            to.Split(';').Each(s => mail.To.Add(s));
            var emailTemplate = _jobDataMap.GetString <SendEmailJobDataMap>(map => map.EmailTemplate);

            mail.Body    = _razorEngineService.RunCompile(emailTemplate, Guid.NewGuid().ToString(), null, model);
            mail.From    = new MailAddress(ConfigurationManager.AppSettings["ThresholdEmailJobFrom"]);
            mail.Subject = subjectTemplate;
            Sender.Send(mail);
        }
Exemple #24
0
            /// <summary>
            /// 编译并执行
            /// </summary>
            /// <param name="name">模板名称</param>
            /// <param name="source">模板提供者</param>
            /// <param name="model">模型</param>
            /// <returns></returns>
            public static string RunCompile(string name, ITemplateSource source, object model)
            {
                if (model == null)
                {
                    throw new ArgumentNullException(nameof(model));
                }

                lock (syncRoot)
                {
                    if (templateNames.Add(name) == true)
                    {
                        razor.AddTemplate(name, source);
                        razor.Compile(name);
                    }
                }

                return(razor.RunCompile(name, model.GetType(), model));
            }
        private async Task SendNotificationEmail(string userId, string email)
        {
            log.Info($"Sending invitation to user {userId}");
            var code = await userManager.GenerateEmailConfirmationTokenAsync(userId);

            var emailModel = new VerificationTokenEmailModel
            {
                CallbackUrl =
                    Url.Action("ConfirmEmail", "UserAdministration", new { userId, code, area = string.Empty }, Request.Url.Scheme),
                InformationUrl    = Url.Action("Index", "Home", new { area = string.Empty }, Request.Url.Scheme),
                VerificationToken = code,
                Recipient         = email
            };
            var emailBody = razor.RunCompile("NewUserInvitation.cshtml", typeof(VerificationTokenEmailModel), emailModel);
            await userManager.SendEmailAsync(userId, "Invitation to Star Quest by Monkton Stargazers", emailBody);

            log.Info($"Successfully sent invitation email to user id {userId}");
        }
Exemple #26
0
        public string Execute(string source)
        {
            var compileSource = string.Format(_compileTemplate, string.IsNullOrWhiteSpace(source) ? "return null;" : source);
            var templateKey   = "Roslyn" + source.GetHashCode().ToString().Replace("-", "_");
            var result        = "";

            try
            {
                result = _service.RunCompile(compileSource, templateKey, null, new { Name = templateKey });
            }
            catch (TemplateCompilationException tcex)
            {
                result = tcex.CompilerErrors.Aggregate(result, (current, error) => current + ("<b>" + error.ErrorNumber + "</b><br />" + error.ErrorText + "<br />"));
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }

            return(result);
        }
        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);
        }
Exemple #28
0
        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));
        }
        /// <summary>
        /// 从给定model生成代码字符串
        /// TODO:里面对模板进行了缓存,为了支持模板文件修改后自动清除缓存,需要实现一个文件内容监视功能
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string Generate()
        {
            ITemplateKey key = _razor.GetKey(this.TemplatePath);

            if (!_razor.IsTemplateCached(key, this.ModelType))         //第一次没缓存
            {
                string template = File.ReadAllText(this.TemplatePath); //读取模板文件内容
                _razor.AddTemplate(key, template);                     //添加模板
            }

            try
            {
                //输出
                using (TextWriter tw = new StringWriter())
                {
                    _razor.RunCompile(key, tw, this.ModelType, this._model, (DynamicViewBag)this.ViewBag); //编译模板得到结果,并缓存
                    return(tw.ToString());
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("{0},模板运行出错", this.TemplatePath), ex);
            }
        }
Exemple #30
0
 public void RunCompile(ITemplateKey key, System.IO.TextWriter writer, Type modelType = null, object model = null, DynamicViewBag viewBag = null)
 {
     CheckModelType(modelType);
     _origin.RunCompile(key, writer, modelType, GetDynamicModel(modelType, model, _allowMissingPropertiesOnDynamic), viewBag);
 }