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 !!!

Print | posted on Tuesday, July 21, 2009 7:20 AM

Comments on this post

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

Requesting Gravatar...
Good work..thanks for sharing..let me try ;)
Left by Mahesh on Jul 21, 2009 11:03 AM

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

Requesting Gravatar...
Nice One ..
I tried this example .
Its good place to start with REST
Left by Manesh on Jul 22, 2009 4:01 AM

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

Requesting Gravatar...
I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.ed hardy
Left by tiffany on Jul 31, 2009 2:59 AM

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

Requesting Gravatar...
Nice tutorial.. Thx for sharing :)
Left by Nyubi on Aug 01, 2009 9:26 AM

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

Requesting Gravatar...
Great stuff. Will now spend my Sunday afternoon working my way through it.
Left by Holiday cottages on Aug 02, 2009 6:57 AM

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

Requesting Gravatar...
Great work thanks. We use Twitter a lot on our holiday villas price comparison site and this will help us a lot. Thanks.
Left by Holiday accommodation on Aug 02, 2009 8:59 AM

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

Requesting Gravatar...
Cant wait to get cracking with this! notebook auctions will definately be implementing this on their twitter account for posting!
Left by used macbooks on Aug 04, 2009 5:43 AM

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

Requesting Gravatar...
I have twitter set up on a huge screen tv set in the front of my shop, using this I put a keyboard there so customers can tweet their experiences! Great code - useful start!
Left by flatscreen tv sets on Aug 04, 2009 5:45 AM

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

Requesting Gravatar...
that's all right ,i think so
Left by christion louboutin on Oct 15, 2009 7:06 PM

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

Requesting Gravatar...
I THIN K SO
Left by christion louboutin on Oct 15, 2009 7:12 PM

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

Requesting Gravatar...
Helpful code and well explained, thanks.
Left by fast property sale on Nov 11, 2009 3:33 AM

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

Requesting Gravatar...
I am receiving the error "There is an error in XML document (6, 4)." at the command line
statuses stats = resp.Content.ReadAsXmlSerializable<statuses>();

Please let me know what this error points to and how can I correct it.

We are using the code to get messages from Twitter.

Your help will be greatly appreciated.

Thanks..
Left by Sunil on Feb 08, 2010 5:37 PM

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

Requesting Gravatar...
Very nice tutorial. I am going to try to integrate it into my web app allowing my clients to auto tweet when they make updates to their website.
Left by Houston NightClubs on Mar 22, 2010 7:23 AM

# cheap ysl

Requesting Gravatar...
Better means more features.
good post,I think so!
Left by ysl shoes on Apr 01, 2010 7:53 PM

# cheap christian louboutin shoes

Requesting Gravatar...
I agree with your idea!
Left by summer on Apr 08, 2010 7:36 PM

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

Requesting Gravatar...
You would need to install the WCF REST Starter Kit Preview 2
Left by Acai marja on May 02, 2010 4:19 AM

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

Requesting Gravatar...
i like your weiste, it is nice ,ahha
Left by cheap purses on May 04, 2010 3:43 AM

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

Requesting Gravatar...
let me bookmakr your aritcles, ilook i read it
Left by true religion jeans on May 04, 2010 3:45 AM

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

Requesting Gravatar...
Thansk for share, jucarii
Left by freddy on Jun 08, 2010 8:54 PM

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

Requesting Gravatar...
Cheers for the tutorial

Left by Lemon Diet Pills on Jul 13, 2010 5:36 PM

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

Requesting Gravatar...
Hi,
I had simillar friends_timeline reader as a web part for sharepoint. Now since Twitter changes its basic authetication to oAuth, its really getting complicated. Have any one tried simillar in recent days and used oAuth.
your help will be appretiated.

Thanks
Left by Roshan on Sep 13, 2010 10:38 PM

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

Requesting Gravatar...
Nice to find the post related to my searching criteria.
Left by bachelorette party supplies on Oct 01, 2010 7:25 PM

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

Requesting Gravatar...
awesome article you've describe here, ill bookmark it
Left by get rid of pimples overnight on Sep 11, 2012 10:19 PM

Your comment:

 (will show your gravatar)