public void SetUp()
		{
			ve = new VelocityEngine();
			ve.Init();

			ctx = new VelocityContext();
		}
Beispiel #2
0
        public void Setup()
        {
            context = new VelocityContext();

            ve = new VelocityEngine();
            ve.Init();
        }
        public string Eval(string text, bool wrapBetweenQuote)
        {
            VelocityContext c = new VelocityContext();
            Hashtable hash2 = new Hashtable();
            hash2["id"] = "123";
            c.Put("params", hash2);
            c.Put("style", "style='color:red'");
            c.Put("survey", 1);
            c.Put("id", 2);
            c.Put("siteRoot", String.Empty);
            c.Put("Helper", new Helper());
            c.Put("DictHelper", new DictHelper());

            StringWriter sw = new StringWriter();

            VelocityEngine velocityEngine = new VelocityEngine();
            velocityEngine.Init();

            string templatePrefix = "$Helper.Dump(";
            string templateSuffix = ")";
            string templateContent = (wrapBetweenQuote) ? '"' + text + '"' : text;

            string template = templatePrefix + templateContent + templateSuffix;

            bool ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", template);

            Assert.IsTrue(ok, "Evaluation returned failure");

            string result = sw.ToString();

            return result.StartsWith(templatePrefix) ? text : result;
        }
        public void 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 LineComponent1()
        {
            VelocityContext context = new VelocityContext();

            Template template = velocityEngine.GetTemplate(
                GetFileName(null, "componentusage1", TemplateTest.TMPL_FILE_EXT));

            StringWriter writer = new StringWriter();

            template.Merge(context, writer);

            System.Console.WriteLine(writer.GetStringBuilder().ToString());

            writer = new StringWriter();

            template.Merge(context, writer);

            System.Console.WriteLine(writer.GetStringBuilder().ToString());

            writer = new StringWriter();

            template.Merge(context, writer);

            System.Console.WriteLine(writer.GetStringBuilder().ToString());
        }
Beispiel #6
0
        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 virtual void Test_Run()
		{
			VelocityContext context = new VelocityContext();

			StringWriter writer = new StringWriter();
			Velocity.Evaluate(context, writer, "vm_chain1", template1);

			String output = writer.ToString();

			Assert.AreEqual(result1, output);
		}
Beispiel #8
0
        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();
        }
Beispiel #9
0
		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());
		}
Beispiel #10
0
		public void MathOperations()
		{
			System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

			VelocityContext context = new VelocityContext();

			context.Put("fval", 1.2f);
			context.Put("dval", 5.3);

			Velocity.Init();

			StringWriter sw = new StringWriter();

			Assert.IsTrue(Velocity.Evaluate(context, sw, string.Empty, "#set($total = 1 + 1)\r\n$total"));
			Assert.AreEqual("2", sw.GetStringBuilder().ToString());

			sw = new StringWriter();

			Assert.IsTrue(Velocity.Evaluate(context, sw, string.Empty, "#set($total = $fval + $fval)\r\n$total"));
			Assert.AreEqual("2.4", sw.GetStringBuilder().ToString());

			sw = new StringWriter();

			Assert.IsTrue(Velocity.Evaluate(context, sw, string.Empty, "#set($total = $dval + $dval)\r\n$total"));
			Assert.AreEqual("10.6", sw.GetStringBuilder().ToString());

			sw = new StringWriter();

			Assert.IsTrue(Velocity.Evaluate(context, sw, string.Empty, "#set($total = 1 + $dval)\r\n$total"));
			Assert.AreEqual("6.3", sw.GetStringBuilder().ToString());

			sw = new StringWriter();

			Assert.IsTrue(Velocity.Evaluate(context, sw, string.Empty, "#set($total = $fval * $dval)\r\n$total"));
			Assert.AreEqual("6.36000025272369", sw.GetStringBuilder().ToString());

			sw = new StringWriter();

			Assert.IsTrue(Velocity.Evaluate(context, sw, string.Empty, "#set($total = $fval - $dval)\r\n$total"));
			Assert.AreEqual("-4.09999995231628", sw.GetStringBuilder().ToString());

			sw = new StringWriter();

			Assert.IsTrue(Velocity.Evaluate(context, sw, string.Empty, "#set($total = $fval % $dval)\r\n$total"));
			Assert.AreEqual("1.20000004768372", sw.GetStringBuilder().ToString());

			sw = new StringWriter();

			Assert.IsTrue(Velocity.Evaluate(context, sw, string.Empty, "#set($total = $fval / $dval)\r\n$total"));
			Assert.AreEqual("0.22641510333655", sw.GetStringBuilder().ToString());
		}
		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;
		}
		public void Setup()
		{
			ve = new VelocityEngine();
			ve.Init();
			
			// creates the context...
			c = new VelocityContext();

			// attach a new event cartridge
			c.AttachEventCartridge(new EventCartridge());

			// add our custom handler to the ReferenceInsertion event
			c.EventCartridge.ReferenceInsertion +=
				new ReferenceInsertionEventHandler(EventCartridge_ReferenceInsertion);
		}
		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 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());
		}
Beispiel #15
0
		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());
		}
Beispiel #16
0
		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);
		}
Beispiel #17
0
		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 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 static string ParseNVelocityTemplate(string template, Hashtable paramList)
        {
            System.Text.StringBuilder builder = new System.Text.StringBuilder(template);

            VelocityEngine vltEngine = new VelocityEngine();

            vltEngine.Init();

            VelocityContext vltContext = new VelocityContext();

            foreach (DictionaryEntry item in paramList)
            {
                vltContext.Put(item.Key.ToString(), item.Value);
            }

            System.IO.StringWriter vltWriter = new System.IO.StringWriter();

            vltEngine.Evaluate(vltContext, vltWriter, null, builder.ToString());

            return(vltWriter.GetStringBuilder().ToString());
        }
Beispiel #20
0
        /// <summary>
        /// 渲染模板引擎
        /// </summary>
        /// <param name="dic">需要替换的参数</param>
        /// <param name="temp">html文件名</param>
        /// <returns></returns>
        public static string WriteTemplate(object data, string temp)
        {
            //用的时候考代码即可,只需改三个地方:模板所在文件夹、添加数据、设定模板
            VelocityEngine vltEngine = new VelocityEngine();

            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹,例如我的模板为templates文件夹下的TestNV.html
            vltEngine.Init();

            VelocityContext vltContext = new VelocityContext();

            vltContext.Put("data", data);                       //可添加多个数据,基本支持所有数据类型,包括字典、数据、datatable等  添加数据,在模板中可以通过$dataName来引用数据
            Template vltTemplate = vltEngine.GetTemplate(temp); //设定模板

            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            vltTemplate.Merge(vltContext, vltWriter);

            string html = vltWriter.GetStringBuilder().ToString();

            return(html);//返回渲染生成的标准html代码字符串
        }
