c USES the simple factory pattern to implement encapsulated class sharing for generating html files

  • 2020-06-12 10:29:48
  • OfStack

Because this paragraph of time is easily, so think of a lot of enterprise website, news websites need to be static page, and then write a wrapper class to implement the generation of static files, way of thinking is simple, but not perfect, the users according to their own ideas to expand such, use of simple factory pattern, let's look at a static class parent class: StaticBase (abstract)


public abstract class StaticBase : IDisposable
    {
        /// <summary>
        ///  Default encoding mode 
        /// </summary>
        protected Encoding code = Encoding.GetEncoding("utf-8");
        /// <summary>
        ///  Writes to the page data stream 
        /// </summary>
        protected StreamWriter sw = null;
        /// <summary>
        ///  Read the page data stream 
        /// </summary>
        protected StreamReader sr = null;
        /// <summary>
        ///  The generated static pages save the folder path 
        /// </summary>
        protected string SavePath = "/Default/";
        /// <summary>
        ///  The folder path for the template page 
        /// </summary>
        protected string PagePath = "/Master/";
        public abstract bool Osucess { set; get; }
        public abstract string Errorstring { set; get; }
        /// <summary>
        ///  Concrete generation of static methods 
        /// </summary>
        protected abstract bool WriteFile();
        /// <summary>
        ///  File names for different modules 
        /// </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  Members of the 
        public void Dispose()
        {
            sw.Dispose();
            sr.Dispose();
        }
        #endregion
    }
    #region  The corresponding page name 
    /// <summary>
    ///  The corresponding page name 
    /// </summary>
    public enum FlagsFileName : byte
    {
        /// <summary>
        ///  news 
        /// </summary>
        [Description(" news ")]
        News = 0,
        /// <summary>
        ///  The head 
        /// </summary>
        [Description(" The head ")]
        head=1,
        /// <summary>
        ///  The foot 
        /// </summary>
        [Description(" The foot ")]
        foot=2,
    }

The last enumeration is used to define the subclasses of static pages in different locations or categories. Next, take a look at the implementation of one of the subclasses (this subclass is used for all single pages, such as 100 news records in the database, then 100 news html pages are generated accordingly, in the format defined by the template).
First of all, the template file is static html page, where all fields that need to be replaced from the database are contained by 1 pair of $. If the news title field in the database is titles, then the corresponding title position in the template page is represented by $titles$, and the page is as follows


<!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">&nbsp;</td>
  </tr>
    <tr>
      <td class="ri_mid" id="mid_box">&nbsp;</td>
    </tr>
    <tr>
      <td height="44" class="ri_bottom">&nbsp;</td>
    </tr>
</table>
  </div>
  <!--wp end-->
</div>
<!--wrap end-->
$foot$
<!--ft end-->
</body>
</html>

So to get a sense of what's going on, here is the implementation of this subclass of page type, which I've defined as ViewPage, because all pages that can be displayed individually can be subclassed as follows


public class ViewPage : StaticBase
    {
        /// <summary>
        ///  Operation success or not 
        /// </summary>
        private bool o_sucess = true;
        /// <summary>
        ///  The error message 
        /// </summary>
        private string errorstring = string.Empty;
        /// <summary>
        ///  Template file name 
        /// </summary>
        private string masterhtml;
        /// <summary>
        ///  The data source  
        /// </summary>
        private IEnumerable<DataRow> rowlist;
        /// <summary>
        ///  The module class 
        /// </summary>
        private FlagsFileName fname;
        /// <summary>
        ///  Specifies a flag column for a named file (from a field in the database) 
        /// </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>
        ///  The constructor generates the object statically 
        /// </summary>
        /// <param name="rlist"> Data sources that need to generate static files </param>
        /// <param name="fn"> File category enumeration </param>
        /// <param name="myid"> This field is the field in the database table that specifies the generated file name flag  </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// Reads from the specified template file html code 
            {
                sr = new StreamReader(HttpContext.Current.Server.MapPath(PagePath + this.masterhtml), code);
                str = sr.ReadToEnd();
            }
            catch (Exception ex)// The exception specifies the error message to return  
            {
                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);
            // The name of the file to save 
            string htmlfilename = string.Empty;
            string changestring = "";// String to change 
            foreach (DataRow row in this.rowlist)// Traverse each table in the data source array 
            {
                string newString = str;
                try
                {
                    htmlfilename = FileName[fname] + "_" + row[thekey].ToString() + ".html";// Name the file 
                    foreach (DataColumn c in row.Table.Columns)// Iterate over the column names of a single data table 
                    {
                        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;
        }
    }

Good, here to implement the idea of what the underlying design, the call is very simple, a aspx page, a button button, a click event Button_Click, click event need to do is declared within a base class StaticBase, instance it into a subclass ViewPage, parameters passed for a collection of data items, DataRow [] to read from the data in the table set, contains the fields need to be replaced, For example, select titles,contens,id from news (identify id, title, content from the news table), and type ES37en.News is the enumeration type mentioned in the pre-space base class, for the way individual pages are generated, the identity column has been renamed, in this case, id, the generated page format is
news_1.html, news_2.html and so on, the code is as follows


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>");
                }
            }
        }

See here if you look at the first time, I believe you can understand the static file generation principle.


Related articles: