Facebook RSS Feed Reader in MVC 4
In
this blog post you will learn how to setup the Facebook RSS Feed Reader in MVC 4. Let’s
look at an image of what we will be creating in this post; see:
Where to find the RSS feed of my wall?
To
find the RSS feed for your wall, login to your Facebook account and then
navigate to the URL https://www.facebook.com/notifications. On the top you will find a link to open the RSS feed page.
Once
you are there, you will notice following page and its root <item>.
Now let’s get started with the coding.
First
of all create the following model classes.
public class FacebookRSS
{
public string Title { get; set; }
public string Link { get; set; }
public string Description { get; set; }
public string PubDate { get; set; }
}
public class FBRssReader
{
public static IEnumerable<FacebookRSS> GetFeed()
{
var client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/4.0
(compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
var xmlData = client.DownloadString("https://www.facebook.com/feeds/notifications.php?id=164214527076029&viewer=108743653424029&key=ACk_XJqgt56etdrK&format=rss20"); //remember to update this url
XDocument xml = XDocument.Parse(xmlData);
var FBUpdates = (from story in xml.Descendants("item")
select new FacebookRSS
{
Title = ((string)story.Element("title")),
Link = ((string)story.Element("link")),
Description =
((string)story.Element("description")),
PubDate = ((string)story.Element("pubDate"))
}).Take(10);
return FBUpdates;
}
}
In the above code, we have two classes. The very first one ‘FacebookRSS’ has
couple of properties and the second one ‘FBRssReader’ has a method ‘GetFeed()’ and this method will return IEnumerable data.
Rest code the code is pretty simple and you can understand it easily. Once you are done with
the model, go ahead and create or update the existing controller.
public ActionResult Index()
{
ViewBag.FBFeed = RSS_Reader.Models.FBRssReader.GetFeed();
return View();
}
Now,
go ahead and update the view that will show our result on the web page.
<table>
<tr>
<th>
<h3>Facebook Updates</h3>
</th>
</tr>
@foreach (var item in ViewBag.FBFeed)
{
<tr>
<td>
<b>@item.Title</b><a href="@item.Link" target="_blank"> more </a> on @Convert.ToDateTime(item.PubDate)
<br />
@Html.Raw(item.Description)
</td>
</tr>
}
</table>
And
now, I’m done with everthing and am ready to run the application, here is my output
screen:
Hope
this helps. Thanks.
Nice article, thanks.
ReplyDelete