Beispiel #21
0
        private string HtmlMenu(Componente componente)
        {
            if (componente.Conteudo == null)
            {
                componente.Conteudo = "";
            }
            var writer  = new StringWriter();
            var context = new VelocityContext();

            context.Put("menu", Pagina.GetPaginasUsuario());
            context.Put("area", Pagina.GetAreaCorrente(false));
            context.Put("site", Pagina.Site());
            var pagina = Pagina.Current();

            if (pagina != null)
            {
                context.Put("pagina_corrente", pagina);
            }
            Velocity.Evaluate(context, writer, "", componente.Conteudo);
            return(writer.GetStringBuilder().ToString());
        }
Beispiel #22
0
        protected void GetEditSetInfo(ref VelocityContext vltContext)
        {
            int @int = base.GetInt("PEPackageID", 0);

            if (@int > 0)
            {
                PEIS.Model.BusPEPackage model = PEIS.BLL.BusPEPackage.Instance.GetModel(@int);
                vltContext.Put("PEPackageID", model.PEPackageID);
                vltContext.Put("PEPackageName", model.PEPackageName);
                vltContext.Put("IDBanOpr", model.IDBanOpr);
                vltContext.Put("CreatorID", model.CreatorID);
                vltContext.Put("InputCode", model.InputCode);
                vltContext.Put("isBanned", model.isBanned);
                vltContext.Put("Note", model.Note);
                vltContext.Put("BanDescribe", model.BanDescribe);
                vltContext.Put("DispOrder", model.DispOrder);
                vltContext.Put("BanDate", model.BanDate);
                vltContext.Put("CreateDate", model.CreateDate);
                vltContext.Put("Forsex", model.Forsex);
            }
        }
Beispiel #23
0
 protected void GetEditFeeReportInfo(int ID_FeeReport, ref VelocityContext vltContext)
 {
     if (ID_FeeReport > 0)
     {
         PEIS.Model.BusFeeReport model = PEIS.BLL.BusFeeReport.Instance.GetModel(ID_FeeReport);
         if (null != model)
         {
             vltContext.Put("ID_FeeReport", model.ID_FeeReport);
             vltContext.Put("ID_Fee", model.ID_Fee);
             vltContext.Put("FeeName", model.FeeName);
             vltContext.Put("Is_Banned", model.Is_Banned);
             vltContext.Put("Operator", model.Operator);
             vltContext.Put("ID_BanOpr", model.ID_Operator);
             vltContext.Put("BanDescribe", model.BanDescribe);
             vltContext.Put("OperateDate", model.OperateDate);
             vltContext.Put("Note", model.Note);
             vltContext.Put("ImageUrl", model.ImageUrl);
             vltContext.Put("ReportKey", model.ReportKey);
         }
     }
 }
Beispiel #24
0
        /// <summary>
        /// 用data数据填充templateName模板,渲染生成html返回
        /// </summary>
        /// <param name="templateName"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string RenderHtml(string templateName, object data)
        {
            VelocityEngine vltEngine = new VelocityEngine();

            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹
            vltEngine.Init();

            VelocityContext vltContext = new VelocityContext();

            vltContext.Put("Data", data);//设置参数,在模板中可以通过$data来引用

            Template vltTemplate = vltEngine.GetTemplate(templateName);

            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            vltTemplate.Merge(vltContext, vltWriter);

            string html = vltWriter.GetStringBuilder().ToString();

            return(html);
        }
		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());
		}
Beispiel #26
0
        /// <inheritdoc />
        /// <summary>
        /// Renderiza um template a partir do nome utilizando masterPage, substituindo as variáveis do template pelas variáveis passadas como parâmetro
        /// </summary>
        /// <param name="masterPage">Nome da master page</param>
        /// <param name="templateName">Nome do Template</param>
        /// <param name="data">Dicionário com as váriáveis (Chave/Valor)</param>
        /// <returns>Template com as variávies substituídas</returns>
        public string RenderTemplate(string masterPage, string templateName, IDictionary <string, object> data)
        {
            if (string.IsNullOrEmpty(templateName))
            {
                throw new ArgumentException("O parâmetro \"templateName\" não foi informado", nameof(templateName));
            }

            var name = !string.IsNullOrEmpty(masterPage)
                ? masterPage : templateName;

            var engine = new VelocityEngine();
            var props  = new ExtendedProperties();

            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, _templatesPath);
            engine.Init(props);

            engine.GetTemplate(name, Encoding.UTF8.BodyName);

            var context      = new VelocityContext();
            var templateData = data ?? new Dictionary <string, object>();

            foreach (var key in templateData.Keys)
            {
                context.Put(key, templateData[key]);
            }

            if (!string.IsNullOrEmpty(masterPage))
            {
                context.Put("childContent", templateName);
            }
            string retorno;

            using (var writer = new StringWriter())
            {
                engine.MergeTemplate(name, Encoding.UTF8.BodyName, context, writer);
                retorno = writer.GetStringBuilder().ToString();
            }

            return(retorno);
        }
Beispiel #27
0
        public void GenerateCode()
        {
            VelocityEngine velocity = new VelocityEngine();

            TextReader reader   = new StreamReader(NvelocityUtil.GetTemplateFolderPath() + "\\CustomItem.base.vm");
            string     template = reader.ReadToEnd();

            //Setup the template with the needed code, and then do the merge
            VelocityContext baseContext = new VelocityContext();

            baseContext.Put("Usings", CustomItemInformation.Usings);
            baseContext.Put("BaseTemplates", CustomItemInformation.BaseTemplates);
            baseContext.Put("CustomItemFields", CustomItemInformation.Fields);
            baseContext.Put("CustomItemInformation", CustomItemInformation);

            //Get the full file path to the .base.cs file
            string filePath = FileUtil.GetClassFilePath(CustomItemInformation.ClassName,
                                                        CustomItemInformation.FolderPathProvider.GetFolderPath(
                                                            CustomItemInformation.Template, CustomItemInformation.BaseFileRoot));


            //Build the folder strucutre so that we have a place to put the .base.cs file
            BuildFolderStructure(CustomItemInformation);

            //Write the .base.cs file
            if (GenerateBaseFile)
            {
                using (StreamWriter sw = new StreamWriter(filePath))
                {
                    //TODO add error checking
                    Velocity.Init();
                    sw.Write(Sitecore.Text.NVelocity.VelocityHelper.Evaluate(baseContext, template, "base-custom-item"));
                    GenerationMessage += filePath + " successfully written\n\n";
                    GeneratedFilePaths.Add(filePath);
                }
            }

            //Write out the other partial files
            OuputPartialFiles(velocity);
        }
Beispiel #28
0
        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());
        }
Beispiel #29
0
        /// <summary>
        /// Ouputs the partial class files for a custom item.
        /// </summary>
        /// <param name="velocity">The velocity.</param>
        private void OuputPartialFiles(VelocityEngine velocity)
        {
            StringWriter writer;
            TextReader   reader     = new StreamReader(NvelocityUtil.GetTemplateFolderPath() + "\\CustomItem.partial.vm");
            string       template   = reader.ReadToEnd();
            string       folderPath = CustomItemInformation.FolderPathProvider.GetFolderPath(CustomItemInformation.Template,
                                                                                             CustomItemInformation.BaseFileRoot);

            VelocityContext partialContext = new VelocityContext();

            partialContext.Put("CustomItemInformation", CustomItemInformation);

            writer = new StringWriter();
            writer.Write(Sitecore.Text.NVelocity.VelocityHelper.Evaluate(partialContext, template, "base-custom-item"));

            //.instance.cs
            if (GenerateInstanceFile)
            {
                //Only create the file if it does not already exist
                string instanceFilePath = folderPath + "\\" + CustomItemInformation.ClassName + ".instance.cs";
                OutputFileIfDoesNotExist(instanceFilePath, writer);
            }

            //.interface.cs
            if (GenerateInterfaceFile)
            {
                //Only create the file if it does not already exist
                string interfaceFilePath = folderPath + "\\" + CustomItemInformation.ClassName + ".interface.cs";
                OutputFileIfDoesNotExist(interfaceFilePath, writer);
            }

            //.static.cs
            if (GenerateStaticFile)
            {
                //Only create the file if it does not already exist
                string staticFilePath = folderPath + "\\" + CustomItemInformation.ClassName + ".static.cs";
                OutputFileIfDoesNotExist(staticFilePath, writer);
            }
        }
        /// <summary>
        /// Generates a report filled with the content supplied by <paramref name="report"/>.
        /// </summary>
        /// <param name="report">Specifies the report model.</param>
        public void Generate(IReport report)
        {
            var engine     = new VelocityEngine();
            var properties = new ExtendedProperties();

            properties.AddProperty("resource.loader", "assembly");
            properties.AddProperty("resource.manager.class", typeof(ResourceManagerImpl).AssemblyQualifiedName);
            properties.AddProperty("directive.manager", EncodeExternalAssemblyQualifiedType(typeof(DirectiveManagerProxy)));
            properties.AddProperty("assembly.resource.loader.class", typeof(AssemblyResourceLoader).AssemblyQualifiedName);
            properties.AddProperty("assembly.resource.loader.assembly", GetType().Assembly.GetName().Name);
            engine.Init(properties);

            var htmlTemplate      = engine.GetTemplate("Xunit.Reporting.Internal.Generator.HtmlTemplate.vm");
            var generationContext = new VelocityContext();

            generationContext.Put("report", report);
            generationContext.Put("pluralizer", new Pluralizer());

            _outputWriter.Write(
                string.Concat(report.ReflectedAssembly, ".html"),
                writer => htmlTemplate.Merge(generationContext, writer));
        }
Beispiel #31
0
        public override IRow Transform(IRow row)
        {
            var context = new VelocityContext();

            foreach (var field in _input)
            {
                context.Put(field.Alias, row[field]);
            }

            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb)) {
                NVelocity.App.Velocity.Evaluate(context, sw, _templateName, Context.Transform.Template);
                sw.Flush();
            }

            sb.Trim(' ', '\n', '\r');
            row[Context.Field] = Context.Field.Convert(sb.ToString());

            Increment();
            return(row);
        }
Beispiel #32
0
        public void Render(ViewContext viewContext, TextWriter writer)
        {
            this.ViewData = viewContext.ViewData;

            bool hasLayout = this._masterTemplate != null;

            VelocityContext context = this.CreateContext(viewContext);

            if (hasLayout)
            {
                var sw = new StringWriter();
                this._viewTemplate.Merge(context, sw);

                context.Put(Config.GetString("template_content_placeholder", "CONTENT_PLACEHOLDER"), sw.GetStringBuilder());

                this._masterTemplate.Merge(context, writer);
            }
            else
            {
                this._viewTemplate.Merge(context, writer);
            }
        }
Beispiel #33
0
 public override void ReplaceContent(ref VelocityContext vltContext)
 {
     vltContext.Put("webName", this.SiteName);
     vltContext.Put("pageTitle", base.GetUrlEncode("title"));
     vltContext.Put("modelName", base.GetString("modelName").ToLower());
     vltContext.Put("type", base.GetString("type").ToLower());
     vltContext.Put("CurDate", DateTime.Now.ToString("yyyy年M月dd日"));
     this.type = base.GetString("type").ToLower();
     if (this.type == "add")
     {
         vltContext.Put("CreateDate", DateTime.Now.ToString("yyyy-MM-dd"));
         vltContext.Put("Creator", this.UserName);
         vltContext.Put("ID_Creator", this.ID_User);
     }
     else if (this.type == "edit")
     {
         string    iD_Team  = base.GetString("ID_Team").Trim();
         string    teamName = base.GetString("TeamName").Trim();
         DataTable teamInfo = CommonTeam.Instance.GetTeamInfo(iD_Team, teamName);
         this.OutPutTable(ref vltContext, teamInfo);
     }
 }
Beispiel #34
0
        public void Render(ViewContext viewContext, TextWriter writer)
        {
            this.ViewData = viewContext.ViewData;

            bool hasLayout = _masterTemplate != null;

            VelocityContext context = CreateContext(viewContext);

            if (hasLayout)
            {
                StringWriter sw = new StringWriter();
                _viewTemplate.Merge(context, sw);

                context.Put("childContent", sw.GetStringBuilder().ToString());

                _masterTemplate.Merge(context, writer);
            }
            else
            {
                _viewTemplate.Merge(context, writer);
            }
        }
Beispiel #35
0
        /// <summary></summary>
        public override string ParseHtml()
        {
            string widgetRuntimeId = StringHelper.ToGuid();

            VelocityContext context = new VelocityContext();

            context.Put("widgetRuntimeId", widgetRuntimeId);

            context.Put("height", (this.Height == 0 ? "height:auto;" : "height:" + this.Height + "px;"));
            context.Put("width", (this.Width == 0 ? "width:auto;" : "width:" + this.Width + "px;"));

            if (string.IsNullOrEmpty(this.options["widgetHtml"]))
            {
                context.Put("widgetHtml", "请编写相关的Html格式编码。");
            }
            else
            {
                context.Put("widgetHtml", this.options["widgetHtml"]);
            }

            return(VelocityManager.Instance.Merge(context, "themes/" + WebConfigurationView.Instance.ThemeName + "/widgets/static-html.vm"));
        }
Beispiel #36
0
        private void GenerateReportFile(
            string outputFileNameFormat,
            string templateFileName,
            Hashtable context)
        {
            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(context);

            velocityContext.Put("settings", settings);
            velocityContext.Put("reportTime", DateTime.Now);

            Template template = velocity.GetTemplate(templateFileName, new UTF8Encoding(false).WebName);

            string outputFileName;

            using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
            {
                velocity.Evaluate(velocityContext, writer, "dummy", outputFileNameFormat);
                writer.Flush();
                outputFileName = writer.ToString();
            }

            string fullOutputFileName = Path.Combine(settings.OutputDirectory, outputFileName);

            // make sure the path exists
            AccipioHelper.EnsureDirectoryPathExists(fullOutputFileName, true);

            using (Stream stream = File.Open(fullOutputFileName, FileMode.Create))
            {
                using (TextWriter writer = new StreamWriter(stream, new UTF8Encoding(false)))
                {
                    template.Merge(velocityContext, writer);
                }
            }
        }
Beispiel #37
0
        public void ParamArraySupport2()
        {
            VelocityContext c = new VelocityContext();

            c.Put("x", new Something2());

            StringWriter sw = new StringWriter();

            VelocityEngine ve = new VelocityEngine();

            ve.Init();

            Boolean ok = false;

            ok = ve.Evaluate(c, sw,
                             "ContextTest.CaseInsensitive",
                             "$x.Contents( \"hammett\", 1 )");

            Assert.IsTrue(ok, "Evalutation returned failure");
            Assert.AreEqual("hammett1", sw.ToString());

            sw = new StringWriter();

            ok = ve.Evaluate(c, sw,
                             "ContextTest.CaseInsensitive",
                             "$x.Contents( \"hammett\", 1, \"x\" )");

            Assert.IsTrue(ok, "Evalutation returned failure");
            Assert.AreEqual("hammett1x", sw.ToString());

            sw = new StringWriter();

            ok = ve.Evaluate(c, sw,
                             "ContextTest.CaseInsensitive",
                             "$x.Contents( \"hammett\", 1, \"x\", \"y\" )");

            Assert.IsTrue(ok, "Evalutation returned failure");
            Assert.AreEqual("hammett1x,y", sw.ToString());
        }
Beispiel #38
0
        public string EsqueciSenha()
        {
            var componente = new Componente();

            componente.Chave = "esqueci_senha";
            componente.Get();
            if (componente.Conteudo == null)
            {
                componente.Conteudo = "";
            }
            var writer  = new StringWriter();
            var context = new VelocityContext();

            context.Put("site", Pagina.Site());
            if (Session.Get("[EsqueciSenha]Login") != null)
            {
                context.Put("mensagem", Session.Get("[EsqueciSenha]Login").ToString());
                Session.Invalidate("[EsqueciSenha]Login");
            }
            Velocity.Evaluate(context, writer, "", componente.Conteudo);
            return(writer.GetStringBuilder().ToString());
        }
        public override string ParseHtml()
        {
            string widgetRuntimeId = StringHelper.ToGuid();

            VelocityContext context = new VelocityContext();

            context.Put("widgetRuntimeId", widgetRuntimeId);

            context.Put("height", (this.Height == 0 ? "height:auto;" : "height:" + this.Height + "px;"));
            context.Put("width", (this.Width == 0 ? "width:auto;" : "width:" + this.Width + "px;"));

            context.Put("categoryIndex", this.options["categoryIndex"]);

            // 设置最大行数
            int maxRowCount;

            int.TryParse(this.options["maxRowCount"], out maxRowCount);

            if (maxRowCount < 1)
            {
                maxRowCount = 1;
            }

            if (maxRowCount > 100)
            {
                maxRowCount = 100;
            }

            context.Put("maxRowCount", maxRowCount);

            // 设置最大标题长度
            int maxLength;

            int.TryParse(this.options["maxLength"], out maxLength);

            context.Put("maxLength", maxLength);

            return(VelocityManager.Instance.Merge(context, "themes/" + WebConfigurationView.Instance.ThemeName + "/widgets/forum.vm"));
        }
        private string GetFileName(string sTemplate, VelocityContext context)
        {
            StreamReader fReader           = new StreamReader(@".\Templates\" + sTemplate);
            string       sFileNameTemplate = fReader.ReadLine();

            if (sFileNameTemplate.StartsWith("##FILENAME:"))
            {
                sFileNameTemplate = sFileNameTemplate.Substring(11);
            }
            else
            {
                // default to base filename
                sFileNameTemplate = "${table.GetClassName}.cs";
            }
            StringReader reader = new StringReader(sFileNameTemplate);
            StringWriter writer = new StringWriter();

            engine.Evaluate(context, writer, null, reader);
            string fileName = writer.GetStringBuilder().ToString();

            return(fileName);
        }
Beispiel #41
0
        public string Login()
        {
            var componente = new Componente();

            componente.Chave = "form_login";
            componente.Get();
            if (componente.Conteudo == null)
            {
                componente.Conteudo = "";
            }
            var writer  = new StringWriter();
            var context = new VelocityContext();

            context.Put("site", Pagina.Site());
            if (Session.Get("[Erro]Login") != null)
            {
                context.Put("erro", Session.Get("[Erro]Login").ToString());
                Session.Invalidate("[Erro]Login");
            }
            Velocity.Evaluate(context, writer, "", componente.Conteudo);
            return(writer.GetStringBuilder().ToString());
        }
Beispiel #42
0
        public string GetHtmlAlterarEndereco()
        {
            var usuario = Usuario.Current();

            var componente = new Componente();

            componente.Chave = "adesao-alterar-endereco";
            componente.Get();
            if (componente.Conteudo == null)
            {
                return("");
            }

            Velocity.Init();
            var writer  = new StringWriter();
            var context = new VelocityContext();

            context.Put("site", Pagina.Site());
            context.Put("usuario", this);
            Velocity.Evaluate(context, writer, "", componente.Conteudo);
            return(writer.GetStringBuilder().ToString());
        }
        public void Expand(WebResponseData response)
        {
            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Expanding template '{0}'", templateFileName);
            }

            VelocityEngine     velocity = new VelocityEngine();
            ExtendedProperties props    = new ExtendedProperties();

            velocity.Init(props);

            Hashtable contextHashtable = new Hashtable();

            foreach (KeyValuePair <string, object> pair in templateParameters)
            {
                contextHashtable.Add(pair.Key, pair.Value);
            }

            VelocityContext velocityContext = new VelocityContext(contextHashtable);

            Template template = velocity.GetTemplate(templateFileName, new UTF8Encoding(false).WebName);

            response.ContentType = contentType;

            using (StreamWriter writer = new StreamWriter(response.OutputStream))
            {
                try
                {
                    template.Merge(velocityContext, writer);
                }
                catch (Exception ex)
                {
                    writer.WriteLine();
                    writer.WriteLine("Error in template '{0}': '{1}'", templateFileName, ex);
                }
            }
        }
