自言自语

I'm Wang Xianyuan, writing for myself, more studying, more experience…

博易随机文章小部件

By

耍宝的文章丰富了,为了平均新旧文章的阅读次数,发挥沉淀的经典旧文的价值,在朋友的启发下,准备开发一个随机文章推介的小部件。这个部件的功能是在所有文章中随机选取一定数量的文章显示在部件区域(WidgetZone),显示文章的数量可以自行设定。演示效果见 www.shuabao.net

在 widgets 目录建立 RandomPosts 目录,并创建 widget.ascx 和 edit.ascx 用户控件,其中 edit.ascx 用于设定显示文章的数量。下面给出 widget.ascx.cs 里面的关键程序段以实现随机选取一定数量的文章并显示。

[code:c#]

public override void LoadWidget()
{
	StringDictionary settings = GetSettings();
	int numberOfPosts = DEFAULT_NUMBER_OF_POSTS;
	if (settings.ContainsKey("numberofposts"))
		numberOfPosts = int.Parse(settings["numberofposts"]);

	if (HttpRuntime.Cache["widget_randomposts"] == null)
	{
		List visiblePosts = Post.Posts.FindAll(delegate(Post p)
		{
			return p.IsVisibleToPublic;//仅显示对游客可见文章
		});

		int max = Math.Min(visiblePosts.Count, numberOfPosts);
		List list = new List();

		for (int i = max; i > 0; i--)
		{
			Random random = new Random();
			int r = random.Next(0, visiblePosts.Count);//生成随机数

			list.Add(visiblePosts[r]);
			visiblePosts.RemoveAt(r);
		}

		HttpRuntime.Cache.Insert("widget_randomposts", list, null, 
		DateTime.Now.AddMinutes(15), TimeSpan.Zero);//缓存文章列表,每15分钟更新
	}

	string content = RenderPosts((List)HttpRuntime.Cache["widget_randomposts"], settings);

	LiteralControl html = new LiteralControl(content);
	phPosts.Controls.Add(html);
}

private string RenderPosts(List posts, StringDictionary settings)
{
	if (posts.Count == 0)
	{
		return "" + Resources.labels.none + "";
	}

	StringBuilder sb = new StringBuilder();
	sb.Append("");

	foreach (Post post in posts)
	{
		if (!post.IsVisible)
			continue;

		sb.AppendFormat(link, post.RelativeLink, HttpUtility.HtmlEncode(post.Title));
	}

	sb.Append("");
	return sb.ToString();
}

[/code]

试用源码:RandomPosts.rar (2.97 kb) 如有问题请联系我

Leave a Reply