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="hiddenSpellError" pre="">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; } } } }
Hy,
can I use the control on my official homepage because of trademarks and guidlines of twitter?
JPS
Yea sure feel free to use it
Let me know if you have any issues !!!
Thanks
Deepu
Hi,
I am getting following error.
Rate limit exceeded. Clients may not make more than 150 requests per hour. Please how can i solve this problem.
It is obvious that you can’t make more than 150 requests per hour..
In my code sample I have mentioned the cache limit as 10 minutes change to 60 minute or some thing
https://deepumi.wordpress.com/2010/08/03/twitter-tweets-in-asp-net-c/
//Updates latest Tweets for every 10 minutes in page refresh.
private static Double Interval = 60;
Let me know if this work for you
Thanks
Deepu
Hi,
This shows only last 5 tweets…how to show all tweets…
Also what if i want to show my entire timeline.ie. my tweets + following people’s tweets…
1) Change TweetsCount property to 10 or 20 or etc….
2) Followers tweets – Currently this functionality is not implemented in the control
Refer : http://dev.twitter.com/doc
http://dev.twitter.com/doc/get/statuses/public_timeline
http://dev.twitter.com/doc/get/statuses/user_timeline
Hope this helps
Deepu
how can i show total no. of tweets & followers/following count?
You may take a look on Twitter API
http://dev.twitter.com/doc
http://dev.twitter.com/doc/get/statuses/public_timeline
http://dev.twitter.com/doc/get/statuses/user_timeline
Hope this helps
Thanks
Deepu
Getting this error – Rate limit exceeded. Clients may not make more than 150 requests per hour. even after setting the cache limit to 60 minute, the error still comes.
kindly give any solution to this..it is very annoying…
Gr8 thanks a lot
Awesome post! I was able to implement your code and then fully customize it for my site’s purposes. I’d first tried Twitter’s own widget but ran into conflicts between the widget and my asp:menu. Yours works just fine.
Thanks
Phil
You are welcome Phil ..
Thanks
Deepu
Would be nice if you could cache them too.
Caching is already implemented in the LoadXML() method…
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;
}
}
By default the tweets will be cached for 10 minutes every 10 minutes this will be reloaded from server. If you want to exceed the interval.. change the member variable Interval 10 to 30 or 60….120.
private static Double Interval = 30;
Hope this helps
Thanks
Deepu
Hi,
great sample, It is simple and effective. I have tweaked it a bit. You can check it out here: http://www.icodeteam.net/default/post/iCodeTeam/34/ASP-NET-C-Twitter-Module-Tweets-Feed/
Thanks again.
Nice one…
But I need latest tweet for display I just decrees the count even it gives me 5 tweets How can i get latest one… pls help me
The default listing is based on latest tweets try the following url in browser and see
http://api.twitter.com/statuses/user_timeline.rss?screen_name=deepumi&count=5
Hope this helps
Thanks
Deepu
Thanks Deepu
I just wanted to say thanks. After an hour of searching this was the only thing that actually worked or wasn’t so complicated in order to display a tweet.
Hi
every one fllowing code is working xxxxxxxx.xml is web sit name its like
http://www.google.com that xml file is google.xml
String xml = wc.DownloadString(“http://twitter.com/statuses/user_timeline/XXXXXXXX.xml?count=2”);
DataSet ds = new DataSet();
ds.ReadXml(new StringReader(xml));
if (ds.Tables[“status”] != null && ds.Tables[“user”]!=null)
{
Response.Write(ds.Tables[“status”].Rows[0][“created_at”].ToString()+” “);
Response.Write(ds.Tables[“user”].Rows[0][“name”].ToString() + “”);
Response.Write(ds.Tables[“status”].Rows[0][“text”].ToString() + “”);
Response.Write(ds.Tables[“user”].Rows[0][“description”].ToString() + “”);
}
Hey there,
Once I download your sample code, am I supposed to be able to run it? I have not changed any coding from your sample code, however when I run it the page shows “No tweets available”. Kindly advise.
Thank you
can you please tell how can i update the twitter status?
I have posted this article on 2010, Recently twitter has changed the API call using oAuth, and You may have to look in to their latest API’s.
https://dev.twitter.com/docs
https://dev.twitter.com/
Hope this helps
Thanks
Deepu
could you please give code for update status into twitter. what ever i tried i could not able to update the status in twitter.
Thanks
Sarathy
The bellow code i was used
// encode the username/password
string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(Username + “:” + Password));
// determine what we want to upload as a status
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(“status=” + message);
// connect with the update page
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“https://twitter.com/?update”);//https://twitter.com/statuses/update
//http://twitter.com/statuses///update.xml //?statuses/update.xml
// set the method to POST
request.Method = “POST”;
request.ServicePoint.Expect100Continue = false; // thanks to argodev for this recent change!
// set the authorisation levels
request.Headers.Add(“Authorization”, “Basic ” + user);
request.ContentType = “application/x-www-form-urlencoded”;
// set the length of the content
request.ContentLength = bytes.Length;
// set up the stream
Stream reqStream = request.GetRequestStream();
// write to the stream
reqStream.Write(bytes, 0, bytes.Length);
// close the stream
reqStream.Close();
//request.Abort
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
but i can’t view the twitt in my home page can you please check and tell where i did mistaken
Thanks advance
yeah thanks a lot for the use full post
the artcle is very nice..can you please suggest how to get profile image by modifying the existing code.it is very imp o include image in our project ,please suggest me as son as possible
I also need to do the same. Did you figure out? if so how?
Looks like they have changed the API’s. Please refer twitter developer site