当前位置: 移动技术网 > IT编程>开发语言>c# > c#使用简单工厂模式实现生成html文件的封装类分享

c#使用简单工厂模式实现生成html文件的封装类分享

2019年07月18日  | 移动技术网IT编程  | 我要评论

由于这段时间比较轻松,于是想到很多的企业网站,新闻网站需要将页面静态化,于是写了个封装类来实现静态文件的生成,思路比较简单,但未完善,网友可根据自己的思路将此类扩展,运用了简单工厂模式,先来看看静态类的父类:staticbase(抽象类)

复制代码 代码如下:

public abstract class staticbase : idisposable
    {
        /// <summary>
        /// 默认编码方式
        /// </summary>
        protected encoding code = encoding.getencoding("utf-8");
        /// <summary>
        /// 写入页面数据流
        /// </summary>
        protected streamwriter sw = null;
        /// <summary>
        /// 读取页面数据流
        /// </summary>
        protected streamreader sr = null;
        /// <summary>
        /// 生成的静态页面保存文件夹路径
        /// </summary>
        protected string savepath = "/default/";
        /// <summary>
        /// 模板页面的文件夹路径
        /// </summary>
        protected string pagepath = "/master/";
        public abstract bool osucess { set; get; }
        public abstract string errorstring { set; get; }
        /// <summary>
        /// 具体生成静态方法
        /// </summary>
        protected abstract bool writefile();
        /// <summary>
        /// 不同模块的文件名称
        /// </summary>
        protected dictionary<flagsfilename, string> filename
        {
            get
            {
                return new dictionary<flagsfilename, string>
                {
                    {flagsfilename.news,"article"},
                    {flagsfilename.head,"head"},
                    {flagsfilename.foot,"foot"},
                };
            }
        }
       // http://www.cnblogs.com/roucheng/
        #region idisposable 成员

        public void dispose()
        {
            sw.dispose();
            sr.dispose();
        }

        #endregion
    }
    #region 对应的页面名称
    /// <summary>
    /// 对应的页面名称
    /// </summary>
    public enum flagsfilename : byte
    {
        /// <summary>
        /// 新闻
        /// </summary>
        [description("新闻")]
        news = 0,
        /// <summary>
        /// 头部
        /// </summary>
        [description("头部")]
        head=1,
        /// <summary>
        /// 脚部
        /// </summary>
        [description("脚部")]
        foot=2,
    }

最后的一个枚举用于定义不同位置或不同类别的静态页所对应的子类,接下来看看其中一个子类的实现(该子类是用于所有单页,如数据库中有100条新闻记录,那相应的生成100个新闻html页面,格式用模板定义的格式确定)
首先模板文件时静态的html页面,其中所有的需要从数据库中替换的字段用一对$包含,如数据库中的新闻标题字段为titles,则模板页中相应的标题位置用$titles$表示,页面如下

复制代码 代码如下:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>$titles$</title>
</script>
</head>
<body>
<div id="wrap">
  $head$
  <!--hd end-->
  <div class="clear"></div>
  <div id="wp">
  <table border="0" cellpadding="0" cellspacing="0" width="980">
    <tr>
      <td rowspan="3" valign="top" id="main_box" class="index_box2">
      <div class="subtitle subtitle4"></div>
      <div class="article">
      <div class="title">$titles$</div>
         $contents_tw$
      </div>

      
      </td>
      <td width="48" height="44" class="ri_top"> </td>
  </tr>
    <tr>
      <td class="ri_mid" id="mid_box"> </td>
    </tr>
    <tr>
      <td height="44" class="ri_bottom"> </td>
    </tr>
</table>
  </div>
  <!--wp end-->
</div>
<!--wrap end-->

$foot$
<!--ft end-->
</body>
</html>

到这里知道个大概了吧,接下来就是这中页面类型的子类实现,我将它的名称定义为viewpage,因为所有可以单独显示的页面都可以用这个子类,代码如下

复制代码 代码如下:

public class viewpage : staticbase
    {
        /// <summary>
        /// 是否操作成功
        /// </summary>
        private bool o_sucess = true;
        /// <summary>
        /// 错误信息
        /// </summary>
        private string errorstring = string.empty;
        /// <summary>
        /// 模板文件名称
        /// </summary>
        private string masterhtml;
        /// <summary>
        /// 数据源
        /// </summary>
        private ienumerable<datarow> rowlist;
        /// <summary>
        /// 模块类别
        /// </summary>
        private flagsfilename fname;
        /// <summary>
        /// 指定命名文件的标志列(从数据库中的字段)
        /// </summary>
        private string thekey;
        public override bool osucess
        {
            get { return o_sucess; }
            set { o_sucess = value; }
        }
        public override string errorstring
        {
            get { return errorstring; }
            set { errorstring = value; }
        }
        /// <summary>
        /// 构造器静态生成对象
        /// </summary>
        /// <param name="rlist">需要生成静态文件的数据源</param>
        /// <param name="fn">文件类别枚举</param>
        /// <param name="myid">此字段为数据库表中字段,由该字段指定生成的文件名字标志 </param>
        public viewpage(datarow[] rlist,flagsfilename fn,string myid)
        {
            this.thekey = myid;
            this.fname = fn;
            this.rowlist = rlist;
            this.masterhtml = filename[fn] + ".html";
            writefile();
        }

        protected override bool writefile()
        {
            string str = "";
            try//从指定模板文件中读取html代码
            {
                sr = new streamreader(httpcontext.current.server.mappath(pagepath + this.masterhtml), code);
                str = sr.readtoend();
            }
            catch (exception ex)//异常则指定返回的错误信息
            {
                sr.close();
                sr.dispose();
                this.o_sucess = false;
                this.errorstring = ex.message;
                return this.o_sucess;
            }
            sr.close();
            sr.dispose();
            list<flagsfilename> fn = new list<flagsfilename>();
            fn.add(flagsfilename.head);
            fn.add(flagsfilename.foot);
            pointpage pg = new pointpage(fn, str);
            //要保存的文件名称
            string htmlfilename = string.empty;
            string changestring = "";//要更改的字符串
            foreach (datarow row in this.rowlist)//遍历数据源数组中的每个数据表
            {
                string newstring = str;
                try
                {
                    htmlfilename = filename[fname] + "_" + row[thekey].tostring() + ".html";//给文件命名
                    foreach (datacolumn c in row.table.columns)//遍历单个数据表的列名
                    {
                        changestring = "$" + c.columnname + "$";
                        newstring = newstring.replace(changestring, row[c].tostring());
                    }
                    sw = new streamwriter(httpcontext.current.server.mappath(savepath + htmlfilename), false, code);
                    sw.write(newstring);
                    sw.flush();
                }
                catch (exception ex)
                {
                    this.o_sucess = false;
                    this.errorstring = ex.message;
                    return this.o_sucess;
                }

            }
            sw.dispose();
            sw.close();
            return true;
        }
    }

好,到这里实现了底层的思路设计,那调用就很简单了,某个aspx页面,一个按钮button,一个点击事件button_click,点击事件内需要做的就是声明一个基类staticbase,将它实例化成一个子类viewpage,传递的参数为一个数据项集合,datarow[]为从数据表中读取的集合,包含需要替换的字段,如select titles,contens,id from news(从新闻表中获得标识id,标题,内容),以及类型flagsfilename.news为前天基类提到过的枚举类型,为单独页面的生成方式,已经重命名的标识列,如此处为id,则生成的页面格式为
news_1.html,news_2.html以此类推,代码如下

复制代码 代码如下:

protected void create_click(object sender, eventargs e)
        {
            ienumerable<datarow> rowlist = tnotice_command.selecttnotice(-1);
            using (staticbase sb = new viewpage((datarow[])rowlist, flagsfilename.news, "nid"))
            {
                if (!sb.osucess)
                {
                    response.write("<script language=javascript>alert('" + sb.errorstring + "')</script>");
                }
            }
        }

看到这里大家如果再从头看一遍,相信就能知道静态文件的生成的原理了。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网