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; } } } }

29 thoughts on “Twitter Tweets in Asp.Net C#

  1. 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.

  2. 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…

  3. 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…

  4. 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

    • 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

  5. 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

  6. 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.

  7. 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() + “”);

    }

  8. 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

  9. 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

  10. 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

Leave a reply to swarna Cancel reply