/// <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 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 SetUp() { ve = new VelocityEngine(); ve.Init(); ctx = new VelocityContext(); }
public void Setup() { context = new VelocityContext(); ve = new VelocityEngine(); ve.Init(); }
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() { 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 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 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 Init(string templatDir) { velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(templatDir)); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatDir); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");//gb2312 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(); //context.Put("format", new VelocityFormatter(context)); }
public ModelGenerator(FileExists p_FileExists, string p_NameSpace, bool p_MakePartial, bool p_PropChange, bool p_Validate) { this._FileExists = p_FileExists; this._NameSpace = p_NameSpace; this._MakePartial = p_MakePartial; this._PropChange = p_PropChange; this._EnableValidationAttributes = p_Validate; this._fhResult = FileHandlingResult.None; this.engine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.AddProperty("file.resource.loader.path", new ArrayList(new string[] { ".", ".\\Templates" })); this.engine.Init(extendedProperties); }
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 TestFileBasedConfig() { VelocityEngine velocityEngine = appContext.GetObject("cnFileVelocityEngine") as VelocityEngine; Assert.IsNotNull(velocityEngine, "velocity engine is null"); Assert.AreEqual(VelocityConstants.File, getSingleProperty(velocityEngine, RuntimeConstants.RESOURCE_LOADER), "incorrect resource loader"); Assert.AreEqual(TemplateDefinitionConstants.FileResourceLoaderClass, getSingleProperty(velocityEngine, TemplateNamespaceParser.getResourceLoaderProperty(VelocityConstants.File, VelocityConstants.Class)), "incorrect resource loader type"); Assert.AreEqual(new string[] { "Template/Velocity/", "Template/" }, velocityEngine.GetProperty( TemplateNamespaceParser.getResourceLoaderProperty(VelocityConstants.File, VelocityConstants.Path)), "incorrect resource loader path"); Assert.AreEqual(DEFAULT_CACHE_SIZE, velocityEngine.GetProperty(RuntimeConstants.RESOURCE_MANAGER_DEFAULTCACHE_SIZE), "incorrect default cache size"); Assert.AreEqual(DEFAULT_MOD_CHECK, velocityEngine.GetProperty( VelocityConstants.File + VelocityConstants.Separator + PropertyModificationCheck), "incorrect mod check interval"); Assert.AreEqual(DEFAULT_CACHE_FLAG, velocityEngine.GetProperty(VelocityConstants.File + VelocityConstants.Separator + PropertyResourceLoaderCachce), "incorrect caching flag"); AssertMergedValue(velocityEngine, "SimpleTemplate.vm"); }
public static string RenderHtml(string name, object data) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/template"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); vltContext.Put("Data", data);//设置参数,在模板中可以通过$data来引用 Template vltTemplate = vltEngine.GetTemplate(name); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); return(vltWriter.GetStringBuilder().ToString()); }
public void TestSpringBasedConfig() { VelocityEngine velocityEngine = appContext.GetObject("cnSpringVelocityEngine") as VelocityEngine; Assert.IsNotNull(velocityEngine, "velocity engine is null"); const string PropertySpring = TemplateDefinitionConstants.Spring; Assert.AreEqual(PropertySpring, getSingleProperty(velocityEngine, RuntimeConstants.RESOURCE_LOADER), "incorrect resource loader"); Assert.AreEqual(TemplateDefinitionConstants.SpringResourceLoaderClass, getSingleProperty(velocityEngine, TemplateNamespaceParser.getResourceLoaderProperty(PropertySpring, VelocityConstants.Class)), "incorrect resource loader type"); // no way to test the path property other than trying to actually perform a merge (it is set in velocity engine as an application attribute which is not exposed) Assert.AreEqual(DEFAULT_CACHE_SIZE, velocityEngine.GetProperty(RuntimeConstants.RESOURCE_MANAGER_DEFAULTCACHE_SIZE), "incorrect default cache size"); Assert.AreEqual(DEFAULT_CACHE_FLAG, velocityEngine.GetProperty(PropertySpring + VelocityConstants.Separator + PropertyResourceLoaderCachce), "incorrect caching flag"); AssertMergedValue(velocityEngine, "SimpleTemplate.vm"); AssertMergedValue(velocityEngine, "EmbeddedTemplate.vm"); }
/// <summary> /// The render. /// </summary> /// <param name="viewContext"> /// The view context. /// </param> /// <param name="writer"> /// The writer. /// </param> public void Render(ViewContext viewContext, TextWriter writer) { // 系统变量 this.context.Put("SiteUrl", Config.SiteUrl); this.context.Put( "ThemeUrl", string.Format( "{0}{1}{2}", Config.SiteUrl, Config.GetString("theme_root", "/theme/"), Setting.GetString("site_theme", "default")).ToLower()); this.context.Put("Settings", Setting.Settings); this.context.Put("Configs", Config.Configs); this.context.Put("RouteData", viewContext.RouteData); this.context.Put("UrlHelper", new UrlHelper(viewContext.RequestContext)); // Action视图包 foreach (var item in viewContext.ViewData) { this.context.Put(item.Key, item.Value); } var template = this.velocity.GetTemplate(this.viewName); if (this.layoutPath.Length != 0 && this.layoutName.Length != 0 && !controllerContext.IsChildAction) { var mainWriter = new StringWriter(); template.Merge(this.context, mainWriter); this.context.Put(Config.GetString("template_content_placeholder", "CONTENT_PLACEHOLDER"), mainWriter.ToString()); this.velocity = new VelocityEngine(); // 使用设置初始化VelocityEngine var props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, MachineHelper.MapPath(this.layoutPath)); // props.AddProperty(RuntimeConstants, viewPath); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); this.velocity.Init(props); Template layout = this.velocity.GetTemplate(this.layoutName); layout.Merge(this.context, writer); } else { template.Merge(this.context, writer); } }
internal string GetInvoiceText_Template(string templatefilename, string pathToDatabase, string userID, Invoice inv, InvoiceDtls[] list) { string template = GetTemplateFile(templatefilename, pathToDatabase); if (string.IsNullOrEmpty(template)) { return(""); } MyModel model = new MyModel(); model.Customer = GetCustomer(inv.custcode, model, pathToDatabase); model.PrintDate = DateTime.Now; model.UserID = userID; model.Invoicehdr = inv; model.InvDtls = new List <InvoiceDtls> (); model.TaxSumm = new List <TaxInfo> (); foreach (var item in list) { model.InvDtls.Add(item); } GetInvTaxInfo(list, pathToDatabase, model); VelocityEngine fileEngine = new VelocityEngine(); fileEngine.Init(); VelocityContext context = new VelocityContext(); StreamWriter ws = new StreamWriter(new MemoryStream()); context.Put("util", new CustomTool()); context.Put("model", model); fileEngine.Evaluate(context, ws, null, template); string text = ""; 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(); return(text); }
public void Generate(TestSuite testSuite) { VelocityEngine velocity = new VelocityEngine(); velocity.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); //velocity.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, settings.TemplatesDirectory); velocity.Init(); VelocityContext velocityContext = new VelocityContext(); velocityContext.Put("testSuite", testSuite); Template template = velocity.GetTemplate(templateFileName, new UTF8Encoding(false).WebName); using (StreamWriter writer = new StreamWriter(outputFileName, false, Encoding.UTF8)) { template.Merge(velocityContext, writer); } }
/// <summary> /// 创建NVelocity模板引擎,读取设计好的模板页面,替换占位符。 /// </summary> /// <param name="templateName"></param> /// <param name="data"></param> /// <param name="templateFilePath"></param> /// <returns></returns> public static string RenderTemplate(string templateName, object data, string templateFilePath) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath(templateFilePath)); vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); vltContext.Put("data", data); Template vltTemplate = vltEngine.GetTemplate(templateName + ".html"); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); return(vltWriter.GetStringBuilder().ToString()); }
/// <inheritdoc /> public override void Run() { Encoding encoding = new UTF8Encoding(false); string reportPath = Helper.Paging.GetReportPath(0); Template template = VelocityEngine.GetTemplate(Path.GetFileName(TemplatePath), encoding.BodyName); var stringBuilder = new StringBuilder(); using (var stringWriter = new StringWriter(stringBuilder)) { template.Merge(VelocityContext, stringWriter); using (var fileWriter = new StreamWriter(ReportWriter.ReportContainer.OpenWrite(reportPath, ContentType, encoding))) { fileWriter.Write(FormatHtmlHelper.Flatten(stringBuilder.ToString())); } } ReportWriter.AddReportDocumentPath(reportPath); }
public NVelocityViewEngine(IDictionary properties) { if (properties == null) { properties = DEFAULT_PROPERTIES; } var props = new ExtendedProperties(); foreach (string key in properties.Keys) { props.AddProperty(key, properties[key]); } _masterFolder = props.GetString("master.folder", string.Empty); _engine = new VelocityEngine(); _engine.Init(props); }
public static string RenderHtml(string templateName) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templete"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); 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> /// 初始话NVelocity模块 /// </summary> public void Init(string templatDir) { //创建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(templatDir)); //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(); }
protected void SetUp() { ve = new VelocityEngine(); ExtendedProperties ep = new ExtendedProperties(); ep.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); ep.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true"); ep.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true"); ep.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true"); ep.SetProperty("userdirective", "X3Platform.Velocity.Runtime.Directive.Component;X3Platform.Velocity,X3Platform.Velocity.Runtime.Directive.BlockComponent;X3Platform.Velocity"); ve.Init(ep); testProperties = new ExtendedProperties(); testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read)); }
private List <GenerateResult> GenerateInternal(TemplateOption option, List <Table> tables, CodeGenerateHandler handler) { var references = new List <Reference>(); foreach (var table in tables) { references.AddRange(table.ForeignKeys); } var tparts = option.Partitions.Where(s => s.Loop == PartitionLoop.Tables).ToList(); var nparts = option.Partitions.Where(s => s.Loop == PartitionLoop.None).ToList(); var engine = new VelocityEngine(); foreach (var table in tables) { var context = new VelocityContext(); context.Put("Tables", tables); context.Put("References", references); context.Put("Current", table); context.Put("Profile", option.Profile); foreach (var part in option.Partitions) { var props = new ExtendedProperties(); var info = new FileInfo(part.FilePath); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, info.DirectoryName); props.AddProperty(RuntimeConstants.COUNTER_INITIAL_VALUE, "0"); engine.Init(props); using (var writer = new StringWriter()) { engine.MergeTemplate(info.Name, "gb2312", context, writer); MessageBoxHelper.ShowExclamation(writer.ToString()); } } } return(null); }
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 " ; }
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 "; }
/// <summary>求值</summary> /// <param name="context">上下文环境</param> /// <param name="templateValue">模板信息</param> /// <returns></returns> public string Evaluate(VelocityContext context, string templateValue) { try { StringWriter writer = new StringWriter(); engine.Evaluate(context, writer, string.Empty, templateValue); return(writer.GetStringBuilder().ToString()); } catch { // 发生内部错误, 重启引擎. instance = null; engine = null; throw; } }
public ComponentDirectiveTestCase() { 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)); }
/// <summary> /// 生成内容 /// </summary> /// <returns></returns> public string GetString() { VelocityEngine ve = new VelocityEngine(); //模板引擎实例化 ExtendedProperties ep = new ExtendedProperties(); //模板引擎参数实例化 ep.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)300); //缓存时间(秒) ve.Init(ep); VelocityContext vc = new VelocityContext(); //当前的数据信息载体集合 foreach (var item in Items) { vc.Put(item.Key, item.Value); } TextWriter writer = new StringWriter(); ve.MergeTemplate(TemplateName, "utf-8", vc, writer); return(writer.ToString()); }
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 void ApplyTemplate(string templateName, Hashtable context, string outputFileName) { VelocityEngine velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); velocity.Init(props); string templateFileName = fileManager.GetFullFileName("Templates", templateName); Template template = velocity.GetTemplate(templateFileName); using (Stream stream = File.Open(outputFileName, FileMode.Create)) { using (TextWriter writer = new StreamWriter(stream)) { VelocityContext velocityContext = new VelocityContext(context); template.Merge(velocityContext, writer); } } }
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); } }
private void Init(string templatePath) { //创建VelocityEngine实例对象 velocity = new VelocityEngine(); //使用设置初始化VelocityEngine ExtendedProperties props = new ExtendedProperties(); if (!string.IsNullOrEmpty(templatePath)) { props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath); } props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); velocity.Init(props); //为模板变量赋值 context = new VelocityContext(); }
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)); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Initializes a new instance of the <see cref="LcmGenerateImpl"/> class. /// </summary> /// <param name="doc">The XMI document.</param> /// <param name="outputDir">The output dir.</param> /// <param name="outputFile">The output file name.</param> /// ------------------------------------------------------------------------------------ public LcmGenerateImpl(XmlDocument doc, string outputDir, string outputFile) { Generator = this; m_Document = doc; m_OutputDir = outputDir; m_OutputFileName = outputFile; var entireModel = (XmlElement)doc.GetElementsByTagName("EntireModel")[0]; m_Model = new Model(entireModel); m_Engine = new VelocityEngine(); m_Engine.Init(); m_Context = new VelocityContext(); m_Context.Put("lcmgenerate", this); m_Context.Put("model", m_Model); RuntimeSingleton.RuntimeServices.SetApplicationAttribute("LcmGenerate.Engine", m_Engine); RuntimeSingleton.RuntimeServices.SetApplicationAttribute("LcmGenerate.Context", m_Context); }
//public static string templatePath = ""; public TemplateHelper(string 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.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(); }
/// <summary> /// 初始化NVelocity /// </summary> /// <param name="templatDir">模板文件夹路径</param> public void Init(string templatDir) { //创建VelocityEngine实例对象 velocity = new VelocityEngine(); //设置模板文件夹 TemplateFolder = templatDir; //使用设置初始化VelocityEngine ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateFolder); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); velocity.Init(props); //为模板变量赋值 context = new VelocityContext(); }
/// <summary> /// Constructor. /// </summary> /// <param name="velocityEngine">The velocity engine</param> /// <param name="velocityContext">The current velocity context.</param> /// <param name="reportWriter">The report writer</param> /// <param name="templatePath">The template path.</param> /// <param name="contentType">The content type of the report.</param> /// <param name="extension">The extension of the report file.</param> /// <param name="helper">The formatting helper class.</param> protected VtlReportWriter(VelocityEngine velocityEngine, VelocityContext velocityContext, IReportWriter reportWriter, string templatePath, string contentType, string extension, FormatHelper helper) { if (velocityEngine == null) { throw new ArgumentNullException("velocityEngine"); } if (velocityContext == null) { throw new ArgumentNullException("velocityContext"); } if (reportWriter == null) { throw new ArgumentNullException("reportWriter"); } if (templatePath == null) { throw new ArgumentNullException("templatePath"); } if (contentType == null) { throw new ArgumentNullException("contentType"); } if (extension == null) { throw new ArgumentNullException("extension"); } if (helper == null) { throw new ArgumentNullException("helper"); } this.velocityEngine = velocityEngine; this.velocityContext = velocityContext; this.reportWriter = reportWriter; this.templatePath = templatePath; this.contentType = contentType; this.extension = extension; this.helper = helper; InitializeHelper(); }
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()); }
static string GetNVelocityBuffer(BaseType bt, string fileName) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants_Fields.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, "D:\\liubo\\github2\\test2\\AutoGenProtocol\\AutoGenProtocol\\"); vltEngine.Init(); VelocityContext context1 = new VelocityContext(); context1.Put("BaseType", bt); context1.Put("DateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); Template template = vltEngine.GetTemplate(fileName); StringWriter autoScriptWriter = new StringWriter(); template.Merge(context1, autoScriptWriter); return(autoScriptWriter.GetStringBuilder().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()); }
/// <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!"); } }
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 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; }
/// <summary> Default constructor. /// </summary> public ClassloaderChangeTest() : base("ClassloaderChangeTest") { try { /* * use an alternative logger. Set it up here and pass it in. */ ve = new VelocityEngine(); ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this); ve.init(); } catch (System.Exception e) { System.Console.Error.WriteLine("Cannot setup ClassloaderChnageTest : " + e); System.Environment.Exit(1); } }
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 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 NVelocityTemplateEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; velocityEngine.Init(); }
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 Init() { velocityEngine = new VelocityEngine(); velocityEngine.Init(); duck1 = new Duck1(); duck2 = new Duck2(); }
public void BeforeAnyTest() { velocityEngine = new VelocityEngine(); velocityEngine.Init(); }
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 StartNVelocity() { velocityEngine = new VelocityEngine(); velocityEngine.Init(); }
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()); }