最近公司接了一个政府网站来做,要求全静态页面展示,记得以前在学校时用过渐飞cms系统来做学校网站,对cms还算比较了解,开始觉得定义那么多标签比较难实现,现在做出来了,倒觉得cms系统也挺简单的。在开发过程中,参考了渐飞的系统模板和处理的一些方法,主要对正则表达式下了一番功夫。系统数据库不是我设计的,所以定义的标签还依赖于这个系统,也存在不合理的标签。下面将定义的一些标签及主要的标签替换类贴出来。

   

新闻内容标签

标签

说明

[DH:Click]

点击次数

[DH:Year]

[DH:Month]

[DH:Day]

[DH:Hour]

[DH:Minute]

[DH:Second]

[DH:Title]

标题

[DH:Content]

内容

[DH:Source]

来源

[DH:Author]

作者

[DH:Editer]

责任编辑

[DH:ColumnName]

所属栏目名称

[DH:PicturePath]

新闻图片路径

[DH:Description]

文章描述

[DH:LinkURL]

链接地址

[DH:KeyWord]

新闻关键字

[DH:PrevNews]

显示上一条新闻路径 未做

[DH:PrevTitle]

显示上一条新闻标题 未做

[DH:NextNews]

显示下一条新闻路径 未做

[DH:NextTitle]

显示下一条新闻标题 未做

 

 

栏目循环标签

标签

说明

[DH:Loop NewsCount=number TitleNum=type AddStr=”…” CategoryID=number NewsType =Title Order=desc Sort=Click]    开始循环

[DH:Loop]

开始循环

NewsCount=number

新闻调用数量,number为任意有效英文数字

TitleNum=number

指定新闻标题的显示字符数量,number可以是任意有效的数值

AddStr=word

标题字数被截取之后,是否加上"..."类似这样的点。word任意字符(注意:请不要使用引号)

CategoryID

CategoryID=id

调用指定ID栏目的新闻

 

不指定参数默认调用本栏目新闻,如在首页模板,则默认调用所有栏目新闻

CategoryID=ID1|ID2|ID3

调用指定多个ID栏目的新闻,ID为有效整数,ID间用“|”分隔

 

CategoryID=All

调用网站所有栏目新闻

 

 

NewsType

Title          调用标题新闻

Recommend      调用推荐新闻

FlashPict      调用首页Flash新闻轮播图片文章

Order = desc|asc

排序 降序还是升序任选一个 不指定默认为降序(desc)

Sort= DateTime|Click

排序方式 按发布日期,点击次数任选一个 不指定默认为发布日期(DateTime)

[/DH:Loop]

结束循环

 

 

Loop 改为 LoopPage 则表示分页循环(一个页面里只允许一个DH:LoopPage) 继承Loop所有属性 ,这个标签没有CategoryID属性 只允许在分页模板中使用

 

 

分页标签

标签

说明

[DH:PageSize]

每页记录数

[DH:PageCount]

总页数

[DH:RecordCount]

总记录数

[DH:CurrentPage]

当前页码

[DH:FirstPage]

首页

[DH:PrevPage]

上一页

[DH:ListPage]

页码列表 未做

[DH:NextPage]

下一页

[DH:LastPage]

尾页

[DH:DropDownList]

页码下拉框

 

 

公共标签

[DH:Navigation]

导航标签:显示的效果为

地区概况>>>自然地理

[DH:UrlPath]

URL路径   作废

[DH:More ColumnID=1]

栏目链接标签 ColumnID为栏目ID

[DH:ImgPath Type=1]

图片的路径

[DH:ImgURL Type=1]

图片的链接地址

[DH:SQL SELECT= Multiple=1 Str=</tr><tr> ]

执行SQL开始 SELECT为要执行的SQL查询语句 语句中不能出现引号

Multiple与Str

表示循环到Multiple指字数字的倍数时加上Str指定的字符,用于多列排板.

[DH:Field Name=Id WordNum=100|All HTML=True|False ]

显示的字段ID

WordNum

要显示的字符数

HTML

是否取消HTML

[/DH:SQL]

执行SQL结束 循环次数为SQL取得的记录数

 

 

*********************************************************************************
 * ClassName:       TemplateTag
 * Description:     处理模板标签类
 * MemberVariable:
 * Functions:       
 * Modify information:  
 *  Date        ModifyFlag    Charged by       Description      
 * 2008-8-5     New           YangWenBing      Create Class
 * 
 * ********************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using Entity;
using log4net;
using System.Data;
using Business.common;

namespace Business.Template
{
    
/// <summary>
    
/// 模板标签处理类
    
/// </summary>
    public class TemplateTag
    {
        
private static readonly ILog logger = LogManager.GetLogger(typeof(TemplateTag));

        
/// <summary>
        
/// 创建文件
        
/// </summary>
        
/// <param name="filePath">路径</param>
        
/// <param name="text">内容</param>
        private void CreateFile(string filePath, string text)
        {
            Business.Folder.Files.CreateFolder(filePath.Substring(
0,filePath.LastIndexOf("\\")+1));
            
try {
                StreamWriter sw 
= new StreamWriter(filePath, false, Encoding.GetEncoding("gb2312"));
                sw.WriteLine(text);
                sw.Flush();
                sw.Close();
            }
            
catch (Exception ex) {
                logger.Error(
"创建文件出错 文件地址:"+filePath, ex);                
                
throw ex;
            }
        }

        
/// <summary>
        
/// 生成新文章
        
/// </summary>
        
/// <param name="obj">MArticleInfo</param>
        public void NewArticle(MArticleInfo obj)
        {
            
string path = GetApplicationPath() + obj.FilePath + obj.FileName;

            
if (obj.MTemplate == nullreturn;

            
string template = obj.MTemplate.Template;
            template 
= PublicTag(template, obj.MColumn);
            
//下面的各种标签的替换
            string ClickPath = "<script src='" + getapppath() + "Click.aspx?ArticleID=" + obj.Id.ToString() + "'></script>";
            template 
= Replace(template, @"\[DH:UrlPath\]""/");
            template 
= Replace(template, @"\[DH:Click\]", ClickPath);
            template 
= Replace(template, @"\[DH:Year\]", obj.CreatedDate.Value.Year.ToString());
            template 
= Replace(template, @"\[DH:Month\]", obj.CreatedDate.Value.Month.ToString());
            template 
= Replace(template, @"\[DH:Day\]", obj.CreatedDate.Value.Day.ToString());
            template 
= Replace(template, @"\[DH:Hour\]", obj.CreatedDate.Value.Hour.ToString());
            template 
= Replace(template, @"\[DH:Minute\]", obj.CreatedDate.Value.Minute.ToString());
            template 
= Replace(template, @"\[DH:Second\]", obj.CreatedDate.Value.Second.ToString());
            template 
= Replace(template, @"\[DH:Title\]", obj.Title);
            template 
= Replace(template, @"\[DH:Content\]", obj.Content);
            template 
= Replace(template, @"\[DH:Source\]", obj.ArticleSource);
            template 
= Replace(template, @"\[DH:Author\]", obj.Author);
            template 
= Replace(template, @"\[DH:Editer\]", obj.Editor);
            template 
= Replace(template, @"\[DH:ColumnName\]", obj.MColumn.ColumnName);
            template 
= Replace(template, @"\[DH:PicturePath\]", obj.PicturePath);
            template 
= Replace(template, @"\[DH:LinkURL\]", getapppath() + obj.FilePath.Replace("\\""/"+ obj.FileName.Replace("\\""/"));
            template 
= Replace(template, @"\[DH:Description\]", obj.Description);
            template 
= Replace(template, @"\[DH:KeyWord\]", obj.KeyWord);
            CreateFile(path, template);
        }

        
/// <summary>
        
/// 生成栏目首页
        
/// </summary>
        
/// <param name="obj">MColumn</param>
        public void NewIndexPage(MColumn obj) { 
            
string sql = "SELECT TOP 1 B.Template FROM D_Column_Template A,M_Template B WHERE A.TemplateID=B.TemplateID AND A.IsDefault=1 AND A.TemplateTypeID=1 AND A.ColumnID="+obj.Id.ToString();
            
string template = Convert.ToString(DataAccess.GetFildValueBySql(sql));
            
if (string.IsNullOrEmpty(template)) return;
            template 
= PublicTag(template,obj);
            template 
= LoopTag(template);
            CreateFile(obj.ColumnPhyPath 
+ "index.html", template);
        }
        
/// <summary>
        
/// 生成栏目分页
        
/// </summary>
        
/// <param name="obj"></param>
        public void NewListPage(MColumn obj) {
            
string sql = "SELECT TOP 1 B.Template FROM D_Column_Template A,M_Template B WHERE A.TemplateID=B.TemplateID AND A.IsDefault=1 AND A.TemplateTypeID=2 AND A.ColumnID=" + obj.Id.ToString();
            
string template = Convert.ToString(DataAccess.GetFildValueBySql(sql));
            template 
= PublicTag(template,obj);
            template 
= LoopTag(template);
            LoopPageTag(template, obj);
        }
        
        
/// <summary>
        
/// 替换字符
        
/// </summary>
        
/// <param name="template">要替换的文本</param>
        
/// <param name="tag">标签</param>
        
/// <param name="value">内容</param>
        
/// <returns></returns>
        private string Replace(string template, string tag, string value)
        {
            
if(!string.IsNullOrEmpty(value))
                template 
= Regex.Replace(template, tag, value, RegexOptions.IgnoreCase);
            
else
                template 
= Regex.Replace(template, tag, "", RegexOptions.IgnoreCase);
            
return template;
        }

        
/// <summary>
        
/// loop标签的匹配替换
        
/// </summary>
        
/// <param name="template">模板内容</param>
        private string LoopTag(string template)
        {
            
string Attributes = "";
            
string Text = "";
            
string AllText = "";
            Regex r 
= new Regex(@"(\[DH:loop\s+(?<attributes>[^\]]*?)\](?<text>[\s\S]*?)\[/DH:loop\])", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            
foreach(Match m in r.Matches(template)){
                Attributes 
= m.Groups["attributes"].ToString(); //循环属性集
                Text = m.Groups["text"].ToString();             //循环的内容不包含DH:Loop
                AllText = m.Groups[0].Value.ToString();         //整个匹配的内容包含DH:Loop

                
#region  取得相关属性
                
string NewsCount = null;     //调用数量
                string TitleNum = null;      //新闻标题的显示字符数量
                string AddStr = null;        //标题字数被截取之后,加上"cms系统也不复杂"
                string CategoryID = null;    //调用栏目的ID
                string NewsType = null;      //调用新闻的类型
                string Order = null;         //排序,默认为降序
                string Sort = null;          //排序方式 按发布日期,点击次数任选一个 不指定默认为发布日期(DateTime)

                NewsCount 
= TagVal(Attributes, "NewsCount");
                
if (NewsCount == null) {
                    logger.Error(
"DH:Loop缺少必要的属性NewsCount");
                    
throw new ArgumentNullException("DH:Loop缺少必要的属性NewsCount");
                }
                TitleNum 
= TagVal(Attributes, "TitleNum");
                
if (TitleNum == null) {
                    logger.Error(
"DH:Loop缺少必要的属性TitleNum");
                    
throw new ArgumentNullException("DH:Loop缺少必要的属性TitleNum");
                }

                AddStr 
= TagVal(Attributes, "AddStr");
                
if (AddStr == null) AddStr = "cms系统也不复杂";

                CategoryID 
= TagVal(Attributes, "CategoryID");
                
if (CategoryID == null) CategoryID = "all";

                NewsType 
= TagVal(Attributes, "NewsType");
                
if (NewsType == null) NewsType = "all";

                Order 
= TagVal(Attributes, "Order");
                
if(Order == null) Order = "desc";

                Sort 
= TagVal(Attributes, "Sort");
                
if (Sort == null) Sort = "datetime";
                
#endregion

                
#region 构造 查询SQL语句
                
string sql = "SELECT TOP " + NewsCount + " *,(SELECT ColumnName FROM M_Column WHERE ColumnId=A.ColumnId) as ColumnName FROM M_ArticleInfo A WHERE IsDisabled=0 AND IsAuditing = 1 ";
                
if (CategoryID != "all") {
                    
string[] ids = CategoryID.Split('|');
                    sql 
+= " AND ( 1<>1 ";
                    
foreach (string id in ids) {
                        sql 
+= " OR ColumnID =" + id;
                    }
                    sql 
+= " ) ";
                }
                
if (NewsType != "all") {
                    
switch (NewsType) {
                        
case "title":
                            sql 
+= " AND IsTitle = 1";
                            
break;
                        
case "recommend":
                            sql 
+= " AND IsRecommend = 1";
                            
break;
                        
case "flashpict":
                            sql 
+= " AND IsFlashPict = 1";
                            
break;
                    }
                }
                
if (Sort == "datetime")
                    sql 
+= " ORDER BY CreatedDate ";
                
else
                    sql 
+= " ORDER BY ClickTimes ";
                sql 
+= Order.ToUpper(); 
                
#endregion

                
#region 对循环的内容进行替换
                
string content = "";
                DataTable dt 
= DataAccess.GetDataTable_Sql(sql);
                
if (dt != null && dt.Rows.Count > 0) {
                    
foreach (DataRow dr in dt.Rows) {
                        
string str = Text;
                        str 
= Replace(str, @"\[DH:Click\]", dr["ClickTimes"].ToString());
                        str 
= Replace(str, @"\[DH:Year\]", DateTime.Parse(dr["CreatedDate"].ToString()).Year.ToString());
                        str 
= Replace(str, @"\[DH:Month\]", DateTime.Parse(dr["CreatedDate"].ToString()).Month.ToString());
                        str 
= Replace(str, @"\[DH:Day\]", DateTime.Parse(dr["CreatedDate"].ToString()).Day.ToString());
                        str 
= Replace(str, @"\[DH:Hour\]", DateTime.Parse(dr["CreatedDate"].ToString()).Hour.ToString());
                        str 
= Replace(str, @"\[DH:Minute\]", DateTime.Parse(dr["CreatedDate"].ToString()).Minute.ToString());
                        str 
= Replace(str, @"\[DH:Second\]", DateTime.Parse(dr["CreatedDate"].ToString()).Second.ToString());
                        
string _title = dr["Title"].ToString();
                        
if (_title.Length > int.Parse(TitleNum))
                            _title 
= _title.Substring(0int.Parse(TitleNum) - 1+ AddStr;
                        str 
= Replace(str, @"\[DH:Title\]", _title);
                        str 
= Replace(str, @"\[DH:Source\]", dr["ArticleSource"].ToString());
                        str 
= Replace(str, @"\[DH:Author\]", dr["Author"].ToString());
                        str 
= Replace(str, @"\[DH:Editer\]", dr["Editor"].ToString());
                        str 
= Replace(str, @"\[DH:ColumnName\]", dr["ColumnName"].ToString());
                        str 
= Replace(str, @"\[DH:PicturePath\]", dr["PicturePath"].ToString());
                        str 
= Replace(str, @"\[DH:LinkURL\]", getapppath() + dr["FilePath"].ToString().Replace("\\""/"+ dr["FileName"].ToString().Replace("\\""/"));
                        str 
= Replace(str, @"\[DH:Description\]", dr["Description"].ToString());
                        str 
= Replace(str, @"\[DH:KeyWord\]", dr["KeyWord"].ToString());
                        content 
+= str;
                    }
                }
                
else {
                    logger.Info(
"SQL语句:" + sql + " 查询结果为0");
                }
                
#endregion                
                template 
= template.Replace(AllText, content);
            }
            
return template;
        }

        
/// <summary>
        
/// SQL标签的匹配替换
        
/// </summary>
        
/// <param name="template">替板内容</param>
        
/// <returns></returns>
        private string SqlTag(string template) 
        {
            
string Attributes = "";
            
string Text = "";
            
string AllText = "";
            Regex r 
= new Regex(@"(\[DH:SQL\s+(?<attributes>[^\]]*?)\](?<text>[\s\S]*?)\[/DH:SQL\])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            
foreach (Match m in r.Matches(template)) {
                Attributes 
= m.Groups["attributes"].ToString();//循环属性集
                Text = m.Groups["text"].ToString();            //循环的内容不包含DH:SQL
                AllText = m.Groups[0].Value.ToString();        //整个匹配的内容包含DH:SQL

                
string sql = null;
                sql 
= TagVal(Attributes, "SELECT");
                
if (sql == null) {
                    logger.Error(
"DH:SQL缺少必要的属性SELECT");
                    
throw new ArgumentNullException("DH:SQL缺少必要的属性SELECT");
                }

                
#region 用于多列排板
                
int Multiple = TagVal(Attributes, "Multiple"!= null ? int.Parse(TagVal(Attributes, "Multiple")) : 1;
                
string Str = TagVal(Attributes, "Str");
                
int cols = 1;
                
#endregion

                
string content = "";
                DataTable dt 
= DataAccess.GetDataTable_Sql(sql);
                
if (dt != null && dt.Rows.Count > 0) {
                    
foreach (DataRow dr in dt.Rows) {
                        
string str = Text;
                        Regex _r 
= new Regex(@"(\[DH:Field\s+(?<attributes>[^\]]*?)\])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                        
foreach (Match _m in _r.Matches(str)) {
                            
string _Attributes = _m.Groups["attributes"].ToString();
                            
string fieldName = TagVal(_Attributes, "Name");
                            
try {
                                
string value = dr[fieldName].ToString();
                                
string WordNum = TagVal(_Attributes, "WordNum"); //显示的字符数
                                string HTML = TagVal(_Attributes, "HTML");       //是否取消HTML标签
                                if (HTML != null) {
                                    
if (HTML == "true") value = DropHTML(value).Trim();
                                }
                                
if (WordNum != null) {
                                    
try {
                                        
if (value.Length > int.Parse(WordNum))
                                            value 
= value.Substring(0int.Parse(WordNum)-1);
                                    }
                                    
catch {
                                        
throw new ArgumentException("WordNum 属性只能为数字");
                                    }
                                }
                                str 
= str.Replace(_m.Groups[0].Value.ToString(), value.Replace("\\""/"));
                            }
                            
catch {
                                logger.Info(
"SQL语句:" + sql + " 中没有找到指定字段" + fieldName);
                            }
                        }
                        content 
+= str;
                        
if (Multiple > 1) {
                            
if (cols % Multiple == 0) {
                                content 
+= Str;
                            }
                            cols
++;
                        }
                    }
                    
//处理列数不够的情况
                    if ((cols - 1% Multiple != 0 && Multiple > 1) {
                        
int max = Multiple - (cols - 1% Multiple;
                        
for (int i = 1; i <= max; i++) {
                            
string str = Text;
                            Regex _r 
= new Regex(@"(\[DH:Field\s+(?<attributes>[^\]]*?)\])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                            
foreach (Match _m in _r.Matches(str)) {
                                str 
= str.Replace(_m.Groups[0].Value.ToString(), "");
                            }
                            content 
+= str;
                        }
                    }
                }
                
else {
                    logger.Info(
"SQL语句:" + sql + " 查询结果为0");
                }

                template 
= template.Replace(AllText, content);
            }
            
return template;
        }

        
        
/// <summary>
        
/// loopPage标签匹配替换 
        
/// </summary>
        
/// <param name="template">替板内容</param>
        
/// <param name="columnId">栏目ID</param>
        
/// <returns></returns>
        private void LoopPageTag(string template, MColumn obj)
        {
            LoopPageTag(template, obj.Id.ToString(), 
1,obj.ColumnPhyPath);
        }
        
        
/// <summary>
        
/// loopPage标签匹配替换 
        
/// </summary>
        
/// <param name="template">替板内容</param>
        
/// <param name="columnId">栏目ID</param>
        
/// <param name="pageIndex">当前页索引</param>
        
/// <param name="columnPath">栏目路径</param>
        
/// <returns></returns>
        private void LoopPageTag(string template,string columnId,int pageIndex,string columnPath)
        {
            
string OldTemplate = template;  //将模板保存起来,为了分页时重新生成

            
string Attributes = "";
            
string Text = "";
            
string AllText = "";
            Regex r 
= new Regex(@"(\[DH:loopPage\s+(?<attributes>[^\]]*?)\](?<text>[\s\S]*?)\[/DH:loopPage\])", RegexOptions.Compiled | RegexOptions.IgnoreCase);

            
foreach (Match m in r.Matches(template)) {
                Attributes 
= m.Groups["attributes"].ToString(); //循环属性集
                Text = m.Groups["text"].ToString();             //循环的内容不包含DH:Loop
                AllText = m.Groups[0].Value.ToString();         //整个匹配的内容包含DH:Loop

                
#region  取得相关属性
                
string NewsCount = null;     //调用数量
                string TitleNum = null;      //新闻标题的显示字符数量
                string AddStr = null;        //标题字数被截取之后,加上"cms系统也不复杂"
                string CategoryID = columnId;    //调用栏目的ID
                string NewsType = null;      //调用新闻的类型
                string Order = null;         //排序,默认为降序
                string Sort = null;          //排序方式 按发布日期,点击次数任选一个 不指定默认为发布日期(DateTime)

                NewsCount 
= TagVal(Attributes, "NewsCount");
                
if (NewsCount == null && int.Parse(NewsCount)<1) {
                    logger.Error(
"DH:Loop缺少必要的属性NewsCount");
                    
throw new ArgumentNullException("DH:Loop缺少必要的属性NewsCount");
                }
                TitleNum 
= TagVal(Attributes, "TitleNum");
                
if (TitleNum == null) {
                    logger.Error(
"DH:Loop缺少必要的属性TitleNum");
                    
throw new ArgumentNullException("DH:Loop缺少必要的属性TitleNum");
                }

                AddStr 
= TagVal(Attributes, "AddStr");
                
if (AddStr == null) AddStr = "cms系统也不复杂";

                NewsType 
= TagVal(Attributes, "NewsType");
                
if (NewsType == null) NewsType = "all";

                Order 
= TagVal(Attributes, "Order");
                
if (Order == null) Order = "desc";

                Sort 
= TagVal(Attributes, "Sort");
                
if (Sort == null) Sort = "datetime";
                
#endregion

                
#region 构造 查询SQL语句
                
string sql = "SELECT *,(SELECT ColumnName FROM M_Column WHERE ColumnId=A.ColumnId) as ColumnName FROM M_ArticleInfo A WHERE IsDisabled=0 AND IsAuditing = 1 ";
                
                sql 
+= " AND ColumnID = "+columnId;
                
//if (CategoryID != "all") {
                
//    string[] ids = CategoryID.Split('|');
                
//    sql += " AND ( 1<>1 ";
                
//    foreach (string id in ids) {
                
//        if (string.IsNullOrEmpty(id)) sql += " OR ColumnID =" + id;
                
//    }
                
//    sql += " ) ";
                
//}

                
if (NewsType != "all") {
                    
switch (NewsType) {
                        
case "title":
                            sql 
+= " AND IsTitle = 1";
                            
break;
                        
case "recommend":
                            sql 
+= " AND IsRecommend = 1";
                            
break;
                        
case "flashpict":
                            sql 
+= " AND IsFlashPict = 1";
                            
break;
                    }
                }
                
//if (Sort == "datetime")
                
//    sql += " ORDER BY CreatedDate ";
                
//else
                
//    sql += " ORDER BY ClickTimes ";
                
//sql += Order.ToUpper();
                #endregion

                
#region 对循环的内容进行替换
                
string content = "";
                
int totalCount = 0//总记录数
                int pageSize = int.Parse(NewsCount);  //页大小
                string keyFildName = Sort == "datetime" ? "CreatedDate" : "ClickTimes";  //关键字段
                bool orderType = Order == "desc" ? true : false;      //升序降序
                                
                DataTable dt 
= new BaseDAL<MArticleInfo>().GetCurrentPageDataForSql(sql, keyFildName, pageIndex, pageSize, orderType, out totalCount);
                
                
                
if (dt != null && dt.Rows.Count > 0) {
                    
foreach (DataRow dr in dt.Rows) {
                        
string str = Text;
                        str 
= Replace(str, @"\[DH:UrlPath\]""/");
                        str 
= Replace(str, @"\[DH:Year\]", DateTime.Parse(dr["CreatedDate"].ToString()).Year.ToString());
                        str 
= Replace(str, @"\[DH:Month\]", DateTime.Parse(dr["CreatedDate"].ToString()).Month.ToString());
                        str 
= Replace(str, @"\[DH:Day\]", DateTime.Parse(dr["CreatedDate"].ToString()).Day.ToString());
                        str 
= Replace(str, @"\[DH:Hour\]", DateTime.Parse(dr["CreatedDate"].ToString()).Hour.ToString());
                        str 
= Replace(str, @"\[DH:Minute\]", DateTime.Parse(dr["CreatedDate"].ToString()).Minute.ToString());
                        str 
= Replace(str, @"\[DH:Second\]", DateTime.Parse(dr["CreatedDate"].ToString()).Second.ToString());
                        
string _title = dr["Title"].ToString();
                        
if (_title.Length > int.Parse(TitleNum))
                            _title 
= _title.Substring(0int.Parse(TitleNum) - 1+ AddStr;
                        str 
= Replace(str, @"\[DH:Title\]", _title);
                        str 
= Replace(str, @"\[DH:Source\]", dr["ArticleSource"].ToString());
                        str 
= Replace(str, @"\[DH:Author\]", dr["Author"].ToString());
                        str 
= Replace(str, @"\[DH:Editer\]", dr["Editor"].ToString());
                        str 
= Replace(str, @"\[DH:ColumnName\]", dr["ColumnName"].ToString());
                        str 
= Replace(str, @"\[DH:PicturePath\]", dr["PicturePath"].ToString());
                        str 
= Replace(str, @"\[DH:LinkURL\]", getapppath() + dr["FilePath"].ToString() + dr["FileName"].ToString());
                        str 
= Replace(str, @"\[DH:Description\]", dr["Description"].ToString());
                        str 
= Replace(str, @"\[DH:KeyWord\]", dr["KeyWord"].ToString());
                        content 
+= str;
                    }
                }
                
else {
                    logger.Info(
"SQL语句:" + sql + " 查询结果为0");
                }
                
#endregion
                template 
= template.Replace(AllText, content);

                
int pageCount = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;  //总页数
                if (pageCount == 0) pageCount = 1;
                
#region 替换分页标签
                template 
= Replace(template, @"\[DH:PageSize\]", pageSize.ToString());
                template 
= Replace(template, @"\[DH:PageCount\]", pageCount.ToString());
                template 
= Replace(template, @"\[DH:RecordCount\]", totalCount.ToString());
                template 
= Replace(template, @"\[DH:CurrentPage\]", pageIndex.ToString());
                template 
= Replace(template, @"\[DH:FirstPage\]", (pageCount == 1? "#" : "index_1.html");
                template 
= Replace(template, @"\[DH:LastPage\]", (pageCount == pageIndex) ? "#" : "index_" + pageCount.ToString() + ".html");

                template 
= Replace(template, @"\[DH:PrevPage\]", pageIndex == 1 ? "#" : "index_" + Convert.ToString(pageIndex - 1+ ".html");
                template 
= Replace(template, @"\[DH:NextPage\]", pageIndex == pageCount ? "#" : "index_" + Convert.ToString(pageIndex + 1+ ".html");

                
string ddl = "<select onchange=\"if(this.options[this.selectedIndex].value!=''){location=this.options[this.selectedIndex].value;}\">";
                
for (int i = 1; i <= pageCount; i++) {
                    ddl 
+= "<option value=\"index_" + i.ToString() + ".html\" " + ((i == pageIndex) ? "selected" : ""+ ">第" + i.ToString() + "页</option>";
                }
                ddl 
+= "</select>";
                template 
= Replace(template, @"\[DH:DropDownList\]", ddl);
                
#endregion

                CreateFile(columnPath 
+ "index_" + pageIndex.ToString() + ".html", template);
                
if (pageIndex != pageCount && pageCount != 0)
                    LoopPageTag(OldTemplate, columnId, pageIndex 
+ 1, columnPath);


            }
            
//return template;
        }

        
/// <summary>
        
/// 公共标签替换
        
/// </summary>
        
/// <param name="template">模板内容</param>
        
/// <param name="MColumn">栏目</param>
        
/// <returns></returns>
        private string PublicTag(string template,MColumn obj)
        {
            template 
= Replace(template, @"\[DH:\s?Navigation\]", getNavigation(obj));

            template 
= Replace(template, @"\[DH:UrlPath\]""/");
            Regex r 
= new Regex(@"(\[DH:More\s+ColumnID=" + "\"" + @"(?<ColumnID>[^" + "\"" + "]*)" + "\"" + @"\])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            foreach (Match m in r.Matches(template)) {
                
string ColumnID = m.Groups["ColumnID"].ToString();
                
string sql = "SELECT ColumnVirPath FROM M_Column WHERE ColumnID =" + ColumnID;                
                template 
= template.Replace(m.Groups[0].Value.ToString(), getapppath() + Convert.ToString(DataAccess.GetFildValueBySql(sql)).Replace("\\""/"));
            }
            r 
= new Regex(@"(\[DH:Img(?<Name>(Name|Path|URL))\s+Type=" + "\"" + @"(?<ID>[^" + "\"" + "]*)" + "\"" + @"\])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            foreach (Match m in r.Matches(template)) {
                
string Name = m.Groups["Name"].ToString();
                
string ID = m.Groups["ID"].ToString();
                
string sql = "SELECT TOP 1 FileName AS Name,FilePath AS Path,LinkURL AS URL FROM M_FileInfo A,S_FileType B WHERE A.FileTypeID=B.FileTypeID AND A.IsDisabled=0 AND A.IsDefault=1 AND B.FileTypeID =" + ID;
                DataTable dt 
= DataAccess.GetDataTable_Sql(sql);
                
if (dt.Rows.Count == 0) {
                    logger.Info(
"SQL语句:"+sql+"查询结果为0");
                    template 
= template.Replace(m.Groups[0].Value.ToString(), "");
                }
                
else
                    template 
= template.Replace(m.Groups[0].Value.ToString(), dt.Rows[0][Name].ToString());
            }
            
return SqlTag(template);
        }

        
/// <summary>
        
/// 得到栏目导航
        
/// </summary>
        
/// <param name="obj">栏目对象</param>
        
/// <returns></returns>
        private string getNavigation(MColumn obj)
        {
            
if (obj.Parent == null
                
return string.Format("<a href='{0}'>{1}</a>""/" + obj.ColumnCode, obj.ColumnName);
            
else 
                
return getNavigation(obj.Parent) + " >> " + string.Format("<a href='{0}'>{1}</a>""/" + obj.Parent.ColumnVirPath.Replace("\\","/"+ obj.ColumnCode, obj.ColumnName);            
        }


        
/// <summary>
        
/// 返回应用程序根目录的URL
        
/// </summary>
        
/// <returns></returns>
        public string getapppath()
        {
            
string AppPath = System.Web.HttpContext.Current.Request.ApplicationPath.Trim();
            
if (AppPath.Length > 1) {
                AppPath 
= AppPath + "/";
            }
            
return ("http://" + System.Web.HttpContext.Current.Request.Url.Authority + AppPath);  
        }

        
/// <summary>
        
/// 获得当前WEB应用程序的物理路径
        
/// </summary>
        
/// <returns></returns>
        private string GetApplicationPath()
        {
            
return Business.Folder.Files.GetApplicationPath();
        }

        
/// <summary>
        
/// 返回一组标签中指定属性的值小写格式
        
/// 属性值必须被双引号括起来。
        
/// </summary>
        
/// <param name="Tag">一组标签</param>
        
/// <param name="TagName">属性名称</param>
        
/// <returns>属性的小写值</returns>
        private string TagVal(string tag, string tagName)
        {
            Regex rt 
= new Regex(@"(?<Keyword>\w+)\s*=\s*(?<Value>" + "\"" + "[^\"]*\")", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            foreach (Match mt in rt.Matches(tag)) {
                
if (mt.Groups["Keyword"].ToString().Trim().ToLower() == tagName.ToLower()) {
                    
return mt.Groups["Value"].ToString().ToLower().Replace("\"""");
                }
            }
            
return null;
        }
        
        
/// <summary>
        
/// 去掉所有HTML标签
        
/// </summary>
        
/// <param name="strHtml"></param>
        
/// <returns></returns>
        private string DropHTML(string strHtml)
        {
            
return Regex.Replace(strHtml,"<[^>]*>","");
        } 
    }
}

 

 

相关文章:

  • 2022-12-23
  • 2022-01-01
  • 2021-06-24
  • 2021-10-25
  • 2022-12-23
  • 2022-02-19
  • 2022-12-23
  • 2021-06-19
猜你喜欢
  • 2021-05-16
  • 2021-11-14
  • 2022-12-23
  • 2021-10-17
  • 2021-04-25
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案