first_page the funky knowledge base
personal notes from way, _way_ back and maybe today

C# and ASP.NET: Writing HTML Targeted from Code-Behind Designs; Using Regular Expressions to Write HTML

Although the title of this article makes no mention of it, my remarks here will be flippant:

You can target areas of an HTML page for writing by using a combination of the PlaceHolder Control (System.Web.UI.WebControls.PlaceHolder), the Literal Control (System.Web.UI.WebControls.Literal) and by running tags at the server (with the runat="server" attribute). For efficiency, most controls can be accessed via the HtmlGenericControl class. The C# code below finds an HTML HEAD element with attributes id="Head" and runat="server" and formats its "inner HTML" with Regular Expressions:

protected void FormatHead() { string HTML = ""; string str = "";

Match RegMatch = null;

GenControl = (HtmlGenericControl)this.FindControl("Head");
if(GenControl != null)
{
    HTML = GenControl.InnerHtml;
    //LINK tag:
    str = String.Format(@"href=""{0}""",p_webSummary.WebCss);
    RegMatch = Regex.Match(HTML,@"<\\s*link\\s+.*(href="""")+.*>"
        ,RegexOptions.IgnoreCase);
    if(RegMatch.Success) HTML = HTML.Replace(RegMatch.Groups[1].Value,str);

    //SCRIPT tag:
    str = String.Format(@"src=""{0}""",p_webSummary.WebJs);
    RegMatch = Regex.Match(HTML,@"<\\s*script\\s+.*(src="""")+.*>"
        ,RegexOptions.IgnoreCase);
    if(RegMatch.Success) HTML = HTML.Replace(RegMatch.Groups[1].Value,str);

    //TITLE tag:
    str = String.Format("<title>{0}</title>",p_webSummary.WebName);
    HTML = HTML.Replace("<title></title>",str);

    GenControl.InnerHtml = HTML;
}

}

This technique is for people who really want a lot of control over their HTML and have an undying love for Regular Expressions. By the way, this is the targeted HTML for the example above:

<head id="Head" runat="server"> <link href="" id="LinkCss" rel="stylesheet" type="text/css"> <meta name="CODE_LANGUAGE" content="C#"> <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> <script language="javascript" src="" type="text/javascript"></script> <title></title> </head>

Note that you can't run LINK or SCRIPT tags at the server with empty strings or any kind of bogus place holders without causing an exception to be thrown. If you insist, you can try some kind of data-binging design but this violates my new principle of using only tags in my HTML pages.

So, flippantly speaking, Regular Expressions are cool but right about now I am more attracted to using the PlaceHolder control to load *.ascx pages and then using Literal controls inside those pages to be targeted by an HtmlTextWriter in a code-behind design.

mod date: 2003-10-30T21:02:08.000Z