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

  • Elige a la plancha de pelo depende de la longitud del cabello y el moldeador, dispuestos a gastar

    Posted by xynnlm951 on 07/25/2013 09:24pm

    pelo ghd es hermosa arma secreta peinado de una mujer. El famoso GHD es el encanto de la manera de conquistar a la mujer exigente y estilista? En primer lugar, entendemos el pelo ghd en los principales productos funktioner.GHD enderezador principales, técnica de calentamiento, principalmente de cerámica, el uso de la producción de calentador de cerámica y Corea del Sur, placa caliente, y se implanta la nanotecnología, la tecnología de infrarrojos y la tecnología de iones negativos, los productos , en su mayoría a cargo de luz de la superficie, elegante excelente calidad. Todos los productos son fabricados de acuerdo con la norma británica GS, seguro y confiable. rosa ghd sigue siendo el producto más vendido en 2011, esta GHD Qué encanto? [url=http://cheapghdoutlet.jimdo.com/]planchas ghd[/url] plancha de pelo ghd utiliza placas de cerámica para liso, fácil de moldear. Control de la tensión, puede crear el más apropiado entre las placas cerámicas de pelo liso. El producto también tiene el mismo anión, la conservación de hacer que el cabello suave y brillante, para evitar el pánico. Cuerpo con una configuración de calor digitales, pantalla digital hace que sea fácil seleccionar la función deseada o ajustar la forma de la temperatura. Puede ayudar a elegir el pelo bien y la temperatura deseada. Pulse un botón, tendrá un efecto perfecto de inmediato. 1 función de apagado automático hora le permite utilizar más paz de la mente. Planchas ghd como operación segura y simple. Ocupar gran cuota de mercado. Convertido en una moda de comprar. Debido a esto, a menudo parece falsa, por lo que cada vez más personas están comprando auténticos planchas ghd. Nuestra tienda, aunque las ventas de negro pelo ghd. Pero somos productos ghd regulares. No traen todo tipo de daño fuego falso. Nuestro producto de mapa con el mapa físico es exactamente el mismo. Para asegurar que los productos reales y fiables. Y vendemos planchas ghd baratas, 7 * 24 funciones en línea, usted puede comprar en cualquier momento. Siempre y cuando haya seleccionado el tipo deseado, complete la información personal, etc temas relacionados, el producto puede ser enviado directamente a las manos de espera. Por favor, comprar productos ghd sentimientos antes, mira a nuestra política de privacidad, Quiénes somos, transporte, preguntas más frecuentes y las políticas más relevantes, esto le ayudará a comprar nuestros productos. Gracias por tu colaboración. [url=http://ghdplanchasonline.manifo.com/]planchas ghd[/url] Somos ghd planchas para el pelo red profesional, tenemos un trabajo en equipo fuerte para llegar a más gente sobre la necesidad de ghd glattejern.vi constantemente actualizada constantemente transformere.du tiene una buena y agradable de compras miljø.og venta de planchas ghd, bajo price.For diferente productos de consumo a las familias a garantizar produktsikkerhed.Danmark es primera monarquía constitucional del mundo. Desde la Segunda Guerra Mundial, los daneses, con su constante espíritu se desarrollará en Dinamarca naciones industriales de Occidente. Su economía es un desarrollo gradual. Pero Dinamarca con otras personas que les gusta la búsqueda de la moda del disfrute material de la vida. Pero ellos tienen sus propios límites. Ellos saben cuándo ir demasiado lejos. sentido estético

    Reply
  • duLKv eRj USXL

    Posted by WZptwrROcu on 06/05/2013 07:55pm

    buy propecia can you buy propecia online no prescription - much does propecia cost boots

    Reply
  • toms on sale

    Posted by carpinteyrocux on 03/11/2013 11:28pm

    793150 [b]Tags:[url=http://www.tomsshoesonsalecn.com/]toms outlet[/url]|[url=http://www.cheaptomsoutletcn.com/]toms outlet[/url]|[url=http://www.tomsoutletsale2012.com/]toms sale[/url]|[url=http://www.tomsoutletonsalecn.com/]discount toms[/url]|[url=http://www.cheaptomsshoescn.com/]cheap toms[/url] &Links;: [url=http://www.twitter.com/]toms shoes retailers[/url][/b] as long as that someone prefer Bottega Veneta stepped up to the plate.A curvaceous wedge can't be marked for a big alteration of lesson,as I write this blog post. I equitable got news from the publisher of my present paperback thatStart Something that Mattersis instantly a 1 New York Times Best Seller! Never among my wildest dreams did I imagine this would occur plus all I can think of right now namely how grateful I am apt each plus everyone of you that has supported TOMS over the past five years. This moment goes apt you!With all my adore plus thanks,plus I adore the way the colors work together The shades of ruddy turquoise,but it largely lacks the inexplicable missteps that have characterized Choo's recent collections. This is a solid, set deep amid the heart of London's maximum creative and cultural 15 min The 2010 edition brings you more of everything: more stages,As part of the last show to be subject to Mr. McQueen's direct approval I anticipate these aspiration be both coveted and collectible.And, the finish with its crocodile seal detailing is more than barely silver,

    Reply
  • купить маскарадный костюм

    Posted by Fapaveactuach on 02/22/2013 01:21am

    Уважаемые господа!Оформить заказ выгодный для Вас! Тогда читайте новость - красивые платья картинки женские сумки интернет и дорогая бижутерия купить красивые платья фото ... Хороших Вам покупок! :::::::::::: Kamagra tablets next day shipping - Buy and purchase Kamagra Online or kamagra generica - online drug stores Kamagra where to Buy , Kamagra direct 4 u - what is Kamagra used for !!!!

    Reply
  • купить пончо пальто

    Posted by Fapaveactuach on 02/21/2013 06:08pm

    Здраствуйте!Хотите заказать одежду на выгодных условиях? Тогда читайте новость - каталог одежды для полных женщин женская обувь больших размеров и интернет магазин детская одежда скидки интернет магазин одежды в украине ... Удачи Всем! :::::::::::: order Kamagra India - Kamagra Oral Jelly 100mg canada methscopolamine nitrate or international Generic Kamagra - Kamagra Online prescription , kamagra kopen - Cheap Kamagra online !!!!

    Reply
  • молодежная одежда каталог

    Posted by VadyJargearly on 02/20/2013 05:59am

    Привет Всем!У меня есть новость магазину он-лайн Тогда читайте новость - платья барабашово купить недорого платье и серебряная бижутерия магазин мужской обуви ... Всем пока рад был сообщить... :::::::::::: Kamagra Oral Jelly passport - 100mg Buy Kamagra tablets or www kamagra de - is Kamagra illegal UK , kamagra en suisse - Kamagra bristol !!!!

    Reply
  • Dot net training in chennai

    Posted by lisa on 02/20/2013 03:52am

    This is definitely one of the best articles I have read in this website! Thanks Mate Dot netTraining in Chennai

    Reply
  • Dot net training in chennai

    Posted by lisa on 02/20/2013 03:51am

    This is definitely one of the best articles I have read in this website! Thanks Mate Dot netTraining in Chennai

    Reply
  • производитель стильной женской одежды

    Posted by Mocajeola on 02/17/2013 02:15pm

    Как дела?Оформить заказ выгодный для Вас! Тогда читайте новость - купить юбка из фатина магазин одежды для беременных и с чем носить платье известные бренды одежды ... Хороших Вам покупок! :::::::::::: price Kamagra - kwick kamagra or kamagra primobolan - Kamagra by mail , Kamagra online Fedex overnight shipping - Oral Jelly australia free shipping Kamagra pills !!!!

    Reply
  • карамелли детская одежда интернет магазин

    Posted by fubyprerroulp on 02/17/2013 12:06am

    Уважаемые господа!Хотите заказать одежду на выгодных условиях? Тогда читайте новость - купить носки онлайн formalab и интернет магазин детской одежды интернет магазин верхней детской одежды ... Всем пока рад был сообщить... :::::::::::: Kamagra Oral Jelly suppliers usa rapid heartbeat - apcalis erectalis Kamagra plus or Generic Kamagra meridia - te koop echte Kamagra , kamagra mastercard - shop for shop for Kamagra UK !!!!

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • QA teams don't have time to test everything yet they can't afford to ship buggy code. Learn how Coverity can help organizations shrink their testing cycles and reduce regression risk by focusing their manual and automated testing based on the impact of change.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds