Friday, October 21, 2011
Integrating Twitter Into An ASP.NET Website
Introduction
Twitter is a popular social networking web service for writing and sharing short messages. These tidy text messages are referred to as tweets and are limited to 140 characters. Users can leave tweets and follow other users directly from Twitter's website or by using the Twitter API. Twitter's API makes it possible to integrate Twitter with external applications. For example, you can use the Twitter API to display your latest tweets on your blog. A mom and pop online store could integrate Twitter such that a new tweet was added each time a customer completed an order. And ELMAH, a popular open-source error logging library, can be configured to send error notifications to Twitter.Twitter's API is implemented over HTTP using the design principles of Representational State Transfer (REST). In a nutshell, inter-operating with the Twitter API involves a client - your application - sending an XML-formatted message over HTTP to the server - Twitter's website. The server responds with an XML-formatted message that contains status information and data. While you can certainly interface with this API by writing your own code to communicate with the Twitter API over HTTP along with the code that creates and parses the XML payloads exchanged between the client and server, such work is unnecessary since there are many community-created Twitter API libraries for a variety of programming frameworks.
This article shows how to integrate Twitter with an ASP.NET website using the Twitterizer library, which is a free, open-source .NET library for working with the Twitter API. Specifically, this article shows how to retrieve your latest tweets and how to post a tweet using Twitterizer. Read on to learn more!
An Overview of the Demo
The demo available for download at the end of this article shows how to use the Twitterizer API to integrate with Twitter from an ASP.NET website. Before we look at using Twitterizer to integrate, let's first take a moment to review the demo application. The demo consists of a single ASP.NET page,
Default.aspx
, along with a master page,Site.master
. As the following screen shot shows, the master page and CSS rules define a layout that divides the screen into left and right portions. The right portion contains page-specific content. The left portion shows the most recent tweets from a specific Twitter user and appears on every page that uses the master page. There are five tweets in the screen shot below, the most recent one listed at the top - "Tweeting for fun and profit." What's more, the master page uses the ASP.NET Ajax Library'sUpdatePanel and Timer Web controls to automatically and seamlessly refresh the list of latest tweets every 60 seconds.Default.aspx
page (shown above) includes a text box where the user can enter a post and have that sent to Twitter. Clicking the "Post My Tweet" button causes a postback, and on postback the page uses Twitterizer to tweet the text entered into the text box. Also, the list of latest tweets is refreshed to include the just-tweeted post.aspIntegration, a Dummy Twitter Account |
---|
When building this demo I created a dummy Twitter user account named aspIntegration. The username and password for this account are stored in the demo's Web.config file. Any tweets you make from the demo appear in this Twitter account. If you download the demo and run it, please keep this in mind when making test tweets - don't tweet anything private or offensive, as others will see it when they run the demo. To test against your own Twitter account, locate the username and password entries in the <appSettings> section in Web.config and update them accordingly. |
Getting Started With Twitterizer
Using Twitterizer in one of your projects is easy - just download the Twitterizer assembly, copy it to your application's
/Bin
folder, and start coding! The download available at the end of this article includes the latest version of Twitterizer at the time of writing, version 1.0.1.120. To get the latest version of Twitterizer, visit the project page athttp://code.google.com/p/twitterizer/.The Twitterizer library contains a number of classes that model the information exchanged between the client and the server when making Twitter API calls, along with the low-level plumbing necessary to make the HTTP requests and to serialize the object model into the appropriate XML and vice-a-versa. The main workhorse of the library is theTwitter
class. When using this class you'll want to provide the username and password of the Twitter account that you want to integrate with. These credentials can be passed into the Twitter class' constructor, as the following code snippet shows:// C# |
From there, you can use any of the
Twitter
class's methods to get or submit information via the Twitter API. For example, to get back a list of recent tweets from username, use the following code:// C# |
To make a tweet for username, use the following code:
// C# |
It's that simple. With Twitterizer you don't need to muck around with XML. Instead, you work with a tidy object model with all of the benefits therein (compile-time type checking, IntelliSense, no magic strings, and so forth). For a complete rundown of how to use Twitterizer to accomplish various Twitter-related tasks, refer to the Getting Started page on the Twitterizer Wiki.
Displaying Recent Tweets
The demo's
Site.master
master page defines the markup and code used to display the configured user's most recent tweets. The latest tweets are displayed using a ListView control, although the markup could certainly be rendered iteratively, by using a Repeater, or through some other mechanism. The master page's source code portion contains a public method named RefreshTweets
that, when called, uses the Twitterizer library to go and get the user's most recent tweets; this collection of tweets is then bound to the ListView control.The markup to display the latest tweets follows. The data-binding syntax is highlighted in red. Keep in mind that the ListView is being bound to a list of TwitterStatus
objects. The TwitterStatus
class has properties like Text
and Created
, which return the text of the tweet and the date and time is was posted, respectively. There's also aTwitterUser
property, which returns a TwitterUser
object with information about the user who posted the tweet. To reference these properties, use the data-binding syntax <%# Eval("propertyName") %>
.<asp:ListView ID="lvTweets" runat="server"> |
Check out the formatting function
RelativeTime
. RelativeTime
takes in an absolute time - (the date and time the tweet was made), compares it to the current time, and generates a relative time value. For example, if a tweet was made on February 17th, 4:50 PM GMT and the current universal time is February 17th, 5:01 PM GMT, theRelativeTime
method will return the string, "about 6 minutes ago."The ListView of tweets is contained inside of an UpdatePanel control, which also contains a Timer. The Timer is configured to "tick" every 60 seconds. Whenever the Timer control "ticks" it causes a postback; because the Timer is in an UpdatePanel it's a partial page postback. On postback, the Timer's
Tick
event fires and the event handler runs. This event handler calls the RefreshTweets
method, which uses Twitterizer to reload the most recent tweets in the ListView. Long story short, this setup will seamlessly requery Twitter every 60 seconds. Any new tweets will automatically appear in the ListView. For more information on using the Timer control to seamlessly update web page content, check out Building Interactive User Interfaces with Microsoft ASP.NET AJAX: Using the Timer Control.Returning Fewer Tweets | |
---|---|
By default, Twitterizer's UserTimeline returns the 20 most recent tweets for the configured user. To return fewer tweets, you'll need to create aTwitterParameters object, add a Count parameter specifying the maximum number of tweets to return, and then pass this object into theUserTimeline method call like so:
Bear i mind that the Twitter API does not allow more than 20 tweets to be returned in one API call. However, you can use the Page parameter to get a user's second page of 20 tweets (tweets number 21 through 40). |
Tweeting From The Website
The demo's
Default.aspx
page includes a text box and button. When the button is clicked, a postback ensues and the contents entered into the text box are posted to the configured user's Twitter account. When posting tweets it is important to keep in mind that Twitter limits tweets to 140 characters. The markup in Default.aspx
includes a RegularExpressionValidator that ensures the text entered is between 0 and 140 characters.Posting a tweet using the Twitterizer library can be done with just one line of code (once the Twitter
object has been instantiated). Simply call the Update
method, passing in the text to tweet. Here is a code snippet from the demo that shows how to programmatically post the contents of the txtTweet
TextBox to Twitter using Twitterizer:// C# |
Each tweet in Twitter includes information as to where the tweet came from. For instance, if you post from Twitter's website the tweet will say, "from web." By default, tweets made from the Twitterizer library report that the tweet came from Twitterizer, as you might expect. The source of the tweet is configurable from the
Source
parameter, which can be passed into the Twitter
object's constructor. Specifically, the source is the name of the API that the tweet came from. If you have your own application registered with Twitter then you can supply your application's name here and your tweets posted from Twitterizer will report that they are from your application. (See the Twitterizer FAQ for more information on this topic.)Alternatively, if you put in a random string here that does not map to any known registered application, Twitter will report that the tweet came from the web. To go this route, you can pass in a new GUID as the source, since it is safe to assume that there are no registered applications with the same name. To accomplish this, use code like the following:
// C# |
Conclusion
Like many social networking websites, Twitter offers a rich API for integration. There are numerous free, open-source libraries available for integrating with Twitter. One such library for the .NET Framework is Twitterizer. This article (and its accompanying demo) showed how to use Twitterizer to view the latest tweets in an ASP.NET website, along with how to post a tweet from a website. The concepts discussed here would work equally well with any other sort of connected application, such as a WinForms or WPF application, or from a WCF or Windows Service.