#region Using
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;
using System.Collections.Generic;
using BlogEngine.Core;
#endregion
public partial class widgets_Tag_cloud_widget : WidgetBase
{
public override void LoadWidget()
{
foreach (string key in WeightedList.Keys)
{
HtmlGenericControl li = new HtmlGenericControl("li");
li.InnerHtml = string.Format(LINK, Utils.RelativeWebRoot + "?tag=/" + Utils.RemoveIllegalCharacters(key), WeightedList[key], "Tag: " + key, key);
ulTags.Controls.Add(li);
}
}
///
/// Initializes the class.
///
static widgets_Tag_cloud_widget()
{
Post.Saved += delegate { Reload(); };
}
public static void Reload()
{
_WeightedList = null;
}
#region Private fields
private const string LINK = "{3} ";
private static Dictionary _WeightedList;
private static object _SyncRoot = new object();
#endregion
private int _MinimumPosts = 1;
private int MinimumPosts
{
get
{
StringDictionary settings = GetSettings();
if (settings.ContainsKey("minimumposts"))
{
int.TryParse(settings["minimumposts"], out _MinimumPosts);
}
return _MinimumPosts;
}
}
private Dictionary WeightedList
{
get
{
if (_WeightedList == null)
{
lock (_SyncRoot)
{
if (_WeightedList == null)
{
_WeightedList = new Dictionary();
SortList();
}
}
}
return _WeightedList;
}
}
///
/// Builds a raw list of all tags and the number of times
/// they have been added to a post.
///
private static SortedDictionary CreateRawList()
{
SortedDictionary dic = new SortedDictionary(StringComparer.InvariantCultureIgnoreCase);
foreach (Post post in Post.Posts)
{
if (post.IsVisibleToPublic)
{
foreach (string tag in post.Tags)
{
if (dic.ContainsKey(tag))
dic[tag]++;
else
dic[tag] = 1;
}
}
}
return dic;
}
///
/// Sorts the list of tags based on how much they are used.
///
private void SortList()
{
SortedDictionary dic = CreateRawList();
int max = 0;
foreach (int value in dic.Values)
{
if (value > max)
max = value;
}
foreach (string key in dic.Keys)
{
if (dic[key] < MinimumPosts)
continue;
double weight = ((double)dic[key] / max) * 100;
if (weight >= 99)
_WeightedList.Add(key, "biggest");
else if (weight >= 70)
_WeightedList.Add(key, "big");
else if (weight >= 40)
_WeightedList.Add(key, "medium");
else if (weight >= 20)
_WeightedList.Add(key, "small");
else if (weight >= 3)
_WeightedList.Add(key, "smallest");
}
}
///
/// Gets the name. It must be exactly the same as the folder that contains the widget.
///
///
public override string Name
{
get { return "Tag cloud"; }
}
///
/// Gets wether or not the widget can be edited.
///
/// The only way a widget can be editable is by adding a edit.ascx file to the widget folder.
///
///
///
public override bool IsEditable
{
get { return true; }
}
}