Twitter Plugin MVC .NET – Yet another twitter reader
As I have free time this morning, I thought I’d share a simple twitter feed reader. Yes I know there are hundreds if not thousands out-there, whoever another will not hurt and might just help someone.
Left start with the “File > New Project” in Visual Studio 2010.
First we need to create a basic Model for our tweet, which we’ll call “TheTweet.cs”

Now we have an empty class, lets add the basics for parts to handle the tweets.
namespace TwitterFeedReader.Models
{
public class TheTweet
{
public string Title { get; set; }
public string Date { get; set; }
public string Photo { get; set; }
}
}
Next lets create the main function that we need in order to read our Twitter feed. I was going to do this in a few stages, however time is limited this morning so I’ll just bulk it all together, and its not that much code so it should easy to understand.
We want to display some tweets on your pages and try and reduce the need for fetching tweets on each view, so we are going to drop the results in to cache memory for 2 minutes. We’ll also wrap a try/catch around the loading of RSS feed, just encase we can’t load it.
public class TwitterReader
{
public IEnumerable GetFeed(int tweetCount)
{
//Setup Cache holder
var TwitterCache = HttpRuntime.Cache;
//Setup Cache key
const string key = "twitter";
//Initials TheTweet
IEnumerable Result;
//Check to see if we already have tweet in memory and has not expired
if (TwitterCache[key] == null)
{
try
{
//Handle XML namespage
XNamespace AtomNs = "http://www.w3.org/2005/Atom";
const string url = "http://search.twitter.com/search.atom?q=from%3AArranM";
//Load the twitter feed in.
var Element = XElement.Load(url);
//Look through the returned twitter feed and grab X tweets in to our Result
Result = (from Tweet in Element.Descendants(AtomNs + "entry").Take(tweetCount)
select new TheTweet
{
Title = ConvertTwitterLinks((string)Tweet.Element(AtomNs + "title")),
Date = ConvertTimeDiff(DateTime.Parse((string)Tweet.Element(AtomNs + "published")))
});
//Store the tweets in to memory for 2 minutes.
TwitterCache.Insert(key, Result, null, DateTime.Now.AddMinutes(2), Cache.NoSlidingExpiration);
}
catch
{
//We have an issue, Return a friendly message to the model, so we don't crash. (//log it)
Result = new List {new TheTweet {Title = "Unable to load twitter feed.", Date = "1 second"}};
}
}
else
{
//Yes we have tweets in memory, so we'll use those
Result = (IEnumerable)TwitterCache[key];
}
return Result;
}
}
Aren’t we great, we are now reading tweets! Hold on, what about links in the tweet? Mmm OK, lets create a quick function to process the tweet and convert any WWW, # or @ we find in to useable links.
I converted some PHP code I found on the web, which seems simple and easy to use.
private static String ConvertTwitterLinks(string input)
{
const string strWebLinks = @"(^|[\n ])([\w]+?://[\w]+[^ \n\r\t< ]*)";
const string strWebLinksWww = @"(^|[\n ])((www|ftp)\.[^ \t\n\r< ]*)";
const string strTwitterNames = @"@(\w+)";
const string strTwitterTags = @"#(\w+)";
input = Regex.Replace(input, strWebLinks, " <a href=\"$2\" rel=\"external nofollow\">$2</a>");
input = Regex.Replace(input, strWebLinksWww, " <a href=\"http://$2\" rel=\"external nofollow\">$2</a>");
input = Regex.Replace(input, strTwitterNames, " <a href=\"http://www.twitter.com/$1\" rel=\"external nofollow\">@$1</a>");
input = Regex.Replace(input, strTwitterTags, " <a href=\"http://search.twitter.com/search?q=$1\" rel=\"external nofollow\">#$1</a>");
return input;
}
Now we have the ability to enable href’s, @, # tags as links, let go back to GetFeed() function and added it in.
Title = ConvertTwitterLinks((string)Tweet.Element(AtomNs + "title")),
Cool.. But can we do something with the Date/Time? Well we can, so lets do that.
private static String ConvertTimeDiff(DateTime tweetTime)
{
//Setup our timestamps
DateTime Dt1 = DateTime.Now;
DateTime Dt2 = tweetTime;
TimeSpan Ts = Dt1.Subtract(Dt2);
string TimeDiff = String.Empty;
//if it's been more than 24 hours, then returns day/s
if (Ts.TotalHours > 24)
{
TimeDiff = String.Format(Ts.Days >= 2 ? "{0} days, " : "{0} day, ", Ts.Days);
}
//if it's been more than 60 minutes, then returns hour/s
if (Ts.TotalMinutes > 60)
{
TimeDiff = Ts.Hours >= 2
? TimeDiff + String.Format("{0} hrs, ", Ts.Hours)
: TimeDiff + String.Format("{0} hr, ", Ts.Hours);
}
//finally return all our string of days/hours/minutes
return TimeDiff + String.Format("{0} minutes", Ts.Minutes);
}
Now we just need to parse the date/time from the Twitter feed and return our calculated time in text. We’ll change a line in the main reader function to this one.
Date = ConvertTimeDiff(DateTime.Parse((string)Tweet.Element(AtomNs + "published")))
Now that’s all done!
Let hook up the Controller to use your new excellent Twitter plugin.
Open /Controllers/HomeController.cs and create a new ActionResult to handle the PartialView we will be using, thus allowing us to use the Twitter Plugin on any page.
First add a reference to our “Models” where our new function is.
using TwitterFeedReader.Models;
Next create a new “ActionResult” for the Twitter Feed.
public ActionResult TwitterFeed(int tweetCount)
{
//could extend to take URL and cache time
var Twitter = new TwitterReader();
var Tg = Twitter.GetFeed(tweetCount);
return PartialView(Tg);
}
Great we are almost there. Now lets create our PartialView to handle displaying the Tweets. Right click on “TwitterFeed” in the name of the ActionResult definition and select “Add View”, you should then be presented with the following dialog box, which we will instruct to be Strongly Typed, and as PartialView..
Let populate the View with a simple HTML definition list element and the always ubiquitous UL LI.
@model IEnumerable</pre>
<dl><dt>Twitter Feed</dt>
<dd>
<ul>
@foreach (var item in Model)
{
<li>@Html.Raw(item.Title) (sent @item.Date ago)</li>
}
</ul>
</dd></dl>
<pre>
I’ll let you worry about the styling. Now on to the final part… Adding the call to the Partial View from our page. Now we can either pop it into the _Layout.cshtml (or Site.Master) or we in the individual view. For the purpose of this quick blog post I will call the Partial View from the /Views/Home/Index.cshtml
@{Html.RenderAction("TwitterFeed", "Home", new { tweetCount = 5});}
There we go, All done. So you should have something like this :
Full project code is available for download (See right hand navigation)
If you found this helpful and would like to buy me a beer to say thanks, please 





