Posting Status Updates (Tweets) To A Twitter Profile Via ASP.NET

Update, 16 Feb 2011: Please note that this routine will no longer work with the Twitter API. It is retained solely to prevent negative search engine rankings.

I have a client that posts several news stories to its Web site every day. So it makes tremendous sense for them to post the headlines to Twitter as tweets, so that followers might be informed of breaking news, or just what’s new on the site.

The Twitter API makes posting status updates (tweets) to Twitter as simple as invoking a WebRequest. Unfortunately, most of the ASP.NET examples on the Web that aim to show you how to post status updates are either written in C#, have coding errors, simply will not work, or all three.

So here’s a simple VB.NET subroutine that will post tweets.

Sub TwitIt(ByVal strUser As String, ByVal strPass As String, ByVal strMessage As String)
	'this subroutine requires your ASP.NET page to have a label control with an ID of lblStatus

	'create post variable for tweet
	Dim strTweet As String = "status=" & Server.HtmlEncode(strMessage)
	'convert post variable to byte array for transmission purposes
	Dim bRequest As Byte() = System.Text.Encoding.ASCII.GetBytes(strTweet)

	Try
		'create HttpWebRequest to status update API resource
		Dim objRequest As HttpWebRequest = WebRequest.Create("http://twitter.com/statuses/update.xml")
		'pass basic authentication credentials
		objRequest.Credentials = New NetworkCredential(strUser, strPass)
		'set method to post and pass request as a form
		objRequest.Method = "POST"
		objRequest.ContentType = "application/x-www-form-urlencoded"
		'tell the server it will not receive a 100 Continue HTTP response
		objRequest.ServicePoint.Expect100Continue = False
		'set content length of request
		objRequest.ContentLength = bRequest.Length

		'capture the stream (content) of the request
		Dim objStream As Stream = objRequest.GetRequestStream()
		'put the bytes into request
		objStream.Write(bRequest, 0, bRequest.Length)
		'close the stream to complete the request
		objStream.Close()

		'uncomment line below to report success
		'lblStatus.Text = "Tweet sent!"

		'You can also capture the XML response Twitter sends back
		'uncomment lines below to capture responses
		'Dim objResponse As WebResponse = objRequest.GetResponse()
		'Dim objReader As New StreamReader(objResponse.GetResponseStream())
		'lblStatus.Text = objReader.ReadToEnd()

	Catch ex As Exception
		'uncomment line below to report ASP.NET errors
		'lblStatus.Text = ex.Message
	End Try
End Sub

Update, July 19, 2009: I have moved the XML response block up into the try block, to avoid an error you will get if the API request returns an error. Thanks to Rob for noting this issue.

Some important notes about the code above:

  • This code requires the System.Net and System.IO namespaces. Chances are strong, if you used Visual Studio to create your Web application, those namespaces are already referenced in your web.config file.
  • This code should work for ASP.NET versions 1.1 and later.
  • Twitter prefers you use the OAuth protocol to authenticate your API requests and will eventually require it. However, they also say that they have not set a date at which they will no longer allow basic HTTP authentication requests. Since it’s far more concise, and generally secure enough, to use basic authentication, that’s what I am using here. Using OAuth to authenticate both requires you to get a key from Twitter and write about twice as much code.
  • The message you send is restricted to the standard length of a tweet (140 characters).
  • You need to set the Expect100Continue property (at Line 16) to false because otherwise, the HttpWebRequest will first send the request headers, then wait for a 100 HTTP status code from Twitter before proceeding with the body of the request (that is, the tweet). It will wait in vain; Twitter will not send a 100 Continue HTTP response; so Twitter will thus wait in vain for the rest of the message, unless you set Expect100Continue to false.
  • I have commented out several lines that set the text for a label ID’ed lblStatus. I always include such a label on my ASP.NET pages for debugging purposes. If you choose to uncomment those lines, remember to add a label to your ASP.NET page with the ID of lblStatus.
  • Every request to the XML version of the Twitter API will be answered with an XML reply that describes the results of the request. If you are having problems, consider uncommenting the code at the end of the subroutine to have the XML document echoed back to your page (and remember to add a label with the ID of lblStatus to your page).

This subroutine takes three arguments: Your Twitter username, your Twitter password, and the tweet. (Note that Twitter usernames and passwords are case-sensitive.) So, assuming your Twitter username is foobar, your password is barfoo, and your tweet is Hello World!, you would invoke the subroutine thus:

TwitIt("foobar", "barfoo", "Hello World!")

Suppose you want to have a form on your page that sends a user-supplied tweet to your Twitter account. The form would look like this:

<form ID="form1" runat="server">
	<label>Enter your Tweet: </label>
	<asp:TextBox runat="server" ID="tbTweet" Columns="50" MaxLength="140" />
	<asp:RequiredFieldValidator runat="server" ID="rfvTweet" ControlToValidate="tbTweet" ErrorMessage="Please provide a tweet!" Display="Dynamic" />
	<br />
	<asp:Button runat="server" ID="btnSubmit" OnClick="btnSubmit_click" Text="Tweet!" />
</form>

Your OnClick handler would be:

Sub btnSubmit_click(ByVal Sender As Object, ByVal E As EventArgs)
	TwitIt("foobar", "barfoo", tbTweet.Text)
End Sub

And you could also give people a gateway to post tweets to their own accounts:

<form ID="form1" runat="server">
	<label>Enter your Twitter Username: </label>
	<asp:TextBox runat="server" ID="tbUser" Columns="20" MaxLength="20" />
	<asp:RequiredFieldValidator runat="server" ID="rfvUser" ControlToValidate="tbUser" ErrorMessage="Please provide your user name!" Display="Dynamic" />
	<br />
	<label>Enter your Twitter Password: </label>
	<asp:TextBox runat="server" ID="tbPass" TextMode="Password" Columns="20" MaxLength="20" />
	<asp:RequiredFieldValidator runat="server" ID="rfvPass" ControlToValidate="tbPass" ErrorMessage="Please provide a password!" Display="Dynamic" />
	<br />
	<label>Enter your Tweet: </label>
	<asp:TextBox runat="server" ID="tbTweet" Columns="50" MaxLength="140" />
	<asp:RequiredFieldValidator runat="server" ID="rfvTweet" ControlToValidate="tbTweet" ErrorMessage="Please provide a tweet!" Display="Dynamic" />
	<br />
	<asp:Button runat="server" ID="btnSubmit" OnClick="btnSubmit_click" Text="Tweet!" />
</form>
Sub btnSubmit_click(ByVal Sender As Object, ByVal E As EventArgs)
	TwitIt(tbUser.Text, tbPass.Text, tbTweet.Text)
End Sub

It’s important to note that there are usage limits for the Twitter API; if you run an open application that lets people post tweets from your Web site, there’s a strong chance your site will be blacklisted by Twitter for exceeding the API rate limits.

Or, you could also add your Twitter username and password to your web.config file, remove them as arguments to the TwitIt() function, and just pass along the tweet as an argument:

<appSettings>
	<add key="TwitterUsername" value="foobar" />
	<add key="TwitterPassword" value="barfoo" />
</appSettings>
Sub TwitIt(ByVal strMessage As String)
	Dim strTweet As String = "status=" & Server.HtmlEncode(strMessage)
	Dim bRequest As Byte() = System.Text.Encoding.ASCII.GetBytes(strTweet)

	Dim objRequest As HttpWebRequest = WebRequest.Create("http://twitter.com/statuses/update.xml")
	objRequest.Credentials = New NetworkCredential(ConfigurationManager.AppSettings("TwitterUsername"), ConfigurationManager.AppSettings("TwitterPassword"))
	objRequest.Method = "POST"
	objRequest.ContentType = "application/x-www-form-urlencoded"
	objRequest.ServicePoint.Expect100Continue = False
	objRequest.ContentLength = bRequest.Length

	Dim objStream As Stream = objRequest.GetRequestStream()
	objStream.Write(bRequest, 0, bRequest.Length)
	objStream.Close()
End Sub

And that’s all there is to it. I don’t have a working example (because of the API rate limits) but I have tested this code and know it works. I distribute all code under the GNU GPL version 3.

14 thoughts on “Posting Status Updates (Tweets) To A Twitter Profile Via ASP.NET

  1. Pingback: Shortening URLs With The bit.ly API Via ASP.NET » dougv.com « The Web home of Doug Vanderweide

  2. rob

    thanks for the example

    i copied it exactly and uncommented the lines at the bottom to see why the comments are not posting ( i get the tweet sent message – but no message appears in twitter)

    Dim objResponse As WebResponse = objRequest.GetResponse()

    error message Name ‘objRequest’ is not declared.

    any ideas?

    i have the following decalarations

  3. Doug Vanderweide Post author

    Rob: The error message you are getting is because your request either isn’t going out or isn’t authenticating. I have moved the code for capturing the XML response into the try block, which should remove the error you are getting.

    If you would like me to help you with this further, I would be happy to do so in exchange for a purchase from my Amazon Wish List.

  4. DuckNet

    Hi there, I’m trying this but despite not throwing any errors, my profile is not updating on twitter. Has the OAuth protocol been enforced??… or should this be working ?

  5. vinny

    Hi,

    This method of updating the status worked for me. I am trying to send direct message using Twitter Api but fails. can you help me with that.

    Thanks !

  6. balu

    Hi
    Thanks for the sample
    The code is working without error.But the status is not getting updated in twitter.
    my username and password in in lowercase and its given so.Is there any other reason??
    Thanks in advance.

  7. anas rahat

    I copied the code in C # it is not giving any error but filling the
    Stream objStream = objRequest.GetRequestStream(); It gives the ‘System.NotSupportedException’

Leave a Reply