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));
            }
        }
Beispiel #2
0
 public override void PreCompile(View view)
 {
     if (!_razor.IsTemplateCached(view.Hash, view.ModelType.Type))
     {
         _razor.Compile(view.Source, view.Hash, view.ModelType.Type);
     }
 }
        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 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));
        }
Beispiel #5
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);
        }
Beispiel #6
0
        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);
        }
Beispiel #7
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);
            }
        }
Beispiel #9
0
        public void Init()
        {
            //load file setting with config in header
            RazorTemplate = FileTemplateManager.LoadFileTemplate(_filePath, _fileContent);
            //create config for razor engine
            //http://antaris.github.io/RazorEngine/
            var config = new TemplateServiceConfiguration();

            config.EncodedStringFactory = new RawStringFactory();
            config.BaseTemplateType     = typeof(CustomTemplateBase <>);
            config.TemplateManager      = new DelegateTemplateManager();
            var referenceResolver = new MyIReferenceResolver();

            referenceResolver.DllFolder = RazorTemplate.InputDllFolder;
            config.ReferenceResolver    = referenceResolver;
            _engine      = RazorEngineService.Create(config);
            _templateKey = Engine.Razor.GetKey(MyTemplateKey.MAIN_TEMPLATE);
            //setup viewbag input Folder for render partial
            _viewBag = new DynamicViewBag();
            _viewBag.AddValue("InputFolder", RazorTemplate.InputFolder);
            //check template is compile
            if (!_engine.IsTemplateCached(_templateKey, null))
            {
                //add include template file
                var includeTemplate = new StringBuilder();
                foreach (var filepath in RazorTemplate.ListImportFile)
                {
                    includeTemplate.Append(FileUtils.ReadFileContent(filepath));
                }
                var data = RazorTemplate.TemplateData;
                data            = includeTemplate.ToString() + data;
                _templateSource = new LoadedTemplateSource(data);
                _engine.AddTemplate(_templateKey, _templateSource);
                _engine.Compile(_templateKey, _modeldata.GetType());
            }
        }
Beispiel #10
0
 public bool IsTemplateCached(ITemplateKey key, Type modelType)
 {
     CheckModelType(modelType);
     return(_origin.IsTemplateCached(key, modelType));
 }
        /// <summary>
        /// Checks if a given template is already cached.
        /// </summary>
        /// <param name="service"></param>
        /// <param name="name"></param>
        /// <param name="modelType"></param>
        /// <returns></returns>
        public static bool IsTemplateCached(this IRazorEngineService service, string name, Type modelType)
        {
            var key = service.GetKey(name);

            return(service.IsTemplateCached(key, modelType));
        }
Beispiel #12
0
 public bool IsTemplateCached(ITemplateKey key, Type modelType)
 {
     return(_razor.IsTemplateCached(key, modelType));
 }
Beispiel #13
0
        /// <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);
            }
        }
Beispiel #14
0
 /// <summary>Checks if a given template is already cached.</summary>
 /// <returns></returns>
 public bool IsTemplateCached(ITemplateKey key, Type modelType)
 {
     return(m_engineService.IsTemplateCached(key, modelType));
 }