public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); int t = 0; t = String_Manage.Return_Request_Int("t", 0); context.Put("t", t); int logintype = 0; int third_logintype = 1; try { if (CookieManage_HongRenHui.IsHaveCookie("RED_HREN_USERID")) { logintype = Convert.ToInt32(CookieManage_HongRenHui.GetCookieValue("RED_HREN_Login_Type")); third_logintype = Convert.ToInt32(CookieManage_HongRenHui.GetCookieValue("RED_HREN_Third_Login")); CookieManage_HongRenHui.AddCookie("RED_HREN_USERID", CookieManage_HongRenHui.GetCookieValue("RED_HREN_USERID"), -1, true); CookieManage_HongRenHui.AddCookie("FINDRED_HREN_USERID", CookieManage_HongRenHui.GetCookieValue("FINDRED_HREN_USERID"), -1, true); CookieManage_HongRenHui.AddCookie("FINDTEL_HREN_STATE", CookieManage_HongRenHui.GetCookieValue("FINDTEL_HREN_STATE"), -1, true); CookieManage_HongRenHui.AddCookie("RED_HREN_Login_Type", CookieManage_HongRenHui.GetCookieValue("RED_HREN_Login_Type"), -1, true); CookieManage_HongRenHui.AddCookie("RED_HREN_Third_Login", CookieManage_HongRenHui.GetCookieValue("RED_HREN_Third_Login"), -1, true); CookieManage_HongRenHui.AddCookie("RED_HREN_Login_Urls", CookieManage_HongRenHui.GetCookieValue("RED_HREN_Login_Urls"), -1, true); CookieManage_HongRenHui.ClearCookie("RED_HREN_USERID"); CookieManage_HongRenHui.ClearCookie("FINDRED_HREN_USERID"); CookieManage_HongRenHui.ClearCookie("FINDTEL_HREN_STATE"); CookieManage_HongRenHui.ClearCookie("RED_HREN_Login_Type"); CookieManage_HongRenHui.ClearCookie("RED_HREN_Third_Login"); CookieManage_HongRenHui.ClearCookie("RED_HREN_Login_Urls"); HttpCookie aCookie; string cookieName; int limit = HttpContext.Current.Request.Cookies.Count; for (int i = 0; i < limit; i++) { cookieName = HttpContext.Current.Request.Cookies[i].Name; if (!cookieName.ToLower().Contains("redparty")) { aCookie = new HttpCookie(cookieName); aCookie.Expires = DateTime.Now.AddDays(-1); HttpContext.Current.Response.Cookies.Add(aCookie); } } } } catch (Exception ex) { } context.Put("logintype", logintype); context.Put("third_logintype", third_logintype); }
public void Process(String templateFile) { // Velocity 初始化. // 从配置文件读取配置信息. Velocity.Init("nvelocity.properties"); // 创建 Velocity Context VelocityContext context = new VelocityContext(); // 将列表的数据, 以 list 作为名称,放入 context. context.Put("list", Names); // 模版. Template template = null; // 尝试加载模版文件. try { template = Velocity.GetTemplate(templateFile); } catch (ResourceNotFoundException) { System.Console.Out.WriteLine("Example1 : error : cannot find template " + templateFile); } catch (ParseErrorException pee) { System.Console.Out.WriteLine("Example1 : Syntax error in template " + templateFile + ":" + pee); } // 处理模版信息. if (template != null) { template.Merge(context, System.Console.Out); } }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); #region 加载头部及Title NewXzc.Web.templatecs.Head head = new Head(); head.Init_Head(context, 0); context.Put("title", "找回密码_女装搭配|衣品搭配"); #endregion int uid = CheckIsLogin_HongRenHui.GetUserID("FINDRED_HREN_USERID"); if (uid <= 0) { context.Put("redirecturl", "/findpwd"); } else { context.Put("codes", String_Manage.Return_Request_Str("code")); string tel = new BLL.RED_USER().GetModel(uid).TEL; //tel = tel.Substring(0, 3) + "****" + tel.Substring(7, 4); context.Put("tel", tel); } }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); #region 加载头部及Title NewXzc.Web.templatecs.Head head = new Head(); head.Init_Head(context, 0); context.Put("title", "基础资料_个人中心"); context.Put("keywords", "红人,衣品搭配,红人网,网络红人,微博红人,爱拍红人,红人服装,网络红人排行榜"); context.Put("description", "衣品搭配,专注发掘不一样的红人神咖.衣品搭配是红人,衣品搭配,红人网,网络红人,微博红人,爱拍红人,红人服装,网络红人排行榜等综合红人报道平台.衣品搭配网络红人聚集平台,跟踪报道红人资讯,最新红人作品等等,第一时间满足粉丝需求."); #endregion #region 企业基础资料 Model.RED_USER user_model = new BLL.RED_USER().GetModel(UserID_HongRenHui); if (user_model != null) { string user_head = user_model.USER_HEAD; context.Put("comlogo", user_head); context.Put("comlogo_small", ImgHelper.Return_User_Head(user_head, 3)); context.Put("comlogo_middle", ImgHelper.Return_User_Head(user_head, 2)); context.Put("comlogo_big", ImgHelper.Return_User_Head(user_head, 1)); context.Put("nickname", user_model.USERNAME); } else { context.Put("redirecturl", "/404"); } #endregion }
/// <summary> /// 验证是否登录成功 /// </summary> /// <param name="context"></param> private void Login_States(NVelocity.VelocityContext context) { int login_type = String_Manage.Return_Request_Int("logintype", 0); string urls = String_Manage.Return_Request_Str("urls"); CookieManage_HongRenHui.AddCookie("RED_HREN_Login_Type", login_type.ToString(), 7, false); if (urls != "" && urls != "0") { CookieManage_HongRenHui.AddCookie("RED_HREN_Login_Urls", urls, 7, false); } else { CookieManage_HongRenHui.AddCookie("RED_HREN_Login_Urls", CheckIsLogin_HongRenHui.Get_User_CenterUrl_HongRenHui(), 7, false); } if (CheckIsLogin_HongRenHui.IsLogin("RED_HREN_USERID")) { if (urls != "") { context.Put("redirecturl", urls); } else { context.Put("redirecturl", CheckIsLogin_HongRenHui.Get_User_CenterUrl_HongRenHui()); } } }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); //获取文章详情 GetDetail(context); }
/// <summary> /// 加载首页头部 /// </summary> /// <param name="context"></param> public void Init_Head(NVelocity.VelocityContext context) { //context.Put("title", "网红,网络红人,网红经济,衣品搭配"); //context.Put("keywords", "网红,网络红人,网红经济,网红直播,网红营销,红人,衣品搭配"); //context.Put("description", "衣品搭配是中国首家网络红人门户,有丰富的网红资讯是网络红人综合业务报道和网红推广的平台,可以满足广告主的投放诉求和网红的变现诉求实现网红经济化,提供红薯直播平台让主播们的分成更多,还能成就不少网红的明星梦。"); context.Put("title", "穿衣搭配网|女装搭配|服装搭配|衣服搭配-衣品搭配网"); context.Put("keywords", "女装,穿衣搭配,服装搭配,服饰搭配,韩国服饰,穿衣搭配网"); context.Put("description", "衣品搭配网是最专业最权威的服装搭配网站。除了展示各类女装及配饰还有最专业最潮流的穿衣搭配指南,让时尚变的触手可及!"); ////加载头部导航 //context.Put("nav_list", Get_Top_Nav(context)); //获取微信登录信息 string wcode = String_Manage.Return_Request_Str("code"); if (wcode != "") { context.Put("redirecturl", "/userlogin/wechat_return_url.aspx?code=" + wcode); } //Save_Img_Http.Save_Img_WebRequest("http://wx.qlogo.cn/mmopen/Q3auHgzwzM6Gv0vqjANHBUX7npN7tQGicuXxIkelKa3ibP8P5EBOPcb9yqougxLicZqcL9bwmo9M56QM8ibDPgXHia7M7kKEt7CNKK4PAPjNHiaxw/0", "jpg", 0); //string pwd = NewXzc.Common.DEncrypt.DESEncrypt.Encrypt("608");//给密码加密 }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); HttpContext.Current.Response.Status = "404 Not Found"; GetList(context); }
public static string RenderTemplateToString(string templateFile, Map map) { NVelocity.VelocityContext vc = new NVelocity.VelocityContext(map); using (StringWriter contentWriter = new StringWriter()) { VelocityHelper.RenderTemplateToWriter(templateFile, contentWriter, vc); return contentWriter.ToString(); } }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); #region 加载头部及Title string title_val = ""; string keywords_val = title_val; #endregion #region 热点 //context.Put("hotarticle", ArticleHelper.Get_Hot_Articel()); #endregion try { season_require_id = DbHelperSQL.GetSingle("select top 1 season_id from HRENH_SET_ARTICLE_SHOW_SEASON order by id desc").ToString(); } catch (Exception ex) { } season_require_id_linshi = "," + season_require_id + ","; prname = "jingxuan"; typeurl = "/" + prname + ""; context.Put("typepurl", typeurl); head.Init_Head(context, type); #region 加载二级和三级 title_val = typename + ""; title_val = "精选|穿衣搭配|女装精选-衣品搭配网|穿衣搭配网"; context.Put("title", title_val); context.Put("keywords", "精选,穿衣搭配,服装搭配,服饰搭配"); context.Put("keywords_cname", "搭配"); context.Put("description", "精选栏目汇聚众多小编精挑细选出来的服装搭配图片以及搭配技巧,每篇文章都会让你体学到新的搭配知识。"); #endregion // 加载文章列表 GetList(context); }
/// <summary> /// 获取类型的名字 /// </summary> /// <param name="idlist">类型或平台的ID</param> /// <returns></returns> private void Get_type_New_Zixun__name(string idlist, NVelocity.VelocityContext context) { if (idlist != "") { string sql = "select id,typename,TypeRename from HRENH_ARTICLE_TYPE where id in(" + idlist + ")"; DataSet ds = DbHelperSQL.Query(sql); if (ds != null && ds.Tables[0].Rows.Count > 0) { string dpid = ""; for (int d = 0; d < ds.Tables[0].Rows.Count; d++) { string did = ds.Tables[0].Rows[d]["id"].ToString(); string dtypename = ds.Tables[0].Rows[d]["typename"].ToString(); string dTypeRename = ds.Tables[0].Rows[d]["TypeRename"].ToString(); if (d == 0) { //context.Put("son_type",dtypename); dpid = did; } else { bool f = false; try { DataSet find_son = DbHelperSQL.Query("select typename,TypeRename from HRENH_ARTICLE_TYPE where pid=" + dpid + " and id=" + did + ""); if (find_son != null && find_son.Tables[0].Rows.Count > 0) { foreach (DataRow ddr in find_son.Tables[0].Rows) { dtypename = ddr["typename"].ToString(); dTypeRename = ddr["TypeRename"].ToString(); context.Put("third_type", dtypename); context.Put("third_type_url", "/" + dTypeRename + type_shouzimu + "/"); f = true; } } } catch (Exception ex) { } if (f) { break; } } } } } }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); #region 加载头部及Title string title_val = ""; string keywords_val = title_val; #endregion #region 热点 //context.Put("hotarticle", ArticleHelper.Get_Hot_Articel()); #endregion try { season_require_id = DbHelperSQL.GetSingle("select top 1 season_id from HRENH_SET_ARTICLE_SHOW_SEASON order by id desc").ToString(); } catch (Exception ex) { } season_require_id_linshi = "," + season_require_id + ","; head.Init_Head(context, type); #region 加载二级和三级 title_val = "穿衣搭配专题|女装搭配专题|服装搭配专题-衣品搭配网|衣服搭配专题"; context.Put("title", title_val); context.Put("keywords", "专题,穿衣搭配,服装搭配,服饰搭配"); context.Put("keywords_cname", keywords_val.Replace("红人", "")); context.Put("description", "专题栏目涵盖所有和服装搭配相关的内容,在专题页你可以全面了解和学习关于服装搭配的知识和技巧。"); Get_Second_Third(context); #endregion int pageid = 2300; #region 列表页最新排行上方轮播图 context.Put("topadimg", ArticleHelper.Get_Tj_Img(1, pageid, 1001)); #endregion }
/// <summary> /// 相关搜索 /// </summary> /// <param name="context"></param> public void Init_Xgss(NVelocity.VelocityContext context) { StringBuilder sbr = new StringBuilder(); DataSet ds = null; try { string sql = "select top 6 id,title,types,isimg,img_url from hrenh_article where isend=0 and types in(1,3,4,5) and pub_state=0"; sql += " order by read_cnt desc,id desc"; ds = DbHelperSQL.Query(sql); if (ds != null && ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { DataRow dr = ds.Tables[0].Rows[i]; int article_id = String_Manage.Return_Int(dr["id"].ToString(), 0); string article_title = String_Manage.Return_Str(dr["title"].ToString(), ""); string show_article_title = StringHelper.ReturnNumStr(article_title, 1, 10); string article_url = "href=\"/article_detail_" + article_id + "\" target=\"_blank\" title=\"" + article_title + "\""; article_url = "href=\"/" + ArticleHelper.Get_Nav_Type_Name(Convert.ToInt32(dr["types"].ToString())) + "/detail_" + article_id + ".html\" target=\"_blank\" title=\"" + article_title + "\""; int isimg = String_Manage.Return_Int(dr["isimg"].ToString(), 0); string article_img = "/template/img/nocontent.png"; if (isimg == 1) { article_img = ImgHelper.Get_UploadImgUrl(dr["img_url"].ToString(), 1); } sbr.AppendFormat("<li>"); sbr.AppendFormat("<a {0}>{1}", article_url, show_article_title); //sbr.AppendFormat("<img src=\"{0}\" height=\"80\" width=\"140\" alt=\"{1}\">", article_img, article_title); //sbr.AppendFormat("<p>{0}</p>", show_article_title); //sbr.AppendFormat("<i class=\"vedioIcon\"></i>"); sbr.AppendFormat("</a>"); sbr.AppendFormat("</li>"); } } else { sbr.Append("<div class=\"nodata\">没有找到相关数据</div>"); } } catch (Exception ex) { sbr.AppendFormat(ex.ToString()); } context.Put("xgss", sbr.ToString()); }
public void TestJuxtaposePage() { SiteInfo site = new SiteInfo(); site.Copyright = "©2014 - 2015"; site.Description = ""; site.Host = "localhost"; site.KeyWords = ""; site.Logo = ""; site.Name = "xxx"; site.SiteDirectory = ""; site.Theme = "Blue"; site.ThemeDirectory = "theme"; site.Title = "jntemplate测试页"; site.Url = string.Concat("http://localhost"); if (!string.IsNullOrEmpty(site.SiteDirectory) && site.SiteDirectory != "/") { site.Url += "/" + site.SiteDirectory; } site.ThemeUrl = string.Concat(site.Url, "/", site.ThemeDirectory, "/", site.Theme); string basePath = new System.IO.DirectoryInfo(System.Environment.CurrentDirectory).Parent.Parent.FullName; string path = basePath + "\\templets\\nv"; NVelocity.Context.IContext ctx = new NVelocity.VelocityContext(); ctx.Put("func", new TemplateMethod()); ctx.Put("Site", site); NVelocity.App.VelocityEngine velocity = new NVelocity.App.VelocityEngine(); Commons.Collections.ExtendedProperties props = new Commons.Collections.ExtendedProperties(); props.AddProperty(NVelocity.Runtime.RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(NVelocity.Runtime.RuntimeConstants.FILE_RESOURCE_LOADER_PATH, path); props.AddProperty(NVelocity.Runtime.RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(NVelocity.Runtime.RuntimeConstants.OUTPUT_ENCODING, "utf-8"); velocity.Init(props); NVelocity.Template t = velocity.GetTemplate("questionlist.html"); string result; using (System.IO.StringWriter write = new StringWriter()) { t.Merge(ctx, write); result = write.ToString(); } //可直接查看项目录下的html/nv.html 文件效果 System.IO.File.WriteAllText(basePath + "\\html\\nv.html", result); }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); Model.RED_USER resumeModel = new BLL.RED_USER().GetModel(UserID_HongRenHui); string HeadImg = "/template/img/default_head/large_default.jpg"; if (!string.IsNullOrEmpty(resumeModel.USER_HEAD)) { HeadImg = NewXzc.Common.ImgHelper.Return_User_Head(resumeModel.USER_HEAD, 1); } context.Put("HeadImg", HeadImg); }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); #region 加载头部及Title NewXzc.Web.templatecs.Head head = new Head(); head.Init_Head(context, 0); context.Put("title", "注册"); context.Put("keywords", "注册衣品搭配"); context.Put("description", "注册衣品搭配"); #endregion }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); #region 加载头部及Title NewXzc.Web.templatecs.Head head = new Head(); head.Init_Head(context, 0); context.Put("title", "修改密码_个人中心"); context.Put("keywords", "红人,衣品搭配,红人网,网络红人,微博红人,爱拍红人,红人服装,网络红人排行榜"); context.Put("description", "衣品搭配,专注发掘不一样的红人神咖.衣品搭配是红人,衣品搭配,红人网,网络红人,微博红人,爱拍红人,红人服装,网络红人排行榜等综合红人报道平台.衣品搭配网络红人聚集平台,跟踪报道红人资讯,最新红人作品等等,第一时间满足粉丝需求."); #endregion }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); int ftype = String_Manage.Return_Request_Int("type", 0); context.Put("f", ftype); if (ftype > 0) { // 获取指定文件夹下的所有文件 Get_Folder_Files(ftype, context); } }
/// <summary> /// 获取文章详情 /// </summary> /// <param name="context"></param> private void GetDetail(NVelocity.VelocityContext context) { int articleid = String_Manage.Return_Request_Int("id", 0); string ishave_rcode = "0"; string result = "ok"; if (articleid == 0) { context.Put("redirecturl", "/404"); } else { try { DataSet ds = DbHelperSQL.Query("select top 1 New_Zixun_Tbk_Url from hrenh_article a where id=" + articleid + " ");// and a.pub_state=0 if (ds != null && ds.Tables[0].Rows.Count > 0) { for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { DataRow dr = ds.Tables[0].Rows[i]; #region 文章详情的信息 string New_Zixun_Tbk_Url = dr["New_Zixun_Tbk_Url"].ToString(); #endregion #region 加载文章详情 context.Put("redirecturl", New_Zixun_Tbk_Url); #endregion } } else { context.Put("redirecturl", "/404"); } } catch (Exception ex) { context.Put("redirecturl", "/404"); } } }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); #region 加载头部及Title NewXzc.Web.templatecs.Head head = new Head(); head.Init_Head(context, 0); context.Put("title", "找回密码_女装搭配|衣品搭配"); #endregion if (CheckIsLogin_HongRenHui.GetUserID("FINDRED_HREN_USERID") <= 0 || CookieManage_HongRenHui.GetCookieValue("FINDTEL_HREN_STATE") != "1") { context.Put("redirecturl", "/findpwd"); } }
/// <summary> /// 获取当前类型的封面图和描述 /// </summary> /// <param name="context"></param> private void Get_Type_Show_Dest(NVelocity.VelocityContext context) { try { DataSet tds = DbHelperSQL.Query("select typename,show_img_url,show_desc from hrenh_article_type where id=" + stype + ""); if (tds != null && tds.Tables[0].Rows.Count > 0) { StringBuilder tsdr = new StringBuilder(); foreach (DataRow tdr in tds.Tables[0].Rows) { string ttypename = tdr["typename"].ToString(); string tshowimg = tdr["show_img_url"].ToString(); tshowimg = ImgHelper.GetCofigShowUrl() + tshowimg; string tshowdesc = tdr["show_desc"].ToString(); tsdr.AppendFormat("<div class=\"detailtop\">"); tsdr.AppendFormat("<dl>"); tsdr.AppendFormat("<dt><a href=\"javascript:;\" title=\"{0}\"><img src=\"{1}\" alt=\"{0}\"></a></dt>", ttypename, tshowimg); tsdr.AppendFormat("<dd>"); tsdr.AppendFormat("<h3>{0}</h3>", ttypename); tsdr.AppendFormat("<div class=\"worddetail\">"); tsdr.AppendFormat("<div class=\"heightauto\" style=\"height:auto\">"); tsdr.AppendFormat("{0}", tshowdesc); tsdr.AppendFormat("</div>"); tsdr.AppendFormat("</div>"); tsdr.AppendFormat("<span class=\"wordmore\" style=\"display:none;\">加载更多</span>"); tsdr.AppendFormat("</dd>"); tsdr.AppendFormat("</dl>"); tsdr.AppendFormat("</div>"); } context.Put("typeshow", tsdr.ToString()); } } catch (Exception ex) { } }
/// <summary> /// 获取指定文件夹下的所有文件 /// </summary> /// <param name="ftype"></param> private void Get_Folder_Files(int ftype, NVelocity.VelocityContext context) { try { string path = String_Manage.Return_Request_Str("furl"); //context.Put("fl", path); DirectoryInfo di = new DirectoryInfo(path); //找到该目录下的文件 FileInfo[] fis = di.GetFiles(); foreach (FileInfo fi in fis) { //文件名称 string filename = fi.Name; //文件物理路径 string file_path = fi.FullName; //文件扩展名 string file_desc = fi.Extension; if (file_desc == ".txt") { StreamReader sr = new StreamReader(file_path, System.Text.Encoding.Default); String txt_content = sr.ReadToEnd(); txt_content = txt_content.Replace("\r\n", "¤"); txt_content = txt_content.Replace("\n", ""); string[] txtarr = txt_content.Split('¤'); // 添加标题(关键词)和内容到数据库 Add_Title_Content_Keywords(ftype, txtarr); sr.Close(); } } context.Put("r", "执行完成"); } catch (Exception ex) { context.Put("r", ex.ToString()); } }
/// <summary> /// ajax method for demo of parsing NVelocity Temp with VelocityEngine /// </summary> /// <param name="template"></param> /// <param name="dirctionary"></param> public void getParseResult(string template,string dirctionary) { if ((template == null) || (dirctionary == null)) { CancelView(); return; } var map=Newtonsoft.Json.JavaScriptConvert.DeserializeObject<Hashtable>(dirctionary); var writer = new System.IO.StringWriter(); var nve = new NVelocity.App.VelocityEngine(); nve.Init(); var context = new NVelocity.VelocityContext(map); nve.Evaluate(context, writer, "", template); RenderText(writer.GetStringBuilder().ToString()); writer.Close(); CancelView(); }
public static bool RenderStringTemplateToString(string templateString, Map dati, out string ret) { NVelocity.App.VelocityEngine engine = new NVelocity.App.VelocityEngine(); engine.Init(); NVelocity.VelocityContext vc = new NVelocity.VelocityContext(dati); StringBuilder sb = new StringBuilder(); string logMsg = null; bool bOk = false; try { using (StringWriter wr = new StringWriter(sb)) using (StringReader rdr = new StringReader(templateString)) bOk = engine.Evaluate(vc, wr, logMsg, rdr); ret = bOk ? sb.ToString() : logMsg; } catch (Exception e) { Logger.Warn("Errore in RenderStringTemplateToString", e); ret = e.Message; } return bOk; }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); #region 加载首页友情链接 StringBuilder sbr_foot = new StringBuilder(); DataSet ds_foot = null; BLL.RED_RECOMMEND recommend_bll_foot = new BLL.RED_RECOMMEND(); ds_foot = recommend_bll_foot.GetList_NewIndex(0, " pageid=2000 and cid=1001 "); if (ds_foot != null && ds_foot.Tables[0].Rows.Count > 0) { sbr_foot.AppendFormat("<div class=\"friendLink\">"); sbr_foot.AppendFormat("<div class=\"box\">"); sbr_foot.AppendFormat("<div>"); sbr_foot.AppendFormat("<h2>友情链接</h2>"); for (int i = 0; i < ds_foot.Tables[0].Rows.Count; i++) { DataRow dr = ds_foot.Tables[0].Rows[i]; string title = StringHelper.ReturnNumStr(dr["v1"].ToString(), 3, 0); string httpurl = String_Manage.Return_Str(dr["url"].ToString(), ""); //链接打开方式,1:在本页面打,2:在新页面打开 int openstyle = String_Manage.Return_Int(dr["v4"].ToString(), 0); sbr_foot.AppendFormat("<a {1} title=\"{0}\">{0}</a>", title, Return_HttpURL.Return_Url(httpurl, openstyle)); if (i < ds_foot.Tables[0].Rows.Count - 1) { sbr_foot.AppendFormat("<i>|</i>"); } } sbr_foot.AppendFormat("</div>"); sbr_foot.AppendFormat("</div>"); sbr_foot.AppendFormat("</div>"); } context.Put("foot_link", sbr_foot.ToString()); #endregion }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); #region 加载头部及Title NewXzc.Web.templatecs.Head head = new Head(); head.Init_Head(context, 0); context.Put("title", "微信登录"); context.Put("keywords", "红人,衣品搭配,红人网,网络红人,微博红人,爱拍红人,红人服装,网络红人排行榜"); context.Put("description", "衣品搭配,专注发掘不一样的红人神咖.衣品搭配是红人,衣品搭配,红人网,网络红人,微博红人,爱拍红人,红人服装,网络红人排行榜等综合红人报道平台.衣品搭配网络红人聚集平台,跟踪报道红人资讯,最新红人作品等等,第一时间满足粉丝需求."); #endregion //string appid = "wx2fbe800be068f5ec";// NewXzc.Common.ConfigHelper.GetConfigString("weixin_appid"); //string appsecret = "592edb2d54ec68eb935b3b731441cbf8";// NewXzc.Common.ConfigHelper.GetConfigString("weixin_AppSecret"); //string recall_url = HttpContext.Current.Request.Url.ToString().ToLower(); //string cur_host = HttpContext.Current.Request.Url.Host; //recall_url = "http://m.ypindapei.com/userlogin/wechat_return_url.aspx"; //recall_url = HttpContext.Current.Server.UrlEncode(recall_url); //string return_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + recall_url + "&response_type=code&scope=snsapi_login&state=1#wechat_redirect"; ////context.Put("redirecturl",return_url); //http://www.ypindapei.com/wechat?appid=wx2fbe800be068f5ec&scope=snsapi_login&state=1&redirect_uri=http%3a%2f%2fm.ypindapei.com%2fuserlogin%2fwechat_return_url.aspx&code=001HvRos1i2eer08Tjms1mB6ps1HvRod string returl_url = String_Manage.Return_Request_Str("redirect_uri").ToLower(); string returl_code = String_Manage.Return_Request_Str("code"); if (returl_url.Contains("m.ypindapei.com")) { if (returl_code != "") { context.Put("redirecturl", returl_url + "?code=" + returl_code); } } }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); #region 加载头部及Title //NewXzc.Web.templatecs.Head head = new Head(); //head.Init_Head(context, 0); NewXzc.Web.templatecs.Head_Article head = new Head_Article(); head.Init_Head(context, 0); context.Put("title", "关于我们-衣品搭配"); context.Put("keywords", "红人,红人汇,红人网,网络红人,微博红人,爱拍红人,红人服装,网络红人排行榜"); context.Put("description", "红人汇,专注发掘不一样的红人神咖.红人汇是红人,红人汇,红人网,网络红人,微博红人,爱拍红人,红人服装,网络红人排行榜等综合红人报道平台.红人汇网络红人聚集平台,跟踪报道红人资讯,最新红人作品等等,第一时间满足粉丝需求."); #endregion #region 加载左侧 NewXzc.Web.templatecs.Help.common left = new NewXzc.Web.templatecs.Help.common(); left.Init_Help(context, 1); #endregion }
public static void RenderTemplateToResponse(string templateFile, Map map, bool useMaster) { DisableBrowserCache(); string requestedFormat = HttpContext.Current.Request.QueryString["format"]; if (requestedFormat != null && requestedFormat.ToUpper() == "JSON") { HttpContext.Current.Response.Write(map.ToJson()); return; } if (requestedFormat != null && requestedFormat.ToUpper() == "XML") { HttpContext.Current.Response.ContentType = "text/xml"; map.WriteToXml(HttpContext.Current.Response.Output); return; } NVelocity.VelocityContext vc = new NVelocity.VelocityContext(map); if (useMaster) { vc.Put("childContent", VelocityHelper.RenderTemplateToString(templateFile, map)); vc.Put("templateFile", templateFile); templateFile = VelocityHelper.MASTER_TEMPLATE; } using (StreamWriter pageWriter = new StreamWriter(HttpContext.Current.Response.OutputStream)) VelocityHelper.RenderTemplateToWriter(templateFile, pageWriter, vc); }
public void Process(String templateFile) { // Velocity 初始化. // 从配置文件读取配置信息. Velocity.Init("nvelocity.properties"); // 创建 Velocity Context VelocityContext context = new VelocityContext(); // 将列表的数据, 以 list 作为名称,放入 context. context.Put("list", Names); // 模版. Template template = null; // 尝试加载模版文件. try { template = Velocity.GetTemplate(templateFile); } catch (ResourceNotFoundException) { System.Console.Out.WriteLine("Example1 : error : cannot find template " + templateFile); } catch (ParseErrorException pee) { System.Console.Out.WriteLine("Example1 : Syntax error in template " + templateFile + ":" + pee); } // 处理模版信息. if (template != null) { template.Merge(context, System.Console.Out); } }
private void Wchat_Register(NVelocity.VelocityContext context) { string result = "no"; #region 获取微信登录的信息 string wcode = String_Manage.Return_Request_Str("code"); if (wcode != "") { // 获取用户的access_token和openid wcode = Get_Http_Url_Content.GetPostContent("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx2fbe800be068f5ec&secret=592edb2d54ec68eb935b3b731441cbf8&code=" + wcode + "&grant_type=authorization_code"); NewXzc.Web.templatecs.Handle.ThirdRegisterHandle.Wchat wchat_access_token = JsonHelper.JsonDeserialize <NewXzc.Web.templatecs.Handle.ThirdRegisterHandle.Wchat>(wcode); if (!string.IsNullOrEmpty(wchat_access_token.access_token)) { // 获取用户信息 wcode = Get_Http_Url_Content.GetPostContent("https://api.weixin.qq.com/sns/userinfo?access_token=" + wchat_access_token.access_token + "&openid=" + wchat_access_token.openid + ""); NewXzc.Web.templatecs.Handle.ThirdRegisterHandle.GetUser_Wchat wchat_userinfo = JsonHelper.JsonDeserialize <NewXzc.Web.templatecs.Handle.ThirdRegisterHandle.GetUser_Wchat>(wcode); if (!string.IsNullOrEmpty(wchat_userinfo.openid)) { result = Is_Register_Wchat(wchat_userinfo.nickname, wchat_userinfo.sex, wchat_userinfo.headimgurl, 3, wchat_userinfo.openid); } } } context.Put("resultss", result); if (result.Contains("people")) { context.Put("redirecturl", "http://www.ypindapei.com"); } #endregion }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); //int ftype = String_Manage.Return_Str_Int("type", 0); //context.Put("f",ftype); //if (ftype > 0) //{ // // 获取指定文件夹下的所有文件 // Get_Folder_Files(ftype,context); //} ////获取所有文章内容和文章封面图 //Get_All_Contents(context); try { DataSet numds = DbHelperSQL.Query("select (select count(*) from CREATE_HTML_ARTICLE_TITLE) as total,(select count(*) from CREATE_HTML_ARTICLE_TITLE where isuse=0) as leftss"); if (numds != null && numds.Tables[0].Rows.Count > 0) { foreach (DataRow dr in numds.Tables[0].Rows) { int totals = Convert.ToInt32(dr["total"].ToString()); int ltotals = Convert.ToInt32(dr["leftss"].ToString()); context.Put("totals", totals); context.Put("leftss", ltotals); } } } catch (Exception ex) { } }
/// <summary> /// 验证当前页面是否被选中,1:关于我们,2:报道红人,3:入驻红人爱品,4:联系我们,5:招募自媒体人,6:红人微吧招募兴趣吧吧主 /// </summary> /// <param name="context"></param> /// <param name="cur">1:关于我们,2:报道红人,3:入驻红人爱品,4:联系我们,5:招募自媒体人,6:红人微吧招募兴趣吧吧主</param> public void Init_Help(NVelocity.VelocityContext context, int cur) { context.Put("curi", cur); }
/// <summary> /// Process a template in the dictionary's context /// </summary> /// <param name="context">Dictionary holding the key/values that can be accessed through the template, similar to ViewData</param> /// <param name="template">string template</param> /// <returns>rendered template + context</returns> public static string Process(IDictionary<string, object> context, string template) { //checks if template contains scripting elements. if ((template.IndexOf('$') == -1) && (template.IndexOf('#') == -1)) return template; //gets a new engine instance var engine = GetEngine(); //create a log object for this execution TemplateEngineLog log = new TemplateEngineLog(); engine.SetProperty(NVelocity.Runtime.RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, log); NVelocity.Template nvtemplate; if (!m_templates.TryGetValue(template, out nvtemplate)) { //gets the string resource repository var repo = NVelocity.Runtime.Resource.Loader.StringResourceLoader.GetRepository(); Guid guidcode = Guid.NewGuid(); //puts a new template inside it repo.PutStringResource(guidcode.ToString(), template); nvtemplate = engine.GetTemplate(guidcode.ToString(), "UTF-8"); //save in dictionary m_templates[template] = nvtemplate; } //create a context NVelocity.VelocityContext vcontext = new NVelocity.VelocityContext(); //put default values vcontext.Put("null", null); vcontext.Put("true", true); //add the context values foreach (var key in context.Keys) vcontext.Put(key, context[key]); System.IO.StringWriter sw = new System.IO.StringWriter(); //attempt to render the template try { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); //merge uses a saved template nvtemplate.Merge(vcontext, sw); ////evaluate uses an unsaved template, recompiles on every execution, very slow. //if (engine.Evaluate(vcontext, sw, "", template) == false) //{ // throw new TemplateEngineException(log.GetContents()); //} stopwatch.Stop(); Debug.WriteLine("Engine took {0}ms", stopwatch.ElapsedMilliseconds); } catch (Exception ex) { return ex.ToString(); } return sw.ToString(); }
public void TestJuxtaposePage() { SiteInfo site = new SiteInfo(); site.Copyright = "©2014 - 2015"; site.Description = ""; site.Host = "localhost"; site.KeyWords = ""; site.Logo = ""; site.Name = "xxx"; site.SiteDirectory = ""; site.Theme = "Blue"; site.ThemeDirectory = "theme"; site.Title = "jntemplate测试页"; site.Url = string.Concat("http://localhost"); if (!string.IsNullOrEmpty(site.SiteDirectory) && site.SiteDirectory != "/") { site.Url += "/" + site.SiteDirectory; } site.ThemeUrl = string.Concat(site.Url, "/", site.ThemeDirectory, "/", site.Theme); string basePath = new System.IO.DirectoryInfo(System.Environment.CurrentDirectory).Parent.Parent.FullName; string path = basePath + "\\templets\\nv"; NVelocity.Context.IContext ctx = new NVelocity.VelocityContext(); ctx.Put("func", new TemplateMethod()); ctx.Put("Site", site); NVelocity.App.VelocityEngine velocity = new NVelocity.App.VelocityEngine(); Commons.Collections.ExtendedProperties props = new Commons.Collections.ExtendedProperties(); props.AddProperty(NVelocity.Runtime.RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(NVelocity.Runtime.RuntimeConstants.FILE_RESOURCE_LOADER_PATH, path); props.AddProperty(NVelocity.Runtime.RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(NVelocity.Runtime.RuntimeConstants.OUTPUT_ENCODING, "utf-8"); velocity.Init(props); NVelocity.Template t = velocity.GetTemplate("questionlist.html"); string result; using (System.IO.StringWriter write = new StringWriter()) { t.Merge(ctx, write); result = write.ToString(); } //可直接查看项目录下的html/nv.html 文件效果 System.IO.File.WriteAllText(basePath + "\\html\\nv.html", result); }
/// <summary> /// 今日热点 /// </summary> /// <param name="context"></param> private string Get_Jrrd(NVelocity.VelocityContext context) { StringBuilder sbr = new StringBuilder(); DataSet ds = null; int pid = 2100; sbr.Clear(); ds = recommend_bll.GetList_NewIndex(24, " pageid=" + pid + " and cid=1012 "); if (ds != null && ds.Tables[0].Rows.Count > 0) { int total = ds.Tables[0].Rows.Count; int cols = 6; int rows = 0; if (total % cols == 0) { rows = total / cols; } else { rows = total / cols + 1; } for (int i = 0; i < rows; i++) { sbr.AppendFormat("<div class=\"today_div\">"); for (int j = i * cols; j < (i + 1) * cols; j++) { if (j < total) { DataRow dr = ds.Tables[0].Rows[j]; string title = StringHelper.ReturnNumStr(dr["v1"].ToString(), 0, 0); string show_title = StringHelper.ReturnNumStr(title, 1, 17); string httpurl = String_Manage.Return_Str(dr["url"].ToString(), ""); //链接打开方式,1:在本页面打,2:在新页面打开 int openstyle = String_Manage.Return_Int(dr["v4"].ToString(), 0); sbr.AppendFormat("<div class=\"fcut\">"); sbr.AppendFormat("<div class=\"mask\">"); sbr.AppendFormat("<a {0} title=\"{1}\">", Return_HttpURL.Return_Url(httpurl, openstyle), title); sbr.AppendFormat("{0}</a>", show_title); sbr.AppendFormat("</div>"); sbr.AppendFormat("</div>"); } else { break; } } sbr.AppendFormat("</div>"); } } return(sbr.ToString()); }
/// <summary> /// 获取议会活动列表 /// </summary> /// <param name="context"></param> private void GetList(NVelocity.VelocityContext context) { sbr.Clear(); PageClass pc = new PageClass(); int record_cnt = 0; int page_cnt = 0; int curpage = 1; int pagesize = 10; curpage = String_Manage.Return_Request_Int("page", 1); int page = 0; if (curpage > 0) { page = curpage - 1; } string where = " and (types=" + type + " or types_pid=" + type + ") and isend=0 and a.pub_state=0 "; if (stype > 0) { where = " and types=" + stype + " and isend=0 "; } context.Put("stype", stype); ds = pc.TagList_New("*", " istop desc,edittime desc ", " hrenh_article a ", where, page, pagesize, " id,title,isimg,img_url,contents,(isnull(read_cnt,0)+FALSH_READ_CNT) as read_cnt,isnull((select count(*) from hrenh_article_REVIEW_REPLY where article_id=a.id and reply_id=0),0) as review_cnt,edittime "); if (ds != null && ds.Tables[2].Rows.Count > 0) { record_cnt = Convert.ToInt32(ds.Tables[0].Rows[0][0].ToString()); page_cnt = Convert.ToInt32(ds.Tables[1].Rows[0][0].ToString()); for (int i = 0; i < ds.Tables[2].Rows.Count; i++) { DataRow dr = ds.Tables[2].Rows[i]; #region 文章列表的信息 int article_id = String_Manage.Return_Int(dr["id"].ToString(), 0); string article_title = String_Manage.Return_Str(dr["title"].ToString(), ""); string show_article_title = StringHelper.ReturnNumStr(article_title, 0, 36); int isimg = String_Manage.Return_Int(dr["isimg"].ToString(), 0); string article_img = "/template/img/nocontent.png"; if (isimg == 1) { article_img = ImgHelper.Get_UploadImgUrl(dr["img_url"].ToString(), 1); } string article_contents = StringHelper.ReturnNumStr(dr["contents"].ToString(), 1, 76); string article_contents_noimg = StringHelper.ReturnNumStr(dr["contents"].ToString(), 1, 170); string article_addtime = TimeParser.ReturnCurTime(dr["edittime"].ToString(), 1); int read_cnt = String_Manage.Return_Int(dr["read_cnt"].ToString(), 0); int review_cnt = String_Manage.Return_Int(dr["review_cnt"].ToString(), 0); string article_url = "href=\"/article_detail_" + article_id + "\" target=\"_blank\" title=\"" + article_title + "\""; string parent_type_url = ArticleHelper.Get_Nav_Type_Name(type); string surl = parent_type_url + "/detail"; //if (stype >= 359 && stype <= 362) //{ // surl = "zhinan/"; // switch (stype) // { // case 359: // surl += "clys"; // break; // case 360: // surl += "fzdp"; // break; // case 361: // surl += "hzjq"; // break; // case 362: // surl += "hdth"; // break; // case 369: // surl += "psdp"; // break; // } // surl += "/show"; //} surl += "_" + article_id + ".html"; article_url = "href=\"/" + surl + "\" target=\"_blank\" title=\"" + article_title + "\""; #endregion #region 加载文章列表 sbr.AppendFormat("<li>"); sbr.AppendFormat("<dl>"); //if (isimg == 1) //{ sbr.AppendFormat("<dt><a {0}><img src=\"{1}\" alt=\"{2}\"></a></dt>", article_url, article_img, article_title); //} sbr.AppendFormat("<dd style=\"position:absolute;left:0;top:20px;left:336px;max-height:69px;\">"); string static_class = ""; //if (isimg != 1) //{ // //static_class = "style=\"position:static;\""; // article_contents = article_contents_noimg; //} sbr.AppendFormat("<h4 {2} style=\"position:static;\"><a {0}>{1}</a></h4>", article_url, show_article_title, static_class); sbr.AppendFormat("<p class=\"list-content\" {2} style=\"position:static;\"><a {0}> {1}</a></p>", article_url, article_contents, static_class); sbr.AppendFormat("<p style=\"position:relative;background:url('/template/img/clock.png') no-repeat left center;\">"); //sbr.AppendFormat("<span style=\"margin-left:0px;\">网络红人</span>"); //sbr.AppendFormat("<span class=\"mar12\">国家运动员</span>"); //sbr.AppendFormat("<span>网络红人</span>"); sbr.AppendFormat("<span style=\"border:0;margin-left:0px;color:#999;padding-left:20px;\" >{0}</span>", article_addtime); sbr.AppendFormat("<i style=\"position:absolute; right: -20px;top: 13px;\">{0}人阅</i>", read_cnt); sbr.AppendFormat("</p>"); sbr.AppendFormat("</dd>"); sbr.AppendFormat("</dl>"); sbr.AppendFormat("</li>"); #endregion } } else { sbr.Append("<div class=\"nodata\">没有找到相关数据</div>"); } if (curpage > page_cnt) { curpage = page_cnt; } context.Put("list", sbr.ToString()); context.Put("listPage", NewXzc.Common.GenerPage.pageHtml(record_cnt, pagesize, curpage, "GoPage")); }
private void butApplyTemplate2_Click(object sender, EventArgs e) { char tabCaracter = '\u0009'; try { String plantilla = util.loadFile(general.templateSelectedFullUri); // clean cmbGotocode cmbGoToCode.Items.Clear(); table tab = new table(); String tableSelected = cmbTablesx.Text; if (tableSelected.Equals("")) { rt1.Text = "Please, select a table"; } foreach (table item in general.actualProject.tables) { if (item.Name.Equals(tableSelected)) { tab = item; if (tab.GetKey == null) { MessageBox.Show("Alert, review data, table doesnt have a key"); AsyncWriteLine("Alert, review data, table doesnt have a key"); } } } string numerocampos = tab.fields.Count.ToString(); try { // si da un error en singleton es que falta la libreria commons o log4net.. Velocity.Init(); //VelocityEngine velocityEngine = new VelocityEngine(); //ExtendedProperties props = new ExtendedProperties(); //props.AddProperty("input.encoding", "UTF-8"); //props.AddProperty("output.encoding", "UTF-8"); //velocityEngine.Init(props); } catch (System.Exception exx) { rt1.Text = "Problem initializing Velocity : " + exx; return; } // lets make a Context and put data into it VelocityContext context = new VelocityContext(); context.Put("project", general.actualProject); context.Put("table", tab); // lets render a template StringWriter writer = new StringWriter(); try { //Velocity.MergeTemplate(plantilla, context, writer); Velocity.Evaluate(context, writer, "prueba", plantilla); // now we got the template , so lets take the variables from the template variablesTemplate var = new variablesTemplate(); var = util.getVariablesFromTemplate(writer.GetStringBuilder().ToString()); // now we delete the variables from the template cause there are no needed... string finalText = util.deleteVariablesFromTemplate(writer.GetStringBuilder().ToString()); // le quitamos saltos de linea extra finalText = finalText.Replace("\r\n\r\n", "\r\n").Replace("\r\n\r\n\r\n", "").Replace("\r\n\r\n\r\n\r\n", ""); // le quitamos los tabuladores extra finalText = finalText.Replace(tabCaracter.ToString(), " "); // rt1.Text = finalText; writeText(finalText); // number of lines written with generator try { long numberOfLinesWrittenBefore = 0; long numberOfLinesWritten = 0; numberOfLinesWrittenBefore = sf.toLong(System.Configuration.ConfigurationManager.AppSettings["numberOfLinesWritten"]); numberOfLinesWritten = numberOfLinesWrittenBefore + util.CountLinesInString(finalText); labNumberOfLinesWritten.Values.Text = sf.cadena(numberOfLinesWritten) + " lines written with myWay"; // save data... System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["numberOfLinesWritten"].Value = sf.cadena(numberOfLinesWritten); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); } catch (Exception) { throw; } // now we got all the functions contained in the code // and populate a combo with this... // Instantiating Regex Object Regex re = new Regex(@"(private|public|protected)\s\w(.)*\((.)*\)", RegexOptions.IgnoreCase); MatchCollection mc = re.Matches(finalText); foreach (Match mt in mc) { string st = ""; st = mt.ToString(); st = st.Replace("public", ""); st = st.Replace("private", ""); st = st.Replace("static", ""); st = st.Replace("void", ""); cmbGoToCode.Items.Add(st.Trim()); // Response.Write(mt.ToString() + "<br />"); } } catch (System.Exception exx) { //util.playSimpleSound(Path.Combine(util.sound_dir, "zasentodalaboca.wav")); SystemSounds.Asterisk.Play(); AsyncWriteLine(exx.Message); rt1.Text = exx.Message; //System.Console.Out.WriteLine("Problem merging template : " + exx); System.Console.Out.WriteLine("Problem evaluating template : " + exx); } SystemSounds.Exclamation.Play(); //util.playSimpleSound(Path.Combine(util.sound_dir, "risapetergriffin.wav")); } catch (Exception ex) { // util.playSimpleSound(Path.Combine(util.sound_dir, "zasentodalaboca.wav")); SystemSounds.Asterisk.Play(); rt1.Text = ex.Message; } }
/// <summary> /// The actually processing happens in this method /// </summary> private void UpdateSolution() { AddToStatus("Adding AndroMDA support to solution..."); Project commonProject = null; Project coreProject = null; Project schemaExportProject = null; Project testProject = null; Project webProject = null; Project webCommonProject = null; m_srcPath = m_settings.SolutionWizardResourcesLocation + "\\"; m_dstPath = m_configuration["solution.path"] + "\\"; string versionControlType = m_configuration["application.versioncontrol"]; bool versionControl = versionControlType != "None"; string ignoreFile = string.Empty; switch (versionControlType) { case "CVS": ignoreFile = ".cvsignore"; break; } nvelocityContext = new VelocityContext(); foreach (string key in m_configuration.Keys) { object value = m_configuration[key]; if (m_configuration[key] == "true" || m_configuration[key] == "false") { value = GetConfigSettingBool(key); } nvelocityContext.Put("wizard." + key, value); nvelocityContext.Put("wizard_" + key.Replace('.', '_'), value); } AddToStatus("Creating AndroMDA configuration files..."); // Create mda directory CreateDirectory("mda"); // Create mda/conf directory CreateDirectory("mda/conf"); // Render /cvsignore if (versionControl) { WriteFile("cvsignore", ignoreFile); } if (m_configuration["application.andromda.bootstrap"] == "Apache Maven 2.x") { // Render /pom.xml WriteFile("pom.xml", WriteFileProperties.RenderTemplate | WriteFileProperties.ParseVariables); // Render /mda/pom.xml WriteFile("mda/pom.xml", WriteFileProperties.RenderTemplate | WriteFileProperties.ParseVariables); // Render /mda/conf/andromda.xml WriteFile("mda/conf/andromda.xml", WriteFileProperties.RenderTemplate | WriteFileProperties.ParseVariables); // Create mda/conf/mappings directory CreateDirectory("mda/conf/mappings"); // Render /mda/conf/mappings/MergeMappings.xml WriteFile("mda/conf/mappings/MergeMappings.xml"); // Render /mda/conf/mappings/NHibernateTypeMappings.xml (Required for NHibernate 1.2) WriteFile("mda/conf/mappings/NHibernateTypeMappings.xml"); // Create mda/resources CreateDirectory("mda/resources"); // Create mda/resources CreateDirectory("mda/resources/templates"); // Create mda/resources CreateDirectory("mda/resources/templates/cs"); // Create mda/resources CreateDirectory("mda/resources/templates/nspring"); // Create mda/resources CreateDirectory("mda/resources/templates/nhibernate"); } // Write mda/cvsignore if (versionControl) { WriteFile("mda/cvsignore", "mda/" + ignoreFile); } AddToStatus("Creating empty model file..."); // Create mda/src directory CreateDirectory("mda/src"); // Create mda/src/uml directory CreateDirectory("mda/src/uml"); { string modelPackageXML = "<UML:Model xmi.id='_9_5_1_874026a_1149883877463_480535_0' name='" + m_configuration["solution.name"] + "'><UML:Namespace.ownedElement>"; string xmiIdBase = "_9_5_1_874026a_" + DateTime.Now.Ticks.ToString(); modelPackageXML += GetXMI(m_configuration["solution.name"].Split('.'), xmiIdBase); modelPackageXML += "</UML:Namespace.ownedElement></UML:Model>"; string emptyModelFileData = ReadFile("mda/src/uml/empty-model.xmi"); emptyModelFileData = emptyModelFileData.Replace("${wizard.model.packagestructure.xml}", modelPackageXML); WriteFileProperties modelProperties = WriteFileProperties.SourceFileIsContent | WriteFileProperties.RenderTemplate | WriteFileProperties.ParseVariables; if (GetConfigSettingBool("application.model.zipped")) { modelProperties |= WriteFileProperties.Compressed; } WriteFile(emptyModelFileData, "mda/src/uml/" + m_configuration["application.model.filename"], modelProperties); } // Create the AndroMDA solution folder AddToStatus("Adding solution folder..."); Solution2 sol = m_applicationObject.Solution as Solution2; Project solutionFolder = null; try { solutionFolder = sol.AddSolutionFolder("AndroMDA"); if (m_configuration["application.andromda.bootstrap"] == "Apache Maven 2.x") { solutionFolder.ProjectItems.AddFromFile(m_dstPath + "mda\\pom.xml"); } solutionFolder.ProjectItems.AddFromFile(m_dstPath + "mda\\conf\\andromda.xml"); solutionFolder.ProjectItems.AddFromFile(m_dstPath + "mda\\conf\\mappings\\MergeMappings.xml"); solutionFolder.ProjectItems.AddFromFile(m_dstPath + "mda\\conf\\mappings\\NHibernateTypeMappings.xml"); //solutionFolder.ProjectItems.AddFromFile(m_dstPath + "mda\\src\\uml\\" + m_configuration["application.model.filename"]); } catch { } ////////////////////////////////// // Create/find the common project if (GetConfigSettingBool("projects.common.create")) { AddToStatus("Creating common project " + m_configuration["projects.common.name"] + "..."); commonProject = VSSolutionUtils.AddClassLibraryProjectToSolution(m_configuration["projects.common.name"], (Solution2)m_applicationObject.Solution); } else { AddToStatus("Using existing common project " + m_configuration["projects.common.name"] + "..."); commonProject = VSSolutionUtils.FindProjectByName(m_configuration["projects.common.name"], m_applicationObject.Solution); } try { commonProject.ProjectItems.AddFolder("src", Constants.vsProjectItemKindPhysicalFolder); } catch { } try { commonProject.ProjectItems.AddFolder("target", Constants.vsProjectItemKindPhysicalFolder); } catch { } // Write common/cvsignore if (versionControl) { WriteFile("Common/cvsignore", m_configuration["projects.common.dir"] + "/" + ignoreFile); } ////////////////////////////////// // Create/find the core project if (GetConfigSettingBool("projects.core.create")) { AddToStatus("Creating core project " + m_configuration["projects.core.name"] + "..."); coreProject = VSSolutionUtils.AddClassLibraryProjectToSolution(m_configuration["projects.core.name"], (Solution2)m_applicationObject.Solution); } else { AddToStatus("Using existing core project " + m_configuration["projects.core.name"] + "..."); coreProject = VSSolutionUtils.FindProjectByName(m_configuration["projects.core.name"], m_applicationObject.Solution); } try { coreProject.ProjectItems.AddFolder("src", Constants.vsProjectItemKindPhysicalFolder); } catch {} try { coreProject.ProjectItems.AddFolder("target", Constants.vsProjectItemKindPhysicalFolder); } catch { } // Write core/cvsignore if (versionControl) { WriteFile("Core/cvsignore", m_configuration["projects.core.dir"] + "/" + ignoreFile); } ////////////////////////////////// // Create the schema export project if (GetConfigSettingBool("projects.schemaexport.create")) { AddToStatus("Creating schema export project " + m_configuration["projects.schemaexport.name"] + "..."); schemaExportProject = VSSolutionUtils.AddConsoleAppProjectToSolution(m_configuration["projects.schemaexport.name"], (Solution2)m_applicationObject.Solution); WriteFile("SchemaExport/App.config", m_configuration["projects.schemaexport.dir"] + "/App.config"); WriteFile("SchemaExport/nhibernate.config", m_configuration["projects.schemaexport.dir"] + "/nhibernate.config"); WriteFile("SchemaExport/SchemaExport.cs", m_configuration["projects.schemaexport.dir"] + "/SchemaExport.cs"); WriteFile("SchemaExport/TestDataManager.cs", m_configuration["projects.schemaexport.dir"] + "/TestDataManager.cs"); ProjectItem appConfig = schemaExportProject.ProjectItems.AddFromFile(m_dstPath + m_configuration["projects.schemaexport.dir"] + "\\App.config"); ProjectItem nhibernateConfig = schemaExportProject.ProjectItems.AddFromFile(m_dstPath + m_configuration["projects.schemaexport.dir"] + "\\nhibernate.config"); // Set the config files 'Copy to Output Directory' property to 'Copy if Newer' appConfig.Properties.Item("CopyToOutputDirectory").Value = 2; appConfig.Properties.Item("BuildAction").Value = VSLangProj.prjBuildAction.prjBuildActionContent; nhibernateConfig.Properties.Item("CopyToOutputDirectory").Value = 2; nhibernateConfig.Properties.Item("BuildAction").Value = VSLangProj.prjBuildAction.prjBuildActionContent; schemaExportProject.ProjectItems.AddFromFile(m_dstPath + m_configuration["projects.schemaexport.dir"] + "\\SchemaExport.cs"); schemaExportProject.ProjectItems.AddFromFile(m_dstPath + m_configuration["projects.schemaexport.dir"] + "\\TestDataManager.cs"); // Write SchemaExport/cvsignore if (versionControl) { WriteFile("SchemaExport/cvsignore", m_configuration["projects.schemaexport.dir"] + "/" + ignoreFile); } } ////////////////////////////////// // Configure the web project if (GetConfigSettingBool("projects.web.configure")) { ////////////////////////////////// // Create/find the web project if (GetConfigSettingBool("projects.web.create")) { AddToStatus("Creating web project " + m_configuration["projects.web.name"] + "..."); webProject = VSSolutionUtils.AddWebProjectToSolution(m_configuration["projects.web.name"], (Solution2)m_applicationObject.Solution); } else { AddToStatus("Using existing web project " + m_configuration["projects.web.name"] + "..."); webProject = VSSolutionUtils.FindProjectByName(m_configuration["projects.web.dir"], m_applicationObject.Solution); } // Write the nhibernate.config if required if (GetConfigSettingBool("projects.web.usenhibernateconfig")) { WriteFile("Web/nhibernate.config", webProject.Name + "nhibernate.config", WriteFileProperties.DestinationPathAlreadyComplete | WriteFileProperties.ParseVariables); } string webConfigDstFile = webProject.Name + "Web.config"; if (!System.IO.File.Exists(webConfigDstFile)) { // Write out the web.config file WriteFile("Web/web.config", webConfigDstFile, WriteFileProperties.DestinationPathAlreadyComplete | WriteFileProperties.ParseVariables); webProject.ProjectItems.AddFromFile(webConfigDstFile); } // Open the web.config file System.Configuration.Configuration webconfig = OpenWebConfig(webConfigDstFile); // If the nhibernate settings are stored in nhibernate.config if (GetConfigSettingBool("projects.web.usenhibernateconfig")) { // Add that to the app settings if (webconfig.AppSettings.Settings["nhibernate.config"] == null) { webconfig.AppSettings.Settings.Add("nhibernate.config", "~/nhibernate.config"); } else { webconfig.AppSettings.Settings.Add("nhibernate.config", "~/nhibernate.config"); } // Remove the nhibernate section if it exists if (webconfig.Sections.Get("nhibernate") != null) { webconfig.Sections.Remove("nhibernate"); } } else { // Remove the nhibernate.config app setting if it exists if (webconfig.AppSettings.Settings["nhibernate.config"] != null) { webconfig.AppSettings.Settings.Remove("nhibernate.config"); } // Add the nhibernate config to the web.config DefaultSection nhibernateSection = new DefaultSection(); nhibernateSection.SectionInformation.Type = "System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"; nhibernateSection.SectionInformation.SetRawXml(ParseVariables(ReadFile("web/web.config.nhibernate"))); webconfig.Sections.Add("nhibernate", nhibernateSection); } // Write Web/cvsignore and Web\Bin\cvsignore if (versionControl) { WriteFile("web/cvsignore", webProject.Name + ignoreFile, WriteFileProperties.DestinationPathAlreadyComplete); CreateDirectory(webProject.Name + "Bin", false); WriteFile("web/bin/cvsignore", webProject.Name + "Bin\\" + ignoreFile, WriteFileProperties.DestinationPathAlreadyComplete); } if (GetConfigSettingBool("projects.web.common.configure")) { // Create/find the core project if (GetConfigSettingBool("projects.web.common.create")) { AddToStatus("Creating web common project " + m_configuration["projects.web.common.name"] + "..."); webCommonProject = VSSolutionUtils.AddClassLibraryProjectToSolution(m_configuration["projects.web.common.name"], (Solution2)m_applicationObject.Solution); } else { AddToStatus("Using existing web common project " + m_configuration["projects.web.common.name"] + "..."); webCommonProject = VSSolutionUtils.FindProjectByName(m_configuration["projects.web.common.name"], m_applicationObject.Solution); } } // Get the web site object VsWebSite.VSWebSite webSite = webProject.Object as VsWebSite.VSWebSite; // Refresh folder view webSite.Refresh(); // Add Membership support if (GetConfigSettingBool("projects.web.addmembership")) { AddToStatus("Adding membership support..."); string file; ProjectItem membershipFolder = VSSolutionUtils.FindProjectFolder(webCommonProject, "Membership"); if (membershipFolder == null) { membershipFolder = webCommonProject.ProjectItems.AddFolder("Membership", Constants.vsProjectItemKindPhysicalFolder); } // Render DomainMembershipProvider.cs WriteFile("Membership/DomainMembershipProvider.cs", m_configuration["projects.web.common.dir"] + "/Membership/DomainMembershipProvider.cs"); membershipFolder.ProjectItems.AddFromFile(m_dstPath + m_configuration["projects.web.common.dir"] + "\\Membership\\DomainMembershipProvider.cs"); // Render DomainRoleProvider.cs WriteFile("Membership/DomainRoleProvider.cs", m_configuration["projects.web.common.dir"] + "/Membership/DomainRoleProvider.cs"); membershipFolder.ProjectItems.AddFromFile(m_dstPath + m_configuration["projects.web.common.dir"] + "\\Membership\\DomainRoleProvider.cs"); // Render DomainMembershipUser.cs WriteFile("Membership/DomainMembershipUser.cs", m_configuration["projects.web.common.dir"] + "/Membership/DomainMembershipUser.cs"); membershipFolder.ProjectItems.AddFromFile(m_dstPath + m_configuration["projects.web.common.dir"] + "\\Membership\\DomainMembershipUser.cs"); // Create core/src/* folder tree from namespace string solutionName = m_configuration["solution.name"]; string[] namespaces = solutionName.Split('.'); file = m_configuration["projects.core.dir"] + "\\src\\"; foreach (string folder in namespaces) { file = file + folder; CreateDirectory(file); file = file + "\\"; } CreateDirectory(file + "Domain"); CreateDirectory(file + "Service"); // Render UserDao.cs WriteFile("Membership/UserDao.cs", file + "Domain/UserDao.cs"); coreProject.ProjectItems.AddFromFile(m_dstPath + file + "Domain\\UserDao.cs"); // Render MembershipService.cs WriteFile("Membership/MembershipService.cs", file + "Service/MembershipService.cs"); coreProject.ProjectItems.AddFromFile(m_dstPath + file + "Service\\MembershipService.cs"); ConfigurationSectionGroup systemweb = webconfig.SectionGroups["system.web"]; systemweb.Sections["membership"].SectionInformation.SetRawXml(ParseVariables(ReadFile("web/web.config.membershipsection"))); systemweb.Sections["roleManager"].SectionInformation.SetRawXml(ParseVariables(ReadFile("web/web.config.rolesection"))); systemweb.Sections["membership"].SectionInformation.ForceSave = true; systemweb.Sections["roleManager"].SectionInformation.ForceSave = true; // Turn on authentication systemweb.Sections["authentication"].SectionInformation.SetRawXml("<authentication mode=\"Forms\"> <forms name=\"FormsAuth\" timeout=\"30\" loginUrl=\"~/Public/Login.aspx\" defaultUrl=\"~/Default.aspx\" path=\"/\" protection=\"All\"/></authentication>"); } // Save the changes to the web.config webconfig.Save(); } // Create the lib directory CreateDirectory("Lib"); // Write the libraries out WriteBinaryFile("Lib/AndroMDA.NHibernateSupport.dll"); WriteBinaryFile("Lib/Bamboo.Prevalence.dll"); WriteBinaryFile("Lib/Castle.DynamicProxy.dll"); //WriteBinaryFile("Lib/HashCodeProvider.dll"); WriteBinaryFile("Lib/Iesi.Collections.dll"); WriteBinaryFile("Lib/log4net.dll"); WriteBinaryFile("Lib/NHibernate.Caches.Prevalence.dll"); WriteBinaryFile("Lib/NHibernate.Caches.SysCache.dll"); WriteBinaryFile("Lib/NHibernate.dll"); //WriteBinaryFile("Lib/NHibernate.Nullables2.dll"); WriteBinaryFile("Lib/Nullables.dll"); WriteBinaryFile("Lib/Nullables.NHibernate.dll"); ////////////////////////////////// // Configure the tests project if (GetConfigSettingBool("projects.tests.configure")) { // Create/find the core project if (GetConfigSettingBool("projects.tests.create")) { AddToStatus("Creating testing project " + m_configuration["projects.tests.name"] + "..."); testProject = VSSolutionUtils.AddClassLibraryProjectToSolution(m_configuration["projects.tests.name"], (Solution2)m_applicationObject.Solution); } else { AddToStatus("Using existing testing project " + m_configuration["projects.tests.name"] + "..."); testProject = VSSolutionUtils.FindProjectByName(m_configuration["projects.tests.name"], m_applicationObject.Solution); } WriteFile("Tests/App.config", m_configuration["projects.tests.dir"] + "/App.config", WriteFileProperties.RenderTemplate | WriteFileProperties.ParseVariables); WriteFile("Tests/nhibernate.config", m_configuration["projects.tests.dir"] + "/nhibernate.config"); ProjectItem appConfig = testProject.ProjectItems.AddFromFile(m_dstPath + m_configuration["projects.tests.dir"] + "\\App.config"); ProjectItem nhibernateConfig = testProject.ProjectItems.AddFromFile(m_dstPath + m_configuration["projects.tests.dir"] + "\\nhibernate.config"); // Set the config files 'Copy to Output Directory' property to 'Copy if Newer' appConfig.Properties.Item("CopyToOutputDirectory").Value = 2; appConfig.Properties.Item("BuildAction").Value = VSLangProj.prjBuildAction.prjBuildActionContent; nhibernateConfig.Properties.Item("CopyToOutputDirectory").Value = 2; nhibernateConfig.Properties.Item("BuildAction").Value = VSLangProj.prjBuildAction.prjBuildActionContent; AddToStatus("Writing NUnit assemblies..."); WriteBinaryFile("Lib/nunit.core.dll"); WriteBinaryFile("Lib/nunit.framework.dll"); AddToStatus("Adding NUnit references..."); VSProject vsTestProj = (VSProject)testProject.Object; vsTestProj.References.Add(m_dstPath + "Lib\\nunit.core.dll"); vsTestProj.References.Add(m_dstPath + "Lib\\nunit.framework.dll"); if (GetConfigSettingBool("projects.tests.scenariounit")) { AddToStatus("Writing ScenarioUnit assemblies..."); WriteBinaryFile("Lib/NXUnit.Framework.dll"); WriteBinaryFile("Lib/AndroMDA.ScenarioUnit.dll"); AddToStatus("Adding ScenarioUnit references..."); vsTestProj.References.Add(m_dstPath + "Lib\\NXUnit.Framework.dll"); vsTestProj.References.Add(m_dstPath + "Lib\\AndroMDA.ScenarioUnit.dll"); ProjectItem testDataFolder = testProject.ProjectItems.AddFolder("TestData", Constants.vsProjectItemKindPhysicalFolder); testDataFolder.ProjectItems.AddFolder("actual_output", Constants.vsProjectItemKindPhysicalFolder); testDataFolder.ProjectItems.AddFolder("expected_output", Constants.vsProjectItemKindPhysicalFolder); testDataFolder.ProjectItems.AddFolder("rules", Constants.vsProjectItemKindPhysicalFolder); testDataFolder.ProjectItems.AddFolder("input", Constants.vsProjectItemKindPhysicalFolder); } } // Add the references to all the DLLs we just put in /Lib AddToStatus("Adding project references to common project..."); AddBinaryReferences(commonProject); AddToStatus("Adding project references to core project..."); AddBinaryReferences(coreProject); // Add a reference from the core project to the common project AddProjectReference(coreProject, commonProject); // If we created the schema export project if (schemaExportProject != null) { VSProject proj = schemaExportProject.Object as VSProject; AddToStatus("Adding references to schema export project..."); // Add the references to the DLLs AddBinaryReferences(schemaExportProject); // Add references to the core and common projects AddProjectReference(schemaExportProject, commonProject); AddProjectReference(schemaExportProject, coreProject); AddToStatus("Adding System.Configuration reference to schema export project..."); try { proj.References.Add("System.Configuration"); } catch { } } // If we created the schema export project if (testProject != null) { AddToStatus("Adding references to testing project..."); // Add the references to the DLLs AddBinaryReferences(testProject); // Add references to the core and common projects AddProjectReference(testProject, commonProject); AddProjectReference(testProject, coreProject); } if (webProject != null) { AddToStatus("Adding project references to web project..."); VsWebSite.VSWebSite proj = webProject.Object as VsWebSite.VSWebSite; proj.References.AddFromFile(m_dstPath + "Lib\\AndroMDA.NHibernateSupport.dll"); try { proj.References.AddFromProject(commonProject); } catch {} try { proj.References.AddFromProject(coreProject); } catch {} if (webCommonProject != null) { try { proj.References.AddFromProject(webCommonProject); } catch { } } //m_applicationObject.Solution.Properties.Item("StartupProject").Value = webProject.Name; } if (webCommonProject != null) { VSProject proj = webCommonProject.Object as VSProject; AddToStatus("Adding common project reference to web common project..."); try { proj.References.AddProject(commonProject); } catch { } AddToStatus("Adding core project reference to web common project..."); try { proj.References.AddProject(coreProject); } catch { } AddToStatus("Adding System.Configuration reference to web common project..."); try { proj.References.Add("System.Configuration"); } catch { } AddToStatus("Adding System.Web reference to web common project..."); try { proj.References.Add("System.Web"); } catch { } } AddToStatus("Processing complete, cleaning up..."); }
/// <summary> /// /// </summary> /// <param name="templateFile"></param> /// <param name="IsTopN"></param> public void WriteAllReportHTML(string templateFile, bool IsTopN) { try { bool bGen = false; bool bReportGen = true; string name = ""; string strTmp = ""; string strGenSection = ""; string strGenKey = ""; string strGenValue = ""; string strGroupRight = ""; string strReportName = ""; string strBaseDirectory = ""; string strZipFileName = ""; DateTime tmEnd = DateTime.Now; DateTime tmStart = DateTime.Now; if (IsTopN) { file = iniFileDao.GetIniFile("topnreportset.ini"); StatsTable = new DataTable(); StatsTable.Columns.Add("hashKey"); StatsTable.Columns.Add("����");//StatName StatsTable.Columns.Add("����ֵ����");//StatReturnName StatsTable.Columns.Add("���ֵ");//StatMax StatsTable.Columns.Add("��Сֵ");//StatMin StatsTable.Columns.Add("ƽ��ֵ", typeof(double));//StatAverage StatsTable.Columns.Add("���һ��");//StatLatest StatsTable.Columns.Add("���ֵʱ��"); } else { file = iniFileDao.GetIniFile("reportset.ini"); } //�����û��������� �������б��� foreach (string key in file.Keys) { strGroupRight = ""; strReportName = ""; bGen = false; bReportGen = false; string strReportFile = ""; //�Ƿ�����ʱ�� string strGenerate = file[key]["Generate"]; if (strGenerate == "" || strGenerate == null) continue; int nHours = int.Parse(strGenerate); if (nHours == DateTime.Now.Hour) { bGen = true; } //����ֹ ������ ִ����һ������ if (file[key]["Deny"] == "No") { strGroupRight = file[key]["GroupRight"]; if (strGroupRight == "" || strGroupRight == null) continue; //string[] monitorList = strGroupRight.Split(','); //δ������ʱ�� ������ ִ����һ������ if (bGen) { //��ȡ��������ʱ��� if (file[key]["Period"] == "�ձ�") { string szEndTime = file[key]["EndTime"]; string szStartTime = file[key]["StartTime"]; //szEndTime = "12:30"; string szHour = "00"; string szMinute = "00"; if (IsTopN) { szEndTime = "00"; szStartTime = "00"; } else { if (szEndTime == "" || szEndTime == null) continue; if (szStartTime == "" || szStartTime == null) continue; int pos = szEndTime.IndexOf(":", 0); if (pos <= 0) continue; szHour = szEndTime.Substring(0, pos); szMinute = szEndTime.Substring(pos + 1, szEndTime.Length - pos - 1); } tmEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(szHour), int.Parse(szMinute), 0); //tmEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(szStartTime), int.Parse(szEndTime), 0); tmStart = tmEnd.Subtract(new TimeSpan(1, 0, 0, 0, 0)); bReportGen = true; this.DatePart = "day"; } else if (file[key]["Period"] == "�ܱ�") { if (file[key]["WeekEndTime"] == "" || file[key]["WeekEndTime"] == null) continue; int nWeekDay; nWeekDay = int.Parse(file[key]["WeekEndTime"]); if ((int)(DateTime.Now.DayOfWeek) == nWeekDay) { tmEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0); tmStart = tmEnd.Subtract(new TimeSpan(7, 0, 0, 0, 0)); bReportGen = true; } this.DatePart = "week"; } else if (file[key]["Period"] == "�±�") { if ((int)DateTime.Now.Day == 1) { if (DateTime.Now.Month == 1) { tmStart = new DateTime(DateTime.Now.Year - 1, 12, 1, 0, 0, 0); tmEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0); } else { tmStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month - 1, 1, 0, 0, 0); tmEnd = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0); } bReportGen = true; } this.DatePart = "month"; } else { } } else { continue; } } else { continue; } //�� ���ɴ˱��� �� if (bReportGen) { if (IsTopN) { strReportName = tmStart.ToString() + tmEnd.ToString() + key + "TopN"; } else { strReportName = tmStart.ToString() + tmEnd.ToString() + key; } //��ѯ������������ int index = 200;//һ�β�ѯ��200�������� if (IsTopN) { IDictionary<string, NameValueCollection> monitoidToType = impl.QueryTopnMonitorInfo(); IDictionary<string, MonitorTemplet> topnMontiorTemplet = new Dictionary<string, MonitorTemplet>(); IMonitorTempletDao templetDao = new MonitorTempletDaoImpl(); foreach (string key1 in monitoidToType.Keys) { if (monitoidToType[key1]["sv_monitortype"] == null) continue; if (!topnMontiorTemplet.ContainsKey(monitoidToType[key1]["sv_monitortype"])) { MonitorTemplet[] templet = templetDao.FindById(new string[] { monitoidToType[key1]["sv_monitortype"] }, true); topnMontiorTemplet.Add(monitoidToType[key1]["sv_monitortype"], templet[0]); } } string strSelMonitorType = file[key]["Type"];//�û�ѡ��ļ�������� string strMark = file[key]["Mark"]; int strCount = int.Parse(file[key]["Count"]); string strSort = file[key]["Sort"]; if (strSelMonitorType == "" || strSelMonitorType == null) continue; if (strMark == "" || strMark == null) continue; strTmp = ""; foreach (string strMonitorId in strGroupRight.Split(',')) { if (strMonitorId != "" && monitoidToType.Keys.Contains(strMonitorId)) { if (topnMontiorTemplet[monitoidToType[strMonitorId]["sv_monitortype"]].Name == strSelMonitorType) { strTmp += strMonitorId; strTmp += ","; } } } //��ּ����ID,���з�����ѯ�� int splitLength = strTmp.Split(',').Length; this.StatsTable.Rows.Clear(); this.QueryReportData.Rows.Clear(); if (splitLength > index) { int sect = splitLength / index; DataTable StatsTableTimp = StatsTable.Clone(); string[] strArray = strTmp.Split(','); for (int split = 0; split < sect; split++) { DataTable QueryReportDataTemp = QueryReportData.Clone(); string splitString = ""; int _splitCount = split * index; for (int splitCount = _splitCount; splitCount < (split + 1) * index; splitCount++) { splitString += strArray[splitCount]; splitString += ","; } QueryReportDataTemp = impl.QueryReportData(splitString, true, false, tmStart, tmEnd); foreach (DataRow QrdrTemp in QueryReportDataTemp.Rows) { QueryReportData.ImportRow(QrdrTemp); } foreach (DataRow StdrTemp in impl.StatsTable.Rows) { StatsTableTimp.ImportRow(StdrTemp); } } string splitStringLast = ""; int _splitCountLast = sect * index; for (int splitCount = _splitCountLast; splitCount < splitLength; splitCount++) { splitStringLast += strArray[splitCount]; splitStringLast += ","; } DataTable QueryReportDataTempLast = impl.QueryReportData(splitStringLast, true, false, tmStart, tmEnd); foreach (DataRow QrdrTemp in QueryReportDataTempLast.Rows) { QueryReportData.ImportRow(QrdrTemp); } foreach (DataRow StdrTemp in impl.StatsTable.Rows) { StatsTableTimp.ImportRow(StdrTemp); } ChangeColumnType(StatsTableTimp); } else { QueryReportData = impl.QueryReportData(strTmp, true, false, tmStart, tmEnd); ChangeColumnType(impl.StatsTable); } //QueryReportData = impl.QueryReportData(strTmp, true, false, tmStart, tmEnd); //this.StatsTable.Rows.Clear(); //for (int a = 0; a < impl.StatsTable.Rows.Count; a++) //{ // DataRow dr = this.StatsTable.NewRow(); // for (int b = 0; b < impl.StatsTable.Columns.Count; b++) // { // if (b == 5) // { // dr[b] = double.Parse(impl.StatsTable.Rows[a][b].ToString()); // } // else // { // dr[b] = impl.StatsTable.Rows[a][b].ToString(); // } // } // this.StatsTable.Rows.Add(dr); //} //DataView dv = this.StatsTable.DefaultView; DataView dv = new DataView(this.StatsTable); dv.Sort = "ƽ��ֵ desc"; //���Դ��� //*********************************************** if (key == "AqcTestSNMP Cpu") { this.DataTableToExcel(dv.ToTable(), "c:\\" + key + DateTime.Now.ToShortDateString() + ".csv"); this.DataTableToExcel(this.StatsTable, "c:\\" + key + "stat" + DateTime.Now.ToShortDateString() + ".csv"); } //************************************************* selectDataTable(dv.ToTable(), strMark, strCount, strSort); } else { impl.ReturnFilter = "sv_primary,sv_drawimage"; int splitLength = strGroupRight.Split(',').Length; this.StatsTable.Rows.Clear(); this.QueryReportData.Rows.Clear(); this.dstrTable.Rows.Clear(); if (file[key]["Parameter"].Equals("Yes")) { //��ּ����ID,���з�����ѯ�� if (splitLength > index) { int sect = splitLength / index; DataTable StatsTableTimp = StatsTable.Clone(); string[] strArray = strGroupRight.Split(','); imgTables = new Dictionary<string, DataTable>(); for (int split = 0; split < sect; split++) { DataTable QueryReportDataTemp = QueryReportData.Clone(); string splitString = ""; int _splitCount = split * index; for (int strCount = _splitCount; strCount < (split + 1) * index; strCount++) { splitString += strArray[strCount]; splitString += ","; } QueryReportDataTemp = impl.QueryReportData(splitString, true, true, tmStart, tmEnd); foreach (DataRow QrdrTemp in QueryReportDataTemp.Rows) { QueryReportData.ImportRow(QrdrTemp); } foreach (DataRow StdrTemp in impl.StatsTable.Rows) { StatsTable.ImportRow(StdrTemp); } foreach (KeyValuePair<string, DataTable> Kv in impl.ImgTableHash) { if (!imgTables.ContainsKey(Kv.Key)) { imgTables.Add(Kv); } } foreach (DataRow dr in impl.DstrTable.Rows) { this.dstrTable.ImportRow(dr); } } string splitStringLast = ""; int _splitCountLast = sect * index; for (int strCount = _splitCountLast; strCount < splitLength; strCount++) { splitStringLast += strArray[strCount]; splitStringLast += ","; } DataTable QueryReportDataTempLast = impl.QueryReportData(splitStringLast, true, true, tmStart, tmEnd); foreach (DataRow QrdrTemp in QueryReportDataTempLast.Rows) { QueryReportData.ImportRow(QrdrTemp); } foreach (DataRow StdrTemp in impl.StatsTable.Rows) { StatsTable.ImportRow(StdrTemp); } foreach (KeyValuePair<string, DataTable> Kv in impl.ImgTableHash) { if (!imgTables.ContainsKey(Kv.Key)) { imgTables.Add(Kv); } } foreach (DataRow dr in impl.DstrTable.Rows) { this.dstrTable.ImportRow(dr); } //imgTables = impl.ImgTableHash; } else { QueryReportData = impl.QueryReportData(strGroupRight, true, true, tmStart, tmEnd); StatsTable = impl.StatsTable; imgTables = impl.ImgTableHash; } } else { if (splitLength > index) { int sect = splitLength / index; DataTable StatsTableTimp = StatsTable.Clone(); string[] strArray = strGroupRight.Split(','); imgTables = new Dictionary<string, DataTable>(); for (int split = 0; split < sect; split++) { DataTable QueryReportDataTemp = QueryReportData.Clone(); string splitString = ""; int _splitCount = split * index; for (int strCount = _splitCount; strCount < (split + 1) * index; strCount++) { splitString += strArray[strCount]; splitString += ","; } QueryReportDataTemp = impl.QueryReportData(splitString, true, false, tmStart, tmEnd); foreach (DataRow QrdrTemp in QueryReportDataTemp.Rows) { QueryReportData.ImportRow(QrdrTemp); } foreach (DataRow StdrTemp in impl.StatsTable.Rows) { StatsTable.ImportRow(StdrTemp); } foreach (KeyValuePair<string, DataTable> Kv in impl.ImgTableHash) { if (!imgTables.ContainsKey(Kv.Key)) { imgTables.Add(Kv); } } } string splitStringLast = ""; int _splitCountLast = sect * index; for (int strCount = _splitCountLast; strCount < splitLength; strCount++) { splitStringLast += strArray[strCount]; splitStringLast += ","; } DataTable QueryReportDataTempLast = impl.QueryReportData(splitStringLast, true, false, tmStart, tmEnd); foreach (DataRow QrdrTemp in QueryReportDataTempLast.Rows) { QueryReportData.ImportRow(QrdrTemp); } foreach (DataRow StdrTemp in impl.StatsTable.Rows) { StatsTable.ImportRow(StdrTemp); } foreach (KeyValuePair<string, DataTable> Kv in impl.ImgTableHash) { if (!imgTables.ContainsKey(Kv.Key)) { imgTables.Add(Kv); } } //imgTables = impl.ImgTableHash; } else { QueryReportData = impl.QueryReportData(strGroupRight, true, false, tmStart, tmEnd); StatsTable = impl.StatsTable; imgTables = impl.ImgTableHash; } } //if (file[key]["Parameter"].Equals("Yes")) //{ // QueryReportData = impl.QueryReportData(strGroupRight, true, true, tmStart, tmEnd); //} //else //{ // QueryReportData = impl.QueryReportData(strGroupRight, true, false, tmStart, tmEnd); //} //StatsTable = impl.StatsTable; //imgTables = impl.ImgTableHash; } //���ɱ���ͼƬ�ļ� Savepictures(key, tmStart.ToString(), tmEnd.ToString(), IsTopN); //����ģ�岢���� WriteLogFile("nvelocity.properties"); CreateVM(templateFile, IsTopN,key); Velocity.SetProperty(RuntimeConstants.INPUT_ENCODING, "GB2312"); Velocity.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "GB2312"); Velocity.Init(BasePath + "\\nvelocity.properties"); //... //�Ƿ��г���ֵ //�Ƿ��г����� //�Ƿ��г�Σ�� //�Ƿ��г���ֹ VelocityContext context = new VelocityContext(); //context.Put("RunName", RunName); //context.Put("RunRight", RunRight); //context.Put("Rundanger", Rundanger); //context.Put("RunWrong", RunWrong); //context.Put("RunPass", RunPass); //context.Put("RunLatest", RunLatest); //context.Put("StatName", StatName); //context.Put("StatReturnName", StatReturnName); //context.Put("StatMax", StatMax); //context.Put("StatMin", StatMin); //context.Put("StatAverage", StatAverage); //context.Put("StatLatest", StatLatest); if (IsTopN) { context.Put("MakeTitleTable", MakeTitle(file[key]["Title"].ToString().Split('|')[0], tmStart.ToString(), tmEnd.ToString())); context.Put("MakeTopNhtmltable", MakeTopNhtmltable()); context.Put("MakeTopNhtmlPicture", MakeTopNhtmlPicture(key, tmStart.ToString(), tmEnd.ToString())); } else { //�г���ϸ���� bool IsStatusResultVisible = file[key]["Parameter"].Equals("Yes"); //�Ƿ��г���ֵ bool IsListClicketVisible = file[key]["ListClicket"].Equals("Yes"); //�Ƿ��г����� bool IsListErrorVisible = file[key]["ListError"].Equals("Yes"); //�Ƿ��г�Σ�� bool IsListDangerVisible = file[key]["ListDanger"].Equals("Yes"); //�Ƿ��г���ֹ bool IsDenyVisible = file[key]["Deny"].Equals("Yes"); //�Ƿ��г�ͼƬ bool IsGraphic = file[key]["Graphic"].Equals("Yes"); DataTable tb = new DataTable(); DataColumn c1 = new DataColumn("����"); DataColumn c2 = new DataColumn("ʱ��"); DataColumn c3 = new DataColumn("״̬"); DataColumn c4 = new DataColumn("����ֵ"); DataColumn[] c5 = { c1, c2, c3, c4 }; tb.Columns.AddRange(c5); if (file[key]["ListError"].Equals("Yes")) { tb.Rows.Clear(); foreach (DataRow dr in impl.DstrTable.Select("״̬='Error'")) { tb.Rows.Add(dr.ItemArray); } context.Put("MakeErrorDataStrTable", MakeDataStrTable(tb)); } if (file[key]["ListDanger"].Equals("Yes")) { tb.Rows.Clear(); foreach (DataRow dr in impl.DstrTable.Select("״̬='warning'")) { tb.Rows.Add(dr.ItemArray); } context.Put("MakeDangerDataStrTable", MakeDataStrTable(tb)); } context.Put("MakeTitleTable", MakeTitle(file[key]["Title"].ToString().Split('|')[0], tmStart.ToString(), tmEnd.ToString())); //context.Put("RunQueryReportData", RunQueryReportData); context.Put("MakeRunHTMLTable", MakeRunHTMLTable()); context.Put("MakeStatehtmltable", MakeStatehtmltable(key, tmStart.ToString(), tmEnd.ToString())); context.Put("MakeStatehtmlPicture", MakeStatehtmlPicture(key, tmStart.ToString(), tmEnd.ToString())); if (file[key]["Parameter"].Equals("Yes")) { context.Put("MakeDataStrTable", MakeDataStrTable(this.dstrTable)); } else { context.Put("MakeDataStrTable", MakeDataStrTable(impl.DstrTable)); } context.Put("IsStatusResultVisible", IsStatusResultVisible);//�г�״̬�ܽ� context.Put("IsListClicketVisible", IsListClicketVisible);//�Ƿ��г���ֵ context.Put("IsListErrorVisible", IsListErrorVisible);//�Ƿ��г����� context.Put("IsListDangerVisible", IsListDangerVisible);//�Ƿ��г�Σ�� context.Put("IsDenyVisible", IsDenyVisible); //�Ƿ��г���ֹ context.Put("IsGraphic", IsGraphic);//�Ƿ��г�ͼƬ } //���ɱ��� html Template template = null; try { //��ȡģ�� //�����ĸ�Ŀ¼���棿 template = Velocity.GetTemplate("\\ReportTemplate\\" + templateFile); //���HTML if (template != null) { strTmp = strReportName.Replace(" ", "_").Replace(":", "_").Replace("*", "_").Replace("/", "_"). Replace("\\", "_").Replace("?", "_").Replace("|", "_").Replace("<", "_").Replace(">", "_").Replace("\"", "_"); strReportName = strTmp; StringWriter writer = new StringWriter(); template.Merge(context, writer); string p = BasePath + "ReportTemplate\\" + DatePart + "\\" + strReportName; if (!Directory.Exists(p)) { Directory.CreateDirectory(p); } strReportFile = p + "\\" + strReportName + ".html"; StreamWriter s = new StreamWriter(strReportFile, false, System.Text.Encoding.UTF8); s.WriteLine(writer.ToString()); s.Flush(); s.Close(); } } catch (ResourceNotFoundException xxx) { MessageBox.Show(xxx.Message + "�����ģ���ļ�����ʾ��Ŀ¼"); } catch (ParseErrorException pee) { MessageBox.Show(pee.Message); } //д��Ϣ�� reportgenerate.ini strGenKey = ""; strGenValue = ""; strTmp = ""; //section�ڸ�ʽ��������$��ʼʱ��$��ֹʱ��$ strGenSection = file[key]["Title"].ToString().Split('|')[1] + "$" + tmStart.ToString() + "$" + tmEnd.ToString() + "$"; if (!IsTopN) { for (int i = 0; i < imgTables.Count; i++) { //��ֵ��ʽ���������$����ֵ����$ strTmp = StatsTable.Rows[i][1].ToString() + "$" + StatsTable.Rows[i][2].ToString() + "$"; strGenKey = strTmp.Replace(" ", "_").Replace(":", "_").Replace("*", "_").Replace("/", "_"). Replace("\\", "_").Replace("?", "_").Replace("|", "_").Replace("<", "_").Replace(">", "_").Replace("\"", "_"); //ֵ��ʽ����Сֵ$ƽ��ֵ$���ֵ$ strTmp = StatsTable.Rows[i][4].ToString() + "$" + StatsTable.Rows[i][5].ToString() + "$" + StatsTable.Rows[i][3].ToString(); strGenValue = strTmp.Replace(" ", "_").Replace(":", "_").Replace("*", "_").Replace("/", "_"). Replace("\\", "_").Replace("?", "_").Replace("|", "_").Replace("<", "_").Replace(">", "_").Replace("\"", "_"); //дIni //iniFileDao.WriteIniFileString("reportgenerate.ini", strGenSection, strGenKey, strGenValue); iniFileDao.WriteIniFileString("mmcreportgenerate.ini", strGenSection, strGenKey, strGenValue); } } else { //��ֵ��ʽ��$����ֵ����$ strTmp = file[key]["Mark"]; if (strTmp == "") { strTmp = file[key]["Type"]; } strGenKey = "$" + strTmp + "$"; //ֵ��ʽ����Сֵ$ƽ��ֵ$���ֵ$ --> ��ʱû���� //strTmp = StatsTable.Rows[i][4].ToString() + "$" + StatsTable.Rows[i][5].ToString() + "$" + StatsTable.Rows[i][3].ToString(); //strGenValue = strTmp.Replace(" ", "_").Replace(":", "_").Replace("*", "_").Replace("/", "_"). // Replace("\\", "_").Replace("?", "_").Replace("|", "_").Replace("<", "_").Replace(">", "_").Replace("\"", "_"); //дIni //iniFileDao.WriteIniFileString("topnreportgenerate.ini", strGenSection, strGenKey, strGenValue); iniFileDao.WriteIniFileString("mmctopnreportgenerate.ini", strGenSection, strGenKey, strGenValue); } //����û��ṩ�� �ʼ���ַ ��ѹ�������ļ������� if (bSendMail && file[key]["EmailSend"] != "" && file[key]["EmailSend"] != null) { //���淢�͵�ַ strToInfo = file[key]["EmailSend"]; //�齨ѹ�����ļ��� strBaseDirectory = ""; strZipFileName = ""; string p = BasePath + "ReportTemplate\\" + DatePart + "\\" + strReportName; if (!IsTopN) { //�齨ѹ����Ŀ¼ if (!Directory.Exists(BasePath + "ReportTemplate\\statreport")) { Directory.CreateDirectory(BasePath + "ReportTemplate\\statreport"); Directory.CreateDirectory(BasePath + "ReportTemplate\\statreport\\jpeg"); } else { CleanFiles(BasePath + "ReportTemplate\\statreport"); CleanFiles(BasePath + "ReportTemplate\\statreport"); Directory.CreateDirectory(BasePath + "ReportTemplate\\statreport"); Directory.CreateDirectory(BasePath + "ReportTemplate\\statreport\\jpeg"); } strBaseDirectory = BasePath + "ReportTemplate\\statreport\\"; strZipFileName = BasePath + "ReportTemplate\\statreport" + key.Split('|')[1] + ".zip"; //����html�ļ� File.Copy(strReportFile, strBaseDirectory + strReportName + ".html"); //����jpegͼƬ�ļ� for (int i = 0; i < imgTables.Count; i++) { strTmp = key.Split('|')[1] + tmStart.ToString() + tmEnd.ToString() + StatsTable.Rows[i][1].ToString(); name = strTmp.Replace(" ", "_").Replace(":", "_").Replace("*", "_").Replace("/", "_"). Replace("\\", "_").Replace("?", "_").Replace("|", "_").Replace("<", "_").Replace(">", "_").Replace("\"", "_"); if (File.Exists(p + "\\jpeg\\" + i + name + ".Png")) File.Copy(p + "\\jpeg\\" + i + name + ".Png", strBaseDirectory + "\\jpeg\\" + i + name + ".Png"); } } else { //�齨ѹ����Ŀ¼ if (!Directory.Exists(BasePath + "ReportTemplate\\topnreport")) { Directory.CreateDirectory(BasePath + "ReportTemplate\\topnreport"); Directory.CreateDirectory(BasePath + "ReportTemplate\\topnreport\\jpeg"); } else { CleanFiles(BasePath + "ReportTemplate\\topnreport"); CleanFiles(BasePath + "ReportTemplate\\topnreport"); Directory.CreateDirectory(BasePath + "ReportTemplate\\topnreport"); Directory.CreateDirectory(BasePath + "ReportTemplate\\topnreport\\jpeg"); } strBaseDirectory = BasePath + "ReportTemplate\\topnreport\\"; strZipFileName = BasePath + "ReportTemplate\\topnreport" + key.Split('|')[1] + ".zip"; //����html�ļ� File.Copy(strReportFile, strBaseDirectory + strReportName + ".html"); //����jpegͼƬ�ļ� strTmp = key + tmStart.ToString() + tmEnd.ToString() + "TopN"; name = strTmp.Replace(" ", "_").Replace(":", "_").Replace("*", "_").Replace("/", "_"). Replace("\\", "_").Replace("?", "_").Replace("|", "_").Replace("<", "_").Replace(">", "_").Replace("\"", "_"); name += ".Png"; if (File.Exists(p + "\\jpeg\\" + name)) File.Copy(p + "\\jpeg\\" + name, strBaseDirectory + "\\jpeg\\" + name); } //ѹ��Ŀ¼ ZipFileMain(strBaseDirectory, strZipFileName); //�����ʼ� if (!IsTopN) { SendSMTPEMail(strSmtpServerInfo, strFromInfo, strFromUserInfo, strFromPwdInfo, strToInfo, "statreport", "statreport", strZipFileName); } else { SendSMTPEMail(strSmtpServerInfo, strFromInfo, strFromUserInfo, strFromPwdInfo, strToInfo, "topnreport", "topnreport", strZipFileName); } } } System.Threading.Thread.Sleep(50); } } catch (System.Exception ex) { MessageBox.Show(ex.StackTrace, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Question); } }
public override void Page_Load(ref NVelocity.VelocityContext context) { base.Page_Load(ref context); }
public void GenerateScript(Provider p) { string now = DateTime.Now.ToShortDateString().Replace("/", "-"); _provider = p; velocityCtx = new NVelocity.VelocityContext(); _coverageAreas.Clear(); _usedCodes.Clear(); _sqlEntities.Clear(); _baseProducts.Clear(); _services.Clear(); _feeScheduleMap.Clear(); System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); velocityCtx.Put("version", Kernel.VERSION); velocityCtx.Put("username", System.Security.Principal.WindowsIdentity.GetCurrent().Name); velocityCtx.Put("produced_date", DateTime.Now.ToString()); velocityCtx.Put("option_reportEnabled", ReportEnabled.ToString()); velocityCtx.Put("option_writeSqlScriptToReport", WriteSqlScriptToReport); velocityCtx.Put("option_WriteRadScriptToReport", WriteRadScriptToReport); velocityCtx.Put("option_IncludeUnreferencedSqlVariables", IncludeUnreferencedSqlVariables); velocityCtx.Put("option_UseMarkdown", UseMarkdown); velocityCtx.Put("rad_script", HttpUtility.HtmlEncode(ScriptExpression.Trim())); velocityCtx.Put("num_validation_errors", DomainEntityValidations.Count); List<HtmlTable> entityTables = RenderReportEntities(); using (MemoryStream ms = new MemoryStream()) { HtmlTextWriter htmlWriter = new HtmlTextWriter(new StreamWriter(ms)); foreach (var table in entityTables) { table.RenderControl(htmlWriter); htmlWriter.WriteBreak(); } htmlWriter.Flush(); StreamReader reader = new StreamReader(ms); ms.Position = 0; string x = reader.ReadToEnd(); velocityCtx.Put("entity_tables", x); } if (DomainEntityValidations.Count == 0) { Gather(); string sql = GenerateSql(); string sqlFilename = Path.Combine(Path.GetTempPath(), _provider.Name + " " + now + ".sql"); StreamWriter sqlWriter = new StreamWriter(sqlFilename); velocityCtx.Put("sql_script", HttpUtility.HtmlEncode(sql)); velocityCtx.Put("sql_validation_errors", _sqlValidations.Count); sqlWriter.WriteLine(sql); sqlWriter.Flush(); sqlWriter.Close(); //Process.Start(sqlFilename); } foreach (var qpi in _popups.Values) { qpi.Content = qpi.Content .Replace("'", "''") .Replace("\r\n", "<br />") .Replace("\r", "<br />") .Replace("\n", "<br />"); } watch.Stop(); velocityCtx.Put("processing_time", watch.Elapsed.TotalMilliseconds.ToString() + "ms"); velocityCtx.Put("qtip_popups", _popups.Values); string reportFilename = Path.Combine(Path.GetTempPath(), _provider.Name + " " + now + ".html"); StreamWriter reportWriter = new StreamWriter(reportFilename); Velocity.Evaluate(velocityCtx, reportWriter, null, Resource1.Report); reportWriter.Close(); if (ReportEnabled) Process.Start(reportFilename); }
internal VelocityContext(string templateText) { _templateText = templateText; _context = new NVelocity.VelocityContext(); }
private void tratarFile(object file) { // ahora tratamos cada archivo en una nueva tarea... try { string archivito = ""; archivito = file.ToString(); AsyncWriteLine("Procesando " + archivito); char tabCaracter = '\u0009'; try { String plantilla = util.loadFile(archivito); // sacamos las variables de la plantilla variablesTemplate var = new variablesTemplate(); var = util.getVariablesFromTemplate(plantilla); // vamos a sacar unas variables que luego nos serviran... string nombreArchivo = ""; string nombreArchivoFinal = ""; string nombreDirectorioAgrabar = ""; string rutaArchivoFinal = ""; nombreArchivo = util.ExtractFilename(archivito); // sacamos de la ruta el directorio del archivo ... nombreDirectorioAgrabar = archivito; nombreDirectorioAgrabar = nombreDirectorioAgrabar.Replace(general.actualProject.projectTemplatesDirectory, ""); nombreDirectorioAgrabar = nombreDirectorioAgrabar.Replace(nombreArchivo, ""); if (nombreDirectorioAgrabar.StartsWith("\\") && !nombreDirectorioAgrabar.Equals("")) nombreDirectorioAgrabar = nombreDirectorioAgrabar.Substring(1, nombreDirectorioAgrabar.Length - 2); rutaArchivoFinal = Path.Combine(general.targetDirectory, nombreDirectorioAgrabar); if (var.namefile != null) { nombreArchivoFinal = Path.Combine(rutaArchivoFinal, var.namefile + "." + var.extensionFile); } else { nombreArchivoFinal = Path.Combine(rutaArchivoFinal, nombreArchivo); } if (!Directory.Exists(Path.Combine(general.targetDirectory, nombreDirectorioAgrabar))) Directory.CreateDirectory(Path.Combine(general.targetDirectory, nombreDirectorioAgrabar)); // si no tiene variables de configuracion es que no es un template... if (var.description == null && var.extensionFile == null) // no es una plantilla... { // simplemente lo grabamos a disco //util.saveTextToFile(nombreArchivoFinal, plantilla); System.IO.File.Copy(archivito, nombreArchivoFinal, true); } else // es una plantilla... { try { // si da un error en singleton es que falta la libreria commons o log4net.. Velocity.Init(); //VelocityEngine velocityEngine = new VelocityEngine(); //ExtendedProperties props = new ExtendedProperties(); //props.AddProperty("input.encoding", "UTF-8"); //props.AddProperty("output.encoding", "UTF-8"); //velocityEngine.Init(props); } catch (System.Exception exx) { AsyncWriteLine("Problem initializing Velocity : " + exx.Message); return; } if (var.appliesToAllTables.Equals("true")) { foreach (table item in general.actualProject.tables) { if (item.excludeFromGeneration) { } else { // tenemos que aplicar esta plantilla una vez por cada tabla... // lets make a Context and put data into it VelocityContext context = new VelocityContext(); context.Put("project", general.actualProject); context.Put("table", item); // lets render a template StringWriter writer = new StringWriter(); try { //Velocity.MergeTemplate(plantilla, context, writer); Velocity.Evaluate(context, writer, "prueba", plantilla); // sacamos las variables del archivo antes de borrarlas variablesTemplate varT = new variablesTemplate(); varT = util.getVariablesFromTemplate(writer.GetStringBuilder().ToString()); if (varT.namefile != null) { if (!Directory.Exists(Path.Combine(rutaArchivoFinal, varT.targetDirectory))) Directory.CreateDirectory(Path.Combine(rutaArchivoFinal, varT.targetDirectory)); nombreArchivoFinal = Path.Combine(Path.Combine(rutaArchivoFinal, varT.targetDirectory), varT.namefile + "." + var.extensionFile); } // now we delete the variables from the template cause there are no needed... string finalText = util.deleteVariablesFromTemplate(writer.GetStringBuilder().ToString()); // todo... // le quitamos saltos de linea extra finalText = finalText.Replace("\r\n\r\n", "\r\n").Replace("\r\n\r\n\r\n", "").Replace("\r\n\r\n\r\n\r\n", ""); // le quitamos los tabuladores extra finalText = finalText.Replace(tabCaracter.ToString(), " "); // grabamos segun el util.saveTextToFile(nombreArchivoFinal, finalText); } catch (System.Exception exx) { // file AsyncCleanRt1(""); AsyncWriteLine("Problem with the template : " + file.ToString()); AsyncWriteLine("Error : " + exx.Message); AsyncWriteLine("file://" + file.ToString()); errores.Add(file.ToString()); //AsyncAddControl(file.ToString()); //rt1.Text = exx.Message; //System.Console.Out.WriteLine("Problem merging template : " + exx); System.Console.Out.WriteLine("Problem evaluating template : " + exx); } }// end de else excludeFromGeneration } // end de for each } else { // es un template que no utiliza las tablas... // lets make a Context and put data into it VelocityContext context = new VelocityContext(); context.Put("project", general.actualProject); //context.Put("table", tab); // lets render a template StringWriter writer = new StringWriter(); try { //Velocity.MergeTemplate(plantilla, context, writer); Velocity.Evaluate(context, writer, "prueba", plantilla); // now we delete the variables from the template cause there are no needed... string finalText = util.deleteVariablesFromTemplate(writer.GetStringBuilder().ToString()); // todo... // le quitamos saltos de linea extra finalText = finalText.Replace("\r\n\r\n", "\r\n").Replace("\r\n\r\n\r\n", "").Replace("\r\n\r\n\r\n\r\n", ""); // le quitamos los tabuladores extra finalText = finalText.Replace(tabCaracter.ToString(), " "); util.saveTextToFile(nombreArchivoFinal, finalText); } catch (System.Exception exx) { rt1.Text = exx.Message; //System.Console.Out.WriteLine("Problem merging template : " + exx); System.Console.Out.WriteLine("Problem evaluating template : " + exx); } } } // //StringTemplate hello = new StringTemplate(plantilla); //hello.SetAttribute("table", tab); //rt1.Text = hello.ToString(); } catch (Exception ex) { AsyncWriteLine(ex.Message); } } catch (Exception ex) { AsyncWriteLine("Error " + ex.Message); //throw; } }