Tuesday, July 21, 2009 #

Posting Twitter Tweets from ASP.NET using the WCF REST Starter Kit Preview 2

With Twitter becoming more and more popular, I have always wanted to explore its developer wiki and find out ways to post to Twitter programmatically.  While there are a tons of third party tools such as TweetDeck etc., that allow you to tweet right from your desktop, I was looking for a resource that allows me to update my Twitter status from ASP.NET.  I stumbled upon this video http://www.pluralsight.com/main/screencasts/screencast.aspx?id=httpclient-consuming-twitter-in-under-3-minutes for read/write to Twitter using the WCF REST Starter Kit Preview 2.

I just wanted to take the same experience to post it from ASP.NET Webform, so the credit for the REST logic goes to the above post/video.

However, for the purpose of this post, I am explaining the pre-requisites.  You would need to install the WCF REST Starter Kit Preview 2 from http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24644. Also you would need Visual Studio SP1 or the free Visual Web Developer Express SP1

Creating your Web Client

Create a new ASP.NET Web Application and add reference to Microsoft.Http & Microsoft.Http.Extensions DLLs.  They are found typically at C:\Program Files\Microsoft WCF REST\WCF REST Starter Kit Preview 2\Assemblies once you install the WCF REST Starter Kit (link above)

Open the Default.aspx, add a TextBox, Label, 2 Buttons say btnPostStatus & btnGetStatus as well as a GridView.  The overall markup looks as below:-

 

<asp:Label ID="lblStatus" runat="server" Font-Bold="True" ForeColor="#006600" />
      <br />
      <br />
      <asp:Button  ID="btnGetStatus" runat="server" Text="Get Tweets"
          OnClick="btnGetStatus_Click" 
           />
      <br />
      <br />
       <asp:textbox ID="Textbox1" runat="server" MaxLength="135" 
          Width="333px"></asp:textbox>
      <asp:Button ID="btnPostStatus" runat="server" Text="Post Tweet" OnClick="btnPostStatus_Click" />
      <br />
      <br />
      <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
          GridLines="None" AutoGenerateColumns="false">
          <RowStyle BackColor="#EFF3FB" />
          <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
          <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
          <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
          <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
          <EditRowStyle BackColor="#2461BF" />
          <AlternatingRowStyle BackColor="White" />
          <Columns>
              <asp:TemplateField HeaderText="Posted By">
                  <ItemTemplate>
                      <asp:Label ID="Label1" runat="server" Text='<%#Eval("user.screen_name") %>' />
                  </ItemTemplate>
              </asp:TemplateField>
              <asp:TemplateField HeaderText="Tweet Count">
                  <ItemTemplate>
                      <asp:Label ID="Label1" runat="server" Text='<%#Eval("user.statuses_count") %>' />
                  </ItemTemplate>
              </asp:TemplateField>
              <asp:BoundField HeaderText="Status" DataField="text" />
              <asp:BoundField HeaderText="Posted Time" DataField="created_at" />
          </Columns>
      </asp:GridView>

In the Default.aspx.cs, add the following using statements:-

using Microsoft.Http;

using System.Xml.Serialization;

using System.Net;

Generate the click events for the btnPostStatus & btnGetStatus

Getting the Twitter Friends Feed

Login to your Twitter account and then type the URL http://twitter.com/statuses/friends_timeline.xml  It may ask you for your credentials again and if so, provide the same.

Grab (copy) the XML File and paste into notepad.

(Replace all “&” with “&amp;” and remove leading blank spaces, - (hyphen) using a simple find and replace with nothing.  i.e. in Find, you type the – and in the Replace, leave it blank to avoid XML parsing error.  If your XML is in good shape, you can save it with a <filename>.xml and then should be able to browse it using Internet Explorer.  It points out if there are any errors in parsing the XML, that can be fixed)

After the above corrections, copy the XML and in the Default.aspx.cs (created above), after the class definition, point the cursor and from the Edit Menu select “Paste XML as Types” to generate serialization class for the XML Feed.  If you receive an error at this point, make sure the XML is well formed (check steps above)

It gives two items.  A partial class statuses and another partial class statusesStatus.  We will use these to Post and Get Twitter Feeds.

Posting to Twitter

In the btnPostStatus event in the code behind, paste the following code snippet:-

