Telerik blogs

My Last 5 TweetsAs I mentioned in my previous blog post, I'll be having a little fun over the next few weeks talking about all of the Social Media APIs I've been experimenting with. I thought I would start out today by talking about one of the most popular services, Twitter. Twitter is essentially a microblogging service that allows its users to post messages of up to 140 characters long known as Tweets. Users can subscribe to each other and see tweets from all of their subscriptions in their main feed listings. Due to this ease of providing and receiving updates to and from the masses, Twitter has been adopted by anything from bloggers to celebrities to large corporations.

If you have a blog or just a website in general, having a Twitter account alongside it could potentially be a useful way to attract new visitors. Displaying your tweets on your website and allowing your users to re-tweet them using their own Twitter accounts could potentially be even more useful. In this entry, I am going to show you how to create a simple ASP.NET UserControl that lists your latest tweets and allows people to easily click a link to re-tweet them amongst their own subscribers. My library of choice for this exercise is known as TweetSharp.

TweetSharp

TweetSharp is complete .NET library for microblogging platforms. It currently supports services such as Twitter and Yammer. Through the use of its fluent API you can easily create advanced queries that pull back any type of information the Twitter API provides. You can download the latest version of TweetSharp by paying a visit to its website. The documentation for TweetSharp is available here, however it always helps if you keep a reference to the actual Twitter API around as well. Twitters API documentation is available here.

Creating the TweetListing UserControl

In order to get started building this UserControl, I've initially created a new web application. To this application I've added a couple references to the necessary TweetSharp .NET Framework 3.5 assemblies:

  • TweetSharp.dll
    • This assembly contains the fluent API we will be using to interact with Twitter.
  • Newtonsoft.Json.dll
    • This assembly is .NET library developed by James Newton-King. It simplifies the task of working with JavaScript and JSON formatted data. Although you probably won't be using anything from this assembly directly, TweetSharp relies on it to more easily communicate with Twitters API.

I've also added a single UserControl, in which I will be adding the code to retrieve and display tweets. I've named this file, TweetListing.ascx.

The Markup

The markup of the TwitterListing UserControl consists of a simple Repeater control. I will be binding an IEnumerable<TwitterStatus> collection retrieved from TweetSharp directly to the repeater in the code-behind. The TwitterStatus object defined in the collection contains several useful fields pertaining to the actual tweet text, creation date, user, etc. I will only be using the Text field in this example, but if you'd like to, it should be quite simple to display additional fields.

<h1>My Last 5 Tweets</h1>
<ul class="TweetList">
    <asp:Repeater ID="rptTweets" runat="server" onitemdatabound="rptTweets_ItemDataBound">
        <ItemTemplate>   
                <li class="Tweet">                    
                    <p><%# DataBinder.Eval(Container.DataItem, "Text") %></p>
                    <asp:HyperLink ID="hlRetweet" runat="server">Retweet</asp:HyperLink>
                </li>
        </ItemTemplate>
    </asp:Repeater>
</ul>

The markup for the css styles I am referencing is provided below.

<style type="text/css">   
    ul.TweetList
    {
        width:250px;
        list-style-type: none;
        margin-left: 0px;
        padding-left: 0px;
    }
      
    li.Tweet
    {
        border: solid 1px black;
        margin-bottom:5px;
        background-color: #4FD3FF;
    }
</style>

The Code-Behind

In the code-behind for the UserControl, the first thing I've created is a UserId property. The value of this property represents the user for which tweets should be displayed and needs to be provided by all pages that utilize this control. As you may have noticed, the type of UserId is long. This probably leads you to the question, "Where do I get my User Id?" Well, there are a number of different ways you can get it, including through the use of the API. However, one of the quickest and easiest ways to get it is by pulling the id from the address of the RSS feed for your account. You can find the RSS feed under the profile and favorites information on your twitter home page. The feed address of my account is, http://twitter.com/statuses/user_timeline/17163814.rss, and as you can see, I've bolded my User Id.

public long UserId
{
    get;
    set;
}

When interacting with Twitter, the primary class you will use from the TweetSharp library is FluentTwitter. This static class allow you to essentially compose query strings that can be passed to Twitters API. In the below code, I've created a query that requests the five latest posts from the specified UserId.

var twitter = FluentTwitter.CreateRequest()
                .Statuses()
                .OnUserTimeline()
                .Take(5)
                .For(UserId);

Passing the query information to Twitter is as simple as calling the Request method on the returned object. It should be noted here that I've chosen to make this request synchronously in my application, but it is also possible to make this call asynchronously by using the RequestAsync method.

var response = twitter.Request();
IEnumerable<TwitterStatus> statuses = response.AsStatuses();

If you've never made a call directly to Twitters API or any other Social Media APIs, check out what you would have had to parse for this one. TweetSharp saved us tons of time by generating the query string and parsing the response received from Twitter.

Here is the completed code for the Page_Load event in the code-behind. It uses the above code to retrieve an IEnumerable of statuses from Twitter, then binds them to the repeater control specified in the markup.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        var twitter = FluentTwitter.CreateRequest()
                        .Statuses()
                        .OnUserTimeline()
                        .Take(5)
                        .For(UserId);
  
        var response = twitter.Request();
  
        IEnumerable<TwitterStatus> statuses = response.AsStatuses();
  
        rptTweets.DataSource = statuses;
        rptTweets.DataBind();
    }
}

One of the fundamental reasons you might want to display a control like this on your site, is to allow visitors to retweet your status updates. This will propagate your status amongst their friends, and if one of their friends likes the status they may retweet it and follow you as well, and so on. Ultimately, this could result in more visitors to your site if you plan on linking to content through your Twitter account. The following code sets up the hyperlinks being generated in the repeater to allow users to retweet your posts.

protected void rptTweets_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        TwitterStatus status = e.Item.DataItem as TwitterStatus;
  
        HyperLink hlRetweet = (HyperLink)e.Item.FindControl("hlRetweet");
        hlRetweet.NavigateUrl = hlRetweet.ResolveUrl(string.Format("http://twitter.com/home?status={0}", status.Text));
    }
}

Accounting for Twitter Limitations

Although Twitter does provide us with a fantastic API that is very feature rich, it does unfortunately have a few downsides. API calls are subject to rate limiting which limits calls to the REST API to 150 requests per hour. This rate limiting is based on a user limit, if you authenticate, or an IP address if you don't. Since calls to the API will be made from the server responsible for running this application, the limit this application will face is based on its servers IP address. Fortunately for us, ASP.NET includes a convenient feature called OutputCaching. Using this feature, we can tell the server to hold on to copies of our page for a specified amount of time before allowing it to be regenerated. This will guarantee that we don't go over our limit.

<%@ OutputCache Duration="60" VaryByParam="none" %>

Using the Control

Embedding the control in your application's aspx pages is as simple as first making sure to register it, then creating an instance of it in the markup. In order for the control to work properly, you will need to be sure to specify the UserId property as described previously.

<%@ Register Src="~/TweetListing.ascx" TagName="TweetListing" TagPrefix="social" %>
  
<social:TweetListing ID="Tweets" UserId="17163814" runat="server" />

Click here to download the source code.


Comments

Comments are disabled in preview mode.