Twitter Tweets in Asp.Net C#


I’ve been working on the twitter feed in one of my recent project where tweets getting updated on a regular interval time (say for every 30 minutes or 1 hr). I am creating this as a ASCX control so that I can reuse for multiple projects.

You can Download the complete source code from here

I am dropping a ListView control in the ASCX page which render the Twitter Profile name along with  Title, Description and Published date for the latest tweets.

Couple of properties need to configure to use this control

TwitterProfileName – Your twitter profile name or screen name

TweetsCount – No of tweets you want to return (default is 10).

<asp:ListView ID="lvTweets" runat="server">
<LayoutTemplate>
<table border="0" cellpadding="2" cellspacing="0">
<tr>
<td height="30" runat="server">
<a href="http://twitter.com/<%=<span class=&quot;hiddenSpellError&quot; pre=&quot;&quot;>TwitterProfileName</span>%>" target="_new"></a>
<%= TwitterProfileName%>
</td>
</tr>
<tr>
<td>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</td>
</tr>
<tr>
77B5D2;">
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<a target="_new" href='<%# DataBinder.Eval(Container.DataItem, "Link")%>'>
<%# DataBinder.Eval(Container.DataItem, "Title")%></a>
<br />
<div>
<%# DataBinder.Eval(Container.DataItem, "PublishedDate", "{0:h:mm  tt MMM d}")%>
</td>
</tr>
</ItemTemplate>
<EmptyDataTemplate>
<div>
<h3>
No tweets available.</h3>
</div>
</EmptyDataTemplate>
<ItemSeparatorTemplate>
<tr>
1px solid lightgrey;">
</td>
</tr>
</ItemSeparatorTemplate>
</asp:ListView>
using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;

public partial class TweetsControl : System.Web.UI.UserControl
{
private static DateTime? lastUpdated = null; //holds last updated time

private static XDocument xDoc = null; //static variable to store the result xml.

//Updates latest Tweets for every 10 minutes in page refresh.
private static Double Interval = 10;

//Determine its time to get the new tweets
private static Boolean IsTimeForUpdate
{
get
{
if (lastUpdated.HasValue && DateTime.Now > lastUpdated.Value.AddMinutes(Interval))
{
return true;
}
return false;
}
}

//Hold no of tweets default set it as 10.
public Int32? TweetsCount { get; set; }

//Twitter profile name or screen name.
public String TwitterProfileName { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetTweets();
}
}

private void GetTweets()
{
var xml = LoadXML();
IEnumerable query = null;
if (xml != null)
{
query = from e in xml.Descendants("item")
select new
{
Title = e.Element("title").Value,
Link = e.Element("link").Value,
PublishedDate = Convert.ToDateTime((e.Descendants("pubDate").First().Value)),
};
}
lvTweets.DataSource = query;
lvTweets.DataBind();
}

private XDocument LoadXML()
{
if (xDoc != null && !IsTimeForUpdate)
{
return xDoc;
}
else
{
try
{
TweetsCount = TweetsCount.HasValue ? TweetsCount : 10;
var url = string.Format("http://api.twitter.com/statuses/user_timeline.rss?screen_name={0}&count={1}", TwitterProfileName, TweetsCount);
xDoc = XDocument.Load(url);
lastUpdated = DateTime.Now;
return xDoc;
}
catch
{
return null;
}
}
}

}

Refer more api information on Twitter API

You can Download the complete source code from here

Hope this helps

Thanks
Deepu