try
            {
                HttpClient httpClient = new HttpClient("
http://twitter.com/statuses/");
                httpClient.TransportSettings.Credentials = new NetworkCredential("TWITTER USERNAME", "TWITTER PASSWORD");
                System.Net.ServicePointManager.Expect100Continue = false;
                HttpResponseMessage responseMessage = httpClient.Get("friends_timeline.xml");

                HttpUrlEncodedForm form = new HttpUrlEncodedForm();
                form.Add("status", Textbox1.Text);
                responseMessage = httpClient.Post("update.xml", form.CreateHttpContent());
                responseMessage.EnsureStatusIsSuccessful();
                lblStatus.Text = "Your Tweet is posted successfully";
            }
            catch (Exception)
            {
                lblStatus.ForeColor = System.Drawing.Color.Red;
                lblStatus.Text = "There seems to be some issue.  Please try again later";
            }
            finally
            {
                Textbox1.Text = null;
            }

 

Basically, we are using the HtpClient Class from Microsoft.Http that is shipped as a part of the WCF REST Starter Kit Preview 2.  Using this, we provide a GET request to firends_timeline.xml which is the Twitter Feed XML.  Therafter, we are creating a UrlEncodedForm to post the TextBox content using the httpClient’s POST Method to the update.xml Twitter Feed XML.  The rest of the stuff is pretty self explanatory.

Get Feeds from Twitter

In the btnGetStatus event in the code behind, paste the following code snippet:-

HttpClient http = new HttpClient("http://twitter.com/statuses/");
           http.TransportSettings.Credentials = new NetworkCredential("TWITTER USERNAME", "TWITTER PASSWORD");
           System.Net.ServicePointManager.Expect100Continue = false;

           HttpResponseMessage resp = http.Get("friends_timeline.xml");
           resp.EnsureStatusIsSuccessful();

           statuses stats = resp.Content.ReadAsXmlSerializable<statuses>();
           GridView1.DataSource = stats.status;
           GridView1.DataBind();

In this, we are using the HttpClient and issuing a GET request to firneds_timeline.xml and then binding it using the stats.Status that is available as a part of the serialized XML that we pasted in the above steps.  Once that is done, GridView binding and Template Columns is regular stuff with a little amount of UI formatting.

Once you are done with the above, you should be able to Get the Feeds of your friend when you click “Get Status” and also post status to Twitter once you type it in the TextBox and click on the “Post Status” Button. 

The code snippet for GET/POST requests is taken from Aaron’s video available at http://www.pluralsight.com/main/screencasts/screencast.aspx?id=httpclient-consuming-twitter-in-under-3-minutes where he creates a Console Application using the Twitter Feeds and REST StarterKit.

Herebelow is a snapshot of how the Tweet Feeds look like

TweetPic

 

You can download the sample from the link below

NOTE: You need to change TWITTER USER NAME & TWITTER PASSWORD to your actual Twitter Username and Password.

Some people may argue on what is the great benefit of using an ASP.NET Webform to do that when I can directly browse the Twitter portal and upload it.  The same may hold good for Desktop Applications as well since you anyway need Internet to post / view feed.  The only case where a client app makes sense is when you can save Tweet Draft and also do more rich UI customizations.  I am trying to build a similar sample using WPF / Silverlight and would post it in my blog once it is ready.  Secondly, this may be useful when you want to pull Tweet Feeds and show in your site/portal like the one that appears in this blog down right.

More than anything, this shows the capabilities the WCF REST Starter Kit offers and can be extended to Winforms / WPF easily.

If you receive a “Unable to locate remote host twitter.com” error, most probably you are facing a firewall / Proxy issue for issuing a Network Request.  To fix that, you need to add the following to your Web.Config after </system.web> settings

<system.net>
        <defaultProxy>
            <proxy
            usesystemdefault="False"
            proxyaddress="http://address:port"
            bypassonlocal="False"/>
        </defaultProxy>
    </system.net>

Note, you need to replace the Address & Port of your configuration.  To read more about this, visit my earlier post http://geekswithblogs.net/ranganh/archive/2005/08/29/51474.aspx 

Cheers !!!

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Posted On Tuesday, July 21, 2009 7:20 AM | Feedback (23)