/// <summary> /// This test starts a VelocityEngine for each execution /// </summary> public void ExecuteMethodUntilSignal1() { startEvent.WaitOne(int.MaxValue, false); while(!stopEvent.WaitOne(0, false)) { VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); StringWriter sw = new StringWriter(); VelocityContext c = new VelocityContext(); c.Put("x", new Something()); c.Put("items", items); bool ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", @" #foreach( $item in $items ) $item, #end "); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("a,b,c,d,", Normalize(sw)); } }
public void SetUp() { ve = new VelocityEngine(); ve.Init(); ctx = new VelocityContext(); }
public void ForEachSimpleCase() { ArrayList items = new ArrayList(); items.Add("a"); items.Add("b"); items.Add("c"); VelocityContext c = new VelocityContext(); c.Put("x", new Something2()); c.Put("items", items); c.Put("d1", new DateTime(2005, 7, 16)); c.Put("d2", new DateTime(2005, 7, 17)); c.Put("d3", new DateTime(2005, 7, 18)); StringWriter sw = new StringWriter(); VelocityEngine ve = new VelocityEngine(); ve.Init(); Boolean ok = false; ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "#foreach( $item in $items )\r\n" + "#if($item == \"a\")\r\n $x.FormatDate( $d1 )#end\r\n" + "#if($item == \"b\")\r\n $x.FormatDate( $d2 )#end\r\n" + "#if($item == \"c\")\r\n $x.FormatDate( $d3 )#end\r\n" + "#end\r\n"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual(" 16 17 18", sw.ToString()); }
public void Test() { var velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); velocityEngine.Init(extendedProperties); VelocityContext context = new VelocityContext(); context.Put("yada", "line"); Template template = velocityEngine.GetTemplate( GetFileName(null, "nv37", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); #pragma warning disable 612,618 velocityEngine.MergeTemplate("nv37.vm", context, writer); #pragma warning restore 612,618 //template.Merge(context, writer); Console.WriteLine(writer); }
public void Setup() { context = new VelocityContext(); ve = new VelocityEngine(); ve.Init(); }
public void Setup() { items = new ArrayList(); items.Add("a"); items.Add("b"); items.Add("c"); items.Add("d"); velocityEngine = new VelocityEngine(); velocityEngine.Init(); }
public void DoesNotGiveNullReferenceExceptionWhenAmbiguousMatchBecauseOfNullArg() { VelocityEngine engine = new VelocityEngine(); engine.Init(); VelocityContext ctx = new VelocityContext(); ctx.Put("test", new TestClass()); ctx.Put("nullObj", null); StringWriter writer = new StringWriter(); Assert.IsTrue(engine.Evaluate(ctx, writer, "testEval", "$test.DoSomething($nullObj)")); Assert.AreEqual("$test.DoSomething($nullObj)", writer.GetStringBuilder().ToString()); }
public void SetUp() { engine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true"); engine.Init(extendedProperties); context = new VelocityContext(); }
public void Setup() { velocityEngine = new VelocityEngine(); velocityEngine.Init(); // creates the context... velocityContext = new VelocityContext(); // attach a new event cartridge velocityContext.AttachEventCartridge(new EventCartridge()); // add our custom handler to the ReferenceInsertion event velocityContext.EventCartridge.ReferenceInsertion += EventCartridge_ReferenceInsertion; }
/// <summary> /// Render nVelocity template to HTML /// </summary> /// <param name="output">Output text writer</param> public override void Render(TextWriter output) { // .Replace(',', ';') нужен за внутренними надобнастями NVelocity // Внутри библиотеки символы меняются обратно. // Проблема связана с форматом представления массивов векторов и строк. String loader_class_name = typeof(CustomResourceLoader).AssemblyQualifiedName.Replace(',', ';'); VelocityEngine velocity = new VelocityEngine(); velocity.AddProperty(RuntimeConstants.RESOURCE_LOADER, "webcore"); velocity.AddProperty("webcore.resource.loader.class", loader_class_name); velocity.AddProperty("webcore.resource.loader.domain", DomainName); velocity.Init(); Template tpl = velocity.GetTemplate(ViewName); tpl.Merge(this.items, output); }
public void ParamArraySupport1() { VelocityContext c = new VelocityContext(); c.Put("x", new Something()); StringWriter sw = new StringWriter(); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); Boolean ok = false; ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Print( \"aaa\" )"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("aaa", sw.ToString()); sw = new StringWriter(); ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents()"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual(string.Empty, sw.ToString()); sw = new StringWriter(); ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents( \"x\" )"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("x", sw.ToString()); sw = new StringWriter(); ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents( \"x\", \"y\" )"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("x,y", sw.ToString()); }
public void DuplicateMethodNames() { StringWriter sw = new StringWriter(); VelocityContext c = new VelocityContext(); c.Put("model", new ModelClass()); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); bool ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$model.DoSome('y') $model.DoSome(2) "); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("x:y 4 ", sw.ToString()); }
public void Test() { var velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); velocityEngine.Init(extendedProperties); VelocityContext context = new VelocityContext(); Template template = velocityEngine.GetTemplate( GetFileName(null, "nv09", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); template.Merge(context, writer); }
public void Setup() { items = new ArrayList(); items.Add("a"); items.Add("b"); items.Add("c"); items.Add("d"); c = new VelocityContext(); c.Put("x", new Something()); c.Put("items", items); sw = new StringWriter(); velocityEngine = new VelocityEngine(); velocityEngine.Init(); template = @" #foreach( $item in $items ) #before ( #each $item #after ) #between , #odd + #even - #nodata nothing #beforeall < #afterall > #end "; }
protected void SetUp() { velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true"); extendedProperties.SetProperty("userdirective", "NVelocity.Runtime.Directive.Component;NVelocity,NVelocity.Runtime.Directive.BlockComponent;NVelocity"); velocityEngine.Init(extendedProperties); testProperties = new ExtendedProperties(); testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read)); }
public void CaseInsensitive() { // normal case sensitive context VelocityContext c = new VelocityContext(); c.Put("firstName", "Cort"); c.Put("LastName", "Schaefer"); // verify the output, $lastName should not be resolved StringWriter sw = new StringWriter(); VelocityEngine ve = new VelocityEngine(); ve.Init(); Boolean ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "Hello $firstName $lastName"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("Hello Cort $lastName", sw.ToString()); // create a context based on a case insensitive hashtable Hashtable ht = new Hashtable(StringComparer.CurrentCultureIgnoreCase); ht.Add("firstName", "Cort"); ht.Add("LastName", "Schaefer"); c = new VelocityContext(ht); // verify the output, $lastName should be resolved sw = new StringWriter(); ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "Hello $firstName $lastName"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("Hello Cort Schaefer", sw.ToString()); // create a context based on a case insensitive hashtable, verify that stuff added to the context after it is created if found case insensitive ht = new Hashtable(StringComparer.CurrentCultureIgnoreCase); ht.Add("firstName", "Cort"); c = new VelocityContext(ht); c.Put("LastName", "Schaefer"); // verify the output, $lastName should be resolved sw = new StringWriter(); ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "Hello $firstName $lastName"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("Hello Cort Schaefer", sw.ToString()); }
public void DecimalToString() { StringWriter sw = new StringWriter(); VelocityContext c = new VelocityContext(); c.Put("x", (decimal) 1.2); c.Put("model", new ModelClass()); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); bool ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$model.Amount.ToString() \r\n" + "$model.Amount.ToString('#0.00') \r\n" + "$x.ToString() \r\n" + "$x.ToString('#0.00') \r\n"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("1.2 \r\n1.20 \r\n1.2 \r\n1.20 \r\n", sw.ToString()); }
public void ParamArraySupport2() { VelocityContext c = new VelocityContext(); c.Put("x", new Something2()); StringWriter sw = new StringWriter(); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); Boolean ok = false; ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents( \"hammett\", 1 )"); Assert.True(ok, "Evaluation returned failure"); Assert.Equal("hammett1", sw.ToString()); sw = new StringWriter(); ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents( \"hammett\", 1, \"x\" )"); Assert.True(ok, "Evaluation returned failure"); Assert.Equal("hammett1x", sw.ToString()); sw = new StringWriter(); ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents( \"hammett\", 1, \"x\", \"y\" )"); Assert.True(ok, "Evaluation returned failure"); Assert.Equal("hammett1x,y", sw.ToString()); }
/// <summary> /// 构造函数 初始话NVelocity模块 /// </summary> /// <param name="tmplDir">模板文件夹路径</param> public VelocityHelper(string tmplDir) { //创建VelocityEngine实例对象 velocity = new VelocityEngine(); //使用设置初始化VelocityEngine ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(tmplDir)); //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.GetDirectoryName(HttpContext.Current.Request.PhysicalPath)); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); //模板的缓存设置 props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true); //是否缓存 props.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)30); //缓存时间(秒) velocity.Init(props); //为模板变量赋值 context = new VelocityContext(); }
public static void CommonGenerateCode(List <ClassInfo> AllCls, string TemplateFileName, string OutputFile) { var util = new TypeUtil(); util.dict = new Dictionary <string, string>(); util.dict.Add(typeof(int).Name, "int"); util.dict.Add(typeof(Int64).Name, "Int64"); util.dict.Add(typeof(string).Name, "std::string"); foreach (var cls in AllCls) { util.dict.Add(cls.Name, cls.Name); } VelocityEngine ve = new VelocityEngine(); ve.Init(); VelocityContext vc = new VelocityContext(); //传入模板所需要的参数 vc.Put("AllCls", AllCls); //设置参数为对象,在模板中可以通过$dic.dudu 来引用 vc.Put("util", util); StringWriter sw = new StringWriter(); // 注意cls.Name必须是属性,而不是普通的成员变量,要不会无效! string vt = File.ReadAllText(TemplateFileName); ve.Evaluate(vc, sw, "gen-src-tag", vt); Console.WriteLine(sw.GetStringBuilder().ToString()); File.WriteAllText(OutputFile, sw.GetStringBuilder().ToString()); }
public void Expand(WebResponseData response) { if (log.IsDebugEnabled) { log.DebugFormat("Expanding template '{0}'", templateFileName); } VelocityEngine velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); velocity.Init(props); Hashtable contextHashtable = new Hashtable(); foreach (KeyValuePair <string, object> pair in templateParameters) { contextHashtable.Add(pair.Key, pair.Value); } VelocityContext velocityContext = new VelocityContext(contextHashtable); Template template = velocity.GetTemplate(templateFileName, new UTF8Encoding(false).WebName); response.ContentType = contentType; using (StreamWriter writer = new StreamWriter(response.OutputStream)) { try { template.Merge(velocityContext, writer); } catch (Exception ex) { writer.WriteLine(); writer.WriteLine("Error in template '{0}': '{1}'", templateFileName, ex); } } }
public async static Task <string> Generate( string ipAddress, PnPServerContext dbContext ) { var templateConfig = await dbContext.TemplateConfigurations .Include("Template") .Include("NetworkDevice") .Include("Properties") .Where(x => x.NetworkDevice.IPAddress == ipAddress) .FirstOrDefaultAsync(); if (templateConfig == null) { // TODO : Throw return(string.Empty); } string template = templateConfig.Template.Content; var context = new VelocityContext(); foreach (var prop in templateConfig.Properties) { context.Put(prop.Name, prop.Value); } var engine = new VelocityEngine(); engine.Init(); var outputWriter = new StringWriter(); engine.Evaluate(context, outputWriter, "eval1", template); var templateText = outputWriter.GetStringBuilder().ToString(); return(templateText); }
protected void ManipulatePdf(String dest) { // Initialize the velocity engine VelocityEngine engine = new VelocityEngine(); engine.Init(); // Create a velocity context and populate it VelocityContext context = new VelocityContext(); context.Put("message", "Hello World!"); // Load the template StringWriter writer = new StringWriter(); Template template = engine.GetTemplate(SRC); template.Merge(context, writer); using (FileStream stream = new FileStream(dest, FileMode.Create)) { HtmlConverter.ConvertToPdf(writer.ToString(), stream); } }
/// <summary> /// 初始化模板引擎 /// </summary> public static string ProcessTemplate(string path, string template, Dictionary <string, object> dicStru) { var templateEngine = new VelocityEngine(); templateEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); templateEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); templateEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); //路径 templateEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.Combine(path, "Templates")); var context = new VelocityContext(); foreach (var dbs in dicStru) { context.Put(dbs.Key, dbs.Value); } templateEngine.Init(); var writer = new StringWriter(); templateEngine.Evaluate(context, writer, "mystring", template); return(writer.GetStringBuilder().ToString()); }
public void Test() { Assert.Throws <ParseErrorException>(() => { var velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); velocityEngine.Init(extendedProperties); VelocityContext context = new VelocityContext(); Template template = velocityEngine.GetTemplate( GetFileName(null, "nv14", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); template.Merge(context, writer); Console.WriteLine(writer); }); }
public NVelocityHelper(string templatePath) { this.templatePath = templatePath; velocity = new VelocityEngine(); //使用设置初始化VelocityEngine ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true); //是否缓存 props.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)30); //缓存时间(秒) // props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312"); // props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); // props.SetProperty(RuntimeConstants.RESOURCE_MANAGER_CLASS, "NVelocity.Runtime.Resource.ResourceManagerImpl\\,NVelocity"); velocity.Init(props); //RuntimeConstants.RESOURCE_MANAGER_CLASS //为模板变量赋值 context = new VelocityContext(); }
public void DecimalToString() { StringWriter sw = new StringWriter(); VelocityContext c = new VelocityContext(); c.Put("x", (decimal)1.2); c.Put("model", new ModelClass()); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); bool ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$model.Amount.ToString() \r\n" + "$model.Amount.ToString('#0.00') \r\n" + "$x.ToString() \r\n" + "$x.ToString('#0.00') \r\n"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("1.2 \r\n1.20 \r\n1.2 \r\n1.20 \r\n", sw.ToString()); }
/// <summary> /// 初始话CNVelocity模块 /// </summary> public void Init(BaseModule _bpm, TemplateDB _Theme) { //创建VelocityEngine实例对象 velocity = new VelocityEngine(); //使用设置初始化VelocityEngine ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(String.Format("{0}Templates/{1}/", _bpm.ModulePath, XmlTheme.Name))); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); //模板的缓存设置 props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, false); //是否缓存 props.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)600); //缓存时间(秒) velocity.Init(props); //为模板变量赋值 context = new VelocityContext(); }
/// <summary> /// Creates a new instance. /// </summary> public TemplateTestCase() { try { ve = new VelocityEngine(); ExtendedProperties ep = new ExtendedProperties(); ep.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, TemplateTestBase_Fields.FILE_RESOURCE_LOADER_PATH); ep.SetProperty(RuntimeConstants_Fields.RUNTIME_LOG_ERROR_STACKTRACE, "true"); ep.SetProperty(RuntimeConstants_Fields.RUNTIME_LOG_WARN_STACKTRACE, "true"); ep.SetProperty(RuntimeConstants_Fields.RUNTIME_LOG_INFO_STACKTRACE, "true"); ve.Init(ep); testProperties = new ExtendedProperties(); testProperties.Load(new FileStream(TemplateTestBase_Fields.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read)); } catch (Exception e) { throw new Exception("Cannot setup TemplateTestSuite!"); } }
public static string RenderHtml(string templateName, object data) { //初始化模板引擎 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("Model", data); // 获取模板文件 Template vltTemplate = vltEngine.GetTemplate(templateName); // 输出 StringWriter vltWriter = new StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); return(html); }
/// <summary> /// 用data数据填充templateName模板,渲染生成html返回 /// </summary> /// <param name="templateName"></param> /// <param name="data"></param> /// <returns></returns> public static string RenderHtml(string templateName, object data) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/html"));//模板文件所在的文件夹 vltEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); vltEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); vltContext.Put("Data", data);//设置参数,在模板中可以通过$data来引用 Template vltTemplate = vltEngine.GetTemplate(templateName); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); return(html); }
/// <summary> /// Creates a new instance. /// </summary> public TemplateTestCase() { try { velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true"); velocityEngine.Init(extendedProperties); testProperties = new ExtendedProperties(); testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read)); } catch(Exception) { throw new Exception("Cannot setup TemplateTestSuite!"); } }
/// <summary> /// 初始话CNVelocity模块 /// </summary> public void Init(basePortalModule _bpm) { //创建VelocityEngine实例对象 velocity = new VelocityEngine(); //使用设置初始化VelocityEngine ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(String.Format("{0}Effects/{1}/", _bpm.ModulePath, _bpm.Settings_EffectName))); //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.GetDirectoryName(HttpContext.Current.Request.PhysicalPath)); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); //模板的缓存设置 props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, false); //是否缓存 props.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)600); //缓存时间(秒) velocity.Init(props); //为模板变量赋值 context = new VelocityContext(); }
public static string ProcessTemplate(string templatePath, IDictionary <string, object> templateData, CultureInfo culture = null) { if (culture == null) { culture = System.Threading.Thread.CurrentThread.CurrentCulture; } var resultWriter = new StringWriter(culture); VelocityEngine velocityEngine = new VelocityEngine(); VelocityContext velocityContext = new VelocityContext(); ExtendedProperties properties = new ExtendedProperties(); velocityEngine.Init(properties); foreach (var entry in templateData ?? new Dictionary <string, object>()) { velocityContext.Put(entry.Key, entry.Value); } StreamReader template = File.OpenText(templatePath); velocityEngine.Evaluate(velocityContext, resultWriter, string.Empty, template); return(resultWriter.ToString()); }
public static string ParseVelocity(string path, string name, IDictionary <string, object> parameters) { StringWriter writer = new StringWriter(); ExtendedProperties properties = new ExtendedProperties(); properties.AddProperty("resource.loader", "file"); properties.AddProperty("file.resource.loader.path", path); VelocityEngine engine = new VelocityEngine(); engine.Init(properties); IContext context = new VelocityContext(); foreach (KeyValuePair <string, object> pair in parameters) { context.Put(pair.Key, pair.Value); } Template template = engine.GetTemplate(name); if (template != null) { template.Merge(context, writer); } return(writer.ToString()); }
public void VTLTest1() { // VelocityCharStream vcs = new VelocityCharStream(new StringReader(":=t#${A.T1}ms"), 1, 1); // Parser p = new Parser(vcs); // SimpleNode root = p.process(); // // String nodes = String.Empty; // if (root != null) { // Token t = root.FirstToken; // nodes += t.kind.ToString(); // while (t != root.LastToken) { // t = t.next; // nodes += "," + t.kind.ToString(); // } // } // // throw new System.Exception(nodes); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); VelocityContext c = new VelocityContext(); c.Put("A", new A()); // modified version so Bernhard could continue StringWriter sw = new StringWriter(); Boolean ok = velocityEngine.Evaluate(c, sw, "VTLTest1", "#set($hash = \"#\"):=t${hash}${A.T1}ms"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual(":=t#0ms", sw.ToString()); // the actual problem reported sw = new StringWriter(); ok = velocityEngine.Evaluate(c, sw, "VTLTest1", ":=t#${A.T1}ms"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual(":=t#0ms", sw.ToString()); }
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()); }
/// <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; } }
/// <summary> /// Initializes a new instance of the <see cref="NVelocityDynamicEngine"/> class. /// </summary> public NVelocityDynamicEngine() { velocityEngine = new VelocityEngine(); velocityEngine.Init(); }
public void Test_Example1() { String templateFile = "example1.vm"; try { /* * setup */ VelocityEngine velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); velocityEngine.Init(extendedProperties); /* * 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 = velocityEngine.GetTemplate(templateFile); } catch(ResourceNotFoundException resourceNotFoundException) { Console.Out.WriteLine("Example : error : cannot find template {0} : \n{1}", templateFile, resourceNotFoundException.Message); Assert.Fail(); } catch(ParseErrorException parseErrorException) { Console.Out.WriteLine("Example : Syntax error in template {0} : \n{1}", templateFile, parseErrorException); 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); } }
public void StartNVelocity() { velocityEngine = new VelocityEngine(); velocityEngine.Init(); }
public string Eval(string text, bool wrapBetweenQuote) { VelocityContext c = new VelocityContext(); Hashtable hash2 = new Hashtable(); hash2["id"] = "123"; c.Put("params", hash2); c.Put("style", "style='color:red'"); c.Put("survey", 1); c.Put("id", 2); c.Put("siteRoot", String.Empty); c.Put("Helper", new Helper()); c.Put("DictHelper", new DictHelper()); StringWriter sw = new StringWriter(); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); string templatePrefix = "$Helper.Dump("; string templateSuffix = ")"; string templateContent = (wrapBetweenQuote) ? '"' + text + '"' : text; string template = templatePrefix + templateContent + templateSuffix; bool ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", template); Assert.IsTrue(ok, "Evaluation returned failure"); string result = sw.ToString(); return result.StartsWith(templatePrefix) ? text : result; }
public void ParamArraySupportMultipleCalls() { VelocityContext c = new VelocityContext(); c.Put("x", new Something()); StringWriter sw = new StringWriter(); VelocityEngine ve = new VelocityEngine(); ve.Init(); Boolean ok = false; ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents( \"x\", \"y\" )\r\n$x.Contents( \"w\", \"z\" )\r\n$x.Contents( \"j\", \"f\", \"a\" )"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("x,y\r\nw,z\r\nj,f,a", sw.ToString()); sw = new StringWriter(); ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents( \"x\", \"y\" )\r\n$x.Contents( \"w\", \"z\" )\r\n$x.Contents( \"j\", \"f\", \"a\" )"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("x,y\r\nw,z\r\nj,f,a", sw.ToString()); }
public NVelocityEntryFormatter() { _engine = new VelocityEngine(); _engine.Init(); }
public TemplatingService(String templatesPath) { _engine = new VelocityEngine(); _engine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatesPath); _engine.Init(); }
public void Test_Example1() { String templateFile = "example1.vm"; try { /* * setup */ VelocityEngine ve = new VelocityEngine(); ExtendedProperties ep = new ExtendedProperties(); ep.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, "../../test/templates"); 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); Assertion.Fail(); } catch (ParseErrorException pee) { Console.Out.WriteLine("Example : Syntax error in template " + templateFile + " : \n" + pee); Assertion.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) { Assertion.Fail(ex.Message); } }
/// <summary> /// Main body of the application /// </summary> protected override void ExecuteTask() { if (destDir == null) { String msg = "destdir attribute must be set!"; throw new BuildException(msg); } if (styleFile == null) { throw new BuildException("style attribute must be set!"); } if (velocityPropertiesFile == null) { velocityPropertiesFile = new FileInfo("nvelocity.properties"); } /* * If the props file doesn't exist AND a templatePath hasn't * been defined, then throw the exception. */ if (!velocityPropertiesFile.Exists && templatePath == null) { throw new BuildException("No template path and could not " + "locate nvelocity.properties file: " + velocityPropertiesFile); } Log.WriteLine(LogPrefix + "Transforming into: " + destDir); // projectFile relative to baseDir if (projectFile != null && !projectFile.Exists) { Log.WriteLine(LogPrefix + "Project file is defined, but could not be located: " + projectFile.FullName); projectFile = null; } AnakiaXmlDocument projectDocument = null; try { if (velocityPropertiesFile.Exists) { ve.Init(velocityPropertiesFile.FullName); } else { if (templatePath != null && templatePath.FullName.Length > 0) { ve.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_CACHE, true); ve.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, templatePath.FullName); ve.Init(); } } // Build the Project file document if (projectFile != null) { projectDocument = new AnakiaXmlDocument(); projectDocument.Load(projectFile.FullName); } } catch (System.Exception e) { Log.WriteLine(LogPrefix + "Error: " + e.ToString()); throw new BuildException(e.ToString()); } // get the base directory from the fileset - needed to colapse ../ syntax DirectoryInfo di = new DirectoryInfo(fileset.BaseDirectory); // get a list of files to work on foreach (string filename in fileset.FileNames) { String relativeFilename = filename.Substring(di.FullName.Length + 1); FileInfo file = new FileInfo(filename); if (file.Exists) { Process(di.FullName, relativeFilename, destDir, projectDocument); } } }
//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 bool Generate(StatisticalGraph graph) { g = graph; error = false; FrenchGenerator fr_t = new FrenchGenerator(); EnglishGenerator en_t = new EnglishGenerator(); #region NVelocity setup VelocityEngine velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); velocity.Init(props); //Template template; string strTemplate; // This nested if can be better... if (g.GraphLanguage == null || g.GraphLanguage.Length == 0) { if (g.Prologue.GetLanguageByFilename() != "French") { g.GraphLanguage = IGraphConstants.LANG_ENG; } else { g.GraphLanguage = IGraphConstants.LANG_FRA; } } if (g.GraphLanguage == IGraphConstants.LANG_ENG) { //template = velocity.GetTemplate(@"./English.nv"); byte[] NVtemplate = igl.Properties.Resources.NVenglish; System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); strTemplate = enc.GetString(NVtemplate); } else { //template = velocity.GetTemplate(@"./French.nv"); byte[] NVtemplate = igl.Properties.Resources.NVfrench; System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); strTemplate = enc.GetString(NVtemplate); } VelocityContext context = new VelocityContext(); #endregion context.Put("graph", g); context.Put("french", fr_t); context.Put("english", en_t); context.Put("date", DateTime.Now); // run template matching StringWriter writer = new StringWriter(); try { //setting Culture if (g.GraphLanguage == IGraphConstants.LANG_ENG) { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-CA", false); } else { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-CA", false); } //template.Merge(context, writer); velocity.Evaluate(context, writer, "NVlocity", strTemplate); SaveDescription(writer.GetStringBuilder().ToString()); } catch (Exception e) { log.Error("NVelocity error." + e.Message); error = true; } //Restoring culture System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US", false); return(error); }
/// <summary> /// <p> /// Sets the stylesheet for this transformation set /// </p> /// /// <p> /// Note that don't need this for each document you want /// to transform. Just do it once, and transform away... /// </p> /// </summary> /// <param name="styleReader">Reader with stylesheet char stream</param> public void SetStylesheet(TextReader value) { ready = false; /* * now initialize Velocity - we need to do that * on change of stylesheet */ ve = new VelocityEngine(); /* * if there are user properties, set those first - carefully */ if (velConfig != null) { ConfigureVelocityEngine(ve, velConfig); } /* * register our template() directive */ ve.SetProperty("userdirective", @"NVelocity.Dvsl.Directive.MatchDirective\,NVelocity"); ve.Init(); /* * add our template accumulator */ ve.SetApplicationAttribute("NVelocity.Dvsl.TemplateHandler", templateHandler); /* * load and render the stylesheet * * this sets stylesheet specific context * values */ StringWriter junkWriter = new StringWriter(); styleContext = new VelocityContext(); ve.Evaluate(styleContext, junkWriter, "DVSL:stylesheet", value); /* * now run the base template through for the rules */ // TODO - use ResourceLocator or something else - I don't like the path to the resource Stream s = this.GetType().Assembly.GetManifestResourceStream("NVelocity.Dvsl.Resource.defaultroot.dvsl"); if (s == null) { Console.Out.WriteLine("DEFAULT TRANSFORM RULES NOT FOUND "); } else { ve.Evaluate(new VelocityContext(), junkWriter, "defaultroot.dvsl", new StreamReader(s)); s.Close(); } /* * need a new transformer, as it depends on the * velocity engine */ transformer = new Transformer(ve, templateHandler, baseContext, appVals, validate); }
public NVelocityTemplateEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; velocityEngine.Init(); }
public void Init() { velocityEngine = new VelocityEngine(); velocityEngine.Init(); duck1 = new Duck1(); duck2 = new Duck2(); }
public void BeforeAnyTest() { velocityEngine = new VelocityEngine(); velocityEngine.Init(); }
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 Hashtable1() { VelocityContext c = new VelocityContext(); Hashtable x = new Hashtable(); x.Add("item", "value1"); c.Put("x", x); StringWriter sw = new StringWriter(); VelocityEngine ve = new VelocityEngine(); ve.Init(); Boolean ok = false; ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.get_Item( \"item\" )"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("value1", sw.ToString()); }
public void ProcessRequest(HttpContext context) { //context.Response.Write("1"); //IPage fac=(IPage)Assembly.Load("NewXzc.Web").CreateInstance("NewXzc.Web.Index",true); //fac.Page_Load(context); #region string physicalApplicationPath = context.Request.PhysicalApplicationPath; string str4 = context.Request.PhysicalPath.Replace(physicalApplicationPath, string.Empty).Replace("/", ".").Replace(@"\", ".").Replace(".aspx", string.Empty); string name = str4.Replace(".", "/") + ".html"; string str6 = string.Empty; //新添加测试 //if (str4.ToLower() == "default") //{ // HttpContext.Current.Response.Redirect("/index"); // return; //} //测试结束 if (str4.ToLower() == "index" || str4.ToLower() == "webscan_360_cn" || str4.ToLower() == "baidu_verify_kyltyss6um") { str6 = ""; } else { str6 = "template"; } if (str4.ToLower() == "tools.ueditor.dialogs.image.image") { str6 = ""; str4 = "image"; } else if (str4.ToLower() == "tools.ueditor.dialogs.link.link") { str6 = ""; str4 = "link"; } else if (str4.ToLower() == "tools.ueditor.dialogs.emotion.emotion") { str6 = ""; str4 = "emotion"; } else { str6 = "template"; } string str8 = "text/html"; string str9 = context.Request.ServerVariables["HTTP_ACCEPT"]; VelocityEngine engine = new VelocityEngine(); engine.SetProperty("resource.loader", "file"); engine.SetProperty("file.resource.loader.path", physicalApplicationPath + str6 + @"\"); engine.Init(); VelocityContext ctx = new VelocityContext(); string applicationPath = HttpContext.Current.Request.ApplicationPath; if (applicationPath == "/") { applicationPath = string.Empty; } #region 获取当前用户的登录状态 string url_s = HttpContext.Current.Request.Url.ToString().ToLower(); if (!url_s.Contains("hongrenhui")) { ctx.Put("headinfo", GetUserLoginState(1)); } else { ctx.Put("headinfo", GetUserLoginState(1)); } if (!url_s.Contains("userlogin")) { if (!url_s.Contains("hongrenhui")) { //当前用户还未登录 if (GetCurUserID_HongRenHui() == 0) { //进入中心页面,直接跳转回登录页 if (url_s.Contains("personalcenter")) { HttpContext.Current.Response.Redirect("/login"); } } } else { //当前用户还未登录 if (GetCurUserID_HongRenHui() == 0) { //进入中心页面,直接跳转回登录页 if (url_s.Contains("personalcenter")) { HttpContext.Current.Response.Redirect("/login"); } } } } #endregion ctx.Put("style", "/template/style"); ctx.Put("js", "/template/js"); ctx.Put("img", "/template/img"); ctx.Put("exname", ".aspx"); ctx.Put("showimg", NewXzc.Common.ImgHelper.GetCofigShowUrl()); IHandlerFactory factory = null; try { factory = (IHandlerFactory)Assembly.Load("NewXzc.Web").CreateInstance("NewXzc.Web.templatecs." + str4, true); if (factory == null) { //name = "/index"; name = "/404"; } else if (!(!(context.Request.HttpMethod == "POST"))) { factory.Page_PostBack(ref ctx); } else { factory.Page_Load(ref ctx); } } catch (Exception ex) { //context.Response.Redirect("/404"); context.Response.Write(ex.Message); } if (ctx.Get("redirecturl") != null) { string url = ctx.Get("redirecturl").ToString(); context.Response.Redirect(url); } try { Template template = engine.GetTemplate(name); StringWriter writer2 = new StringWriter(); template.Merge(ctx, writer2); context.Response.ContentType = str8; context.Response.Write(writer2.GetStringBuilder().ToString()); } catch (Exception ex) { context.Response.Write(ex.Message); } #endregion }
public void ParamArraySupportAndForEach2() { ArrayList items = new ArrayList(); items.Add("a"); items.Add("b"); items.Add("c"); VelocityContext c = new VelocityContext(); c.Put("x", new Something()); c.Put("items", items); StringWriter sw = new StringWriter(); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); Boolean ok = false; ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", "#foreach( $item in $items )\r\n" + "#if($item == \"a\")\r\n $x.Contents( \"x\", \"y\" )#end\r\n" + "#if($item == \"b\")\r\n $x.Contents( \"x\" )#end\r\n" + "#if($item == \"c\")\r\n $x.Contents( \"c\", \"d\", \"e\" )#end\r\n" + "#end\r\n"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual(" x,y x c,d,e", sw.ToString()); }
public void PropertiesAreAlsoCaseInsensitive() { // normal case sensitive context VelocityContext c = new VelocityContext(); c.Put("something", new Something()); VelocityEngine ve = new VelocityEngine(); ve.Init(); // verify the output, $lastName should not be resolved StringWriter sw = new StringWriter(); bool ok = ve.Evaluate(c, sw, string.Empty, "Hello $something.firstName"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("Hello hammett", sw.ToString()); sw.GetStringBuilder().Length = 0; ok = ve.Evaluate(c, sw, string.Empty, "Hello $something.Firstname"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("Hello hammett", sw.ToString()); sw.GetStringBuilder().Length = 0; ok = ve.Evaluate(c, sw, string.Empty, "Hello $something.firstname"); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("Hello hammett", sw.ToString()); }