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());
        }
示例#2
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());
		}
示例#3
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 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)");
		}
示例#5
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 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 override string ParseHtml()
        {
            string widgetRuntimeId = StringHelper.ToGuid();

            VelocityContext context = new VelocityContext();

            context.Put("widgetRuntimeId", widgetRuntimeId);

            return(VelocityManager.Instance.Merge(context, "themes/" + WebConfigurationView.Instance.ThemeName + "/widgets/today.vm"));
        }
示例#8
0
        private static VelocityContext GetContextFromDictionary(Dictionary <string, object> param)
        {
            VelocityContext context = new VelocityContext();

            foreach (KeyValuePair <string, object> pair in param)
            {
                context.Put(pair.Key, pair.Value);
            }
            return(context);
        }
        public void TemplateForeachNoDataSection2()
        {
            c.Put("items", null);

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

            Assert.True(ok, "Evaluation returned failure");
            Assert.Equal("nothing", Normalize(sw));
        }
示例#10
0
        public static string FormatText(string templateText, IDictionary <string, object> values)
        {
            var nvelocityContext = new VelocityContext();

            foreach (var tagValue in values)
            {
                nvelocityContext.Put(tagValue.Key, tagValue.Value);
            }
            return(FormatText(templateText, nvelocityContext));
        }
示例#11
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
			";
		}
示例#12
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
			"            ;
        }
示例#13
0
        public void CreateXML(SCModel scModel, string xmlPath)
        {
            VelocityEngine     ve = new VelocityEngine();             //模板引擎实例化
            ExtendedProperties ep = new ExtendedProperties();         //模板引擎参数实例化

            ep.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); //指定资源的加载类型
            string ss = HttpContext.Current.Server.MapPath(".");

            ep.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(".")); //指定资源的加载路径
            //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.GetDirectoryName(HttpContext.Current.Request.PhysicalPath));
            ep.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");                                            //输入格式
            ep.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");                                           //输出格式

            //模板的缓存设置
            ep.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true);            //是否缓存
            ep.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)300); //缓存时间(秒)
            ve.Init(ep);

            //一、加载模板
            Template        template   = ve.GetTemplate("config/XMLTemplate/collection.xml"); //加载模板
            VelocityContext vltContext = new VelocityContext();                               //当前的数据信息载体集合

            //二、填充值
            string serviceID = scModel.ServiceInfo.ServiceID;

            vltContext.Put("servicename", scModel.ServiceInfo.ServiceName);
            vltContext.Put("collectiondes", ((DataSourceCollection)scModel.DataSource).CollectionDescription);
            vltContext.Put("starttimedes", ((DataSourceCollection)scModel.DataSource).StartTimeDescription);
            vltContext.Put("starttime", ((DataSourceCollection)scModel.DataSource).StartTimeValue);
            vltContext.Put("perioddes", ((DataSourceCollection)scModel.DataSource).PeriodDescription);
            vltContext.Put("period", ((DataSourceCollection)scModel.DataSource).PeriodValue);
            vltContext.Put("SCLinks", scModel.SCLinks);
            vltContext.Put("sourceid", scModel.ServiceInfo.SourceID);
            vltContext.Put("servicegroup", scModel.ServiceInfo.ServiceGroup);

            //三、合并模板输出内容
            var vltWriter = new StringWriter();

            template.Merge(vltContext, vltWriter);//合并数据集合对象到输出流.
            string      innerxml = vltWriter.GetStringBuilder().ToString();
            XmlDocument xmlDoc   = new XmlDocument();

            xmlDoc.InnerXml = innerxml;
            string filexml = xmlPath + serviceID + ".xml";

            xmlDoc.Save(filexml);
        }
        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);
        }
 protected override void BeforeFormat(INoticeMessage message, ITagValue[] tagsValues)
 {
     _nvelocityContext = new VelocityContext();
     _nvelocityContext.AttachEventCartridge(new EventCartridge());
     _nvelocityContext.EventCartridge.ReferenceInsertion += EventCartridgeReferenceInsertion;
     foreach (var tagValue in tagsValues)
     {
         _nvelocityContext.Put(tagValue.Tag, tagValue.Value);
     }
     base.BeforeFormat(message, tagsValues);
 }
示例#16
0
        public override void CreateFile()
        {
            PestControlData controlData;

            if (String.IsNullOrEmpty(this.xmlSettingsFile))
            {
                controlData = new PestControlData();
            }
            else
            {
                FileStream readXmlSettings = new FileStream(this.xmlSettingsFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                try
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(PestControlData));
                    controlData = (PestControlData)serializer.Deserialize(readXmlSettings);
                }
                finally
                {
                    readXmlSettings.Close();
                }
            }


            controlData.AddObservationGroupNames(modelRunner.GetRecordedVariableNames());

            //controlData.AddObservationGroupNames((ModelPropertiesOutputRecordingDefinition)modelRunDefinition.Outputs);
            controlData.AddModelIOInformation(templateFile, parameterFile);
            controlData.AddModelIOInformation(instructionFile, resultFile);
            controlData.CreateCommandLine(this.commandLineExecutable, parameterFile);
            controlData.SetDefaultControlValues();
            controlData.AddParameterSet(this.startingPoint);
            controlData.SetMaxNumberOfIterations(this.NumberOfIterations);
            string observationGroupName = controlData.ObservationGroupNames[0];

            controlData.AddObservationalData(observedTimeSeries, observationGroupName);

            VelocityEngine velocity = createNewVelocityEngine();

            // Set up the required velocity data types and parameters

            //TODO: can this be done in the same way as the instruction file?
            Template        controlTemplate = velocity.GetTemplate("CSIRO.Metaheuristics.UseCases.PEST.FileCreation.Resources.ControlFile.vm");
            StringWriter    writer          = new StringWriter();
            VelocityContext controlContext  = new VelocityContext();

            controlContext.Put(VELOCITY_CONTROL_DATA, controlData);
            controlTemplate.Merge(controlContext, writer);

            StreamWriter controlWriter = new StreamWriter(controlFile);

            controlWriter.Write(writer);
            writer.Close();
            controlWriter.Close();
        }
        private static VelocityContext CreateContext(TemplateValues values)
        {
            var context = new VelocityContext();

            foreach (var item in values)
            {
                context.Put(item.Key, item.Value);
            }

            return(context);
        }
示例#18
0
        public string GetConteudoRenderizado(Hashtable parans)
        {
            Velocity.Init();
            var context = new VelocityContext(parans);

            context.Put("template", new Template());
            context.Put("componente", new Componente());
            context.Put("site", Pagina.Site());
            context.Put("area", Pagina.GetAreaCorrente(false));
            var usuario = Usuario.Current();

            if (usuario != null)
            {
                context.Put("usuario", usuario);
            }
            var writer = new StringWriter();

            Velocity.Evaluate(context, writer, "", this.Conteudo.Replace("&#39;", "'"));
            return(writer.GetStringBuilder().ToString());
        }
示例#19
0
 protected void GetEditExamItemGroupInfo(int ID_ExamItemGroup, ref VelocityContext vltContext)
 {
     if (ID_ExamItemGroup > 0)
     {
         PEIS.Model.BusExamItemGroup model = PEIS.BLL.BusExamItemGroup.Instance.GetModel(ID_ExamItemGroup);
         if (null != model)
         {
             vltContext.Put("ID_ExamItemGroup", model.ID_ExamItemGroup);
             vltContext.Put("ExamItemGroupName", model.ExamItemGroupName);
             vltContext.Put("Is_Banned", model.Is_Banned);
             vltContext.Put("Operator", model.Operator);
             vltContext.Put("DispOrder", model.DispOrder);
             vltContext.Put("InputCode", model.InputCode);
             vltContext.Put("ID_BanOpr", model.ID_Operator);
             vltContext.Put("BanDescribe", model.BanDescribe);
             vltContext.Put("OperateDate", model.OperateDate);
             vltContext.Put("Note", model.Note);
         }
     }
 }
