private VelocityEngine GetInitialisedEngine() { VelocityEngine engine = new VelocityEngine(); ExtendedProperties properties = new ExtendedProperties(); properties.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); properties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, agencyService.CurrentAgency.TemplateDirectory); engine.Init(properties); return engine; }
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> /// 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 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); }
protected void InitialiseNVelocity(string templatePath) { ExtendedProperties props = new ExtendedProperties(); props.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplatePath); Velocity.Init(props); }
private VelocityEngine CreateVelocityEngine() { var velocity = new VelocityEngine(); var props = new ExtendedProperties(); props.SetProperty("file.resource.loader.path", _templateDirectory); velocity.Init(props); return velocity; }
public static ExtendedProperties ConvertProperties(ExtendedProperties p) { ExtendedProperties properties = new ExtendedProperties(); IEnumerator keys = p.Keys; while (keys.MoveNext()) { string current = (string)keys.Current; string str2 = p.GetProperty(current).ToString(); properties.SetProperty(current, str2); } return(properties); }
public static ExtendedProperties ConvertProperties(ExtendedProperties p) { ExtendedProperties extendedProperties = new ExtendedProperties(); foreach (string key in p.Keys) { object obj = p.GetProperty(key); if (obj is string) { obj = obj.ToString().Replace(",", "\\,"); } extendedProperties.SetProperty(key, obj); } return(extendedProperties); }
/// <summary> /// Creates a velocity engine that is initiated. It loads up /// templates from the 'Templates' folder. /// </summary> /// <returns></returns> protected virtual string CreateSqlOutput(IEnumerable<Migration> migrations) { VelocityEngine velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory + "\\Templates"); velocityEngine.Init(extendedProperties); var context = new VelocityContext(); context.Put("migrations", migrations.OrderBy(migration => migration.MigrationDate)); var stringWriter = new StringWriter(); velocityEngine.MergeTemplate("deployment_tsql.vm", "ISO-8859-1", context, stringWriter); return stringWriter.GetStringBuilder().ToString(); }
public void Test() { var velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); velocityEngine.Init(extendedProperties); VelocityContext context = new VelocityContext(); Template template = velocityEngine.GetTemplate( GetFileName(null, "nv09", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); template.Merge(context, writer); }
public void 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); }
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(); }
/// <summary> Convert a standard properties class into a configuration /// class. /// * /// </summary> /// <param name="p">properties object to convert into /// a ExtendedProperties object. /// * /// </param> /// <returns>ExtendedProperties configuration created from the /// properties object. /// /// </returns> public static ExtendedProperties ConvertProperties(ExtendedProperties p) { ExtendedProperties c = new ExtendedProperties(); for (IEnumerator e = (IEnumerator) p.Keys; e.MoveNext(); ) { String key = (String) e.Current; String value = p.GetProperty(key).ToString(); c.SetProperty(key, value); } return c; }
/// <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(); } }
protected void Page_Load(object sender, EventArgs e) { if (this.Session["User"] != null) { UserModel model = (UserModel)this.Session["User"]; string isHasBaby = model.Company.IsHasBaby; string isJGBM = model.Branch.IsJGBM; VelocityEngine engine = new VelocityEngine(); ExtendedProperties p = new ExtendedProperties(); p.AddProperty("file.resource.loader.path", base.Server.MapPath("Templete")); p.SetProperty("input.encoding", "utf-8"); p.SetProperty("output.encoding", "utf-8"); engine.Init(p); Template template = engine.GetTemplate("0.vm", "utf-8"); DataTable table = null; string str3 = "0"; string str4 = ""; string sQLString = ""; string str6 = ""; if (base.Request.Params["yl"] != null) { string str7 = base.Server.UrlDecode(base.Request.Params["pk"]).Replace("'", ""); str6 = DbHelperOra.GetSingle("select t.systemusername from DB_CONFIGURATION t").ToString(); TB_QUOTA_Model model2 = new TB_QUOTA_Bll().GetModel(base.Request.Params["pk"]); if (base.Request.Params["yl"] == "1") { sQLString = "select * from v_mes_gs where pd_quota_code in (" + str7 + ")"; if (model2.PD_QUOTA_IFPASS != "1") { str4 = "此指标没有传递,不能打印“业务股室告知乡财”告知书"; } else { template = engine.GetTemplate("1.vm", "utf-8"); } } else if (base.Request.Params["yl"] == "2") { sQLString = "select * from v_mes_gs_2 where pd_quota_code in (" + str7 + ")"; string str8 = ((UserModel)this.Session["User"]).Company.pk_corp; if (str8.Trim() != model2.PD_QUOTA_INPUT_COMPANY.Trim()) { sQLString = sQLString + " and COMPANY_CODE='" + str8 + "'"; } if (model2.PD_QUOTA_ISUP != "1") { str4 = "此指标没有下发,不能打印“乡财告知乡镇”告知书"; } else { template = engine.GetTemplate("2.vm", "utf-8"); } } else if (base.Request.Params["yl"] == "3") { string name = "3.vm"; if (DbHelperOra.Exists("select count(*) from tb_quota where pd_quota_code in (" + str7 + ") and PD_QUOTA_ZJXZ='01'")) { sQLString = "select * from v_mes_gs_4 where pd_quota_code in (" + str7 + ")"; name = "4.vm"; } else { sQLString = "select * from v_mes_gs_3 where pd_quota_code in (" + str7 + ")"; } SMZJ.BLL.TB_QUOTA_DETAIL tb_quota_detail = new SMZJ.BLL.TB_QUOTA_DETAIL(); string strWhere = " PD_QUOTA_CODE='" + base.Request.Params["pk"] + "' and IF_SHOW=1 "; string str11 = ((UserModel)this.Session["User"]).Company.pk_corp; if (str11.Trim() != model2.PD_QUOTA_INPUT_COMPANY.Trim()) { strWhere = strWhere + " and COMPANY_CODE='" + str11 + "'"; sQLString = sQLString + " and COMPANY_CODE='" + str11 + "'"; } DataSet list = tb_quota_detail.GetList(strWhere); if ((list.Tables[0].Rows[0]["ishuizhi"].ToString().Trim() != "是") && (list.Tables[0].Rows[0]["ishuizhi"].ToString().Trim() != "1")) { str4 = "此指标没有回执,不能打印“乡镇回执乡财”告知书"; } else { template = engine.GetTemplate(name, "utf-8"); } } else { str4 = "内部错误,请重新登录"; } if (str4 == "") { table = DbHelperOra.Query(sQLString).Tables[0]; str3 = "1"; } } VelocityContext context = new VelocityContext(); context.Put("XiangZhen", str6); context.Put("xzs", table); context.Put("isnew", str3); context.Put("isHasBaby", isHasBaby.Trim()); context.Put("IsJGBM", isJGBM.Trim()); context.Put("DataPK", base.Request.Params["pk"]); context.Put("PrintTxt", str4); context.Put("rc", ((table == null) || (table.Rows.Count == 0)) ? "0" : table.Rows.Count.ToString()); template.Merge(context, base.Response.Output); } }
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); }
/// <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.Info(" - {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> /// Convert a standard properties class into a configuration class. /// </summary> /// <param name="p">properties object to convert into a ExtendedProperties object.</param> /// <returns>ExtendedProperties configuration created from the properties object.</returns> public static ExtendedProperties ConvertProperties(ExtendedProperties p) { ExtendedProperties c = new ExtendedProperties(); foreach(String key in p.Keys) { Object value = p.GetProperty(key); // if the value is a String, escape it so that if there are delimiters that the value is not converted to a list if (value is String) value = value.ToString().Replace(",", @"\,"); c.SetProperty(key, value); } return c; }
public void Apply(IEnumerable<ChangeScript> changeScripts, bool createChangeLogTable) { string filename = this.syntax.GetTemplateFileNameFor(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); } if (createChangeLogTable) { this.writer.Write(this.syntax.CreateChangeLogTableSqlScript(this.changeLogTableName)); } 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); } }
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; }
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); }
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(); 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); }