private Evaluate ( IContext context, |
||
context | IContext | |
writer | ||
logTag | String | |
instream | Stream | |
return | bool |
private static string ApplyTemplate(string template, VelocityContext context) { VelocityEngine velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); velocity.Init(props); using (var writer = new StringWriter(CultureInfo.CurrentCulture)) { velocity.Evaluate(context, writer, string.Empty, template); return writer.GetStringBuilder().ToString(); } }
public void RenderTemplate(string templateName, object model) { string templateFullPath = applicationInfo.AbsolutizePath("Web/Pages/Templates/" + templateName + ".vm.html"); ITemplateSource template = new CacheableFileTemplate( templateFullPath, fileCache); string templateText = template.GetTemplate(); VelocityEngine velocity = new VelocityEngine(); velocity.Init(); VelocityContext velocityContext = new VelocityContext(); velocityContext.Put("m", model); velocityContext.Put("h", this); using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { if (false == velocity.Evaluate(velocityContext, stringWriter, null, templateText)) throw new InvalidOperationException("Template expansion failed"); writer.InnerWriter.Write(stringWriter.ToString()); } writer.WriteLine(); }
/// <summary>The format.</summary> /// <param name="text">The text.</param> /// <param name="items">The items.</param> /// <returns>The format.</returns> /// <exception cref="TemplateException"></exception> public string Format(string text, Dictionary<string, object> items) { try { VelocityContext velocityContext = new VelocityContext(); if (items != null) { foreach (var pair in items) { velocityContext.Put(pair.Key, pair.Value); } } StringWriter sw = new StringWriter(); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); bool ok = velocityEngine.Evaluate(velocityContext, sw, "ContextTest.CaseInsensitive", text); if (!ok) { throw new TemplateException("Template run error (try adding an extra newline at the end of the file)"); } return sw.ToString(); } catch (ParseErrorException parseErrorException) { throw new TemplateException(parseErrorException.Message, parseErrorException); } }
public void ParamArraySupport1() { 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.Print( \"aaa\" )"); Assert.IsTrue(ok, "Evalutation returned failure"); Assert.AreEqual("aaa", sw.ToString()); sw = new StringWriter(); ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents()"); Assert.IsTrue(ok, "Evalutation returned failure"); Assert.AreEqual("", sw.ToString()); sw = new StringWriter(); ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents( \"x\" )"); Assert.IsTrue(ok, "Evalutation returned failure"); Assert.AreEqual("x", sw.ToString()); sw = new StringWriter(); ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$x.Contents( \"x\", \"y\" )"); Assert.IsTrue(ok, "Evalutation returned failure"); Assert.AreEqual("x,y", sw.ToString()); }
private static string EvaluateTemplate(VelocityEngine engine, IContext context, string templateString) { using (var writer = new StringWriter()) { engine.Evaluate(context, writer, "", templateString); return writer.GetStringBuilder().ToString(); } }
public string Evaluate(string template, IDictionary<string, object> context) { var velocityContext = new VelocityContext(); foreach (var keyValuePair in context) { velocityContext.Put(keyValuePair.Key, keyValuePair.Value); } var velocity = new VelocityEngine(); velocity.Init(); var writer = new StringWriter(); velocity.Evaluate(velocityContext, writer, null, template); return writer.GetStringBuilder().ToString(); }
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 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 ve = new VelocityEngine(); ve.Init(); VelocityContext c = new VelocityContext(); c.Put("A", new A()); // modified version so Bernhard could continue StringWriter sw = new StringWriter(); Boolean ok = ve.Evaluate(c, sw, "VTLTest1", "#set($hash = \"#\"):=t${hash}${A.T1}ms"); Assert.IsTrue(ok, "Evalutation returned failure"); Assert.AreEqual(":=t#0ms", sw.ToString()); // the actual problem reported sw = new StringWriter(); ok = ve.Evaluate(c, sw, "VTLTest1", ":=t#${A.T1}ms"); Assert.IsTrue(ok, "Evalutation returned failure"); Assert.AreEqual(":=t#0ms", sw.ToString()); }
public void ExceptionForAmbiguousMatches() { StringWriter sw = new StringWriter(); VelocityContext c = new VelocityContext(); c.Put("x", (decimal) 1.2); c.Put("model", new ModelClass()); VelocityEngine ve = new VelocityEngine(); ve.Init(); ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$model.Amount.ToString(null)"); }
public static string StringMerge(string templateContext, Hashtable table) { var engine = new VelocityEngine(); engine.Init(); var content = new VelocityContext(); if (table != null) foreach (DictionaryEntry entry in table) { content.Put(entry.Key.ToString(), entry.Value); } using (var writer = new StringWriter()) { engine.Evaluate(content, writer, "", templateContext); return writer.GetStringBuilder().ToString(); } }
public static string ProcessVelocityTemplate(string content, Dictionary<string, object> dict) { var engine = new VelocityEngine(); engine.Init(); var ctx = new Hashtable(); foreach (string key in dict.Keys) ctx.Add(key, dict[key]); var context = new VelocityContext(ctx); using (var writer = new StringWriter()) { engine.Evaluate(context, writer, "", content); return writer.GetStringBuilder().ToString(); } }
public static string CreateCode(string codeString,NVelocity.VelocityContext context) { StringWriter writer = new StringWriter(); try { VelocityEngine engine= new VelocityEngine(); engine.Init(); if (context == null) context = new VelocityContext(); engine.Evaluate(context, writer, "", codeString); } catch (Exception ex) { throw ex; } return writer.ToString(); }
public string RenderFromContentTemplate(string content, IDictionary<string, object> data) { StringWriter writer = new StringWriter(); VelocityEngine e = new VelocityEngine(); e.Init(); var context = new VelocityContext(); var templateData = data ?? new Dictionary<string, object>(); foreach (var key in templateData.Keys) { context.Put(key, templateData[key]); } e.Evaluate(context, writer, "template", content); return writer.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()); }
protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding) { int count = 0; if (string.IsNullOrEmpty(TemplateMarkup)) { DisplayError("No template specified."); } else if (!dataBinding) { DisplayError("Control is not databound."); } else if (dataSource == null) { DisplayError("Data source was null."); } else { VelocityEngine velocity = new VelocityEngine(); velocity.Init(); Hashtable contextHashtable = new Hashtable { { "Model", dataSource}, { "HttpContextCurrent", HttpContext.Current} }; // TODO: Add ResourceManager and other useful things var velocityContext = new VelocityContext(contextHashtable); string evaluatedTemplate; using (StringWriter stringWriter = new StringWriter()) { velocity.Evaluate(velocityContext, stringWriter, /*logTag:*/ string.Empty, TemplateMarkup); evaluatedTemplate = stringWriter.ToString(); } Controls.Add(new LiteralControl { Text = evaluatedTemplate }); } return count; }
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 virtual void Send(IHttpContext context) { VelocityEngine velocity = new VelocityEngine(); velocity.Init(); VelocityContext velocityContext = new VelocityContext(); if (properties != null) { foreach (DictionaryEntry entry in properties) velocityContext.Put(entry.Key.ToString(), entry.Value); } AddStuffToVelocityContext(velocityContext, context); using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { if (false == velocity.Evaluate(velocityContext, stringWriter, null, template.GetTemplate())) throw new InvalidOperationException("Template expansion failed"); context.SetResponse(stringWriter.GetStringBuilder().ToString(), contentType, Encoding.UTF8); } }
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(); }
/// <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 virtual 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) { System.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); }
private void processTemplate() { if (rfctable.Fields.Count ==0 ) { MessageBox.Show("没有字段"); return; } try { VelocityEngine ve = new VelocityEngine(); ve.Init(); VelocityContext ct = new VelocityContext(); AbapCode code = new AbapCode(); ct.Put("rfctable", rfctable); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); ve.Evaluate(ct, vltWriter, null, this.textBoxTemplate.Text); this.textBoxResult.Text = vltWriter.GetStringBuilder().ToString(); MessageBox.Show("处理成功"); } catch (Exception exception) { MessageBox.Show(exception.Message); //throw; } }
string CreateTemplate(List<GeoLocationModel> list) { string path = Path.Combine (Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "erpdata"); VelocityEngine fileEngine = new VelocityEngine(); fileEngine.Init(); string template;//= File.ReadAllText(@"d:\invoice.vm"); using (Stream sr = Assets.Open(@"mylocation.html")) { using (MemoryStream ms = new MemoryStream()) { sr.CopyTo(ms); byte[] data2 = ms.ToArray(); template = Encoding.UTF8.GetString(ms.ToArray(), 0, data2.Length); } } VelocityContext context = new VelocityContext(); // put the states and the transitions into the context StreamWriter ws = new StreamWriter(new MemoryStream()); context.Put("util", new CustomTool()); context.Put("model", list); fileEngine.Evaluate(context, ws, null, template); string text = ""; ws.Flush(); byte[] data = new byte[ws.BaseStream.Length]; ws.BaseStream.Position = 0; int nread = ws.BaseStream.Read(data, 0, data.Length); text = Encoding.GetEncoding("GB18030").GetString(data, 0, nread); string tempfile = Path.Combine (path, "showmap.html"); if (File.Exists(tempfile)){ File.Delete(tempfile); } File.WriteAllBytes(tempfile, data); ws.Close(); return tempfile; }
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, "Evalutation returned failure"); Assert.AreEqual(" 16 17 18", sw.ToString()); }
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 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.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, "Evalutation returned failure"); Assert.AreEqual(" x,y x c,d,e", sw.ToString()); }
public static string GetInvoiceSumm_Template(string template,string pathToDatabase,string userID, DateTime printDate1,DateTime printDate2) { string text = ""; try { ModelSumm model = GetInvoiceSummModel (pathToDatabase, userID, printDate1, printDate2); model.ItemsSumm = SummHelper.GetItemsSummary(pathToDatabase, printDate1); VelocityEngine fileEngine = new VelocityEngine (); fileEngine.Init (); string content = GetTemplateFile (template, pathToDatabase); VelocityContext context = new VelocityContext (); StreamWriter ws = new StreamWriter (new MemoryStream ()); context.Put ("util", new CustomTool ()); context.Put ("model", model); fileEngine.Evaluate (context, ws, null, content); ws.Flush (); byte[] data = new byte[ws.BaseStream.Length - 2]; ws.BaseStream.Position = 2; int nread = ws.BaseStream.Read (data, 0, data.Length); text = Encoding.UTF8.GetString (data, 0, nread); ws.Close (); } catch (Exception ex) { } return text; }
/// <summary> /// 生成代码 /// </summary> public void Gernerate() { try { string template = string.Empty; if (m_FormCodeManager.TemplateCode == null) { MessageBox.Show("请选择代码模板"); return; } var _Code = m_FormCodeManager.GetLatestCode(m_FormCodeManager.TemplateCode); if (_Code == null) { MessageBox.Show("无法读取模板!"); return; } template = _Code.Content; VelocityContext ct = new VelocityContext(); if (m_template_items != null) { foreach (var pair in m_template_items) { ct.Put(pair.Key, pair.Value); } } VelocityEngine ve = new VelocityEngine(); ve.Init(); //ct.Put("tables", m_tableList); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); bool ok = ve.Evaluate(ct, vltWriter, null, template); if (!ok) { MessageBox.Show("生成模板出错"); return; } String result = vltWriter.ToString(); var _newCode = new Code(); _newCode.Content = result; _newCode.Category = _Code.Category; _newCode.Title = m_FormCodeManager.TemplateCode.Title + "_NEW*"; m_FormCodeManager.AddNewCodeToTempFolder(_newCode, true); // newCode.TreeId = m_FormCodeManager.SelectedTree.Id; } catch (Exception ee) { MessageBox.Show(ee.Message); } }
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, "Evalutation returned failure"); Assert.AreEqual("value1", sw.ToString()); }
public string RenderTemplateContent(string templateContent, IDictionary<string, object> data) { if (string.IsNullOrEmpty(templateContent)) throw new ArgumentException("Template content cannot be null", "templateContent"); var engine = new VelocityEngine(); engine.Init(); var context = new VelocityContext(); var templateData = data ?? new Dictionary<string, object>(); foreach (var key in templateData.Keys) { context.Put(key, templateData[key]); } using (var writer = new StringWriter()) { engine.Evaluate(context, writer, "", templateContent); return writer.GetStringBuilder().ToString(); } }
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, "Evalutation 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, "Evalutation 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, "Evalutation returned failure"); Assert.AreEqual("Hello Cort Schaefer", 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, "", "Hello $something.firstName"); Assert.IsTrue(ok, "Evalutation returned failure"); Assert.AreEqual("Hello hammett", sw.ToString()); sw.GetStringBuilder().Length = 0; ok = ve.Evaluate(c, sw, "", "Hello $something.Firstname"); Assert.IsTrue(ok, "Evalutation returned failure"); Assert.AreEqual("Hello hammett", sw.ToString()); sw.GetStringBuilder().Length = 0; ok = ve.Evaluate(c, sw, "", "Hello $something.firstname"); Assert.IsTrue(ok, "Evalutation returned failure"); Assert.AreEqual("Hello hammett", sw.ToString()); }
private void tspProcessTemplate_Click(object sender, EventArgs e) { try { VelocityEngine ve = new VelocityEngine(); ve.Init(); VelocityContext ct = new VelocityContext(); AbapCode code = new AbapCode(); ct.Put("test", this.sapTableField1.TableList); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); ve.Evaluate(ct, vltWriter, null, this.textTemplate.Text); textResultCode.Text = vltWriter.GetStringBuilder().ToString(); } catch (Exception ee) { MessageBox.Show(ee.Message); } }