c# generate static html files and encapsulate classes

Because this period of time is relatively easy, I think of many enterprise websites. News websites need to static pages, so I wrote a package class to generate static files. The idea is relatively simple, but not perfect. Netizens can expand this kind of files according to their own ideas, The simple factory pattern is used (it was a good book to read the design pattern at the beginning). Well, without much nonsense, let's take a look at the parent class of the static class: StaticBase (abstract class)

 1 public abstract class StaticBase : IDisposable
 2     {
 3         /// <summary>
 4         ///Default encoding method
 5         /// </summary>
 6         protected Encoding code = Encoding.GetEncoding("utf-8");
 7         /// <summary>
 8         ///Write page data stream
 9         /// </summary>
10         protected StreamWriter sw = null;
11         /// <summary>
12         ///Read page data stream
13         /// </summary>
14         protected StreamReader sr = null;
15         /// <summary>
16         ///Generated static page save folder path
17         /// </summary>
18         protected string SavePath = "/Default/";
19         /// <summary>
20         ///Folder path to the template page
21         /// </summary>
22         protected string PagePath = "/Master/";
23         public abstract bool Osucess { set; get; }
24         public abstract string Errorstring { set; get; }
25         /// <summary>
26         ///Generate static methods specifically
27         /// </summary>
28         protected abstract bool WriteFile();
29         /// <summary>
30         ///File names of different modules
31         /// </summary>
32         protected Dictionary<FlagsFileName, string> FileName
33         {
34             get
35             {
36                 return new Dictionary<FlagsFileName, string>
37                 {
38                     {FlagsFileName.News,"article"},
39                     {FlagsFileName.head,"head"},
40                     {FlagsFileName.foot,"foot"},
41                 };
42             }
43         }
44        // http://www.cnblogs.com/roucheng/
45         #region IDisposable member
46 
47         public void Dispose()
48         {
49             sw.Dispose();
50             sr.Dispose();
51         }
52 
53         #endregion
54     }
55     #Page name corresponding to region
56     /// <summary>
57     ///Corresponding page name
58     /// </summary>
59     public enum FlagsFileName : byte
60     {
61         /// <summary>
62         ///News
63         /// </summary>
64         [Description("Journalism")]
65         News = 0,
66         /// <summary>
67         ///Head
68         /// </summary>
69         [Description("head")]
70         head=1,
71         /// <summary>
72         ///Feet
73         /// </summary>
74         [Description("Feet")]
75         foot=2,
76     }

The last enumeration is used to define the subclasses corresponding to static pages in different locations or categories

Next, let's look at the implementation of one subclass (this subclass is used for all single pages. For example, if there are 100 news records in the database, 100 news html pages are generated accordingly, and the format is determined by the format defined by the template)

First, the template file is a static html page, in which all fields that need to be replaced from the database are contained in a pair. If the news title field in the database is title, the corresponding title position in the template page is title

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>$Titles$</title>
 6 </script>
 7 </head>
 8 <body>
 9 <div id="wrap">
10   $head$
11   <!--hd end-->
12   <div class="clear"></div>
13   <div id="wp">
14   <table border="0" cellpadding="0" cellspacing="0" width="980">
15     <tr>
16       <td rowspan="3" valign="top" id="main_box" class="index_box2">
17       <div class="subtitle subtitle4"></div>
18       <div class="article">
19       <div class="title">$Titles$</div>
20          $Contents_tw$
21       </div> 
22         
23        
24       </td>
25       <td width="48" height="44" class="ri_top">&nbsp;</td>
26   </tr>
27     <tr>
28       <td class="ri_mid" id="mid_box">&nbsp;</td>
29     </tr>
30     <tr>
31       <td height="44" class="ri_bottom">&nbsp;</td>
32     </tr>
33 </table>
34   </div>
35   <!--wp end-->
36 </div>
37 <!--wrap end-->
38 
39 $foot$
40 <!--ft end-->
41 </body>
42 </html>

http://www.cnblogs.com/roucheng/

Here's a general idea. The next step is the subclass implementation of the page type. I define its name as ViewPage, because all pages that can be displayed separately can use this subclass. The code is as follows

  1 public class ViewPage : StaticBase
  2     {
  3         /// <summary>
  4         ///Is the operation successful
  5         /// </summary>
  6         private bool o_sucess = true;
  7         /// <summary>
  8         ///Error message
  9         /// </summary>
 10         private string errorstring = string.Empty;
 11         /// <summary>
 12         ///Template file name
 13         /// </summary>
 14         private string masterhtml;
 15         /// <summary>
 16         ///Data source 
 17         /// </summary>
 18         private IEnumerable<DataRow> rowlist;
 19         /// <summary>
 20         ///Module category
 21         /// </summary>
 22         private FlagsFileName fname;
 23         /// <summary>
 24         ///Specifies the flag column for the named file (from a field in the database)
 25         /// </summary>
 26         private string thekey;
 27         public override bool Osucess
 28         {
 29             get { return o_sucess; }
 30             set { o_sucess = value; }
 31         }
 32         public override string Errorstring
 33         {
 34             get { return errorstring; }
 35             set { errorstring = value; }
 36         }
 37         /// <summary>
 38         ///Constructor statically generates objects
 39         /// </summary>
 40         ///< param name = "rlist" > data source that needs to generate static files < / param >
 41         ///< param name = "FN" > file category enumeration < / param >
 42         ///< param name = "myid" > this field is a field in the database table, which specifies the generated file name flag < / param >
 43         public ViewPage(DataRow[] rlist,FlagsFileName fn,string myid)
 44         {
 45             this.thekey = myid;
 46             this.fname = fn;
 47             this.rowlist = rlist;
 48             this.masterhtml = FileName[fn] + ".html";
 49             WriteFile();
 50         }
 51 
 52         protected override bool WriteFile()
 53         {
 54             string str = "";
 55             try//Reads html code from the specified template file
 56             {
 57                 sr = new StreamReader(HttpContext.Current.Server.MapPath(PagePath + this.masterhtml), code);
 58                 str = sr.ReadToEnd();
 59             }
 60             catch (Exception ex)//Exception specifies the error information returned 
 61             {
 62                 sr.Close();
 63                 sr.Dispose();
 64                 this.o_sucess = false;
 65                 this.errorstring = ex.Message;
 66                 return this.o_sucess;
 67             }
 68             sr.Close();
 69             sr.Dispose();
 70             List<FlagsFileName> fn = new List<FlagsFileName>();
 71             fn.Add(FlagsFileName.head);
 72             fn.Add(FlagsFileName.foot);
 73             PointPage pg = new PointPage(fn, str);
 74             //Name of the file to save
 75             string htmlfilename = string.Empty;
 76             string changestring = "";//String to change
 77             foreach (DataRow row in this.rowlist)//Traverse each data table in the data source array
 78             {
 79                 string newString = str;
 80                 try
 81                 {
 82                     htmlfilename = FileName[fname] + "_" + row[thekey].ToString() + ".html";//Name the file
 83                     foreach (DataColumn c in row.Table.Columns)//Traverses the column names of a single data table
 84                     {
 85                         changestring = "$" + c.ColumnName + "$";
 86                         newString = newString.Replace(changestring, row[c].ToString());
 87                     }
 88                     sw = new StreamWriter(HttpContext.Current.Server.MapPath(SavePath + htmlfilename), false, code);
 89                     sw.Write(newString);
 90                     sw.Flush();
 91                 }
 92                 catch (Exception ex)
 93                 {
 94                     this.o_sucess = false;
 95                     this.errorstring = ex.Message;
 96                     return this.o_sucess;
 97                 }
 98 
 99             }
100             sw.Dispose();
101             sw.Close();
102             return true;
103         }
104     }

OK, now that we have realized the underlying idea design, the call is very simple. An aspx page, a button, a click event Button_Click, all that needs to be done in the click event is to declare a base class StaticBase and instantiate it into a subclass ViewPage. The passed parameters are a data item collection, DataRow [] is a collection read from the data table, including the fields to be replaced, such as select titles, contents, id from news (get the id, title and content from the news table), and the type FlagsFileName.News is the enumeration type mentioned in the previous space-based class. It is the generation method of a separate page and the renamed identification column. If this is id, the generated page format is

news_1.html,news_2.html and so on, the code is as follows

 1 protected void Create_Click(object sender, EventArgs e)
 2         {
 3             IEnumerable<DataRow> rowlist = TNotice_Command.SelectTNotice(-1);
 4             using (StaticBase sb = new ViewPage((DataRow[])rowlist, FlagsFileName.News, "NID"))
 5             {
 6                 if (!sb.Osucess)
 7                 {
 8                     Response.Write("<script language=javascript>alert('" + sb.Errorstring + "')</script>");
 9                 }
10             }
11         }

See here, if you look at it again from the beginning, I believe you can know the principle of static file generation. Next, if you generate static files for paging pages, the content of the article is simple, but I hope you can give us some ideas.

Publisher: full stack programmer, stack length, please indicate the source for Reprint: https://javaforall.cn/120729.html Original link: https://javaforall.cn

Added by smsharif on Thu, 23 Dec 2021 09:39:41 +0200