示例#20
0
        static void Main(string[] args)
        {
            Boolean write2File       = false;
            List <NetPontoModel> npm = new List <NetPontoModel>();

            #region JustForgetAboutIt


            npm.Add(new NetPontoModel("SAP Analytics Experience - O Poder da Inteligência Colectiva", "Centro Cultural de Belém, Lisboa "));
            npm.Add(new NetPontoModel("Testing Portugal 2013", "SANA Malhoa Hotel"));
            npm.Add(new NetPontoModel("CMO Forum 2013", "Centro Cultural de Belém"));
            npm.Add(new NetPontoModel("Oracle Day - Lisboa", "Centro de Congressos de Lisboa"));
            npm.Add(new NetPontoModel("LXJS - Lisbon Javascript 2013", "Cinema São Jorge"));
            npm.Add(new NetPontoModel("BSidesLisbon 2013", "Forum Picoas"));
            npm.Add(new NetPontoModel("The Portuguese Perl Workshop 2013", " Portugal Telecom"));
            npm.Add(new NetPontoModel("Cisco Connect Portugal 2013", "Centro de Congressos do Estor"));
            npm.Add(new NetPontoModel("Adobe - Create Now RoadShow 2013", "Meliá Ria Hotel & Spa"));
            npm.Add(new NetPontoModel("EMC Forum 2013", "Centro de Congresso Hotel Myriad by Sana Hotel"));
            npm.Add(new NetPontoModel("World Tech - Tour Novos Desafios e Tendências no eProcurement", " Centro Cultural de Belém - "));
            npm.Add(new NetPontoModel("LxMLS - 3rd Lisbon Machine Learning School", " Instituto Superior Técnico"));
            npm.Add(new NetPontoModel("Big Data & Analytics Forum", "Lisboa"));
            npm.Add(new NetPontoModel("43ª Reunião Presencial da Comunidade NetPonto", "Microsoft Lisbon Experience"));

            #endregion

            //1 - Initialize Velocity.
            Velocity.Init();
            //2 - Create a Context object (more on what that is later).
            VelocityContext context = new VelocityContext();

            //3 - Add your data objects to the Context.
            context.Put("Events", npm);

            //4 - Choose a template.
            Template t = Velocity.GetTemplate(@"templates/netponto.vm");
            //5 - 'Merge' the template and your data to produce the ouput.
            StringWriter sw = new StringWriter();
            t.Merge(context, sw);


            String page = sw.GetStringBuilder().ToString();
            //Show the result
            Console.WriteLine(page);

            #region Write2File
            if (write2File)
            {
                StreamWriter file = new StreamWriter(@"templates/netponto.html");
                file.WriteLine(page);
                file.Close();
            }
            #endregion
            Console.ReadKey();
        }
示例#21
0
 public virtual string Process(string source, Dictionary<string, object> context)
 {
     VelocityContext velocityContext = new VelocityContext();
     foreach (KeyValuePair<string, object> pair in context)
     {
         velocityContext.Put(pair.Key, pair.Value);
     }
     StringWriter writer = new StringWriter();
     velocityEngine.Evaluate(velocityContext, writer, "", source);
     return writer.GetStringBuilder().ToString();
 }
示例#22
0
        /// ------------------------------------------------------------------------------------
        /// <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);
        }
 protected void GetEditFinalConclusionTypeInfo(int ID_FinalConclusionType, ref VelocityContext vltContext)
 {
     if (ID_FinalConclusionType > 0)
     {
         PEIS.Model.DctFinalConclusionType model = PEIS.BLL.DctFinalConclusionType.Instance.GetModel(ID_FinalConclusionType);
         if (null != model)
         {
             vltContext.Put("ID_FinalConclusionType", model.ID_FinalConclusionType);
             vltContext.Put("FinalConclusionTypeName", model.FinalConclusionTypeName);
             vltContext.Put("Is_Banned", model.Is_Banned);
             vltContext.Put("ID_BanOpr", model.ID_BanOpr);
             vltContext.Put("BanOperator", model.BanOperator);
             vltContext.Put("BanDescribe", model.BanDescribe);
             vltContext.Put("BanDate", model.BanDate);
             vltContext.Put("DispOrder", model.DispOrder);
             vltContext.Put("Note", model.Note);
             vltContext.Put("FinalConclusionSignCode", model.FinalConclusionSignCode);
         }
     }
 }
        public override string PrintCode()
        {
            VelocityContext context = new VelocityContext();

            context.Put("author", this.Author);
            context.Put("package", this.Package);
            context.Put("className", this.ClassName);
            context.Put("entityClassPackage", this.EntityClassPackage);
            context.Put("entityClass", this.EntityClass);
            context.Put("businessLogicInterfacePackage", this.BusinessLogicInterfacePackage);
            context.Put("businessLogicInterface", this.BusinessLogicInterface);
            context.Put("dataAccessInterfacePackage", this.DataAccessInterfacePackage);
            context.Put("dataAccessInterface", this.DataAccessInterface);

            return(VelocityManager.Instance.ParseTemplateVirtualPath(context,
                                                                     StringHelper.NullOrEmptyTo(TemplateFile, "templates/Java/BusinessLogicServiceImpl.vm")));
        }
        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());
        }
