public GetTemplate ( String name ) : Template | ||
name | String | The file name of the desired template. |
Résultat | Template |
public void ProcessRequest(HttpContext context) { DataBooks book=new DataBooks(); book.name = context.Request["bookname"]; book.type = context.Request["booktype"]; if(book.name!=null) bookcollector.Add(book); context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("msg", ""); vltContext.Put("bookcollector", bookcollector); vltContext.Put("book", book); Template vltTemplate = vltEngine.GetTemplate("Front/ShopingCar.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); }
/// <summary> /// 用data数据填充templateName模板,渲染生成html返回 /// </summary> /// <param name="templateName"></param> /// <param name="data"></param> /// <returns></returns> public static string RenderHtml(string templateName, object data) { //第一步:Creating a VelocityEngine也就是创建一个VelocityEngine的实例 VelocityEngine vltEngine = new VelocityEngine(); //也可以使用带参构造函数直接实例 vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); //vltEngine.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312"); //vltEngine.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312"); //第二步:Creating the Template加载模板文件 //这时通过的是Template类,并使用VelocityEngine的GetTemplate方法加载模板 Template vltTemplate = vltEngine.GetTemplate(templateName); //第三步:Merging the template整合模板 VelocityContext vltContext = new VelocityContext(); vltContext.Put("Data", data);//设置参数,在模板中可以通过$data来引用 //第四步:创建一个IO流来输出模板内容推荐使用StringWriter(因为template中以string形式存放) System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); return html; }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string username = context.Request.Form["username"]; string password = context.Request.Form["password"]; if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password)) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 vltContext.Put("username", ""); vltContext.Put("password", ""); vltContext.Put("msg", ""); Template vltTemplate = vltEngine.GetTemplate("Front/login.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } else { if (dataaccess(username, password)) { context.Session["username"] = username; context.Response.Redirect("Index.ashx"); } else { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 vltContext.Put("username", username); vltContext.Put("password", password); vltContext.Put("msg", "用户名密码错误"); Template vltTemplate = vltEngine.GetTemplate("Front/login.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } } }
public string RenderTemplate(string masterPage, string templateName, IDictionary<string, object> data) { if (string.IsNullOrEmpty(templateName)) { throw new ArgumentException("The \"templateName\" parameter must be specified", "templateName"); } var name = !string.IsNullOrEmpty(masterPage) ? masterPage : templateName; var engine = new VelocityEngine(); var props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, _templatesPath); engine.Init(props); var template = engine.GetTemplate(name); template.Encoding = Encoding.UTF8.BodyName; var context = new VelocityContext(); var templateData = data ?? new Dictionary<string, object>(); foreach (var key in templateData.Keys) { context.Put(key, templateData[key]); } if (!string.IsNullOrEmpty(masterPage)) { context.Put("childContent", templateName); } using (var writer = new StringWriter()) { engine.MergeTemplate(name, context, writer); return writer.GetStringBuilder().ToString(); } }
public static string readerHtml(string path, string name, object data) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath(path));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); vltContext.Put("Data", data);//设置参数,在模板中可以通过$data来引用 Template vltTemplate = vltEngine.GetTemplate(name); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); return vltWriter.GetStringBuilder().ToString(); }
public void Test() { var vlte = new VelocityEngine(); var props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory); vlte.Init(props); var vlc = new VelocityContext(); vlc.Put("test", "test"); var vtp = vlte.GetTemplate("NVelocityTest.vm"); var str = new StringWriter(); vtp.Merge(vlc, str); Console.WriteLine(str.GetStringBuilder().ToString()); }
public void ProcessRequest(HttpContext context) { string searchid= context.Request.Form["searchid"]; string searchtext = context.Request.Form["searchtext"]; dataaccess(searchid, searchtext); if (searchid == "2") { //book context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); vltContext.Put("object", searchtext); string show="<img src='books/"+book.ser+"' width='210' height='150' />"; vltContext.Put("result", show); Template vltTemplate = vltEngine.GetTemplate("Front/Search.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } else if (searchid == "3") { //news context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); vltContext.Put("object", searchtext); vltContext.Put("result", news.news); Template vltTemplate = vltEngine.GetTemplate("Front/Search.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } }
public virtual string FillResponseTemplate(IDictionary<string, object> viewParams) { var engine = new VelocityEngine(); var props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "assembly"); props.AddProperty("assembly.resource.loader.class", "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader, NVelocity"); props.AddProperty("assembly.resource.loader.assembly", GetType().Assembly.FullName); engine.Init(props); var vcontext = new VelocityContext(); foreach (var k in viewParams) { vcontext.Put(k.Key, k.Value); } using (var writer = new StringWriter()) { engine.GetTemplate(ViewName).Merge(vcontext, writer); return writer.GetStringBuilder().ToString(); } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //创建一个模板引擎 VelocityEngine vltEngine = new VelocityEngine(); //文件型模板,还可以是 assembly ,则使用资源文件 vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); //模板存放目录 vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("/template"));//模板文件所在的文件夹 vltEngine.Init(); //定义一个模板上下文 VelocityContext vltContext = new VelocityContext(); //传入模板所需要的参数 vltContext.Put("Title", "标题"); //设置参数,在模板中可以通过$Title来引用 vltContext.Put("Body", "内容"); //设置参数,在模板中可以通过$Body来引用 vltContext.Put("Date", DateTime.Now); //设置参数,在模板中可以通过$Date来引用 //获取我们刚才所定义的模板,上面已设置模板目录 Template vltTemplate = vltEngine.GetTemplate("basic.html"); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); //根据模板的上下文,将模板生成的内容写进刚才定义的字符串输出流中 vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); ////字符串模板源,这里就是你的邮件模板等等的字符串 //const string templateStr = "$Title,$Body,$Date"; ////创建一个模板引擎 //VelocityEngine vltEngine = new VelocityEngine(); ////文件型模板,还可以是 assembly ,则使用资源文件 //vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); //vltEngine.Init(); ////定义一个模板上下文 //VelocityContext vltContext = new VelocityContext(); ////传入模板所需要的参数 //vltContext.Put("Title", "标题"); //设置参数,在模板中可以通过$Title来引用 //vltContext.Put("Body", "内容"); //设置参数,在模板中可以通过$Body来引用 //vltContext.Put("Date", DateTime.Now); //设置参数,在模板中可以通过$Date来引用 ////定义一个字符串输出流 //StringWriter vltWriter = new StringWriter(); ////输出字符串流中的数据 //vltEngine.Evaluate(vltContext, vltWriter, null, templateStr); //context.Response.Write(vltWriter.GetStringBuilder().ToString()); }
/// <summary> /// Generates a report filled with the content supplied by <paramref name="report"/>. /// </summary> /// <param name="report">Specifies the report model.</param> public void Generate(IReport report) { var engine = new VelocityEngine(); var properties = new ExtendedProperties(); properties.AddProperty("resource.loader", "assembly"); properties.AddProperty("resource.manager.class", typeof(ResourceManagerImpl).AssemblyQualifiedName); properties.AddProperty("directive.manager", EncodeExternalAssemblyQualifiedType(typeof(DirectiveManagerProxy))); properties.AddProperty("assembly.resource.loader.class", typeof(AssemblyResourceLoader).AssemblyQualifiedName); properties.AddProperty("assembly.resource.loader.assembly", GetType().Assembly.GetName().Name); engine.Init(properties); var htmlTemplate = engine.GetTemplate("Xunit.Reporting.Internal.Generator.HtmlTemplate.vm"); var generationContext = new VelocityContext(); generationContext.Put("report", report); generationContext.Put("pluralizer", new Pluralizer()); _outputWriter.Write( string.Concat(report.ReflectedAssembly, ".html"), writer => htmlTemplate.Merge(generationContext, writer)); }
public static string GetCodeFileString(HttpServerUtility server, CustomItemInformation info) { VelocityEngine velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); props.SetProperty("file.resource.loader.path", server.MapPath(".")); // The base path for Templates velocity.Init(props); //Template template = velocity.GetTemplate("template.tmp"); NVelocity.Template template = velocity.GetTemplate("CustomItem.vm"); VelocityContext context = new VelocityContext(); context.Put("BaseTemplates", info.BaseTemplates); context.Put("CustomItemFields", info.Fields); context.Put("CustomItemInformation", info); StringWriter writer = new StringWriter(); template.Merge(context, writer); return writer.GetStringBuilder().ToString(); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("msg", ""); dataaccess(); vltContext.Put("NewsPool", NewsPool); vltContext.Put("s", new GotNews()); Template vltTemplate = vltEngine.GetTemplate("Front/News.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); }
/// <summary> /// 通过模版文件路径读取文件内容 /// </summary> /// <param name="path">模版文件路径</param> /// <param name="ht">模版文件的参数</param> /// <returns>StringWriter对象</returns> public static StringWriter GetFileText(string path, Hashtable ht) { if (String.IsNullOrEmpty(path)) { throw new ArgumentNullException("模版文件路径为空!"); } try { string tmpPath = path.Substring(0,path.LastIndexOf(@"\")); string filePath = path.Substring(path.LastIndexOf(@"\")+1); //创建NVelocity引擎的实例对象 VelocityEngine velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, tmpPath); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); velocity.Init(props); //从文件中读取模板 Template temp = velocity.GetTemplate(filePath); IContext context = new VelocityContext(); foreach (string key in ht.Keys) { context.Put(key, ht[key]); } //合并模板 StringWriter writer = new StringWriter(); temp.Merge(context, writer); return writer; } catch (Exception ex) { throw ex; } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); velocityEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("/template")); velocityEngine.Init(); //定义一个模板上下文 VelocityContext velocityContext = new VelocityContext(); //定义类对象 Person p = new Person() { Name = "王三", Age = 20 }; velocityContext.Put("p", p); //定义键值对 Dictionary<string,string> dic=new Dictionary<string, string>(); dic["aa"] = "李四"; dic["bb"] = "30"; velocityContext.Put("dic", dic); //定义list集合 List<string> list=new List<string>(){"张五","马六"}; velocityContext.Put("list", list); //获取定义的模板 Template template = velocityEngine.GetTemplate("baseobject.html"); StringWriter stringWriter = new StringWriter(); template.Merge(velocityContext, stringWriter); string html = stringWriter.GetStringBuilder().ToString(); context.Response.Write(html); }
protected override void InitializeTask(XmlNode taskNode) { base.InitializeTask(taskNode); // Initializes NVelocity velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); velocity.Init(props); template = velocity.GetTemplate(templateFile); // TODO: validate all arguments are present counter = startOrder + 1; }
public override void Configure(DirectoryInfo workingDirectory, NameValueCollection props) { try { File.Delete("nvelocity.log"); } catch (IOException) { // TODO: This is evil! need to investigate further. Cannot get // exclusive lock on the log file with this assembly now a // library (as opposed to an exe). However not convinced that // the line isn't a hangover from java conversion. Need to // investigate further. ; } base.Configure(workingDirectory, props); ExtendedProperties p = new ExtendedProperties(); string templateName = props["template"]; string templateSrc; if (templateName == null) { log.Info("No template file was specified, using default"); p.SetProperty("resource.loader", "class"); p.SetProperty("class.resource.loader.class", "NHibernate.Tool.hbm2net.StringResourceLoader;NHibernate.Tool.hbm2net"); templateSrc = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Tool.hbm2net.convert.vm")). ReadToEnd(); } else { // NH-242 raised issue of where NVelocity looks when supplied with a unpathed file name. Hence // will take responsiblity of explicitly instructing NVelocity where to look. if (!Path.IsPathRooted(templateName)) { templateName = Path.Combine(this.WorkingDirectory.FullName, templateName); } if (!File.Exists(templateName)) { string msg = string.Format("Cannot find template file using absolute path or relative to '{0}'.", this.WorkingDirectory.FullName); throw new IOException(msg); } p.SetProperty("resource.loader", "class"); p.SetProperty("class.resource.loader.class", "NHibernate.Tool.hbm2net.StringResourceLoader;NHibernate.Tool.hbm2net"); using (StreamReader sr = new StreamReader(File.OpenRead(templateName))) { templateSrc = sr.ReadToEnd(); sr.Close(); } } ve = new VelocityEngine(); ve.Init(p); template = ve.GetTemplate(templateSrc); }
public MenuService(Guid uid) { //权限菜单 user = UserService.instance().GetEntityByID(uid); IEnumerable<Role> roles = RoleService.instance().GetEnumByUID(uid); List<Authority> Authoritys = new List<Authority>(); List<Menu> menus = new List<Menu>(); foreach (var item in roles) { Authoritys.AddRange(AuthorityService.instance().GetAuthorityListByRole(item.ID)); } foreach (var item in Authoritys.GroupBy(m => new { m.PID })) { Menu menu = new Menu(); menu.Name = item.First().ParentAuth.Name; menu.Icon = ""; menu.URL = ""; menu.Type = 1; menu.Childs = new List<Menu>(); var xx = item.OrderBy(m => m.Sort); foreach (var auth in xx) { menu.Childs.Add(new Menu() { Name = auth.Name, URL = auth.Description, Icon = "" }); } menus.Add(menu); } //功能菜单 IEnumerable<Class> classs = ClassService.instance().GetChildByID(Guid.Empty, user.CompanyID).OrderBy(m => m.Sort); foreach (var cl in classs) { Menu menu = new Menu(); menu.Name = cl.Title; menu.Type = cl.Type; menu.Childs = new List<Menu>(); menu.ID = cl.ID; if (cl.Ishaschild) { menu.Type = 1; menu.URL = "#"; cl.Childs.Each(m => { menu.Childs.Add(new Menu() { Name = m.Title, Icon = "", Type = m.Type, ID = m.ID }); }); } menus.Add(menu); } VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory); vltEngine.Init(); var vltContext = new VelocityContext(); vltContext.Put("MENU", menus); Template vltTemplate = vltEngine.GetTemplate("_menu.vm"); var vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); this._html = vltWriter.GetStringBuilder().ToString(); }
public void ProcessRequest(HttpContext context) { string login = context.Request.Form["login"]; string register = context.Request.Form["register"]; if (context.Session["username"]==null) { if (!string.IsNullOrEmpty(login)) { context.Response.Redirect("Login.ashx"); } else { if (!string.IsNullOrEmpty(register)) { context.Response.Redirect("Register.ashx"); } context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); string hide = "<div id='start'style='float: right;'><form action='Index.ashx' method='post'><input class='a_demo_four' name='login' type='submit' value='登录'/><input class='a_demo_four' name='register' type='submit' value='注册' /></form></div>"; vltContext.Put("hide", hide); vltContext.Put("show", ""); Template vltTemplate = vltEngine.GetTemplate("Front/Index.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } } else { string quit = context.Request.Form["quit"]; if (string.IsNullOrEmpty(quit)) { context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 //vltContext.Put("username", ""); //vltContext.Put("password", ""); //vltContext.Put("msg", ""); string show = "<div id='start' style='float: right;'><form action='Index.ashx' method='post'><span style='font-size:20px;color:white;background-color:green;'>" + context.Session["username"].ToString() + " 欢迎你!" + "</span><input class='a_demo_four' name='quit' type='submit' value='注销'/></form></div>"; vltContext.Put("show", show); vltContext.Put("hide", ""); Template vltTemplate = vltEngine.GetTemplate("Front/Index.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } else { context.Session.Remove("username"); context.Response.Redirect("Index.ashx"); } } }
//public class MyStringTemplateErrorListener : IStringTemplateErrorListener //{ // public void Error(string msg, Exception e) // { // //throw new NotImplementedException(); // } // public void Warning(string msg) // { // //throw new NotImplementedException(); // } //} public override void Generate(StringBuilder builder) { if (db == null || db.Elements == null || db.Elements.Count == 0) return; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, @"file"); builder.Clear(); // 模板存放目录 vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, @"..\CodeHelper\GenerateUnit\XmlModels"); vltEngine.Init(); // 定义一个模板上下文 VelocityContext vltContext = new VelocityContext(); // 传入模板所需要的参数 //vltContext.Put("Title", "NVelocity 文件模板例子 "); vltContext.Put("model", db); var dict = new Dictionary<string,bool>(); dict.Add("test",true); vltContext.Put("dict", dict); // 获取我们刚才所定义的模板,上面已设置模板目录,此处用相对路径即可 var vltTemplate = vltEngine.GetTemplate("GenSLDomOperClass.gen.cs"); // 定义一个字符串输出流 StringWriter vltWriter = new StringWriter(); // 根据模板的上下文,将模板生成的内容写进刚才定义的字符串输出流中 vltTemplate.Merge(vltContext, vltWriter); // 输出字符串流中的数据 var rr = vltWriter.GetStringBuilder().ToString(); builder.Append(rr); base.Generate(builder); // return; // //var g = new Antlr4.StringTemplate.TemplateGroup(); // //g = Antlr4.StringTemplate.TemplateGroup.DefaultGroup; // ////g.LoadGroupFile(@"..\CodeHelper\GenerateUnit\XmlModels", "GenDomOperClass"); // ////g.LoadGroupFile(@"", @"..\CodeHelper\GenerateUnit\XmlModels\GenDomOperClass"); // ////g.LoadGroupFile(@"D:\workspace\CodeHelper\CodeHelper\GenerateUnit\XmlModels\", @"GenDomOperClass.stg"); // //g.LoadGroupFile("", @"/D:\workspace\CodeHelper\CodeHelper\GenerateUnit\XmlModels\GenDomOperClass.stg"); // //Uri uri = new Uri(@"D:\workspace\CodeHelper\CodeHelper\GenerateUnit\XmlModels\GenDomOperClass.stg"); // var g = new TemplateGroupString(File.ReadAllText(@"D:\workspace\CodeHelper\CodeHelper\GenerateUnit\XmlModels\GenDomOperClass.stg")); // //var g = StringTemplateGroup.LoadGroup(@"..\CodeHelper\GenerateUnit\XmlModels\GenDomOperClass"); // //g.ErrorListener = new MyStringTemplateErrorListener(); // //g..RefreshInterval = new TimeSpan(1000); // builder.Clear(); // var f = db.Elements.ElementAt(0).Fields[0]; // //var gen = g.GetInstanceOf("gen"); // //gen.SetAttribute("model", db); // var gen = g.GetInstanceOf("gen"); // gen.Add("model", db); // var duck = new Duck(); // gen.Add("duck", duck); // //gen.Add("usings", db.UsingNameSpaces); // var r2 = gen.Render(); // builder.Append(r2); // base.Generate(builder); // return; // builder.AppendLine(@"using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; //using CodeHelper.Xml.Core.Nodes; //using System.Xml;"); // var builderUtil = new GeneratorUtil(builder, 0); // builderUtil.AppendLine(); // foreach (var el in db.Elements) // { // Build(el, builderUtil); // builderUtil.AppendLine(); // } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string register = context.Request.Form["register"]; if (string.IsNullOrEmpty(register)) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 vltContext.Put("error", ""); Template vltTemplate = vltEngine.GetTemplate("Front/register.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } else { //先判断用户名是否重复! if (dataaccess(context.Request.Form["username"])) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 vltContext.Put("error", "用户名已被注册!"); Template vltTemplate = vltEngine.GetTemplate("Front/register.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } else { //这边把数据放到数据库里了! if (datawrite(context.Request.Form["username"], context.Request.Form["password"], context.Request.Form["age"], context.Request.Form["colleage"], context.Request.Form["major"], context.Request.Form["city"], context.Request.Form["pointx"], context.Request.Form["pointy"])) { context.Session["username"] = context.Request.Form["username"]; context.Response.Redirect("Index.ashx"); } else { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 vltContext.Put("error", "服务器出现错误,请重新注册!"); Template vltTemplate = vltEngine.GetTemplate("Front/register.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } } } }
protected void Page_Load(object sender, EventArgs e) { if (this.Session["User"] != null) { UserModel model = (UserModel)this.Session["User"]; string isHasBaby = model.Company.IsHasBaby; string isJGBM = model.Branch.IsJGBM; VelocityEngine engine = new VelocityEngine(); ExtendedProperties p = new ExtendedProperties(); p.AddProperty("file.resource.loader.path", base.Server.MapPath("Templete")); p.SetProperty("input.encoding", "utf-8"); p.SetProperty("output.encoding", "utf-8"); engine.Init(p); Template template = engine.GetTemplate("0.vm", "utf-8"); DataTable table = null; string str3 = "0"; string str4 = ""; string sQLString = ""; string str6 = ""; if (base.Request.Params["yl"] != null) { string str7 = base.Server.UrlDecode(base.Request.Params["pk"]).Replace("'", ""); str6 = DbHelperOra.GetSingle("select t.systemusername from DB_CONFIGURATION t").ToString(); TB_QUOTA_Model model2 = new TB_QUOTA_Bll().GetModel(base.Request.Params["pk"]); if (base.Request.Params["yl"] == "1") { sQLString = "select * from v_mes_gs where pd_quota_code in (" + str7 + ")"; if (model2.PD_QUOTA_IFPASS != "1") { str4 = "此指标没有传递,不能打印“业务股室告知乡财”告知书"; } else { template = engine.GetTemplate("1.vm", "utf-8"); } } else if (base.Request.Params["yl"] == "2") { sQLString = "select * from v_mes_gs_2 where pd_quota_code in (" + str7 + ")"; string str8 = ((UserModel)this.Session["User"]).Company.pk_corp; if (str8.Trim() != model2.PD_QUOTA_INPUT_COMPANY.Trim()) { sQLString = sQLString + " and COMPANY_CODE='" + str8 + "'"; } if (model2.PD_QUOTA_ISUP != "1") { str4 = "此指标没有下发,不能打印“乡财告知乡镇”告知书"; } else { template = engine.GetTemplate("2.vm", "utf-8"); } } else if (base.Request.Params["yl"] == "3") { string name = "3.vm"; if (DbHelperOra.Exists("select count(*) from tb_quota where pd_quota_code in (" + str7 + ") and PD_QUOTA_ZJXZ='01'")) { sQLString = "select * from v_mes_gs_4 where pd_quota_code in (" + str7 + ")"; name = "4.vm"; } else { sQLString = "select * from v_mes_gs_3 where pd_quota_code in (" + str7 + ")"; } SMZJ.BLL.TB_QUOTA_DETAIL tb_quota_detail = new SMZJ.BLL.TB_QUOTA_DETAIL(); string strWhere = " PD_QUOTA_CODE='" + base.Request.Params["pk"] + "' and IF_SHOW=1 "; string str11 = ((UserModel)this.Session["User"]).Company.pk_corp; if (str11.Trim() != model2.PD_QUOTA_INPUT_COMPANY.Trim()) { strWhere = strWhere + " and COMPANY_CODE='" + str11 + "'"; sQLString = sQLString + " and COMPANY_CODE='" + str11 + "'"; } DataSet list = tb_quota_detail.GetList(strWhere); if ((list.Tables[0].Rows[0]["ishuizhi"].ToString().Trim() != "是") && (list.Tables[0].Rows[0]["ishuizhi"].ToString().Trim() != "1")) { str4 = "此指标没有回执,不能打印“乡镇回执乡财”告知书"; } else { template = engine.GetTemplate(name, "utf-8"); } } else { str4 = "内部错误,请重新登录"; } if (str4 == "") { table = DbHelperOra.Query(sQLString).Tables[0]; str3 = "1"; } } VelocityContext context = new VelocityContext(); context.Put("XiangZhen", str6); context.Put("xzs", table); context.Put("isnew", str3); context.Put("isHasBaby", isHasBaby.Trim()); context.Put("IsJGBM", isJGBM.Trim()); context.Put("DataPK", base.Request.Params["pk"]); context.Put("PrintTxt", str4); context.Put("rc", ((table == null) || (table.Rows.Count == 0)) ? "0" : table.Rows.Count.ToString()); template.Merge(context, base.Response.Output); } }
public void Apply(IEnumerable<ChangeScript> changeScripts, bool createChangeLogTable) { string filename = this.syntax.GetTemplateFileNameFor(this.GetTemplateQualifier()); var model = new Hashtable(); model.Add("scripts", changeScripts); model.Add("changeLogTableName", this.changeLogTableName); model.Add("delimiter", this.delimiter); model.Add("separator", this.delimiterType is RowDelimiter ? Environment.NewLine : string.Empty); try { ExtendedProperties props = new ExtendedProperties(); var assemblyName = this.GetType().Assembly.GetName().Name; ReplaceManagersWithDbDeployVersions(props, assemblyName); if (this.templateDirectory == null) { props.AddProperty("resource.loader", "assembly"); props.AddProperty("assembly.resource.loader.class", // See the ; there? It will be replaced by , in the resource loader factory // this is because if we add a property with a comma in the value, it will add *two* values to the property. // oh joy. typeof (DbDeployAssemblyResourceLoader).FullName + "; " + assemblyName); props.AddProperty("assembly.resource.loader.assembly", assemblyName); filename = "Net.Sf.Dbdeploy.Resources." + filename; } else { props.SetProperty("file.resource.loader.path", this.templateDirectory.FullName); } if (createChangeLogTable) { this.writer.Write(this.syntax.CreateChangeLogTableSqlScript(this.changeLogTableName)); } var templateEngine = new VelocityEngine(props); var context = new VelocityContext(model); Template template = templateEngine.GetTemplate(filename); template.Merge(context, this.writer); } catch (ResourceNotFoundException ex) { string locationMessage; if (templateDirectory == null) { locationMessage = ""; } else { locationMessage = " at " + templateDirectory.FullName; } throw new UsageException( "Could not find template named " + filename + locationMessage + Environment.NewLine + "Check that you have got the name of the database syntax correct.", ex); } }
/// <summary> /// ��ȡ����ģ�����ɵ�ҳ�� /// </summary> /// <param name="fileName">�ļ���</param> /// <param name="vltContext">ģ�����</param> /// <returns></returns> public string GetTemplateString(string fileName, VelocityContext vltContext) { VelocityEngine vltEngine = new VelocityEngine(); // �ļ���ģ��, �������� "assembly", ��ʹ����Դ�ļ� vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); // ģ����Ŀ¼ vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Server.MapPath("~/webim/")); vltEngine.Init(); // ����������ģ��Ŀ¼, �˴������·������. Template vltTemplate = vltEngine.GetTemplate(fileName); StringWriter vltWriter = new StringWriter(); vltTemplate.Merge(vltContext, vltWriter); return vltWriter.GetStringBuilder().ToString(); }
public void Test_Example1() { String templateFile = "example1.vm"; try { /* * setup */ VelocityEngine ve = new VelocityEngine(); ExtendedProperties ep = new ExtendedProperties(); ep.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); ve.Init(ep); /* * Make a context object and populate with the data. This * is where the Velocity engine gets the data to resolve the * references (ex. $list) in the template */ VelocityContext context = new VelocityContext(); context.Put("list", GetNames()); ExtendedProperties props = new ExtendedProperties(); props.Add("runtime.log", "nvelocity.log"); context.Put("props", props); /* * get the Template object. This is the parsed version of your * template input file. Note that getTemplate() can throw * ResourceNotFoundException : if it doesn't find the template * ParseErrorException : if there is something wrong with the VTL * Exception : if something else goes wrong (this is generally * indicative of as serious problem...) */ Template template = null; try { template = ve.GetTemplate(templateFile); } catch (ResourceNotFoundException rnfe) { Console.Out.WriteLine("Example : error : cannot find template " + templateFile + " : \n" + rnfe.Message); Assert.Fail(); } catch (ParseErrorException pee) { Console.Out.WriteLine("Example : Syntax error in template " + templateFile + " : \n" + pee); Assert.Fail(); } /* * Now have the template engine process your template using the * data placed into the context. Think of it as a 'merge' * of the template and the data to produce the output stream. */ // using Console.Out will send it to the screen TextWriter writer = new StringWriter(); if (template != null) template.Merge(context, writer); /* * flush and cleanup */ writer.Flush(); writer.Close(); } catch (Exception ex) { Assert.Fail(ex.Message); } }
private Template GetTemplate(VelocityEngine engine, string templateName) { return engine.GetTemplate(templateName + ".vm"); }
protected void forwardSend_Click(object sender, EventArgs e) { SortedList noPrivilegeList = new SortedList(); SortedList noEmailAddressList = new SortedList(); SortedList wrongEmailAddressList = new SortedList(); ArrayList allExternalUsers = new ArrayList(); ISubjectFetchProvider subjectProvider = (new SubjectProviderFactory()).GetSubjectFetchProvider(); ArrayList userList = new ArrayList(); IList users = new ArrayList(); const string MatchEmailPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$"; try { StringBuilder mailtoUsers = new StringBuilder(); MailToUser[] jsonObjectArray = WebUtility.DeserializeAjaxResult("[" + hideMailto.Value + "]", typeof(MailToUser[])) as MailToUser[]; String[] externalUsers = this.txtMailto.Value.Trim().Split(';'); //外部收件者 foreach (string emailAddress in externalUsers) { if (externalUsers.Length==0) { break; } string address = emailAddress.Trim(); if (address.Length == 0) { noEmailAddressList.Add(address, address); } else { if (Regex.IsMatch(address, MatchEmailPattern)) { if (allExternalUsers.BinarySearch(address) < 0) { allExternalUsers.Add(address); } } else { wrongEmailAddressList.Add(address, address); } } } foreach (MailToUser mailtoUser in jsonObjectArray) { users.Clear(); switch (Convert.ToInt32(mailtoUser.SubjectType)) { case 0: if (!string.IsNullOrEmpty(mailtoUser.EmailAddress)) { if (Regex.IsMatch(mailtoUser.EmailAddress, MatchEmailPattern)) { userList.Add(mailtoUser); } else { wrongEmailAddressList.Add(mailtoUser.SubjectId, mailtoUser.DisplayName); } } else { noEmailAddressList.Add(mailtoUser.SubjectId, mailtoUser.DisplayName); } break; case 1: users = subjectProvider.GetUsersInOU(mailtoUser.SubjectId); break; case 2: users = subjectProvider.GetUsersInGroup(mailtoUser.SubjectId); break; case 3: users = subjectProvider.GetUsersInRole(mailtoUser.SubjectId); break; default: break; } if (users != null && users.Count > 0) { foreach (User user in users) { if (!string.IsNullOrEmpty(user.EmailAddress)) { if (Regex.IsMatch(user.EmailAddress, MatchEmailPattern)) { userList.Add(ConvertUserToMailToUser(user)); } else { wrongEmailAddressList.Add(user.SubjectId, user.DisplayName); } } else { noEmailAddressList.Add(mailtoUser.SubjectId, mailtoUser.DisplayName); } } } } ArrayList uniList = new ArrayList(); if (userList.Count > 0) { int i; MailToUser preUser = (MailToUser)userList[0]; uniList.Add(preUser); ComparerUtility comp = new ComparerUtility(); comp.ObjectType = (typeof(MailToUser)); comp.SortingOrder = (int)ComparerUtility.SortOrder.Ascending; comp.SortProperty = "SubjectId"; MailToUser[] userAry = userList.ToArray(typeof(MailToUser)) as MailToUser[]; Array.Sort(userAry, comp); //移除重複的,因為上面有先做過排序 for (i = 1; i < userAry.Length; i++) { if (preUser.SubjectId != ((MailToUser)userAry[i]).SubjectId) { preUser = (MailToUser)userAry[i]; uniList.Add(preUser); } } } foreach (MailToUser mailtoUser in uniList) { if (!allowSendToNoPrivilegeUser) { KBUserDetailInfo checkkbuser; checkkbuser = kbuserService.GetKBUserDetailBySubjectId(mailtoUser.SubjectId); if (PrivilegeUtility.HasPrivilege(PrivilegeType.DocumentPrivilege, docId, checkkbuser, DocumentOperationAttributes.DOC_READ_DOCUMENT)) { mailtoUsers.Append(mailtoUser.DisplayName).Append("<").Append(mailtoUser.EmailAddress).Append(">;"); } else { noPrivilegeList.Add(mailtoUser.SubjectId, mailtoUser.DisplayName); } } else { mailtoUsers.Append(mailtoUser.DisplayName).Append("<").Append(mailtoUser.EmailAddress).Append(">;"); } } string mailto = mailtoUsers.ToString(); if (allowSendToNoPrivilegeUser) { if (allExternalUsers.Count>0) { mailto += string.Join(";", ((string[])allExternalUsers.ToArray(typeof(string)))); } } //如果最後還是有 email 要寄送的話 if (mailto.Length > 0) { string subject = "[" + i18n.GetMessage("m858") + "] " + this.txtSubject.Value; string message = this.txtAreaBody.Value.Replace(" ", " ").Replace("\r\n", "<br />"); string mailCC = string.Empty; string mailBCC = string.Empty; if (sendToMe.Checked) { if (!string.IsNullOrEmpty(currentUser.EmailAddress)) { if (Regex.IsMatch(currentUser.EmailAddress, MatchEmailPattern)) { mailCC = currentUser.DisplayName + "<" + currentUser.EmailAddress + ">"; } else { wrongEmailAddressList.Add(currentUser.SubjectId, currentUser.DisplayName); } } else { noEmailAddressList.Add(currentUser.SubjectId, currentUser.DisplayName); } } //建立樣本引擎實體 VelocityEngine velocity = new VelocityEngine(); //設定引擎的一些屬性 ExtendedProperties props = new ExtendedProperties(); //設定樣版被載入的來源位置 props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); ArrayList resourceLocators = new ArrayList(); resourceLocators.Add("."); resourceLocators.Add(System.Configuration.ConfigurationManager.AppSettings["TemplatePath"]); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resourceLocators); //設定讀寫樣版的 Encoding props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); //將設定的屬性塞給引擎 velocity.Init(props); Template detailTemplate = velocity.GetTemplate(System.Configuration.ConfigurationManager.AppSettings["DocumentDetailTemplateFileName"]); Template masterTemplate = velocity.GetTemplate(System.Configuration.ConfigurationManager.AppSettings["ForwardMasterTemplateFileName"]); VelocityContext context = new VelocityContext(); StringWriter detailWriter = new StringWriter(); StringWriter masterWriter = new StringWriter(); string Attachs = string.Empty; ArrayList list = new ArrayList(); string photoPath = System.Configuration.ConfigurationManager.AppSettings["photoPath"]; KBUserInfo kbuser = GetKBUser(doc.VersionCreatorId); string personalPhotoFilenName = kbuser.AvatarPath; if (personalPhotoFilenName == null || personalPhotoFilenName.Trim().Length == 0) { personalPhotoFilenName = "default.jpg"; } string uppath = Server.MapPath(Request.ApplicationPath + photoPath + personalPhotoFilenName); context.Put("UserImage", kbuser.AvatarPath); Attachs = uppath; string folderPath = string.Empty; FolderInfo[] fiArray = folderService.GetFolderPath(currentUser, documentService.GetParentFolders(currentUser, doc.DocumentId)[0].FolderId); for (int i = 0; i < fiArray.Length; i++) { if (!fiArray[i].DisplayName.Equals(GSS.Vitals.KnowledgeBase.SpecialFolder.ROOT_FOLDER)) { if (fiArray[i].DisplayName.Equals(GSS.Vitals.KnowledgeBase.SpecialFolder.PUBLIC_FOLDER)) { folderPath += i18n.GetMessage("m82"); } else { folderPath += fiArray[i].DisplayName; } if (i < fiArray.Length - 1) { folderPath += " / "; } } } context.Put("Author", kbuser.DisplayName.Trim()); context.Put("Modify", i18n.GetMessage("m152")); //修改於 TimeSpan ts2 = WebUtility.GetCurrentUserUTCOffset(currentUser); DateTime dt2 = doc.VersionCreationDatetime.Add(ts2); context.Put("ModifyDateTime", dt2.ToString()); context.Put("DocumentClass", i18n.GetMessage("m273")); context.Put("DocumentClassName", doc.DocumentClass.ClassName.Trim()); context.Put("FolderPath", folderPath); context.Put("Link", System.Configuration.ConfigurationManager.AppSettings["lambdaSite"] + "readdocument.aspx?documentid=" + doc.DocumentId); context.Put("VersionTitle", doc.VersionTitle.Trim()); //render 文件欄位 for (int i = 0; i < doc.DocumentAttributes.Length; i++) { if (doc.DocumentAttributes[i].AttributeType != GSS.Vitals.KnowledgeBase.AttributeType.TITLE) { if (doc.DocumentAttributes[i].Value != string.Empty) { GSS.Vitals.KnowledgeBase.UIField.FieldType ft = GSS.Vitals.KnowledgeBase.UIField.ParseUIFieldType(doc.DocumentAttributes[i].UIFieldInfo); if (ft == GSS.Vitals.KnowledgeBase.UIField.FieldType.CALENDAR) { DateTime dt = KBUtility.ParseISO8601SimpleString(doc.DocumentAttributes[i].Value); dt = dt.Add(WebUtility.GetCurrentUserUTCOffset(currentUser)); list.Add(new InfoItem(doc.DocumentAttributes[i].DisplayName, dt.ToString("yyyy/MM/dd"))); } else if (ft == GSS.Vitals.KnowledgeBase.UIField.FieldType.DATETIME) { DateTime dt = KBUtility.ParseISO8601SimpleString(doc.DocumentAttributes[i].Value); dt = dt.Add(WebUtility.GetCurrentUserUTCOffset(currentUser)); list.Add(new InfoItem(doc.DocumentAttributes[i].DisplayName, dt.ToString("yyyy/MM/dd HH:mm:ss"))); } else if (ft == GSS.Vitals.KnowledgeBase.UIField.FieldType.RICHTEXT) { list.Add(new InfoItem(doc.DocumentAttributes[i].DisplayName, doc.DocumentAttributes[i].Value)); } else { list.Add(new InfoItem(doc.DocumentAttributes[i].DisplayName, WebUtility.crlf2br(doc.DocumentAttributes[i].Value))); } } } } context.Put("Items", list); detailTemplate.Merge(context, detailWriter); //將Detail加入到master當中 context.Put("DocSections", detailWriter.GetStringBuilder().ToString()); string header = String.Format(i18n.GetMessage("m862"), currentUser.DisplayName, "<a href='" + System.Configuration.ConfigurationManager.AppSettings["lambdaSite"] + "'>" + System.Configuration.ConfigurationManager.AppSettings["SystemName"] + "</a>"); context.Put("Header", header); context.Put("Message", i18n.GetMessage("m863") + ":<br/><br/>" + message); masterTemplate.Merge(context, masterWriter); mailService.SendMail(mailService.FromMailAddress, mailto, mailBCC, mailCC, subject, masterWriter.GetStringBuilder().ToString(), Attachs); forwardService.SetForwardRecord((KBUserInfo)currentUser, mailto, mailCC, subject, masterWriter.GetStringBuilder().ToString(), message); this.txtMailto.Value = string.Empty; this.txtAreaBody.Value = string.Empty; this.sendToMe.Checked = false; } if (noEmailAddressList.Count > 0 || wrongEmailAddressList.Count > 0 || noPrivilegeList.Count > 0) { Table a = makeTable(noPrivilegeList, i18n.GetMessage("m478")); Table b = makeTable(noEmailAddressList, i18n.GetMessage("m926")); Table c = makeTable(wrongEmailAddressList, i18n.GetMessage("m927")); renderForwardResult(new Table[] { a, b, c }); } else { forwardResultPanel.Visible = false; } } catch (Exception ex) { log4net.LogManager.GetLogger("MAIL").Error(ex.Message, ex); renderForwardResult(ex); } }