Home > Asp.Net, C#, LINQ > Twitter Tweets in Asp.Net C#

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; } } } }
About these ads
Categories: Asp.Net, C#, LINQ Tags: , ,
  1. Jean-Pierre Schele
    August 31, 2010 at 7:48 am | #1

    Hy,

    can I use the control on my official homepage because of trademarks and guidlines of twitter?

    JPS

    • August 31, 2010 at 4:03 pm | #2

      Yea sure feel free to use it

      Let me know if you have any issues !!!

      Thanks
      Deepu

  2. nrs
    September 10, 2010 at 3:49 pm | #3

    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.

    • September 10, 2010 at 3:59 pm | #4

      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

      http://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

  3. Fenil Desai
    September 15, 2010 at 10:21 am | #5

    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…

  4. Fenil Desai
    September 29, 2010 at 1:55 pm | #7

    how can i show total no. of tweets & followers/following count?

  5. Fenil Desai
    October 5, 2010 at 10:59 am | #9

    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…

  6. Vikram
    October 6, 2010 at 5:28 pm | #10

    Gr8 thanks a lot

  7. Phil Snyder
    January 14, 2011 at 10:50 pm | #11

    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

  8. darzi
    March 1, 2011 at 10:56 pm | #13

    Would be nice if you could cache them too.

    • March 2, 2011 at 4:43 am | #14

      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

  9. April 10, 2011 at 8:32 am | #15

    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.

  10. sravani
    April 18, 2011 at 1:42 pm | #16

    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

  11. hunter
    August 17, 2011 at 9:22 pm | #19

    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.

  12. balaji
    August 23, 2011 at 1:17 pm | #20

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

    }

  13. Man
    August 25, 2011 at 6:14 am | #21

    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

  14. sarathy
    January 18, 2012 at 5:58 pm | #22

    can you please tell how can i update the twitter status?

    • January 18, 2012 at 11:06 pm | #23

      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

      • sarathy
        January 19, 2012 at 7:28 pm | #24

        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

  15. sarathy
    January 18, 2012 at 6:00 pm | #25

    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

  16. pavithra
    March 5, 2012 at 11:00 am | #26

    yeah thanks a lot for the use full post

  17. swarna
    April 26, 2012 at 3:40 pm | #27

    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

    • marudah
      September 6, 2012 at 11:46 pm | #28

      I also need to do the same. Did you figure out? if so how?

      • September 20, 2012 at 8:14 pm | #29

        Looks like they have changed the API’s. Please refer twitter developer site

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 27 other followers

%d bloggers like this: