C# MVC Read Blog Items into an array

Every now and then you would want to enrich your MVC application by displaying a live feed of articles from a blog.
Here is how to do it!

[HttpGet]
public string GetInfo()
{
ArrayList _socialItemsArray = new ArrayList(50);
var i = 0;
var reader2 = System.Xml.XmlReader.Create(“http://myblogurl/feed/”);
var feed2 = System.ServiceModel.Syndication.SyndicationFeed.Load(reader2);
reader2.Close();
foreach (System.ServiceModel.Syndication.SyndicationItem album in feed2.Items)
{

i++;
if (i > 10) { break; }
SocialItem x = new SocialItem();
x.account = “WordPress”;
x.Link = album.Links.First().Uri.ToString();
x.created_at = DateTime.Parse(album.PublishDate.ToString(“g”));

if (album.Title.Text.Length > 90)
{
x.UserDisplayName = album.Title.Text.Substring(0, 87) + “…”;
}
else
{
x.UserDisplayName = album.Title.Text;
}

string postSummary = album.Summary.Text;

if (postSummary.Length >135)
{
postSummary = postSummary.Substring(0, 135);
int lastSpace = postSummary.LastIndexOf(” “);

if (lastSpace != -1)
{
postSummary = postSummary.Substring(0, lastSpace) + “…”;
}
else
{
postSummary = postSummary + “…”;
}
}
x.Content = postSummary;

_socialItemsArray.Add(x);
}

}

If you wish to display the information, just look in the _socialItemsArray and traverse it with a for, foreach or while statement.

Advertisements