#region Using using System; using System.Web; using System.Web.UI; using System.IO; using System.Collections.Generic; using BlogEngine.Core; #endregion namespace Controls { public class TagCloud : Control { static TagCloud() { Post.Saved += delegate { _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; public int MinimumPosts { get { return _MinimumPosts; } set { _MinimumPosts = value; } } 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(); 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"); } } /// /// Renders the control. /// public override void RenderControl(HtmlTextWriter writer) { if (WeightedList.Keys.Count == 0) { writer.Write("

" + Resources.labels.none + "

"); } writer.Write("
    "); foreach (string key in WeightedList.Keys) { writer.Write("
  • "); writer.Write(string.Format(LINK, Utils.RelativeWebRoot + "?tag=/" + HttpUtility.UrlEncode(key), WeightedList[key], "Tag: " + key, key)); writer.Write("
  • "); } writer.Write("
"); writer.Write(Environment.NewLine); } } }