Beispiel #44
0
        public PaymentTicketsStruct GetTickets(Consortium consortium, IList <PaymentTicket> paymentTickets, int month)
        {
            Velocity.Init();
            var toDate = month < 12 ? new DateTime(DateTime.Now.Year, month + 1, 18, 0, 0, 0).ToString("MMM dd", new CultureInfo("es-AR")).ToUpper() :
                         new DateTime(DateTime.Now.Year + 1, 1, 18, 0, 0, 0).ToString("MMM dd", new CultureInfo("es-AR")).ToUpper();

            foreach (var item in paymentTickets)
            {
                item.DiscountDay = item.DiscountDay ?? 0;
            }

            var model = new
            {
                FromDate          = new DateTime(DateTime.Now.Year, month, 18, 0, 0, 0).ToString("MMM dd", new CultureInfo("es-AR")).ToUpper(),
                ToDate            = toDate,
                ConsortiumAddress = consortium.Ownership.Address.Street + " " + consortium.Ownership.Address.Number,
                Items             = paymentTickets,
                FontFamily        = "Arial",
                FontSize          = "12pt"
            };
            var velocityContext = new VelocityContext();

            velocityContext.Put("model", model);

            var templateFile = string.Format(@"{0}\Resources\PaymentTicketsTemplate.html", Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath));
            var template     = new StringBuilder(File.ReadAllText(templateFile));
            var stylesFile   = string.Format(@"{0}\Resources\PaymentTickets.css", Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath));
            var styles       = new StringBuilder(File.ReadAllText(stylesFile));


            var finalTickets = new StringBuilder();

            Velocity.Evaluate(velocityContext, new StringWriter(finalTickets), "Payment Tickets", new StringReader(template.ToString()));

            return(new PaymentTicketsStruct {
                HtmlTickets = finalTickets, HtmlTicketsStyles = styles
            });
        }
Beispiel #45
0
        private string RenderContent()
        {
            if (Contents.Content.Equals(string.Empty))
            {
                _process.Logger.Warn("Template {0} is empty.", Name);
                return(string.Empty);
            }

            string renderedContent;

            if (Engine.Equals("velocity"))
            {
                var context = new VelocityContext();
                context.Put("Process", _process);
                foreach (var parameter in Parameters)
                {
                    context.Put(parameter.Value.Name, parameter.Value.Value);
                }
                using (var sw = new StringWriter()) {
                    Velocity.Evaluate(context, sw, string.Empty, Contents.Content);
                    renderedContent = sw.GetLifetimeService().ToString();
                }
            }
            else
            {
                var config          = new FluentTemplateServiceConfiguration(c => c.WithEncoding(ContentType));
                var templateService = new TemplateService(config);
                Razor.SetTemplateService(templateService);

                renderedContent = Razor.Parse(Contents.Content, new {
                    Process    = _process,
                    Parameters = Parameters.ToExpandoObject()
                });
            }

            _process.Logger.Debug("Rendered {0} template.", Name);
            return(renderedContent);
        }
        public static void CommonGenerateCode(List <ClassInfo> AllCls, string TemplateFileName, string OutputFile)
        {
            var util = new TypeUtil();

            util.dict = new Dictionary <string, string>();

            util.dict.Add(typeof(int).Name, "int");
            util.dict.Add(typeof(Int64).Name, "Int64");
            util.dict.Add(typeof(string).Name, "std::string");

            foreach (var cls in AllCls)
            {
                util.dict.Add(cls.Name, cls.Name);
            }


            VelocityEngine ve = new VelocityEngine();

            ve.Init();


            VelocityContext vc = new VelocityContext();

            //传入模板所需要的参数
            vc.Put("AllCls", AllCls); //设置参数为对象,在模板中可以通过$dic.dudu 来引用
            vc.Put("util", util);


            StringWriter sw = new StringWriter();
            // 注意cls.Name必须是属性,而不是普通的成员变量,要不会无效!
            string vt = File.ReadAllText(TemplateFileName);

            ve.Evaluate(vc, sw, "gen-src-tag", vt);

            Console.WriteLine(sw.GetStringBuilder().ToString());

            File.WriteAllText(OutputFile, sw.GetStringBuilder().ToString());
        }
        /// <summary> Runs the test.
        /// </summary>
        public virtual void  runTest()
        {
            try {
                Template template1 = RuntimeSingleton.getTemplate(getFileName(null, "path1", TMPL_FILE_EXT));

                Template template2 = RuntimeSingleton.getTemplate(getFileName(null, "path2", TMPL_FILE_EXT));

                System.IO.FileStream fos1 = new System.IO.FileStream(getFileName(RESULTS_DIR, "path1", RESULT_FILE_EXT), System.IO.FileMode.Create);

                System.IO.FileStream fos2 = new System.IO.FileStream(getFileName(RESULTS_DIR, "path2", RESULT_FILE_EXT), System.IO.FileMode.Create);

                //UPGRADE_ISSUE: Constructor 'java.io.BufferedWriter.BufferedWriter' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javaioBufferedWriterBufferedWriter_javaioWriter"'
                System.IO.StreamWriter writer1 = new BufferedWriter(new System.IO.StreamWriter(fos1));
                //UPGRADE_ISSUE: Constructor 'java.io.BufferedWriter.BufferedWriter' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javaioBufferedWriterBufferedWriter_javaioWriter"'
                System.IO.StreamWriter writer2 = new BufferedWriter(new System.IO.StreamWriter(fos2));

                /*
                 *  put the Vector into the context, and merge both
                 */

                VelocityContext context = new VelocityContext();

                template1.merge(context, writer1);
                writer1.Flush();
                writer1.Close();

                template2.merge(context, writer2);
                writer2.Flush();
                writer2.Close();

                if (!isMatch(RESULTS_DIR, COMPARE_DIR, "path1", RESULT_FILE_EXT, CMP_FILE_EXT) || !isMatch(RESULTS_DIR, COMPARE_DIR, "path2", RESULT_FILE_EXT, CMP_FILE_EXT))
                {
                    fail("Output incorrect.");
                }
            } catch (System.Exception e) {
                fail(e.Message);
            }
        }
Beispiel #48
0
        public async static Task <string> Generate(
            string ipAddress,
            PnPServerContext dbContext
            )
        {
            var templateConfig = await dbContext.TemplateConfigurations
                                 .Include("Template")
                                 .Include("NetworkDevice")
                                 .Include("Properties")
                                 .Where(x => x.NetworkDevice.IPAddress == ipAddress)
                                 .FirstOrDefaultAsync();

            if (templateConfig == null)
            {
                // TODO : Throw
                return(string.Empty);
            }

            string template = templateConfig.Template.Content;

            var context = new VelocityContext();

            foreach (var prop in templateConfig.Properties)
            {
                context.Put(prop.Name, prop.Value);
            }

            var engine = new VelocityEngine();

            engine.Init();

            var outputWriter = new StringWriter();

            engine.Evaluate(context, outputWriter, "eval1", template);
            var templateText = outputWriter.GetStringBuilder().ToString();

            return(templateText);
        }
        public virtual void Test_Run()
        {
            VelocityContext context = new VelocityContext();
            context.Put("name", "jason");
            context.Put("Floog", "floogie woogie");

            Velocity.Evaluate(context, compare1, "evaltest", input1);

            /*
            FIXME: Not tested right now.

            StringWriter result2 = new StringWriter();
            Velocity.mergeTemplate("mergethis.vm",  context, result2);

            StringWriter result3 = new StringWriter();
            Velocity.invokeVelocimacro("floog", "test", new String[2],
            context, result3);*/

            if (!result1.Equals(compare1.ToString()))
            {
                Assert.Fail("Output incorrect.");
            }
        }
Beispiel #50
0
        public static string RenderHtml(string templateName, object data)
        {
            //初始化模板引擎
            VelocityEngine vltEngine = new VelocityEngine();

            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));
            vltEngine.Init();
            // 设置变量
            VelocityContext vltContext = new VelocityContext();

            vltContext.Put("Model", data);

            // 获取模板文件
            Template vltTemplate = vltEngine.GetTemplate(templateName);
            // 输出
            StringWriter vltWriter = new StringWriter();

            vltTemplate.Merge(vltContext, vltWriter);
            string html = vltWriter.GetStringBuilder().ToString();

            return(html);
        }
Beispiel #51
0
		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());

		}
        /// <summary> Runs the test :
        /// *
        /// uses the Velocity class to eval a string
        /// which accesses a method that throws an
        /// exception.
        /// </summary>
        public virtual void runTest()
        {
            System.String template = "$woogie.doException() boing!";

            VelocityContext vc = new VelocityContext()
            ;

            vc.put("woogie", this);

            System.IO.StringWriter w = new System.IO.StringWriter();

            try {
            Velocity.evaluate(vc, w, "test", template)
            ;
            fail("No exception thrown");
            } catch (MethodInvocationException mie) {
            System.Console.Out.WriteLine("Caught MIE (good!) :");
            System.Console.Out.WriteLine("  reference = " + mie.ReferenceName);
            System.Console.Out.WriteLine("  method    = " + mie.MethodName);

            //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"'
            System.Exception t = mie.WrappedThrowable;
            System.Console.Out.WriteLine("  throwable = " + t);

            if (t is System.Exception) {
            System.Console.Out.WriteLine("  exception = " + ((System.Exception) t).Message);
            }
            } catch (System.Exception e) {
            fail("Wrong exception thrown, first test." + e);
            SupportClass.WriteStackTrace(e, Console.Error);
            }

            /*
            *  second test - to ensure that methods accessed via get+ construction
            *  also work
            */

            template = "$woogie.foo boing!";

            try
            {
            Velocity.evaluate(vc, w, "test", template)
            ;
            fail("No exception thrown, second test.");
            }
            catch (MethodInvocationException mie) {
            System.Console.Out.WriteLine("Caught MIE (good!) :");
            System.Console.Out.WriteLine("  reference = " + mie.ReferenceName);
            System.Console.Out.WriteLine("  method    = " + mie.MethodName);

            //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"'
            System.Exception t = mie.WrappedThrowable;
            System.Console.Out.WriteLine("  throwable = " + t);

            if (t is System.Exception) {
            System.Console.Out.WriteLine("  exception = " + ((System.Exception) t).Message);
            }
            } catch (System.Exception e) {
            fail("Wrong exception thrown, second test");
            }

            template = "$woogie.Foo boing!";

            try
            {
            Velocity.evaluate(vc, w, "test", template)
            ;
            fail("No exception thrown, third test.");
            }
            catch (MethodInvocationException mie) {
            System.Console.Out.WriteLine("Caught MIE (good!) :");
            System.Console.Out.WriteLine("  reference = " + mie.ReferenceName);
            System.Console.Out.WriteLine("  method    = " + mie.MethodName);

            //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"'
            System.Exception t = mie.WrappedThrowable;
            System.Console.Out.WriteLine("  throwable = " + t);

            if (t is System.Exception) {
            System.Console.Out.WriteLine("  exception = " + ((System.Exception) t).Message);
            }
            } catch (System.Exception e) {
            fail("Wrong exception thrown, third test");
            }

            template = "#set($woogie.foo = 'lala') boing!";

            try
            {
            Velocity.evaluate(vc, w, "test", template)
            ;
            fail("No exception thrown, set test.");
            }
            catch (MethodInvocationException mie) {
            System.Console.Out.WriteLine("Caught MIE (good!) :");
            System.Console.Out.WriteLine("  reference = " + mie.ReferenceName);
            System.Console.Out.WriteLine("  method    = " + mie.MethodName);

            //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"'
            System.Exception t = mie.WrappedThrowable;
            System.Console.Out.WriteLine("  throwable = " + t);

            if (t is System.Exception) {
            System.Console.Out.WriteLine("  exception = " + ((System.Exception) t).Message);
            }
            } catch (System.Exception e) {
            fail("Wrong exception thrown, set test");
            }
        }
Beispiel #53
0
		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());			
		}
Beispiel #54
0
		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());
		}
Beispiel #55
0
		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());
		}
Beispiel #56
0
	/// <summary>
	/// Process an XML file using Velocity
	/// </summary>
	private void Process(String basedir, String xmlFile, FileInfo destdir, AnakiaXmlDocument projectDocument) {
	    FileInfo outFile = null;
	    FileInfo inFile = null;
	    StreamWriter writer = null;
	    try {
		// the current input file relative to the baseDir
		inFile = new System.IO.FileInfo(basedir + Path.DirectorySeparatorChar.ToString() + xmlFile);
		// the output file relative to basedir
		outFile = new System.IO.FileInfo(destdir + Path.DirectorySeparatorChar.ToString() + xmlFile.Substring(0, (xmlFile.LastIndexOf((System.Char) '.')) - (0)) + extension);

		// only process files that have changed
		if (lastModifiedCheck == false || (inFile.LastWriteTime.Ticks > outFile.LastWriteTime.Ticks || styleFile.LastWriteTime.Ticks > outFile.LastWriteTime.Ticks || projectFile.LastWriteTime.Ticks > outFile.LastWriteTime.Ticks)) {
		    EnsureDirectoryFor(outFile);

		    //-- command line status
		    Log.WriteLine(LogPrefix + "Input:  " + inFile);

		    // Build the Anakia Document
		    AnakiaXmlDocument root = new AnakiaXmlDocument();
		    root.Load(inFile.FullName);

		    // Shove things into the Context
		    VelocityContext context = new VelocityContext();

		    /*
		    *  get the property TEMPLATE_ENCODING
		    *  we know it's a string...
		    */
		    String encoding = (String) ve.GetProperty(RuntimeConstants_Fields.OUTPUT_ENCODING);
		    if (encoding == null || encoding.Length == 0 || encoding.Equals("8859-1") || encoding.Equals("8859_1")) {
			encoding = "ISO-8859-1";
		    }

		    context.Put("root", root.DocumentElement);
		    context.Put("relativePath", getRelativePath(xmlFile));
		    context.Put("escape", new Escape());
		    context.Put("date", System.DateTime.Now);

		    // only put this into the context if it exists.
		    if (projectDocument != null) {
			context.Put("project", projectDocument.DocumentElement);
		    }

		    // Process the VSL template with the context and write out
		    // the result as the outFile.
		    writer = new System.IO.StreamWriter(new System.IO.FileStream(outFile.FullName, System.IO.FileMode.Create));
		    // get the template to process

		    Template template = ve.GetTemplate(styleFile.Name)
		    ;
		    template.Merge(context, writer);

		    Log.WriteLine(LogPrefix + "Output: " + outFile);
		}
	    } catch (System.Exception e) {
		Log.WriteLine(LogPrefix + "Failed to process " + inFile);
		if (outFile != null) {
		    bool tmpBool2;
		    if (System.IO.File.Exists(outFile.FullName)) {
			System.IO.File.Delete(outFile.FullName);
			tmpBool2 = true;
		    } else if (System.IO.Directory.Exists(outFile.FullName)) {
			System.IO.Directory.Delete(outFile.FullName);
			tmpBool2 = true;
		    } else
			tmpBool2 = false;
		    bool generatedAux3 = tmpBool2;
		}
		SupportClass.WriteStackTrace(e, Console.Error);
	    } finally {
		if (writer != null) {
		    try {
			writer.Flush();
			writer.Close();
		    } catch (System.Exception e) {
			// closing down, just ignore
		    }
		}
	    }
	}
		protected void SetUp()
		{
			provider = new TestProvider();
			al = provider.Customers;
			h = new Hashtable();

			SupportClass.PutElement(h, "Bar", "this is from a hashtable!");
			SupportClass.PutElement(h, "Foo", "this is from a hashtable too!");

			/*
			*  lets set up a vector of objects to test late introspection. See ASTMethod.java
			*/

			vec = new ArrayList();

			vec.Add(new String("string1".ToCharArray()));
			vec.Add(new String("string2".ToCharArray()));

			/*
			*  set up 3 chained contexts, and add our data 
			*  through the 3 of them.
			*/

			context2 = new VelocityContext();
			context1 = new VelocityContext(context2);
			context = new VelocityContext(context1);

			context.Put("provider", provider);
			context1.Put("name", "jason");
			context2.Put("providers", provider.Customers2);
			context.Put("list", al);
			context1.Put("hashtable", h);
			context2.Put("hashmap", new Hashtable());
			context2.Put("search", provider.Search);
			context.Put("relatedSearches", provider.RelSearches);
			context1.Put("searchResults", provider.RelSearches);
			context2.Put("stringarray", provider.Array);
			context.Put("vector", vec);
			context.Put("mystring", new String(string.Empty.ToCharArray()));
			context.Put("runtime", new FieldMethodizer("NVelocity.Runtime.RuntimeSingleton"));
			context.Put("fmprov", new FieldMethodizer(provider));
			context.Put("Floog", "floogie woogie");
			context.Put("boolobj", new BoolObj());

			/*
	    *  we want to make sure we test all types of iterative objects
	    *  in #foreach()
	    */

			Object[] oarr = new Object[] {"a", "b", "c", "d"};
			int[] intarr = new int[] {10, 20, 30, 40, 50};

			context.Put("collection", vec);
			context2.Put("iterator", vec.GetEnumerator());
			context1.Put("map", h);
			context.Put("obarr", oarr);
			context.Put("enumerator", vec.GetEnumerator());
			context.Put("intarr", intarr);
		}
		public void CacheProblems()
		{
			VelocityContext context = new VelocityContext();

			context.Put("AjaxHelper2", new AjaxHelper2());
			context.Put("DictHelper", new DictHelper());

			Template template = velocityEngine.GetTemplate(
				GetFileName(null, "dicthelper", TemplateTest.TMPL_FILE_EXT));

			StringWriter writer = new StringWriter();

			template.Merge(context, writer);

			System.Console.WriteLine(writer.GetStringBuilder().ToString());

			writer = new StringWriter();

			template.Merge(context, writer);

			System.Console.WriteLine(writer.GetStringBuilder().ToString());

			writer = new StringWriter();

			template.Merge(context, writer);

			System.Console.WriteLine(writer.GetStringBuilder().ToString());
		}
