コード例 #1
0
 protected void Page_Load(object sender, EventArgs e)
 {
     this.ltlUserName.Text = CookieUtilities.GetCookieValue("username");
     using (var context = new MemberContext())
     {
         VelocityEngine ve = new VelocityEngine();
         ve.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
         ve.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Server.MapPath("~/html_template"));
         ve.Init();
         VelocityContext vContext = new VelocityContext();
         var             entities = context.RoleFunctions.Where(a => a.RoleId == RoleId && a.ParentID.EndsWith("_0")).Select(a => a).ToList();
         List <Item>     items    = new List <Item>();
         foreach (var entity in entities)
         {
             var item = new Item();
             item.Name      = entity.Name;
             item.IconClass = entity.IconClass;
             item.Url       = entity.Url;
             item.Items     = context.RoleFunctions.Where(a => a.RoleId == RoleId && a.ParentID.StartsWith(entity.ParentID.Substring(0, 2))).Where(a => a.Name != entity.Name).Select(a => new Item
             {
                 Name = a.Name,
                 Url  = a.Url
             }).ToList <Item>();
             items.Add(item);
         }
         vContext.Put("items", items);
         Template     template = ve.GetTemplate("menu.html");
         StringWriter writer   = new StringWriter();
         template.Merge(vContext, writer);
         MenuString = writer.GetStringBuilder().ToString();
     }
 }
コード例 #2
0
        /// <summary>
        /// 初始化模板引擎
        /// </summary>
        protected virtual void InitTemplateEngine()
        {
            try
            {
                //Velocity.Init(NVELOCITY_PROPERTY);
                VelocityEngine templateEngine = new VelocityEngine();
                templateEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");

                templateEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
                templateEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");

                //如果设置了FILE_RESOURCE_LOADER_PATH属性,那么模板文件的基础路径就是基于这个设置的目录,否则默认当前运行目录
                templateEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory);

                templateEngine.Init();

                template = templateEngine.GetTemplate(templateFile);
            }
            catch (ResourceNotFoundException re)
            {
                string error = string.Format("Cannot find template " + templateFile);
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, re, typeof(NVelocityHelper));
                throw new Exception(error, re);
            }
            catch (ParseErrorException pee)
            {
                string error = string.Format("Syntax error in template " + templateFile + ":" + pee.StackTrace);
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, pee, typeof(NVelocityHelper));
                throw new Exception(error, pee);
            }
        }
コード例 #3
0
        /// <summary>
        /// 初始化模板引擎
        /// </summary>
        public static string ProcessTemplate(string template, Dictionary <string, object> param)
        {
            var templateEngine = new VelocityEngine();

            templateEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");

            templateEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            templateEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");

            templateEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory);


            var context = new VelocityContext();

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

            templateEngine.Init();


            var writer = new StringWriter();

            templateEngine.Evaluate(context, writer, "mystring", template);

            return(writer.GetStringBuilder().ToString());
        }
コード例 #4
0
ファイル: generate_code.cs プロジェクト: longde123/test2
        static string GetNVelocityBuffer(BaseType bt, string templateFile)
        {
            templateFile = templateFile.Replace('/', '\\');
            string dirTemplate = templateFile.Substring(0, templateFile.LastIndexOf("\\"));
            string fileName    = templateFile.Substring(dirTemplate.Length + 1);

            VelocityEngine vltEngine = new VelocityEngine();

            vltEngine.SetProperty(RuntimeConstants_Fields.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, dirTemplate);
            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());
        }
コード例 #5
0
        /// <summary>
        /// 初始化模板引擎
        /// </summary>
        public void Init()
        {
            try
            {
                VelocityEngine templateEngine = new VelocityEngine();
                templateEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");

                templateEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
                templateEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");

                //如果设置了FILE_RESOURCE_LOADER_PATH属性,那么模板文件的基础路径就是基于这个设置的目录,
                //否则默认当前运行目录
                templateEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
                                           UnityEngine.Application.dataPath);

                templateEngine.Init();

                template = templateEngine.GetTemplate(FilePathManager.Instance.GetTemplateFilePath());
            }
            catch (NVelocity.Exception.ResourceNotFoundException re)
            {
                string error = string.Format("Cannot find template " + "");

                Console.WriteLine(error);
                throw new Exception(error, re);
            }
            catch (NVelocity.Exception.ParseErrorException pee)
            {
                string error = string.Format("Syntax error in template " + "" + ":" + pee.StackTrace);
                Console.WriteLine(error);
                throw new Exception(error, pee);
            }
        }
