Creating a Tag Cloud for Your ASP.NET Blog

Introduction

Most of the blogs display a set of tags or keywords in the
form of a Tag Cloud.
A tag cloud presents the keywords in font sizes proportional to the number of
blog posts having that tag. If you are using some blogging website or using
some open source blogging engine you already have a tag cloud ready. However,
if you are building your own blog engine or website you will need to build the
tag cloud on your own. This article shows how to do just that.

What is a Tag Cloud?

A tag cloud is a bunch of tags or keywords found on your
blog. Have a look at the following figure that displays a tag cloud:

Tag Cloud
Figure 1: Tag Cloud

As you can see, tag cloud gives some visual indication about
the number of entries for a specific tag. In the above example, tag ASP.NET appears in more posts as compared to other
tags such as Components and Windows Forms. Each tag from a tag cloud will usually
be a hyperlink and clicking on that link will generally present a list of blog
posts having that tag.

Sample Database

To begin creating a tag cloud, create a new ASP.NET website
and add a new SQL
Server
database to its App_Data folder. The SQL Server database will
contain a single table, BlogPosts, whose schema is shown in the following
figure:

Table Schema
Figure 2: Table Schema

As you can see the BlogPosts table has a simple structure
(of course, in a real world blog engine you will have many other columns). The
Tags column stores | separated list of tags belonging to a blog post. e.g.
ASP.NET|AJAX|jQuery

Once you create the database add a few records for testing
purpose. Make sure to keep the density of tags in such a way that you can
confirm that tags are displayed as expected in the tag cloud.

Controlling the Look and Feel of Tag Hyperlinks

One way to control the look and feel of the tag hyperlinks
is to use the style attribute of the anchor (<a>) tag and then set the font-size
and color CSS properties. Though this works fine, this is not recommended if
you are using ASP.NET Themes or separate CSS files to control the look and feel
of the website. It is advisable to include the CSS class in the website theme
and then use these classes for hyperlinks as required. So, add a new Theme
named Default to App_Themes folder and add the following CSS classes to a style
sheet file.

a.TagSize1
{
    font-family: Arial;
    font-size: 20px;
    color: #FF0000;
}
 
a.TagSize2
{
    font-family: Arial;
    font-size: 30px;
    color: #993333;
}
 
a.TagSize3
{
    font-family: Arial;
    font-size: 40px;
    color: #0000FF;
}
 
a.TagSize4
{
    font-family: Arial;
    font-size: 50px;
    color: #009900;
}
 
a.TagSize5
{
    font-family: Arial;
    font-size: 60px;
    color: #9900FF;
}

As you can see, there are five CSS classes, TagSize1 to
TagSize5. TagSize1 is the smallest and TagSize5 is the biggest amongst the set
of classes. We created only five CSS classes because we will have five font
sizes in the tag cloud. You can of course alter this behavior as per your need.

Creating TagCloud User Control

You will create the tag cloud as a User Control so that you
can place it in multiple places (say right or left sidebar and at the bottom of
the home page). So, add a new user control (TagCloud.ascx) to the website and
put a PlaceHolder control on it. You will add HyperLink controls to this
PlaceHolder control dynamically. The TagCloud user control needs to access the BlogPosts
table to determine the "weight" of each and every tag. To facilitate
this data access, add a LINQ to SQL class to the website and drag and drop the BlogPosts
table from Server Explorer onto its design surface. This will generate BlogPost
LINQ to SQL class as shown below:

BloPost Properties
Figure 3: BloPost Properties

Then go to the Page_Load event handler of the user control
and key-in the following code:

protected void Page_Load(object sender, EventArgs e)
{
    DataClassesDataContext db=new DataClassesDataContext();
    SortedDictionary<string, int> tagsDictionary = new SortedDictionary<string, int>();
    var temp = from row in db.BlogPosts
                select row.Tags;
    int postCount = temp.Count();
    foreach (string tags in temp)
    {
        string[] k = tags.Split('|');
        foreach (string s in k)
        {
            if (tagsDictionary.ContainsKey(s))
            {
                tagsDictionary[s]++;
            }
            else
            {
                tagsDictionary.Add(s, 1);
            }
        }
    }
    foreach (string s in tagsDictionary.Keys)
    {
        string tagInUrl = Server.UrlEncode(s);
        HyperLink link = new HyperLink();
        link.Text = s;
        link.NavigateUrl = String.Format("~/ShowPostsByTag.aspx?tag={0}", tagInUrl);
        int tagCount = 0;
        tagsDictionary.TryGetValue(s, out tagCount);
        link.CssClass = GetCssClass(tagCount,postCount);
        PlaceHolder1.Controls.Add(link);
        PlaceHolder1.Controls.Add(new LiteralControl("  "));
    }
}

The code creates an instance of DataContext and selects tag
column for all of the blog posts. The SortedDictionary is intended to store
unique tags in sorted fashion so that they appear in the tag cloud in A-Z
order. A foreach loop iterates through all the blog post rows and with each
iteration the SortedDictionary is populated. Another foreach loop then iterates
through all Keys of the tag dictionary (i.e. unique tags). For every tag in the
tags dictionary a HyperLink control is created programmatically. The Text
property of the new hyperlink is set to the tag name and its NavigateUrl
property to ShowPostsByTag.aspx. The tag name is passed to ShowPostsByTag.aspx
in the query string. To determine the CSS class that needs to be applied to the
hyperlink we use a helper method – GetCssClass. The GetCssClass() method is
shown below:

private string GetCssClass(int tagCount, int postCount)
{
    int result = (tagCount * 100) / postCount;
    if (result <= 20)
        return "TagSize1";
    if (result <= 40)
        return "TagSize2";
    if (result <= 60)
        return "TagSize3";
    if (result <= 80)
        return "TagSize4";
    if (result <= 100)
        return "TagSize5";
    else
        return "";
}

The GetCssClass() method accepts the total number of
occurrences for a tag in the BlogPosts table and the total number of blog
posts. Based on this information a percentage "weight" is calculated.
Recollect that we have created five CSS classes and hence we divide the result
into five slabs. Depending on the slab the CSS class name is returned. You may
consider changing the slab values as per your requirements.

Finally, the dynamically generated HyperLink control is
added to the Controls collection of the PlaceHolder.

Testing TagCloud User
Control

Now that you have built the tag cloud user control, let’s
test it on a web form. Add a new web form to the website and drag and drop the
TagCloud user control on it. Run the web form and you should see something to
the screenshot below:

Tag Cloud
Figure 4: Tag Cloud

Of course, tag names and their sizes will vary depending on
your sample data. All the tag hyperlinks point to ShowPostsByTag.aspx and pass
the tag name as a query string. You can use this query string value in the
ShowPostsByTag.aspx page and display all blog posts having that tag (see a
sample below).

Blog Posts
Figure 5: Blog Posts

As you can see in the code discussed in the preceding
sections, the calculation of tag "weight" will happen every time the
web form is loaded. If your blog is being updated once a day then there is no
need to recalculate the tag weight as it is going to be the same for this time
window. To avoid such repeated processing and improve the performance, you can
implement Output Caching in the TagCloud user control.

Summary

Tag cloud is an essential ingredient of a blog. A tag cloud
displays "weighted" tags as per their number of occurrences in the
blog posts. This article illustrated how a tag cloud can be built for your own
blog. The TagCloud user control thus created can then be used on web forms and
master pages.

More by Author

Must Read