Beispiel #59
0
        /// <summary> Runs the test.
        /// </summary>
        public virtual void runTest()
        {
            VelocityContext context = new VelocityContext();

            try {
            assureResultsDirectoryExists(org.apache.velocity.test.TemplateTestBase_Fields.RESULT_DIR);

            /*
            *  get the template and the output
            */

            /*
            *  Chinese and spanish
            */

            Template template = Velocity.getTemplate(getFileName(null, "encodingtest", org.apache.velocity.test.TemplateTestBase_Fields.TMPL_FILE_EXT), "UTF-8")
            ;

            System.IO.FileStream fos = new System.IO.FileStream(getFileName(org.apache.velocity.test.TemplateTestBase_Fields.RESULT_DIR, "encodingtest", org.apache.velocity.test.TemplateTestBase_Fields.RESULT_FILE_EXT), System.IO.FileMode.Create);

            //UPGRADE_ISSUE: Constructor 'java.io.BufferedWriter.BufferedWriter' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javaioBufferedWriterBufferedWriter_javaioWriter"'
            System.IO.StreamWriter writer = new BufferedWriter(new System.IO.StreamWriter(fos));

            template.merge(context, writer);
            writer.Flush();
            writer.Close();

            if (!isMatch(org.apache.velocity.test.TemplateTestBase_Fields.RESULT_DIR, org.apache.velocity.test.TemplateTestBase_Fields.COMPARE_DIR, "encodingtest", org.apache.velocity.test.TemplateTestBase_Fields.RESULT_FILE_EXT, org.apache.velocity.test.TemplateTestBase_Fields.CMP_FILE_EXT)) {
            fail("Output 1 incorrect.");
            }

            /*
            *  a 'high-byte' chinese example from Michael Zhou
            */

            template = Velocity.getTemplate(getFileName(null, "encodingtest2", org.apache.velocity.test.TemplateTestBase_Fields.TMPL_FILE_EXT), "UTF-8")
            ;

            fos = new System.IO.FileStream(getFileName(org.apache.velocity.test.TemplateTestBase_Fields.RESULT_DIR, "encodingtest2", org.apache.velocity.test.TemplateTestBase_Fields.RESULT_FILE_EXT), System.IO.FileMode.Create);

            //UPGRADE_ISSUE: Constructor 'java.io.BufferedWriter.BufferedWriter' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javaioBufferedWriterBufferedWriter_javaioWriter"'
            writer = new BufferedWriter(new System.IO.StreamWriter(fos));

            template.merge(context, writer);
            writer.Flush();
            writer.Close();

            if (!isMatch(org.apache.velocity.test.TemplateTestBase_Fields.RESULT_DIR, org.apache.velocity.test.TemplateTestBase_Fields.COMPARE_DIR, "encodingtest2", org.apache.velocity.test.TemplateTestBase_Fields.RESULT_FILE_EXT, org.apache.velocity.test.TemplateTestBase_Fields.CMP_FILE_EXT)) {
            fail("Output 2 incorrect.");
            }

            /*
            *  a 'high-byte' chinese from Ilkka
            */

            template = Velocity.getTemplate(getFileName(null, "encodingtest3", org.apache.velocity.test.TemplateTestBase_Fields.TMPL_FILE_EXT), "GBK")
            ;

            fos = new System.IO.FileStream(getFileName(org.apache.velocity.test.TemplateTestBase_Fields.RESULT_DIR, "encodingtest3", org.apache.velocity.test.TemplateTestBase_Fields.RESULT_FILE_EXT), System.IO.FileMode.Create);

            //UPGRADE_ISSUE: Constructor 'java.io.BufferedWriter.BufferedWriter' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javaioBufferedWriterBufferedWriter_javaioWriter"'
            writer = new BufferedWriter(new System.IO.StreamWriter(fos));

            template.merge(context, writer);
            writer.Flush();
            writer.Close();

            if (!isMatch(org.apache.velocity.test.TemplateTestBase_Fields.RESULT_DIR, org.apache.velocity.test.TemplateTestBase_Fields.COMPARE_DIR, "encodingtest3", org.apache.velocity.test.TemplateTestBase_Fields.RESULT_FILE_EXT, org.apache.velocity.test.TemplateTestBase_Fields.CMP_FILE_EXT)) {
            fail("Output 3 incorrect.");
            }

            /*
            *  Russian example from Vitaly Repetenko
            */

            template = Velocity.getTemplate(getFileName(null, "encodingtest_KOI8-R", org.apache.velocity.test.TemplateTestBase_Fields.TMPL_FILE_EXT), "KOI8-R")
            ;

            fos = new System.IO.FileStream(getFileName(org.apache.velocity.test.TemplateTestBase_Fields.RESULT_DIR, "encodingtest_KOI8-R", org.apache.velocity.test.TemplateTestBase_Fields.RESULT_FILE_EXT), System.IO.FileMode.Create);

            //UPGRADE_ISSUE: Constructor 'java.io.BufferedWriter.BufferedWriter' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javaioBufferedWriterBufferedWriter_javaioWriter"'
            writer = new BufferedWriter(new System.IO.StreamWriter(fos));

            template.merge(context, writer);
            writer.Flush();
            writer.Close();

            if (!isMatch(org.apache.velocity.test.TemplateTestBase_Fields.RESULT_DIR, org.apache.velocity.test.TemplateTestBase_Fields.COMPARE_DIR, "encodingtest_KOI8-R", org.apache.velocity.test.TemplateTestBase_Fields.RESULT_FILE_EXT, org.apache.velocity.test.TemplateTestBase_Fields.CMP_FILE_EXT)) {
            fail("Output 4 incorrect.");
            }
            } catch (System.Exception e) {
            fail(e.Message);
            }
        }
		public void ResetContext()
		{
			c = new VelocityContext();
			c.Put("test", new TestClass());
		}