Wednesday, 6 April 2011

Here's a bit of LINQ to XML VB.NET code that will get posts from your blog that have recent Disqus comments. I use it for the 'most popular pages' box on this website.

The code gets posts with comments from the Disqus RSS feed, groups them by post and selects the top eight. Use the StripOutURL function if you want to show just the basic URL for the post without the #comment tag that gives a direct link to the latest comment. The code also replaces the 'Re: ' that Disqus add to the title of the page in the RSS feed.

Function GetPostsWithComments() As String

Dim myIDAPI As New XDocument

myIDAPI = XDocument.Load("http://YOUR_DISQUS_SHORTCODE.disqus.com/latest.rss")

Dim Posts = (From Post In myIDAPI.Descendants("item") _
Select PostTitle = Post.Elements("title").Value, _
PostUrl = StripOutURL(Post.Elements("link").Value), _
PostCount = CInt(Post.Elements("item").Count) _
).GroupBy(Function(Poster) New String(Poster.PostTitle) _
).Take(8)

Dim sb As New StringBuilder

sb.Append("<ul>")

Dim myQuery = From c In Posts

For Each MyX In myQuery

sb.Append("<li><a href=""" & MyX.ElementAt(0).PostUrl & """ >" & Replace(MyX.ElementAt(0).PostTitle, "Re: ", "") & "</a></li>")

Next

sb.Append("</ul>")

Return sb.ToString

End Function


Private Function StripOutURL(ByVal s As String) As String

Dim str As String = ""
str = Left(s, s.IndexOf("#"))

Return str

End Function


blog comments powered by Disqus