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.



About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Related Articles

Downloads

Comments

  • Asp.net web development

    Posted by HANISHA on 09/28/2016 04:42am

    Great post Very useful information !its really useful in custom application development

    Reply
  • Giving

    Posted by santosh on 06/07/2016 09:56pm

    As the applicants who are applying for government jobs your website, it also helped me on many occasions when I needed regular updates related to jobs. As my suggestion include more previous year papers which helps us more in p[reparing for the exams

    Reply
  • Sarkari Result

    Posted by Navatha on 11/02/2015 02:57am

    Good article with excellent idea! I appreciate your post.Regards Sarkari Result

    Reply
  • Sarkari Result

    Posted by sarkari on 09/28/2015 04:47am

    interesting article Regards Sarkari Result

    Reply
  • Thanks for the tutorial

    Posted by David on 09/01/2015 08:58am

    Problem with testing TagCloud solved for my website

    Reply
  • medical assistant

    Posted by Susanne Green on 03/14/2015 11:42am

    Great! We always talk about quality not the quantity. Thanks Susanne Green medical assistant

    Reply
  • Image die

    Posted by toan on 04/02/2012 01:18am

    Link image all die.

    Reply
  • .Net barcode

    Posted by pengdan on 01/10/2012 04:01am

    Hey, nice post. i like your style of writting. 
    and recently i found an interesting thing. Barcode Generator. you can generate different kinds of barcodes as you wants.

    Reply
  • r

    Posted by itsglobalbackerz on 01/05/2012 12:19am

    That's good

    Reply
  • Reply

    Posted by itsglobalbackerz on 01/05/2012 12:16am

    It's so nice....

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date