Software Developer's Resources

Shopping Cart Systems
Mobile Text Marketing Solutions
Online Backup Solutions
ASP.NET Web Development
Skip Navigation Links.

How to Dynamically Compose the Keywords Meta-Tag in ASP.NET C#

This article describes how to dynamically compose the keywords meta-tag by selecting keywords from a database with a custom ASP.NET control.

I use the ASP.NET custom control I created for this web site as an example for this article. My custom control gets a list of ASP.NET Web Controls from a database, composes a comma-separated list of the keywords, and generates a <meta /> tag.

Database

Create a database table to store the keywords:

CREATE TABLE ASPNETWebControls
{
    ControlId BIGINT PRIMARY KEY,
    Name varchar(100)
}

Populate the table with a few keywords:

INSERT INTO ASPNETWebControls (Name) VALUES ('CheckBox');    
INSERT INTO ASPNETWebControls (Name) VALUES ('DropDownList');    
INSERT INTO ASPNETWebControls (Name) VALUES ('TextBox');

Create a stored procedure to select the keywords:

CREATE PROCEDURE ASPNETWebControlsSelect
AS
SELECT Name FROM ASPNETWebControls ORDER BY Name

Create a class to call the stored procedure to read the ASP.NET Web Control names from the database. (Note: I normally use stored procedures in my code. However, in this case the hosting firm doesn't allow execution of MySQL stored procedures from application code level, so I had to resort to in-line SQL statements.).

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace SandyPondResources
{
    public class SPR_ASPNETWebControls
    {
        public DataTable Read()
        {
            SPR_Database DbObj;
            DataTable Dt;
            string Sql = "";
            
            Sql = "SELECT Name FROM ASPNETWebControls ORDER BY Name";
            
            using (DbObj = new SPR_Database())
            {
                DbObj.Command.CommandText = Sql;
                Dt = new DataTable();
                DbObj.DataTableGet(DbObj.Command, Dt);
            }

            return Dt;
        }
    }
}

Create ASP.NET Custom Control

Create a new custom control and derive from SYSTEM.Web.UI.Control:

using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace SandyPondResources
{
    public class SPR_MetaKeywords : System.Web.UI.Control
    {
    }
}    

Compose Keywords List

Compose a comma separated list of the ASP.NET Web Control names.

  • Create a method named KeywordsCompose.
  • Create an instance of SPR_ASPNETWebControls.
  • Call Read method get a DataTable with a set of keywords.
  • Create an empty StringBuilder keywords object.
  • Using a foreach statement walk through every ASP.NET Web Control name in the DataTable and compose a comma-separated list.

When done the list will be:

CheckBox,DropDownList,TextBox
private string KeywordsCompose()
{
    SPR_ASPNETWebControls ControlsObj;
    string Delimiter = "";
    DataTable Dt;
    StringBuilder Keywords;

    ControlsObj = new SPR_ASPNETWebControls();
    Dt = ControlsObj.Read();

    Keywords = new StringBuilder();
    foreach (DataRow Dr in Dt.Select(""))
    {
        Keywords.Append(Delimiter);
        Keywords.Append((string)Dr["Name"]);
        Delimiter = ",";
    }

    return Keywords.ToString();
}

Store Keywords in Session Variable

What are the performance problems of generating the keywords meta-tag for every web page in the application and how do we solve the performance issue?

Reading the keywords from the database for every web page requires obtaining a database connection, sending a command to the database, the database reading the database, the database sending the data to the application, and finally, the application releasing the database connection.

We can reduce the database overhead by using a session variable. We read the keywords from the database upon the first web page request, storing the keywords in a session variable, and retrieving the keywords from the session variable for subsequent web page requests.

Create a property to store the comma-separated keywords list in a session variable.

private readonly string m_KeyKeywords = "Keywords";

private string Keywords
{
    get
    {
        if ((object)Page.Session[m_KeyKeywords] == null) return null;
        return (string)Page.Session[m_KeyKeywords];
    }

    set { Page.Session[m_KeyKeywords] = value; }
}

Generate HTML

Now we have all the pieces. Let's put them together to create an HTML control to generate the keywords meta-tag HTML.

  • Override CreateChildControls method.
  • Get value from Keywords property.
  • If keywords is null then get keywords from database, compose list, and set the session variable.
  • Create instance of HtmlGenericControl passing in "meta". When Render method of HtmlGenericControl is called it will generate an HTML with the "meta" as the name of the tag.
  • Add a "name" attribute with the value "keywords".
  • Add a "content" attribute with the keywords we retrieved from the database.
  • Add the HtmlGenericControl to the Controls collection.

When the Render method is executed it will walk through the set of child controls calling the Render method of each control. Our single child control will generate our custom keywords meta-tag.

    <meta name="keywords" content="CheckBox,DropDownList,TextBox" />

The CreateChildControls method:

    protected override void CreateChildControls()
    {
        HtmlGenericControl MetaObj;

        if (Keywords == null)
        {
            Keywords = KeywordsCompose();
        }

        MetaObj = new HtmlGenericControl("meta");
        MetaObj.Attributes.Add("name", "keywords");
        MetaObj.Attributes.Add("content", Keywords);
        Controls.Add(MetaObj);

        base.CreateChildControls();
    }

Using the Meta-Tag Custom Control

We use the Meta-Tag custom control in an application.

  • Use the Register directive to reference the control
  • Include a call to the custom control in the head section of the HTML document.

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="SPR_Master.master.cs"
    Inherits="SandyPondResources.SPR_Master" %>
<%@ Register Assembly="SandyPondResources" Namespace="SandyPondResources"
TagPrefix="SPR" %>

<head id="Head1" runat="server">
    <title>Sandy Pond Resource></title>
    <SPR:SPR_MetaKeywords runat="server"></SPR:SPR_MetaKeywords>
    <link href="SPR_Stylesheet.css" rel="stylesheet" type="text/css" />
</head>

Conclusion

We've shown how to compose a keywords meta-tag from a database using an ASP.NET custom control and how to use the custom control in an ASP.NET master page.

ASP.NET Custom Control Complete Code

using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace SandyPondResources
{
    public class SPR_MetaKeywords : System.Web.UI.Control
    {
        private readonly string m_KeyKeywords = "Keywords";

        private string Keywords
        {
            get
            {
                if ((object)Page.Session[m_KeyKeywords] == null) return null;
                return (string)Page.Session[m_KeyKeywords];
            }

            set { Page.Session[m_KeyKeywords] = value; }
        }

        private string KeywordsCompose()
        {
            SPR_ASPNETWebControls ControlsObj;
            string Delimiter = "";
            DataTable Dt;
            StringBuilder Keywords;

            ControlsObj = new SPR_ASPNETWebControls();
            Dt = ControlsObj.Read();

            Keywords = new StringBuilder();
            foreach (DataRow Dr in Dt.Select(""))
            {
                Keywords.Append(Delimiter);
                Keywords.Append((string)Dr["Name"]);
                Delimiter = ",";
            }

            return Keywords.ToString();
        }

        protected override void CreateChildControls()
        {
            HtmlGenericControl MetaObj;

            if (Keywords == null)
            {
                Keywords = KeywordsCompose();
            }

            MetaObj = new HtmlGenericControl("meta");
            MetaObj.Attributes.Add("name", "keywords");
            MetaObj.Attributes.Add("content", Keywords);
            Controls.Add(MetaObj);

            base.CreateChildControls();
        }
    }
}