using System; using System.Linq; using System.Xml.Linq; using System.Collections; using System.Collections.Generic; public partial class TweetsControl : System.Web.UI.UserControl { private static DateTime? lastUpdated = null; private static XDocument xDoc = null; private static Double Interval = 10; private static Boolean IsTimeForUpdate { get { if (lastUpdated.HasValue && DateTime.Now > lastUpdated.Value.AddMinutes(Interval)) { return true; } return false; } } public Int32? TweetsCount { get; set; } public String TwitterProfileName { get; set; } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GetTweets(); } } private void GetTweets() { var xml = LoadXML(); IEnumerable query = null; if (xml != null) { query = from e in xml.Descendants(“item”) select new { Title = e.Element(“title”).Value, Link = e.Element(“link”).Value, PublishedDate = Convert.ToDateTime((e.Descendants(“pubDate”).First().Value)), }; } lvTweets.DataSource = query; lvTweets.DataBind(); } private XDocument LoadXML() { if (xDoc != null && !IsTimeForUpdate) { return xDoc; } else { try { TweetsCount = TweetsCount.HasValue ? TweetsCount : 10; var url = string.Format(“http://api.twitter.com/1/statuses/user_timeline.rss?screen_name={0}&count={1}”, TwitterProfileName, TweetsCount); xDoc = XDocument.Load(url); lastUpdated = DateTime.Now; return xDoc; } catch { return null; } } } }

LINQ to XML CRUD Operations


CRUD (Create, Read, Update & Delete) four operations for adding, displaying, modifying and deleting data.  This articles explains how CRUD operation can be achieved using  LINQ to XML. (You can download the entire article from here).

For example you want to store  Members information in an XML file and you may need to implement  add /  edit / delete functionality through a  UI.

So I am going to create a XML file with four nodes like firstName,lastName,email and phone.

<?xml version="1.0" encoding="utf-8"?>
<Members>
 <member id="f02c78b4956f4b2f9ecfb7a5bfbcfbf6">
 <firstName>Deepu</firstName>
 <lastName>M.I</lastName>
 <email>me@gmail.com</email>
 <phone>123-456-7890</phone>
 </member>
</Members>

Screen shots for CRUD Operations (Create Screen)

Using the following method we can Create a new member information to the XML file.


XDocument doc = XDocument.Load(FilePath);  //load the xml file.
 IEnumerable<XElement> oMemberList = doc.Element("Members").Elements("member");
var oMember = new XElement("member",
 new XAttribute("id", Guid.NewGuid().ToString().Replace("-", "")),
 new XElement("firstName", txtFirstName.Value),
 new XElement("lastName", txtLastName.Value),
 new XElement("email", txtEmail.Value),
 new XElement("phone", txtPhone.Value)
 );
oMemberList.Last().AddAfterSelf(oMember);  //add node to the last element.
doc.Save(FilePath);

XDocument class will load the xml file and will find the last member node and save the information to the file.

The next screen will show all the members in the xml file in Grid format using ListView control.

XElement element = XElement.Load(FilePath);  //replace with xml file path
if (element != null)
{
var query = from member in element.Descendants("member")
select new
{
MemberId = (string)member.Attribute("id"),
FirstName = member.Element("firstName").Value,
LastName = member.Element("lastName").Value,
Email = member.Element("email").Value,
Phone = member.Element("phone").Value
};
if (query != null && query.Count() > 0)
{
lvMemberList.DataSource = query.ToList();
lvMemberList.DataBind();
}
}

Update method is similar to create method like load a xml file and find the corresponding member node by Id or email and finally it will update node values using SetElementValue method some thing like below.


XDocument doc = XDocument.Load(FilePath); //replace with xml file path
IEnumerable<XElement> oMemberList = doc.Element("Members").Elements("member"); //get the member node.
var oMember = (from member in oMemberList
 where
 member.Attribute("id").Value == 2
 select member).SingleOrDefault(); //replace memberId by querystring value.
 oMember.SetElementValue("firstName", firstName);
 oMember.SetElementValue("lastName", lastName);
 oMember.SetElementValue("email", email);
 oMember.SetElementValue("phone", phone);
 doc.Save(FilePath);

Finally the Delete will be deleteing a node element from the xml file.


XElement element = XElement.Load(FilePath);
 if (element != null)
 {
 var xml = (from member in element.Descendants("member")
 where
 member.Attribute("id").Value == 2
 select member).SingleOrDefault();

 if (xml != null)
 {
 xml.Remove();
 element.Save(FilePath);
 }
 }

Note : This post does not have the complete source code. please download the full working source code from the download link.

You can download the entire article from here copy paste this URL

http://www.4shared.com/file/236175264/b5df239/CRUD.html

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu

Compare xml files using C# LINQ


In this article you will learn how to compare two xml files using C# LINQ (Language Integrated Query one of the great features  in C# 3.0 release) .Imagine a scenario where you are consuming a third party web service for online book selling site. Every day you may need to update your site if any new book is launched and also you want to sync with your existing information. I am going to create a simple class called Book with three properties.  (You can download the  article source code from the bottom of the page.)

public class Book
{
 public Book()
 {

 }
 public int BookID { get; set; }
 public String Name { get; set; }
 public double Price { get; set; }
 public Book(int bookId, string name, double price)
 {
 this.BookID = bookId;
 this.Name = name;
 this.Price = price;
 }

}

The next step is to create custom comparer class which implements IEqualityComparer. The comparer class  returns true if both bookId’s  are equal.

public class BookComparer : IEqualityComparer<Book>
{
 public bool Equals(Book x, Book y)
 {
 return (x.BookID == y.BookID);
 }

 public int GetHashCode(Book book)
 {
 return book.BookID.GetHashCode();
 }
}

Sample XML files

Book_A.xml

<?xml version="1.0" encoding="utf-8" ?>
<Books>
 <Book bookId="100" name="Asp.Net" price = "230" />
 <Book bookId="101" name="C#" price = "200" />
 <Book bookId="102" name="Silverlight" price = "300" />
 <Book bookId="103" name="MFC Book" price = "300" />
</Books>

Book_B.xml

<?xml version="1.0" encoding="utf-8" ?>
<Books>
 <Book bookId="100" name="Asp.Net" price = "230" />
 <Book bookId="101" name="C#" price = "200" />
 <Book bookId="102" name="Silverlight" price = "300" />
 <Book bookId="104" name="WPF" price = "200" />
 <Book bookId="105" name="WCF" price = "200" />
</Books>

Result.XML

<?xml version="1.0" encoding="utf-8"?>
<Books>
 <Book bookId="100" name="Asp.Net" price="230" />
 <Book bookId="101" name="C#" price="200" />
 <Book bookId="102" name="Silverlight" price="300" />
 <Book bookId="103" name="MFC Book" price="300" />
 <Book bookId="104" name="WPF" price="200" />
 <Book bookId="105" name="WCF" price="200" />
</Books>

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
 {
 IEnumerable<Book> bookA = LoadXML("Books_A.xml");
 IEnumerable<Book> bookB = LoadXML("Books_B.xml");
 BookComparer oComparer = new BookComparer();
 var comparerList = bookA.Except(bookB, oComparer).ToList();
 List<Book> result = new List<Book>();
 result.AddRange(comparerList);
 result.AddRange(bookB);
 result = (from book in result
 orderby book.BookID ascending
 select book).ToList<Book>();

 XElement xElement = new XElement("Books",
 from book in result
 select new XElement("Book",
 new XAttribute("bookId", book.BookID.ToString()),
 new XAttribute("name", book.Name),
 new XAttribute("price", book.Price)
 )
 );
 xElement.Save(Server.MapPath("~/XML/result.xml"));
 }

 IEnumerable<Book> LoadBooksFromXML(string fileName)
 {
 XElement xml = XElement.Load(Server.MapPath("~/XML/" + fileName));
 var query = (from book in xml.Descendants("Book")
 orderby (int)book.Attribute("bookId") ascending
 select new Book(
 (int)book.Attribute("bookId"),
 (string)book.Attribute("name") != null ? (string)book.Attribute("name") : string.Empty,
 (double)book.Attribute("price"))
 );
 return query;
 }

Code Explanation

IEnumerable<Book> bookA = LoadXML(“Books_A.xml”);

LoadXML method load xml file and return a collection of Book class

BookComparer oComparer = new BookComparer(); //The BookComparer class instantiate a new object

var comparerList = bookA.Except(bookB, oComparer).ToList();

The above statement will compare the items in Books_A.xml  with Books_B.xml and return a collection of items which is not found in Book_B.xml

Based on the above XML files the return list would be some thing like below

<Book bookId=”103″ name=”MFC Book” price = “300” />

Finally we need to merge the items in to a new list and save as result.xml file.

Create a new List for hold the result list

List<Book> result = new List<Book>();
result.AddRange(comparerList);  //
result list
result.AddRange(bookB); //
book_B.xml collection.

//sort by book id ascending

result = (from book in result
orderby book.BookID ascending
select book).ToList<Book>();

//Save as new xml file.

XElement xElement = new XElement(“Books”,
from book in result
select new XElement(“Book”,
new XAttribute(“bookId”, book.BookID.ToString()),
new XAttribute(“name”, book.Name),
new XAttribute(“price”, book.Price)
)
);
xElement.Save(Server.MapPath(“~/XML/result.xml”));

You can download the entire article from here or copy paste this URL

http://www.4shared.com/file/232888750/82ac9ddf/XMLComparer.html

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu

how to consume an Atom RSS Feed using Asp.Net C# with LINQ


This article describes how to consume an Atom RSS Feed using Asp.Net C# with LINQ.
There are many ways to achieve this. But I am using LINQ because LINQ has lot of features to customize with minimum code.

XDocument doc = XDocument.Load(“http://www.asp.net/News/rss.ashx&#8221;); //configure your Url here.

var query =from feed in doc.Descendants(“item”)
orderby DateTime.Parse(feed.Element(“pubDate”).Value) descending
select new
{
Title = feed.Element(“title”).Value,
Description = feed.Element(“description”).Value,
Date = DateTime.Parse(feed.Element(“pubDate”).Value)
};

Using Xdocument object in LINQ will help you to read an xml file from the server.
Once you have the document object you can just take advantage of  linq to xml for customize,
So the above code just read all the rss reader from the given url sort by last publishing date.
If you want more customize to the above code to show only top few items from the list you can try with Take() method.

XDocument doc = XDocument.Load(“http://www.asp.net/News/rss.ashx&#8221;);
var query = (from feed in doc.Descendants(“item”)
orderby DateTime.Parse(feed.Element(“pubDate”).Value) descending
select new
{
Title = feed.Element(“title”).Value,
Description = feed.Element(“description”).Value,
Date = DateTime.Parse(feed.Element(“pubDate”).Value)
}).Take(
10).ToList();

Here I am taking Top 10 Feed items from the list and sorting by last publishing date and simply binding to a DataGrid

<asp:DataGrid ID=”dg” runat=”server”></asp:DataGrid>

dg.DataSource = query.ToList();
dg.DataBind();

Note: You may need to replace the attribute name inside the Element tag with your XML node name.

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu