public void SendReferralEmailToProspect() { StringType subjectTemplate; StringType bodyTemplate; MailMessageTypeEnum mailMessage; mailMessage = MailMessageTypeEnum.REFERRAL_PROSPECT_EMAIL; subjectTemplate = Resource.GetResource(ResourceKeyEnum.REFERRAL_PROSPECT_EMAIL_SUBJECT).ResourceText; bodyTemplate = Resource.GetResource(ResourceKeyEnum.REFERRAL_PROSPECT_EMAIL_BODY).ResourceText; // create an NVelocity context with the Referral VelocityContext context = new VelocityContext(new Hashtable(new CaseInsensitiveHashCodeProvider(), new CaseInsensitiveComparer())); context.Put("Referral", this); // merge the template and context StringWriter writer = new StringWriter(); velocity.Evaluate(context, writer, "Referral.SendReferralEmailToProspect", bodyTemplate.ToString()); StringType body = writer.ToString(); writer = new StringWriter(); velocity.Evaluate(context, writer, "Referral.SendReferralEmailToProspect", subjectTemplate.ToString()); StringType subject = writer.ToString(); MailMessage.Create(mailMessage.Code, this.Email, subject, body, MailBodyFormatEnum.TEXT); }
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()); }
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, "Evalutation 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, "Evalutation returned failure"); Assert.AreEqual("x,y\r\nw,z\r\nj,f,a", sw.ToString()); }
public void HideBaseProperty() { ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", @" $chp.Name " ); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("ChildHidesParent", Normalize(sw)); }
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 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()); }
/// <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 string RunCompile(string template) { try { //注意,新版本表达式引擎,不支持获取类的属性,得用方法代替 if (string.IsNullOrEmpty(template)) { return(""); } //由于不知道为什么这个模板解析在.netcore 下运行有点慢,所以暂时如果没有表达式,则不运行了 if (template.IndexOf("${") == -1) { return(template); } System.IO.StringWriter vltWriter = new System.IO.StringWriter(); _vltEngine.Evaluate(_vltContext, vltWriter, null, template.ToString()); string s = vltWriter.GetStringBuilder().ToString(); vltWriter.Close(); return(s); } catch (NullReferenceException) { return(""); } catch (Exception) { return(""); } }
/// <summary> /// 通过字符串【模板】 生成文件 /// </summary> /// <param name="inputString"></param> /// <returns></returns> public static void WriteTemplateByString(string outFilePath, string templateString, Dictionary <string, object> dictKv) { VelocityEngine templateEngine = new VelocityEngine(); templateEngine.Init(); VelocityContext velocityContext = new VelocityContext(); foreach (string key in dictKv.Keys) { velocityContext.Put(key, dictKv[key]); } StringWriter writer = new StringWriter(); templateEngine.Evaluate(velocityContext, writer, null, templateString); FileInfo fileInfo = new FileInfo(outFilePath); //父目录不存在 进行创建 if (!fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } File.WriteAllText(@outFilePath, writer.GetStringBuilder().ToString());//生成文件的路径可以自由选择 //MessageBox.Show(writer.GetStringBuilder().ToString()); }
public void ParamArraySupportAndForEach() { ArrayList items = new ArrayList(); items.Add("a"); items.Add("b"); items.Add("c"); items.Add("d"); 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$x.Contents( \"x\", \"y\" )\r\n#end\r\n"); Assertion.Assert("Evalutation returned failure", ok); Assertion.AssertEquals("x,y\r\nx,y\r\nx,y\r\nx,y\r\n", sw.ToString()); }
static void Main(string[] args) { try { VelocityEngine fileEngine = new VelocityEngine(); fileEngine.Init(); VelocityContext context = new VelocityContext(); context.Put("UserFirstName", "Akshay"); context.Put("UserLastName", "Patel"); context.Put("Company", "Dotnetbees"); var writer = new StringWriter(); string path = @"" + Environment.CurrentDirectory + "\\Template\\Demo.vm"; StreamReader sr = new StreamReader(path); string templateString = sr.ReadToEnd(); sr.Close(); fileEngine.Evaluate(context, writer, null, templateString); Console.WriteLine(writer.GetStringBuilder().ToString()); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } }
public static string MergeTemplateWithResultsByFilepath(string filepath, object obj) { try { VelocityEngine velocity = _engineManager.Engine; _engineManager.WatchTemplateDirectory(filepath); velocity.Init(); VelocityContext context = new VelocityContext(); context.Put("SearchResults", obj); context.Put("CDEContext", new CDEContext()); context.Put("PageContext", HttpContext.Current); context.Put("Tools", new VelocityTools()); StreamReader sr = new StreamReader(HttpContext.Current.Server.MapPath(filepath)); string template = sr.ReadToEnd(); sr.Close(); StringWriter writer = new StringWriter(); velocity.Evaluate(context, writer, "", template); return(writer.GetStringBuilder().ToString()); } catch (Exception ex) { log.Error("MergeTemplateWithResultsByFilepath(): Failed when evaluating results template and object.", ex); throw; } }
public static string ProcessTemplate(SubscriptionResult Subscription, IEmailTemplateRepository emailTemplateRepository, IApplicationConfigRepository applicationConfigRepository) { string body = emailTemplateRepository.GetTemplateBody(Subscription.SaasSubscriptionStatus.ToString()); string applicationName = applicationConfigRepository.GetValuefromApplicationConfig("ApplicationName"); Hashtable hashTable = new Hashtable(); hashTable.Add("ApplicationName", applicationName); hashTable.Add("CustomerEmailAddress", Subscription.CustomerEmailAddress); hashTable.Add("CustomerName", Subscription.CustomerName); hashTable.Add("Id", Subscription.Id); hashTable.Add("SubscriptionName", Subscription.Name); hashTable.Add("SaasSubscriptionStatus", Subscription.SaasSubscriptionStatus); ExtendedProperties p = new ExtendedProperties(); VelocityEngine v = new VelocityEngine(); v.Init(p); VelocityContext context = new VelocityContext(hashTable); StringWriter writer = new StringWriter(); v.Evaluate(context, writer, string.Empty, body); return(writer.ToString()); }
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 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 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> /// 使用模板引擎进行处理。 /// </summary> private void processTemplate() { if (this.sapTableField1.TableList == null) { MessageBox.Show("没有选中的字段"); return; } if (this.sapTableField1.TableList.Count == 0) { MessageBox.Show("没有选中的字段"); return; } try { VelocityEngine ve = new VelocityEngine(); ve.Init(); VelocityContext ct = new VelocityContext(); ct.Put("tables", 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); } }
/// <summary> /// 初始化模板引擎 /// </summary> public static string ProcessTemplate(string template, Dictionary <string, object> param) { 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, AppDomain.CurrentDomain.BaseDirectory); var context = new VelocityContext(); foreach (var item in param) { context.Put(item.Key, item.Value); } templateEngine.Init(); var writer = new StringWriter(); templateEngine.Evaluate(context, writer, "mystring", template); return(writer.GetStringBuilder().ToString()); }
/// <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 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> /// 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 static string GetContent( string template, string nameSpace, string table, string className, IEnumerable <ColumnInfo> columns, string comment, string sql = "", IEnumerable <ColumnEnumListModel> enumLists = null) { var engine = new VelocityEngine(); engine.SetProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8"); engine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); engine.Init(); using (var writer = new StringWriter()) { var context = new VelocityContext(); context.Put("entity", new { hasPrimaryKey = columns.Count(c => c.iskey) > 0, primaryKeyClr = columns.Where(w => w.iskey).Select(s => s.clrtype).FirstOrDefault() ?? string.Empty, nameSpace, name = table, className = className, comment = comment ?? table, cols = columns.OrderByDescending(m => m.iskey), sql = sql, hasEnums = enumLists != null && enumLists.Count() > 0, enumLists = enumLists }); engine.Evaluate(context, writer, "entity", template); return(writer.GetStringBuilder().ToString()); } }
private void RenderInternal(string viewFileName, IContext velocityContext) { using (var template = new StreamReader(context.ServerInfo.FileStorage.GetFile(viewFileName))) { Engine.Evaluate(velocityContext, output, null, template); } }
private void GenerateCode() { if (checkBeforeGernerate() == false) { return; } try { VelocityEngine ve = new VelocityEngine(); ve.Init(); VelocityContext ct = new VelocityContext(); ct.Put("tables", this.m_FormTableField.TableList); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); string template = string.Empty; var _Code = m_FormCodeManager.GetLatestCode(m_FormCodeManager.TemplateCode); template = _Code.Content; ve.Evaluate(ct, vltWriter, null, template); String result = string.Empty; result = vltWriter.GetStringBuilder().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); } }
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; } }
public void InterpolationWithEquals() { VelocityContext c = new VelocityContext(); c.Put("survey", 1); c.Put("id", 2); c.Put("siteRoot", String.Empty); c.Put("AjaxHelper2", new AjaxHelper2()); c.Put("DictHelper", new DictHelper()); StringWriter sw = new StringWriter(); VelocityEngine ve = new VelocityEngine(); ve.Init(); Boolean ok = false; ok = ve.Evaluate(c, sw, "ContextTest.CaseInsensitive", "$AjaxHelper2.LinkToRemote(\"Remove\", " + "\"${siteRoot}/Participant/DeleteEmail.rails\", " + "$DictHelper.CreateDict( \"failure=error\", \"success=emaillist\", \"with=return 'survey=${survey}&id=${id}'\" ) )"); Assertion.Assert("Evalutation returned failure", ok); Assertion.AssertEquals("Remove /Participant/DeleteEmail.rails return 'survey=1&id=2'", sw.ToString()); }
public static String Parse(String template, String key, System.Object parameters) { StringWriter writer = null; try { VelocityEngine ve = new VelocityEngine(); ve.Init(); // 取得velocity的上下文context VelocityContext context = new VelocityContext(); // 把数据填入上下文 context.Put(key, parameters); // 输出流 writer = new StringWriter(); // todo 转换输出, 去除velocity代码缩进的空格符 //template = Regex.Replace(template, @"[ ]*(?<value>#if|#end|#foreach|#elseif)", "${value}", RegexOptions.Singleline); ve.Evaluate(context, writer, "", template); return(writer.ToString()); } catch (Exception e) { throw e; } finally { if (writer != null) { writer.Close(); } } }
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); } }
/* * (non-Javadoc) * * @see NHibernate.Tool.hbm2net.Renderer#render(java.lang.String, * java.lang.String, NHibernate.Tool.hbm2net.ClassMapping, * java.util.Map, java.io.PrintWriter) */ public override void Render(string savedToPackage, string savedToClass, ClassMapping classMapping, IDictionary class2classmap, StreamWriter writer) { VelocityContext context = new VelocityContext(); context.Put("savedToPackage", savedToPackage); context.Put("savedToClass", savedToClass); context.Put("clazz", classMapping); context.Put("class2classmap", class2classmap); context.Put("languageTool", new LanguageTool()); context.Put("runtimeversion", Guid.Empty.GetType().Assembly.ImageRuntimeVersion); StringWriter sw = new StringWriter(); context.Put("classimports", "$classimports"); // First run - writes to in-memory string template.Merge(context, sw); context.Put("classimports", new LanguageTool().GenerateImports(classMapping)); // Second run - writes to file (allows for placing imports correctly and optimized ;) ve.Evaluate(context, writer, "hbm2net", sw.ToString()); }
private String evaluate(String template) { StringWriter writer = new StringWriter(); // use template as its own name, since our templates are short engine.Evaluate(context, writer, template, template); return(writer.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, "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 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 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 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 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 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 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 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 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 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; }