示例#26
0
        public string WriteEditDto()
        {
            Template        template = VelocityEngine.GetTemplate("EditDto.vm");
            VelocityContext context  = new VelocityContext();

            context.Put("people", "华威");

            StringWriter writer = new StringWriter();

            template.Merge(context, writer);
            return(writer.GetStringBuilder().ToString());
        }
示例#27
0
 public virtual string Process(Dictionary<string, object> context,string templateFile)
 {
     VelocityContext velocityContext = new VelocityContext();
     foreach (KeyValuePair<string, object> pair in context)
     {
         velocityContext.Put(pair.Key, pair.Value);
     }
     Template template = velocityEngine.GetTemplate(templateFile);
     StringWriter writer = new StringWriter();
     template.Merge(velocityContext, writer);
     return writer.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());
		}
示例#29
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());
        }
示例#30
0
        /// <summary>
        /// 用data数据填充templateName模板,渲染生成html返回
        /// </summary>
        /// <param name="templateName"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string RenderHtml(string templateName, object data, object data2)
        {
            VelocityEngine vltEngine = new VelocityEngine();

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

            VelocityContext vltContext = new VelocityContext();

            vltContext.Put("Data", data);//设置参数,在模板中可以通过$data来引用
            vltContext.Put("Data2", data2);
            Template vltTemplate = vltEngine.GetTemplate(templateName);

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

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

            return(html);
        }
示例#31
0
 public override void ReplaceContent(ref VelocityContext vltContext)
 {
     vltContext.Put("type", base.GetString("type").ToLower());
     vltContext.Put("modelName", base.GetString("modelName").ToLower());
     vltContext.Put("UserID", this.UserID);
     vltContext.Put("UserName", this.UserName);
     vltContext.Put("CurDate", DateTime.Now.ToString("yyyy-MM-dd"));
     vltContext.Put("pageTitle", "个人登记工作量统计");
     vltContext.Put("RegisterDT", CommonTeam.Instance.StatsUserInfoByRight("13,89"));
 }
示例#32
0
 public override void ReplaceContent(ref VelocityContext vltContext)
 {
     vltContext.Put("flag", base.GetString("flag").ToLower());
     vltContext.Put("type", base.GetString("type").ToLower());
     vltContext.Put("modelName", base.GetString("modelName").ToLower());
     vltContext.Put("UserID", this.UserID);
     vltContext.Put("UserName", this.UserName);
     vltContext.Put("CurDate", DateTime.Now.ToString("yyyy-MM-dd"));
     vltContext.Put("pageTitle", "导检查询");
 }
示例#33
0
 public override void ReplaceContent(ref VelocityContext vltContext)
 {
     vltContext.Put("type", base.GetString("type").ToLower());
     vltContext.Put("modelName", base.GetString("modelName").ToLower());
     vltContext.Put("UserID", this.UserID);
     vltContext.Put("UserName", this.UserName);
     vltContext.Put("CurDate", DateTime.Now.ToString("yyyy-MM-dd"));
     vltContext.Put("pageTitle", "收费项目统计");
     vltContext.Put("BusFeeDT", CommonTeam.Instance.StatsFeeName());
 }
示例#34
0
        public override string ParseHtml()
        {
            // http://www.woaic.com/2013/03/389

            string widgetRuntimeId = StringHelper.ToGuid();

            VelocityContext context = new VelocityContext();

            context.Put("widgetRuntimeId", widgetRuntimeId);

            return(VelocityManager.Instance.Merge(context, "themes/" + WebConfigurationView.Instance.ThemeName + "/widgets/mobile.vm"));
        }
示例#35
0
 public override void ReplaceContent(ref VelocityContext vltContext)
 {
     vltContext.Put("type", base.GetString("type").ToLower());
     vltContext.Put("modelName", base.GetString("modelName").ToLower());
     vltContext.Put("UserID", this.UserID);
     vltContext.Put("UserName", this.UserName);
     vltContext.Put("CurDate", DateTime.Now.ToString("yyyy-MM-dd"));
     vltContext.Put("pageTitle", "收费项目工作量统计");
     vltContext.Put("TeamDT", CommonTeam.Instance.GetTeamInfoByKeyWords(string.Empty));
 }
示例#36
0
        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());
        }
示例#37
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);
        }