コード例 #6
0
 private void InitializeVelocity()
 {
     velocityEngine.SetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "NVelocity.Runtime.Log.NullLogSystem");
     velocityEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateManager.TemplateDirectory);
     velocityEngine.SetProperty(RuntimeConstants.RESOURCE_MANAGER_CLASS, "NVelocity.Runtime.Resource.ResourceManagerImpl");
     velocityEngine.Init();
 }
コード例 #7
0
        /// <summary>
        ///  通过模板文件 生成文件
        /// </summary>
        /// <param name="templatePath"></param>
        /// <param name="templateFileName"></param>
        /// <param name="outFilePath"></param>
        /// <param name="dictKv"></param>
        public static void WriteTemplateByFile(string templatePath, string templateFileName, string outFilePath, Dictionary <string, object> dictKv)
        {
            // 初始化模板引擎
            VelocityEngine ve = new VelocityEngine();

            //可选值:"class"--从classpath中读取,"file"--从文件系统中读取
            ve.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            //如果从文件系统中读取模板,那么属性值为org.apache.velocity.runtime.resource.loader.FileResourceLoader
            ve.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, @templatePath);
            ve.Init();


            //模板内容
            VelocityContext vlc = new VelocityContext();

            foreach (string key in dictKv.Keys)
            {
                vlc.Put(key, dictKv[key]);
            }

            /*
             *指定引擎加载的模版
             */
            Template     vtp = ve.GetTemplate(@templateFileName);
            StringWriter str = new StringWriter();

            vtp.Merge(vlc, str);

            File.WriteAllText(@outFilePath, str.GetStringBuilder().ToString());//生成文件的路径可以自由选择
            MessageBox.Show(str.GetStringBuilder().ToString());
        }
コード例 #8
0
        public static string GetContent(
            string template, string nameSpace, string table, string className,
            IEnumerable <ColumnInfo> columns, string comment, string sql = "", IEnumerable <ColumnEnumListModel> enumLists = null)
        {
            var engine = new VelocityEngine();

            engine.SetProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
            engine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8");
            engine.Init();
            using (var writer = new StringWriter())
            {
                var context = new VelocityContext();
                context.Put("entity", new
                {
                    hasPrimaryKey = columns.Count(c => c.iskey) > 0,
                    primaryKeyClr = columns.Where(w => w.iskey).Select(s => s.clrtype).FirstOrDefault() ?? string.Empty,
                    nameSpace,
                    name      = table,
                    className = className,
                    comment   = comment ?? table,
                    cols      = columns.OrderByDescending(m => m.iskey),
                    sql       = sql,
                    hasEnums  = enumLists != null && enumLists.Count() > 0,
                    enumLists = enumLists
                });
                engine.Evaluate(context, writer, "entity", template);
                return(writer.GetStringBuilder().ToString());
            }
        }
コード例 #9
0
        /// <summary>
        /// 用data数据填充templateName模板,渲染生成html返回
        /// </summary>
        /// <param name="templateName"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string RenderHtml(string templateName, object data)
        {
            //第一步:Creating a VelocityEngine也就是创建一个VelocityEngine的实例
            VelocityEngine vltEngine = new VelocityEngine();   //也可以使用带参构造函数直接实例

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

            //第二步:Creating the Template加载模板文件
            //这时通过的是Template类,并使用VelocityEngine的GetTemplate方法加载模板
            Template vltTemplate = vltEngine.GetTemplate(templateName);

            //第三步:Merging the template整合模板
            VelocityContext vltContext = new VelocityContext();

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

            //第四步:创建一个IO流来输出模板内容推荐使用StringWriter(因为template中以string形式存放)
            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            vltTemplate.Merge(vltContext, vltWriter);

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

            return(html);
        }
コード例 #10
0
        public Helper()
        {
            vltEngine = new VelocityEngine();
            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory);

            vltEngine.Init();
        }
コード例 #11
0
        public void Reload()
        {
            this.engine = new VelocityEngine();

            engine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            engine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, VelocityConfigurationView.Instance.TemplatePath);

            engine.Init();
        }
コード例 #12
0
 static NVelocityBus()
 {
     CACHE_DATETIME = TypeParseHelper.StrToInt32(ConfigHelper.GetAppSettingValue("CACHE_DATETIME"));
     CACHE_DATETIME = Math.Max(CACHE_DATETIME, 20);
     CACHE_DAY      = TypeParseHelper.StrToInt32(ConfigHelper.GetAppSettingValue("CACHE_DAY"));
     CACHE_DAY      = Math.Max(CACHE_DAY, 2);
     //CACHE_REDIS = StackExchangeRedisManager.CACHE_REDIS;
     _VelocityEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
     _VelocityEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, NVelocityBus._TemplatePhysicalPath);//模板文件所在的文件夹
     _VelocityEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, ENCODING);
     _VelocityEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, ENCODING);
     _VelocityEngine.Init();
 }
コード例 #13
0
ファイル: RecordAction.cs プロジェクト: xun404/weixinserver
        /// <summary>
        /// 模版引擎
        /// </summary>
        /// <param name="name">模版名</param>
        /// <param name="data">数据集合体</param>
        /// <returns></returns>
        public static string RenderHtml(string name, object data = null)
        {
            VelocityEngine vltEngine = new VelocityEngine();

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

            vltContext.Put("Model", data);
            Template vltTemplate = vltEngine.GetTemplate(name);

            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            vltTemplate.Merge(vltContext, vltWriter);
            return(vltWriter.GetStringBuilder().ToString());
        }
コード例 #14
0
        public bool Run(TemplateData templateData)
        {
            VelocityContext context = new VelocityContext();

            context.Put("tdo", templateData);

            try
            {
                string loaderPath   = Path.GetDirectoryName(templateData.TemplateFileName);
                string templateFile = Path.GetFileName(templateData.TemplateFileName);
                velocityEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, loaderPath);
                velocityEngine.Init();

                Template template = velocityEngine.GetTemplate(templateFile);
                using (StreamWriter StreamWriter = new StreamWriter(templateData.CodeFileName,
                                                                    false, Encoding.GetEncoding(templateData.Encoding)))
                {
                    template.Merge(context, StreamWriter);
                }
                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(String.Format("NVelocityAdapter:{0}", templateData.CodeFileName), ex);
                return(false);
            }
        }
コード例 #15
0
        public static string readerHtml(string path, string name, object data)
        {
            VelocityEngine vltEngine = new VelocityEngine();

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

            VelocityContext vltContext = new VelocityContext();

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

            Template vltTemplate = vltEngine.GetTemplate(name);

            System.IO.StringWriter vltWriter = new System.IO.StringWriter();
            vltTemplate.Merge(vltContext, vltWriter);
            return(vltWriter.GetStringBuilder().ToString());
        }
コード例 #16
0
        /// <summary>
        /// 创建NVelocity模板引擎,读取设计好的模板页面,替换占位符。
        /// </summary>
        /// <param name="templateName"></param>
        /// <param name="data"></param>
        /// <param name="templateFilePath"></param>
        /// <returns></returns>
        public static string RenderTemplate(string templateName, object data, string templateFilePath)
        {
            VelocityEngine vltEngine = new VelocityEngine();

            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath(templateFilePath));
            vltEngine.Init();

            VelocityContext vltContext = new VelocityContext();

            vltContext.Put("data", data);

            Template vltTemplate = vltEngine.GetTemplate(templateName + ".html");

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

            return(vltWriter.GetStringBuilder().ToString());
        }
コード例 #17
0
        public static string RenderHtml(string templateName)
        {
            VelocityEngine vltEngine = new VelocityEngine();

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

            VelocityContext vltContext = new VelocityContext();

            Template vltTemplate = vltEngine.GetTemplate(templateName);

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

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

            return(html);
        }
コード例 #18
0
        /// <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);
        }
コード例 #19
0
        /// <summary>
        /// <p>
        /// Add mapped properties from hashtable on VelocityEngine.
        /// </p>
        /// <p>
        /// If you are going to use this, ensure you do it *before* setting
        /// the stylesheet, as that creates the VelocityEngine
        /// </p>
        /// </summary>
        private void ConfigureVelocityEngine(VelocityEngine ve, Hashtable map)
        {
            if (ve == null || map == null)
            {
                return;
            }

            foreach (DictionaryEntry entry in map)
            {
                ve.SetProperty((String)entry.Key, entry.Value);
            }
        }
コード例 #20
0
        private static void Initialize()
        {
            if (!_isInitialized)
            {
                lock (lockedObject)
                {
                    if (!_isInitialized)
                    {
                        engine = new VelocityEngine();

                        engine.SetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "NVelocity.Runtime.Log.NullLogSystem");
                        engine.SetProperty(RuntimeConstants.RESOURCE_MANAGER_CLASS, "NVelocity.Runtime.Resource.ResourceManagerImpl");
                        engine.SetProperty(RuntimeConstants.COUNTER_NAME, "count");
                        //engine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,HttpContext.Current.Server.MapPath("~/files/themes/"));
                        engine.Init();

                        _isInitialized = true;
                    }
                }
            }
        }
コード例 #21
0
ファイル: SqlHelperCatalog.cs プロジェクト: fbkc/fist_site
        /// <summary>
        /// 渲染模板引擎
        /// </summary>
        /// <param name="dic">需要替换的参数</param>
        /// <param name="temp">html文件名</param>
        /// <returns></returns>
        public static string WriteTemplate(object data, string temp)
        {
            //用的时候考代码即可,只需改三个地方:模板所在文件夹、添加数据、设定模板
            VelocityEngine vltEngine = new VelocityEngine();

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

            VelocityContext vltContext = new VelocityContext();

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

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

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

            return(html);//返回渲染生成的标准html代码字符串
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: longde123/test2
        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());
        }
コード例 #23
0
        private void GenerateReportFile(
            string outputFileNameFormat,
            string templateFileName,
            Hashtable context)
        {
            VelocityEngine velocity = new VelocityEngine();

            velocity.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            velocity.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, settings.TemplatesDirectory);
            velocity.Init();
            VelocityContext velocityContext = new VelocityContext(context);

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

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

            string outputFileName;

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

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

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

            using (Stream stream = File.Open(fullOutputFileName, FileMode.Create))
            {
                using (TextWriter writer = new StreamWriter(stream, new UTF8Encoding(false)))
                {
                    template.Merge(velocityContext, writer);
                }
            }
        }
コード例 #24
0
ファイル: CommonHelper.cs プロジェクト: xiaoDingc/HuaGongDemo
        public static string RenderHtml(string templateName, object data)
        {
            //初始化模板引擎
            VelocityEngine vltEngine = new VelocityEngine();

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

            vltContext.Put("Model", data);

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

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

            return(html);
        }
コード例 #25
0
        /// <summary>
        /// 初始化模板引擎
        /// </summary>
        public static string ProcessTemplate(string path, string template, Dictionary <string, object> dicStru)
        {
            var templateEngine = new VelocityEngine();

            templateEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            templateEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            templateEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
            //路径
            templateEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.Combine(path, "Templates"));

            var context = new VelocityContext();

            foreach (var dbs in dicStru)
            {
                context.Put(dbs.Key, dbs.Value);
            }
            templateEngine.Init();
            var writer = new StringWriter();

            templateEngine.Evaluate(context, writer, "mystring", template);

            return(writer.GetStringBuilder().ToString());
        }
