/// <summary> /// Starts/configure NVelocity based on the properties. /// </summary> public void BeginInit() { vengine = new VelocityEngine(); var props = new ExtendedProperties(); var expandedTemplateDir = ExpandTemplateDir(templateDir); Log.InfoFormat("Initializing NVelocityTemplateEngine component using template directory: {0}", expandedTemplateDir); var propertiesFile = new FileInfo(Path.Combine(expandedTemplateDir, "nvelocity.properties")); if (propertiesFile.Exists) { Log.Info("Found 'nvelocity.properties' on template dir, loading as base configuration"); using (Stream stream = propertiesFile.OpenRead()) props.Load(stream); } props.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, expandedTemplateDir); props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, EnableCache ? "true" : "false"); vengine.Init(props); }
/// <summary> /// Initializes basic velocity properties. The main purpose of this method is to /// allow this logic to be overrided. /// </summary> /// <param name="props">The <see cref="ExtendedProperties"/> collection to populate.</param> protected virtual void InitializeVelocityProperties(ExtendedProperties props) { props.SetProperty(RuntimeConstants_Fields.RESOURCE_MANAGER_CLASS, "NVelocity.Runtime.Resource.ResourceManagerImpl\\,NVelocity"); props.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, ViewRootDir); // add support for global macros. they must be defined in "Views/macros". ArrayList macros = new ArrayList(); DirectoryInfo macrosPath = new DirectoryInfo(Path.Combine(ViewRootDir, "macros")); if (macrosPath.Exists) { foreach (FileInfo file in macrosPath.GetFiles("*" + TemplateExtension)) { macros.Add("macros/" + file.Name); } } if (macros.Count > 0) { object m = props.GetProperty(RuntimeConstants_Fields.VM_LIBRARY); if (m is ICollection) { macros.AddRange((ICollection)m); } else if (m is string) { macros.Add(m); } props.AddProperty(RuntimeConstants_Fields.VM_LIBRARY, macros); props.AddProperty(RuntimeConstants_Fields.VM_LIBRARY_AUTORELOAD, true); } }
public override void Configure(DirectoryInfo workingDirectory, NameValueCollection props) { try { File.Delete("nvelocity.log"); } catch (IOException) { // TODO: This is evil! need to investigate further. Cannot get // exclusive lock on the log file with this assembly now a // library (as opposed to an exe). However not convinced that // the line isn't a hangover from java conversion. Need to // investigate further. ; } base.Configure(workingDirectory, props); ExtendedProperties p = new ExtendedProperties(); string templateName = props["template"]; string templateSrc; if (templateName == null) { log.Info("No template file was specified, using default"); p.SetProperty("resource.loader", "class"); p.SetProperty("class.resource.loader.class", "NHibernate.Tool.hbm2net.StringResourceLoader;NHibernate.Tool.hbm2net"); templateSrc = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Tool.hbm2net.convert.vm")). ReadToEnd(); } else { // NH-242 raised issue of where NVelocity looks when supplied with a unpathed file name. Hence // will take responsiblity of explicitly instructing NVelocity where to look. if (!Path.IsPathRooted(templateName)) { templateName = Path.Combine(this.WorkingDirectory.FullName, templateName); } if (!File.Exists(templateName)) { string msg = string.Format("Cannot find template file using absolute path or relative to '{0}'.", this.WorkingDirectory.FullName); throw new IOException(msg); } p.SetProperty("resource.loader", "class"); p.SetProperty("class.resource.loader.class", "NHibernate.Tool.hbm2net.StringResourceLoader;NHibernate.Tool.hbm2net"); using (StreamReader sr = new StreamReader(File.OpenRead(templateName))) { templateSrc = sr.ReadToEnd(); sr.Close(); } } ve = new VelocityEngine(); ve.Init(p); template = ve.GetTemplate(templateSrc); }
/// <summary> /// Initialize a SpringResourceLoader for the given VelocityEngine. /// <br/>Called by <code>InitVelocityResourceLoader</code>. /// /// <b>Important</b>: the NVeloctity ResourceLoaderFactory.getLoader /// method replaces ';' with ',' when attempting to construct our resource /// loader. The name on the SPRING_RESOURCE_LOADER_CLASS property /// has to be in the form of "ClassFullName; AssemblyName" in replacement /// of the tranditional "ClassFullName, AssemblyName" to work. /// </summary> /// <param name="velocityEngine">velocityEngine the VelocityEngine to configure</param> /// <param name="extendedProperties"></param> /// <param name="resourceLoaderPathString">resourceLoaderPath the path to load Velocity resources from</param> /// <see cref="SpringResourceLoader"/> /// <see cref="InitVelocityResourceLoader"/> protected void InitSpringResourceLoader(VelocityEngine velocityEngine, ExtendedProperties extendedProperties, string resourceLoaderPathString) { extendedProperties.SetProperty(RuntimeConstants.RESOURCE_LOADER, SpringResourceLoader.NAME); Type springResourceLoaderType = typeof(SpringResourceLoader); string springResourceLoaderTypeName = springResourceLoaderType.FullName + "; " + springResourceLoaderType.Assembly.GetName().Name; extendedProperties.SetProperty(SpringResourceLoader.SPRING_RESOURCE_LOADER_CLASS, springResourceLoaderTypeName); velocityEngine.SetApplicationAttribute(SpringResourceLoader.SPRING_RESOURCE_LOADER, ResourceLoader); velocityEngine.SetApplicationAttribute(SpringResourceLoader.SPRING_RESOURCE_LOADER_PATH, resourceLoaderPathString); }
public NVelocityTemplateParser() { var props = new ExtendedProperties(); props.SetProperty(RuntimeConstants.RESOURCE_LOADER, "direct"); props.SetProperty("direct.resource.loader.class", "Acr.Mail.NVelocityParser.NVelocityDirectResourceLoader; Acr.Mail.NVelocityParser"); engine = new VelocityEngine(); engine.Init(props); }
/// <summary> /// overridden LoadConfiguration that will create a properties file on the fly /// </summary> /// <returns></returns> protected override ExtendedProperties LoadConfiguration() { ExtendedProperties p = new ExtendedProperties(); // override the loader path and log file locations based on where the physical application path is p.SetProperty(NVelocity.Runtime.RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, context.Request.PhysicalApplicationPath); p.SetProperty(NVelocity.Runtime.RuntimeConstants_Fields.RUNTIME_LOG, context.Request.PhysicalApplicationPath + p.GetString(NVelocity.Runtime.RuntimeConstants_Fields.RUNTIME_LOG, "nvelocity.log")); return(p); }
public void SetUp() { engine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true"); engine.Init(extendedProperties); context = new VelocityContext(); }
public ForeachBreakTest() { engine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true"); engine.Init(extendedProperties); context = new VelocityContext(); }
public void Test() { var velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); velocityEngine.Init(extendedProperties); VelocityContext context = new VelocityContext(); context.Put("yada", "line"); Template template = velocityEngine.GetTemplate( GetFileName(null, "nv37", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); #pragma warning disable 612,618 velocityEngine.MergeTemplate("nv37.vm", context, writer); #pragma warning restore 612,618 //template.Merge(context, writer); Console.WriteLine(writer); }
public void Apply(IEnumerable <ChangeScript> changeScripts) { string filename = string.Format(CultureInfo.InvariantCulture, "{0}_{1}.vm", this.syntax, this.GetTemplateQualifier()); var model = new Hashtable(); model.Add("scripts", changeScripts); model.Add("changeLogTableName", this.changeLogTableName); model.Add("delimiter", this.delimiter); model.Add("separator", this.delimiterType is RowDelimiter ? Environment.NewLine : string.Empty); try { ExtendedProperties props = new ExtendedProperties(); var assemblyName = this.GetType().Assembly.GetName().Name; ReplaceManagersWithDbDeployVersions(props, assemblyName); if (this.templateDirectory == null) { props.AddProperty("resource.loader", "assembly"); props.AddProperty("assembly.resource.loader.class", // See the ; there? It will be replaced by , in the resource loader factory // this is because if we add a property with a comma in the value, it will add *two* values to the property. // oh joy. typeof(DbDeployAssemblyResourceLoader).FullName + "; " + assemblyName); props.AddProperty("assembly.resource.loader.assembly", assemblyName); filename = "Net.Sf.Dbdeploy.Resources." + filename; } else { props.SetProperty("file.resource.loader.path", this.templateDirectory.FullName); } var templateEngine = new VelocityEngine(props); var context = new VelocityContext(model); Template template = templateEngine.GetTemplate(filename); template.Merge(context, this.writer); } catch (ResourceNotFoundException ex) { string locationMessage; if (templateDirectory == null) { locationMessage = ""; } else { locationMessage = " at " + templateDirectory.FullName; } throw new UsageException( "Could not find template named " + filename + locationMessage + Environment.NewLine + "Check that you have got the name of the database syntax correct.", ex); } }
/// <summary> /// Constructs VelocityHelper with the provided engine and properties /// </summary> /// <param name="engine">Instance of the Velocity Engine</param> /// <param name="props">Instance of the Velocity Properties</param> public VelocityHelper(VelocityEngine engine, ExtendedProperties props) { _engine = engine; if (props == null || props.Count == 0) { props = new ExtendedProperties(); props.SetProperty("input.encoding", "UTF-8"); props.SetProperty("output.encoding", "UTF-8"); _engine.Init(props); } else { _engine.Init(props); } }
/// <summary> Allows an external system to set a property in /// the Velocity Runtime. /// * /// </summary> /// <param name="String">property key /// </param> /// <param name="String">property value /// /// </param> public virtual void setProperty(System.String key, System.Object value_Renamed) { if (overridingProperties == null) { overridingProperties = new ExtendedProperties(); } overridingProperties.SetProperty(key, value_Renamed); }
/// <summary> /// Allows an external system to set a property in /// the Velocity Runtime. /// </summary> /// <param name="key">property key </param> /// <param name="value">property value</param> public void SetProperty(String key, Object value) { if (overridingProperties == null) { overridingProperties = new ExtendedProperties(); } overridingProperties.SetProperty(key, value); }
protected void SetUp() { velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true"); extendedProperties.SetProperty("userdirective", "NVelocity.Runtime.Directive.Component;NVelocity,NVelocity.Runtime.Directive.BlockComponent;NVelocity"); velocityEngine.Init(extendedProperties); testProperties = new ExtendedProperties(); testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read)); }
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); Assert.Throws <ParseErrorException>(() => velocityEngine.GetTemplate(GetFileName(null, "nv14", TemplateTest.TMPL_FILE_EXT))); }
/// <summary> /// Create and initialize the VelocityEngine instance and return it /// </summary> /// <returns>VelocityEngine</returns> /// <exception cref="VelocityException" /> /// <see cref="FillProperties" /> /// <see cref="InitVelocityResourceLoader" /> /// <see cref="PostProcessVelocityEngine" /> /// <see cref="VelocityEngine.Init()" /> public VelocityEngine CreateVelocityEngine() { ExtendedProperties extendedProperties = new ExtendedProperties(); VelocityEngine velocityEngine = NewVelocityEngine(); LoadDefaultProperties(extendedProperties); // Load config file if set. if (configLocation != null) { if (log.IsInfoEnabled) { log.Info(string.Format("Loading Velocity config from [{0}]", configLocation)); } FillProperties(extendedProperties, configLocation, false); } // merge local properties if set. if (velocityProperties.Count > 0) { foreach (KeyValuePair <string, object> pair in velocityProperties) { extendedProperties.SetProperty(pair.Key, pair.Value); } } // Set a resource loader path, if required. if (!preferFileSystemAccess && resourceLoaderPaths.Count == 0) { throw new ArgumentException("When using SpringResourceLoader you must provide a path using the ResourceLoaderPath property"); } if (resourceLoaderPaths.Count > 0) { InitVelocityResourceLoader(velocityEngine, extendedProperties, resourceLoaderPaths); } // Log via Commons Logging? if (overrideLogging) { velocityEngine.SetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new CommonsLoggingLogSystem()); } PostProcessVelocityEngine(velocityEngine); try { velocityEngine.Init(extendedProperties); } catch (Exception ex) { throw new VelocityException(ex.ToString(), ex); } return(velocityEngine); }
/// <summary> /// This will produce a List of Hashtables, each /// hashtable contains the initialization info for /// a particular resource loader. This Hashtable /// will be passed in when initializing the /// the template loader. /// </summary> private void AssembleResourceLoaderInitializers() { if (resourceLoaderInitializersActive) { return; } ArrayList resourceLoaderNames = runtimeServices.Configuration.GetVector(RuntimeConstants.RESOURCE_LOADER); for (int i = 0; i < resourceLoaderNames.Count; i++) { /* * The loader id might look something like the following: * * file.resource.loader * * The loader id is the prefix used for all properties * pertaining to a particular loader. */ String loaderID = string.Format("{0}.{1}", resourceLoaderNames[i], RuntimeConstants.RESOURCE_LOADER); ExtendedProperties loaderConfiguration = runtimeServices.Configuration.Subset(loaderID); /* * we can't really count on ExtendedProperties to give us an empty set */ if (loaderConfiguration == null) { runtimeServices.Warn( string.Format("ResourceManager : No configuration information for resource loader named '{0}'. Skipping.", resourceLoaderNames[i])); continue; } /* * add the loader name token to the initializer if we need it * for reference later. We can't count on the user to fill * in the 'name' field */ loaderConfiguration.SetProperty(RESOURCE_LOADER_IDENTIFIER, resourceLoaderNames[i]); /* * Add resources to the list of resource loader * initializers. */ sourceInitializerList.Add(loaderConfiguration); } resourceLoaderInitializersActive = true; }
/// <summary> /// Creates a new instance. /// </summary> public TemplateTestCase() { try { velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true"); velocityEngine.Init(extendedProperties); testProperties = new ExtendedProperties(); testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read)); } catch (Exception) { throw new Exception("Cannot setup TemplateTestSuite!"); } }
/// <summary> /// Creates a new instance. /// </summary> public TemplateTestCase() { try { velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_ERROR_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_WARN_STACKTRACE, "true"); extendedProperties.SetProperty(RuntimeConstants.RUNTIME_LOG_INFO_STACKTRACE, "true"); velocityEngine.Init(extendedProperties); testProperties = new ExtendedProperties(); testProperties.Load(new FileStream(TemplateTest.TEST_CASE_PROPERTIES, FileMode.Open, FileAccess.Read)); } catch(Exception) { throw new Exception("Cannot setup TemplateTestSuite!"); } }
/// <summary> /// 设置模板引擎(因为模板引擎读写文件目录不同所以在每次生成模板前要设置模板读写的路径) /// </summary> /// <param name="path">模板引擎将要读取的模板的更目录</param> public static void SetProperty(string path) { engine = new VelocityEngine(); //必须每次都要实例化新的对象,因为模板地址属性没办法重新设置 property.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, path); engine.Init(property); //初始化模板引擎 if (engine.GetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH) != null) { string param = engine.GetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH).ToString(); if (SetNVelociryProperty != null) { SetNVelociryProperty(new DateTime(), param);//发送事件参数,至少有一个封送地址存在,否则报错 } } }
/// <summary> /// Initialize a Velocity resource loader for the given VelocityEngine: /// either a standard Velocity FileResourceLoader or a SpringResourceLoader. /// <br/>Called by <code>CreateVelocityEngine()</code>. /// </summary> /// <param name="velocityEngine">velocityEngine the VelocityEngine to configure</param> /// <param name="extendedProperties"></param> /// <param name="paths">paths the path list to load Velocity resources from</param> /// <see cref="FileResourceLoader"/> /// <see cref="SpringResourceLoader"/> /// <see cref="InitSpringResourceLoader"/> /// <see cref="CreateVelocityEngine"/> protected void InitVelocityResourceLoader(VelocityEngine velocityEngine, ExtendedProperties extendedProperties, IList <string> paths) { if (PreferFileSystemAccess) { // Try to load via the file system, fall back to SpringResourceLoader // (for hot detection of template changes, if possible). IList <string> resolvedPaths = new List <string>(); try { foreach (string path in paths) { IResource resource = ResourceLoader.GetResource(path); resolvedPaths.Add(resource.File.FullName); } extendedProperties.SetProperty(RuntimeConstants.RESOURCE_LOADER, VelocityConstants.File); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, StringUtils.CollectionToCommaDelimitedString(resolvedPaths)); } catch (IOException ex) { if (log.IsDebugEnabled) { log.Error(string.Format("Cannot resolve resource loader path [{0}] to [File]: using SpringResourceLoader", StringUtils.CollectionToCommaDelimitedString(resolvedPaths)), ex); } InitSpringResourceLoader(velocityEngine, extendedProperties, StringUtils.CollectionToCommaDelimitedString(paths)); } } else { // Always load via SpringResourceLoader (without hot detection of template changes). if (log.IsDebugEnabled) { log.Debug("File system access not preferred: using SpringResourceLoader"); } InitSpringResourceLoader(velocityEngine, extendedProperties, StringUtils.CollectionToCommaDelimitedString(paths)); } }
/// <summary> /// Starts/configure NVelocity based on the properties. /// </summary> public void BeginInit() { vengine = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); if (!string.IsNullOrEmpty(assemblyName)) { AddResourceAssembly(assemblyName); } if (assemblies.Count != 0) { if (log.IsInfoEnabled) { log.Info("Initializing NVelocityTemplateEngine component using Assemblies:"); foreach (string s in assemblies) { log.InfoFormat(" - {0}", s); } } props.SetProperty(RuntimeConstants.RESOURCE_LOADER, "assembly"); props.SetProperty("assembly.resource.loader.class", "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader;NVelocity"); props.SetProperty("assembly.resource.loader.cache", EnableCache.ToString().ToLower()); props.SetProperty("assembly.resource.loader.assembly", assemblies); } else { String expandedTemplateDir = ExpandTemplateDir(templateDir); log.InfoFormat("Initializing NVelocityTemplateEngine component using template directory: {0}", expandedTemplateDir); FileInfo propertiesFile = new FileInfo(Path.Combine(expandedTemplateDir, "nvelocity.properties")); if (propertiesFile.Exists) { log.Info("Found 'nvelocity.properties' on template dir, loading as base configuration"); using (Stream stream = propertiesFile.OpenRead()) { props.Load(stream); } } props.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, expandedTemplateDir); props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, EnableCache.ToString().ToLower()); } vengine.Init(props); }
/// <summary> This will produce a List of Hashtables, each hashtable contains the intialization Info for a particular resource loader. This /// Hashtable will be passed in when initializing the the template loader. /// </summary> private void AssembleResourceLoaderInitializers() { ArrayList resourceLoaderNames = rsvc.Configuration.GetVector(RuntimeConstants.RESOURCE_LOADER); StringUtils.TrimStrings(resourceLoaderNames); for (IEnumerator it = resourceLoaderNames.GetEnumerator(); it.MoveNext();) { /* * The loader id might look something like the following: * * file.resource.loader * * The loader id is the prefix used for all properties * pertaining to a particular loader. */ string loaderName = (string)it.Current; StringBuilder loaderID = new StringBuilder(loaderName); loaderID.Append(".").Append(RuntimeConstants.RESOURCE_LOADER); ExtendedProperties loaderConfiguration = rsvc.Configuration.Subset(loaderID.ToString()); /* * we can't really count on ExtendedProperties to give us an empty set */ if (loaderConfiguration == null) { log.Debug("ResourceManager : No configuration information found " + "for resource loader named '" + loaderName + "' (id is " + loaderID + "). Skipping it..."); continue; } /* * Add the loader name token to the initializer if we need it * for reference later. We can't count on the user to fill * in the 'name' field */ loaderConfiguration.SetProperty(RESOURCE_LOADER_IDENTIFIER, loaderName); /* * Add resources to the list of resource loader * initializers. */ sourceInitializerList.Add(loaderConfiguration); } }
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); }
/// <summary> /// Populates the velocity properties from the given resource /// </summary> /// <param name="extendedProperties">ExtendedProperties instance to populate</param> /// <param name="resource">The resource from which to load the properties</param> /// <param name="append">A flag indicated weather the properties loaded from the resource should be appended or replaced in the extendedProperties</param> private static void FillProperties(ExtendedProperties extendedProperties, IInputStreamSource resource, bool append) { try { if (append) { extendedProperties.Load(resource.InputStream); } else { ExtendedProperties overrides = new ExtendedProperties(); overrides.Load(resource.InputStream); foreach (DictionaryEntry entry in overrides) { extendedProperties.SetProperty(Convert.ToString(entry.Key), entry.Value); } } } finally { resource.InputStream.Close(); } }
public override void Init() { ExtendedProperties props = new ExtendedProperties(); String externalProperties = Path.Combine(ViewRootDir, "nvelocity.properties"); if (File.Exists(externalProperties)) { using (FileStream fs = File.OpenRead(externalProperties)) { props.Load(fs); } } // Set up a custom directive manager props.SetProperty("directive.manager", "Castle.MonoRail.Framework.Views.NVelocity.CustomDirectiveManager; Castle.MonoRail.Framework.Views.NVelocity"); InitializeVelocityProperties(props); velocity.Init(props); }
/// <summary> /// Starts/configure NVelocity based on the properties. /// </summary> public void BeginInit() { ExtendedProperties props = new ExtendedProperties(); if (assemblyName != null) { props.SetProperty(RuntimeConstants_Fields.RESOURCE_LOADER, "assembly"); props.SetProperty("assembly.resource.loader.class", "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader;NVelocity"); props.SetProperty("assembly.resource.loader.cache", EnableCache.ToString().ToLower()); props.SetProperty("assembly.resource.loader.assembly", assemblyName); } else { props.SetProperty(RuntimeConstants_Fields.RESOURCE_LOADER, "file"); props.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, templateDir); props.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_CACHE, EnableCache.ToString().ToLower()); } vengine.Init(props); }
public void Initialize() { var props = new ExtendedProperties(); if (ViewSourceLoader.HasSource("nvelocity.properties")) { using (var stream = ViewSourceLoader.GetViewSource("nvelocity.properties").OpenViewStream()) { props.Load(stream); } } // Set up a custom directive manager props.SetProperty("directive.manager", "Castle.MonoRail.Framework.Views.NVelocity.CustomDirectiveManager; Castle.MonoRail.Framework.Views.NVelocity"); InitializeVelocityProperties(props); velocity.SetApplicationAttribute(ServiceProvider, provider); velocity.Init(props); }
private void AssembleResourceLoaderInitializers() { if (!this.resourceLoaderInitializersActive) { ArrayList vector = this.rsvc.Configuration.GetVector("resource.loader"); for (int i = 0; i < vector.Count; i++) { string prefix = vector[i] + ".resource.loader"; ExtendedProperties extendedProperties = this.rsvc.Configuration.Subset(prefix); if (extendedProperties == null) { this.rsvc.Warn("ResourceManager : No configuration information for resource loader named '" + vector[i] + "'. Skipping."); } else { extendedProperties.SetProperty("_RESOURCE_LOADER_IDENTIFIER_", vector[i]); this.sourceInitializerList.Add(extendedProperties); } } this.resourceLoaderInitializersActive = true; } }
public void Test() { Assert.Throws <ParseErrorException>(() => { 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, "nv14", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); template.Merge(context, writer); Console.WriteLine(writer); }); }
public static string GetCodeFileString(HttpServerUtility server, CustomItemInformation info) { VelocityEngine velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); props.SetProperty("file.resource.loader.path", server.MapPath(".")); // The base path for Templates velocity.Init(props); //Template template = velocity.GetTemplate("template.tmp"); NVelocity.Template template = velocity.GetTemplate("CustomItem.vm"); VelocityContext context = new VelocityContext(); context.Put("BaseTemplates", info.BaseTemplates); context.Put("CustomItemFields", info.Fields); context.Put("CustomItemInformation", info); StringWriter writer = new StringWriter(); template.Merge(context, writer); return(writer.GetStringBuilder().ToString()); }
protected override void SetupVelocityEngine(ExtendedProperties properties) { properties.SetProperty("resource.loader", "assembly"); properties.SetProperty("assembly.resource.loader.class", "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader"); properties.SetProperty("assembly.resource.loader.assembly", Assembly.GetExecutingAssembly().GetName().Name); }
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); } }