示例#38
0
        public static VelocityContext PrepareContext(UserActivity userActivity, UserInfo user)
        {
            var velocitycontext = new VelocityContext();

            velocitycontext.Put("activity", userActivity);
            velocitycontext.Put("url", CommonLinkUtility.GetFullAbsolutePath(userActivity.URL));
            velocitycontext.Put("user", user);
            velocitycontext.Put("displayName", user.DisplayUserName());
            velocitycontext.Put("userLink", CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetUserProfile(user.ID, userActivity.ProductID)));
            velocitycontext.Put("moduleName", GetModuleName(userActivity));
            velocitycontext.Put("productName", GetProductName(userActivity));
            velocitycontext.Put("additionalData", userActivity.AdditionalData);
            return(velocitycontext);
        }
示例#39
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);
        }
示例#40
0
        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.");
            }
        }
		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());
		}
示例#42
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());
		}
示例#43
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());

		}
        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);
            }
        }
示例#46
0
		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);
		}
示例#47
0
		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());
		}
示例#48
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());			
		}
		public void ResetContext()
		{
			c = new VelocityContext();
			c.Put("test", new TestClass());
		}
示例#50
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());
		}
示例#51
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());
		}
示例#52
0
		public void Test_Evaluate()
		{
			VelocityContext c = new VelocityContext();
			c.Put("key", "value");
			c.Put("firstName", "Cort");
			c.Put("lastName", "Schaefer");
			Hashtable h = new Hashtable();
			h.Add("foo", "bar");
			c.Put("hashtable", h);

			AddressData address = new AddressData();
			address.Address1 = "9339 Grand Teton Drive";
			address.Address2 = "Office in the back";
			c.Put("address", address);

			ContactData contact = new ContactData();
			contact.Name = "Cort";
			contact.Address = address;
			c.Put("contact", contact);

			// test simple objects (no nesting)
			StringWriter sw = new StringWriter();
			bool ok = Velocity.Evaluate(c, sw, string.Empty, "$firstName is my first name, my last name is $lastName");
			Assert.IsTrue(ok, "Evaluation returned failure");
			String s = sw.ToString();
			Assert.AreEqual("Cort is my first name, my last name is Schaefer", s, "test simple objects (no nesting)");

			// test nested object
			sw = new StringWriter();
			String template = "These are the individual properties:\naddr1=9339 Grand Teton Drive\naddr2=Office in the back";
			ok = Velocity.Evaluate(c, sw, string.Empty, template);
			Assert.IsTrue(ok, "Evaluation returned failure");
			s = sw.ToString();
			Assert.IsFalse(String.Empty.Equals(s), "test nested object");

			// test hashtable
			sw = new StringWriter();
			template = "Hashtable lookup: foo=$hashtable.foo";
			ok = Velocity.Evaluate(c, sw, string.Empty, template);
			Assert.IsTrue(ok, "Evaluation returned failure");
			s = sw.ToString();
			Assert.AreEqual("Hashtable lookup: foo=bar", s, "Evaluation did not evaluate right");

			// test nested properties
			//    	    sw = new StringWriter();
			//	    template = "These are the nested properties:\naddr1=$contact.Address.Address1\naddr2=$contact.Address.Address2";
			//	    ok = Velocity.Evaluate(c, sw, string.Empty, template);
			//	    Assert("Evaluation returned failure", ok);
			//	    s = sw.ToString();
			//	    Assert("test nested properties", s.Equals("These are the nested properties:\naddr1=9339 Grand Teton Drive\naddr2=Office in the back"));

			// test key not found in context
			sw = new StringWriter();
			template = "$!NOT_IN_CONTEXT";
			ok = Velocity.Evaluate(c, sw, string.Empty, template);
			Assert.IsTrue(ok, "Evaluation returned failure");
			s = sw.ToString();
			Assert.AreEqual(String.Empty, s, "test key not found in context");

			// test nested properties where property not found
			//	    sw = new StringWriter();
			//	    template = "These are the non-existent nested properties:\naddr1=$contact.Address.Address1.Foo\naddr2=$contact.Bar.Address.Address2";
			//	    ok = Velocity.Evaluate(c, sw, string.Empty, template);
			//	    Assert("Evaluation returned failure", ok);
			//	    s = sw.ToString();
			//	    Assert("test nested properties where property not found", s.Equals("These are the non-existent nested properties:\naddr1=\naddr2="));
		}
示例#53
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
		    }
		}
	    }
	}