コード例 #26
0
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            VelocityEngine velocity = new VelocityEngine();

            velocity.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            velocity.Init();

            Template template = velocity.GetTemplate(sourceFileName, this.sourceFileEncoding.WebName);

            using (Stream stream = File.Open(expandedFileName, FileMode.Create))
            {
                using (TextWriter writer = new StreamWriter(stream, this.expandedFileEncoding))
                {
                    VelocityContext velocityContext = new VelocityContext(properties);
                    template.Merge(velocityContext, writer);
                }
            }
        }
コード例 #27
0
        public void Generate(TestSuite testSuite)
        {
            VelocityEngine velocity = new VelocityEngine();

            velocity.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            //velocity.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, settings.TemplatesDirectory);
            velocity.Init();

            VelocityContext velocityContext = new VelocityContext();

            velocityContext.Put("testSuite", testSuite);

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

            using (StreamWriter writer = new StreamWriter(outputFileName, false, Encoding.UTF8))
            {
                template.Merge(velocityContext, writer);
            }
        }
コード例 #28
0
        static NVelocityView()
        {
            engine = new VelocityEngine();
            engine.SetProperty("resource.loader", "file");
            engine.SetProperty("file.resource.loader.path", HttpContext.Current.Server.MapPath("~"));
#if DEBUG
            engine.SetProperty("file.resource.loader.cache", false);
#else
            engine.SetProperty("file.resource.loader.cache", true);
            engine.SetProperty("file.resource.loader.modificationCheckInterval", 60L);
#endif

            engine.SetProperty("input.encoding", "utf-8");
            engine.Init();
        }
コード例 #29
0
        public MenuService(Guid uid)
        {
            //权限菜单
            user = UserService.instance().GetEntityByID(uid);
            IEnumerable <Role> roles      = RoleService.instance().GetEnumByUID(uid);
            List <Authority>   Authoritys = new List <Authority>();
            List <Menu>        menus      = new List <Menu>();

            foreach (var item in roles)
            {
                Authoritys.AddRange(AuthorityService.instance().GetAuthorityListByRole(item.ID));
            }
            foreach (var item in Authoritys.GroupBy(m => new { m.PID }))
            {
                Menu menu = new Menu();
                menu.Name   = item.First().ParentAuth.Name;
                menu.Icon   = "";
                menu.URL    = "";
                menu.Type   = 1;
                menu.Childs = new List <Menu>();
                var xx = item.OrderBy(m => m.Sort);
                foreach (var auth in xx)
                {
                    menu.Childs.Add(new Menu()
                    {
                        Name = auth.Name,
                        URL  = auth.Description,
                        Icon = ""
                    });
                }
                menus.Add(menu);
            }



            //功能菜单
            IEnumerable <Class> classs = ClassService.instance().GetChildByID(Guid.Empty, user.CompanyID).OrderBy(m => m.Sort);

            foreach (var cl in classs)
            {
                Menu menu = new Menu();
                menu.Name   = cl.Title;
                menu.Type   = cl.Type;
                menu.Childs = new List <Menu>();
                menu.ID     = cl.ID;
                if (cl.Ishaschild)
                {
                    menu.Type = 1;
                    menu.URL  = "#";
                    cl.Childs.Each(m =>
                    {
                        menu.Childs.Add(new Menu()
                        {
                            Name = m.Title,
                            Icon = "",
                            Type = m.Type,
                            ID   = m.ID
                        });
                    });
                }
                menus.Add(menu);
            }



            VelocityEngine vltEngine = new VelocityEngine();

            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory);
            vltEngine.Init();

            var vltContext = new VelocityContext();

            vltContext.Put("MENU", menus);
            Template vltTemplate = vltEngine.GetTemplate("_menu.vm");
            var      vltWriter   = new System.IO.StringWriter();

            vltTemplate.Merge(vltContext, vltWriter);
            this._html = vltWriter.GetStringBuilder().ToString();
        }
コード例 #30
0
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.Write("1");
            //IPage fac=(IPage)Assembly.Load("NewXzc.Web").CreateInstance("NewXzc.Web.Index",true);
            //fac.Page_Load(context);
            #region
            string physicalApplicationPath = context.Request.PhysicalApplicationPath;
            string str4 = context.Request.PhysicalPath.Replace(physicalApplicationPath, string.Empty).Replace("/", ".").Replace(@"\", ".").Replace(".aspx", string.Empty);
            string name = str4.Replace(".", "/") + ".html";
            string str6 = string.Empty;

            //新添加测试
            //if (str4.ToLower() == "default")
            //{
            //    HttpContext.Current.Response.Redirect("/index");
            //    return;
            //}
            //测试结束


            if (str4.ToLower() == "index" || str4.ToLower() == "webscan_360_cn" || str4.ToLower() == "baidu_verify_kyltyss6um")
            {
                str6 = "";
            }
            else
            {
                str6 = "template";
            }
            if (str4.ToLower() == "tools.ueditor.dialogs.image.image")
            {
                str6 = "";
                str4 = "image";
            }
            else if (str4.ToLower() == "tools.ueditor.dialogs.link.link")
            {
                str6 = "";
                str4 = "link";
            }
            else if (str4.ToLower() == "tools.ueditor.dialogs.emotion.emotion")
            {
                str6 = "";
                str4 = "emotion";
            }
            else
            {
                str6 = "template";
            }
            string         str8   = "text/html";
            string         str9   = context.Request.ServerVariables["HTTP_ACCEPT"];
            VelocityEngine engine = new VelocityEngine();
            engine.SetProperty("resource.loader", "file");
            engine.SetProperty("file.resource.loader.path", physicalApplicationPath + str6 + @"\");
            engine.Init();
            VelocityContext ctx             = new VelocityContext();
            string          applicationPath = HttpContext.Current.Request.ApplicationPath;
            if (applicationPath == "/")
            {
                applicationPath = string.Empty;
            }

            #region  获取当前用户的登录状态
            string url_s = HttpContext.Current.Request.Url.ToString().ToLower();

            if (!url_s.Contains("hongrenhui"))
            {
                ctx.Put("headinfo", GetUserLoginState(1));
            }
            else
            {
                ctx.Put("headinfo", GetUserLoginState(1));
            }



            if (!url_s.Contains("userlogin"))
            {
                if (!url_s.Contains("hongrenhui"))
                {
                    //当前用户还未登录
                    if (GetCurUserID_HongRenHui() == 0)
                    {
                        //进入中心页面,直接跳转回登录页
                        if (url_s.Contains("personalcenter"))
                        {
                            HttpContext.Current.Response.Redirect("/login");
                        }
                    }
                }
                else
                {
                    //当前用户还未登录
                    if (GetCurUserID_HongRenHui() == 0)
                    {
                        //进入中心页面,直接跳转回登录页
                        if (url_s.Contains("personalcenter"))
                        {
                            HttpContext.Current.Response.Redirect("/login");
                        }
                    }
                }
            }
            #endregion

            ctx.Put("style", "/template/style");
            ctx.Put("js", "/template/js");
            ctx.Put("img", "/template/img");
            ctx.Put("exname", ".aspx");
            ctx.Put("showimg", NewXzc.Common.ImgHelper.GetCofigShowUrl());
            IHandlerFactory factory = null;
            try
            {
                factory = (IHandlerFactory)Assembly.Load("NewXzc.Web").CreateInstance("NewXzc.Web.templatecs." + str4, true);

                if (factory == null)
                {
                    //name = "/index";
                    name = "/404";
                }
                else if (!(!(context.Request.HttpMethod == "POST")))
                {
                    factory.Page_PostBack(ref ctx);
                }
                else
                {
                    factory.Page_Load(ref ctx);
                }
            }
            catch (Exception ex)
            {
                //context.Response.Redirect("/404");
                context.Response.Write(ex.Message);
            }
            if (ctx.Get("redirecturl") != null)
            {
                string url = ctx.Get("redirecturl").ToString();
                context.Response.Redirect(url);
            }
            try
            {
                Template template = engine.GetTemplate(name);

                StringWriter writer2 = new StringWriter();
                template.Merge(ctx, writer2);
                context.Response.ContentType = str8;
                context.Response.Write(writer2.GetStringBuilder().ToString());
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message);
            }
            #endregion
        }