.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sharon Maxwell

Home >> Articles >> Web Services >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Creating a Simple Twitter Client Application

Posted By:Mohammad Elsheimy       Posted Date: May 02, 2010    Points: 25    Category: Web Services    URL: http://www.dotnetspark.com  

Creating a Simple Twitter Client Application.In this article you will learn how to access Twitter API Using C#.NET(sample application available.)

This article was previously published in my blog, Just Like a Magic.

Download twittoo; our sample application


This writing discusses the Twitter API and how you can utilize it in your managed application. It begins by a brief discussion of the API and the methods used. After that, it digs into the discussion of how you can utilize the API into your application with help of code samples and examples. At the end of this writing, there's a nice open-source Twitter client application available for download. Worth mentioning that this article focuses on the REST API set of Twitter, specifically XML endpoints.)


Today, we are talking about Twitter as it is one of the most famous social networking services. This article discusses how you can create Twitter clients using .NET Framework. Oh, before we start, I'd like to introduce you my twitter account first J, it's @elsheimy.

Twitter API

What Twitter API is

Before we dig into the discussion of Twitter API we need to know first what the Twitter API is.
Twitter API is a set of endpoints (or methods) that allow applications to work with Twitter data.
Twitter API consists of three parts:
  • Two REST APIs:
    • REST API:
      This is the core API set; it allows developers to access core Twitter data, it contains most (if not all) of the methods and functions you would use to utilize Twitter data in your application, and it supports (mostly) three formats (or endpoints) for each method: XML, Atom, and JSON formats.
    • Search API:
      Fully integrating search methods allows you to search for tweets based on specific criteria and to search for daily/weekly hot trends. It supports only the JSON format. This set of API was originally developed by Summize, Inc. and integrated into the Twitter API. (Twitter is looking forward to unify the REST API.)
  • Streaming API:
    A set of API methods that allow near-realtime access to various subsets of Twitter public statuses. All methods are in JSON format, no XML or ATOM endpoints available.
Actually, the REST API would be very sufficient for you unless you find it easier to handle the JSON format.
It is worth mentioning that the REST API provides very handful and sufficient search methods that your application can use. If you need more searching capabilities (like searching for tweets that confirm to a set of criteria,) you can dig into the REST Search API.
You are not required to stick to a specific set of API methods. You can mix the methods you like from the three APIs.

Wikipedia: REST (Representational State Transfer) is a style of software architecture for distributed hypermedia systems such as the World Wide Web.

: JSON (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange based on the JavaScript programming language.

: Atom Publishing Protocol (AtomPub or APP) is a simple HTTP-based protocol for creating and updating web resources.

This writing focuses on the XML endpoints of the REST API.

API Documentation

Twitter has with a very nice API documentation that documents each and all methods and endpoints of the three parts of the API. This documentation can be found here: http://apiwiki.twitter.com.

To avoid duplication, we are not going to discuss the Twitter API again in this writing; it is already documented and available for all users. Instead, we will take a brief look at the API and discuss how we can utilize it in our .NET application. For simplicity, we will focus on XML endpoints. Therefore, all of our code would rely on the XML features of .NET Framework 2.0 (i.e. System.Xml.dll library.) Oh, you are free to write the code the way you like (e.g. integrating LINQ for XML into the code.)
Now, we are going to look inside the Twitter API.

Things to be Kept into Mind

There are some basics of the Twitter API that a developer should keep into his mind.
  • Calls to the Twitter API are limited:
    Don't expect to post unlimited updates or to follow thousands of users in just an hour! Many methods have a call limit (hourly/daily.) For example, at the time of this writing, you have only 150 API requests per hour, further requests would return an exception. In addition, you can send only 1,000 updates and 250 direct messages per day (can we remove this word "only"?) You can check Twitter limits here.
  • Every endpoint has its HTTP methods that need to be set (e.g. GET, POST, and DELETE) in the request. The documentation of each endpoint lists the HTTP methods required for that endpoint. For more information about HTTP and HTTP methods check the RFC 2616 Section 9 document.
  • Some methods (like methods send updates) require user authentication and others not. Authentication is discussed soon.

API Methods

The following is a discussion about Twitter API methods and how you can call them.

Method Address

Every method has an address (i.e. URI). The address of a method is something like that: http://api.twitter.com/1/statuses/public_timeline.format (for the statuses/public timeline method.) We replace the format field with the format we like to work with (e.g. xml, atom, json.)

Now, try to copy the method address http://api.twitter.com/1/statuses/public_timeline.xml and paste it into your browser. You should get something like that:


    Wed Apr 14 19:32:07 +0000 2010


    35 Ingenious Examples of Footwear - http://su.pr/1JxMAr











      Smashing Magazine


      Freiburg, Germany

      Vitaly Friedman, editor-in-chief of SmashingMagazine.com ...











      Tue Aug 05 14:00:40 +0000 2008



















  . . .

This method returns the 20 most recent statuses from arbitrarily-selected non-protected Twitter users; this list is called the Public Timeline. Because we have selected the XML format (or endpoint) we end up with XML data.

From the data returned we can extract the structure of statuses and users. Twitter API is good enough; it uses the same structure for all data returned. In other words, all methods (in the REST API, remember?) use the same structure (i.e. schema) to represent status and user objects. Those structures are covered soon.

Methods with Arguments

Most of methods accept arguments, some are optional and others are required. An example of a function requires a single argument is the users/show method that returns profile information about a specific user.
This function accepts one of three arguments:
  • id:
    The ID or screen name of the user.
  • user_id:
    The ID of the user.
  • screen_name:
    The screen name of the user.
We set arguments the same way we set web pages query strings. Considering my twitter account @elsheimy as an example, we could query user profile using one of four ways:
All of the four calls return the same results that should be like this:


  Mohammad Elsheimy


  KB, Egypt

  Technology evangelist from Egypt born in 1991











  Wed Jan 28 10:47:36 +0000 2009














    Wed Apr 21 16:21:46 +0000 2010


    I'm reading this, it's really hot: #RFC 2616 - Hypertext Transfer Protocol ...














As you can see, it returns user information and the last update of that user. Notice that the structure of the data is the same in all methods.

Methods Require Authentication

Some methods require user authentication. Examples are functions update status, send direct messages, retrieve friends' timeline, etc.
Let's take an example. Bring up your browser and browse to the address of statuses/friends timeline method that returns user's friends' timeline, http://api.twitter.com/1/statuses/friends_timeline.xml. A small window like this should appear that asks you your Twitter username and password.

Figure 1. IE Authentication

Provide your Twitter username and password to pass to the results. If authentication was OK, you should receive the most recent 20 statuses of your friend timeline in the same structure (schema) as the Public Timeline method. On the other hand, if the authentication process failed, you should receive an error:

  /1/statuses/friends_timeline.xml   Could not authenticate you.

Let's consider another example, the direct_messages/new method. This function sends a new direct message to a specific user from the current user authenticated.This function accepts two required arguments:
  • user:
    The ID or screen name of the recipient user. You can use one of two arguments in place of this argument:
    • screen_name:
      Screen name of the user.
    • user_id:
      The ID of the user.
  • text:
    Message body, not longer than 140 UTF-8-encoded characters.
The following two calls send the same message ("hi, how is it going") to the same user:
Notice that we need to encode arguments before we pass them to the server.

Because this function updates data, it requires HTTP POST method. Therefore, you won't be able to try it from your browser unless your browser allows you to set HTTP methods in the request.

If the function succeeded, it should return the message object that has been sent, and it should be like this:



  all your bases are belong to us.


  Wed Apr 08 20:30:04 +0000 2009





    Doug Williams


    San Francisco, CA

    Twitter API Support. Internet, greed, users, dougw ...











    Sun Mar 18 06:42:26 +0000 2007



    Eastern Time (US & Canada)










    Doug Williams


    North Carolina

    A character.











    Thu Jun 21 21:16:21 +0000 2007



    Eastern Time (US & Canada)








Notice that the sender and recipient are just user objects. It is worth mentioning that the direct_messages function return a list of direct_message objects (like the timeline functions that return list of status objects.)

Twitter and .NET

Now, you have a solid understanding of the Twitter API and how you can access it. Now, let's utilize this API into our .NET applications.

Accessing the API

To access the API from your .NET application you need to create a HTTP request and send it to the server and wait for server response. Let's consider an example. The following code snippet connects to the server and retrieves a System.Xml.XmlDocument that contains the returned data.

public static Main()



 public static XmlDocument GetResponse(string uri)

     WebRequest req = WebRequest.Create(new Uri(uri));

     XmlDocument doc = new XmlDocument();


     return doc;

We have used the System.Xml.WebRequest class to create the request and to get the response (as an instance of System.Xml.WebResponse class) from the server. Once we get the XmlDocument, we can walk through the data and retrieve it.


You can take one of two approaches to authorize Twitter users:
  • OAuth Authorization:
    An authentication protocol that allows users to approve application to act on their behalf without sharing their password. As this function requires more overhead and requires your application to be registered in the Twitter clients' directory, we would better use the second approach in our examples.
  • Request Authorization:
    To provide authentication information in each request you make to the server.
Considering a method like statuses/update method that updates the status information of the user (i.e. sends a tweet) we would develop our previous code to be like this:

public static void Main()


                     "elsheimy", "b@zzword", true);


public static XmlDocument GetResponse(string uri, string username, string password, bool post)

    WebRequest req = WebRequest.Create(new Uri(uri));

    if (post)

        req.Method = "POST";

    if ((username != null) && (username.Trim() != String.Empty) && (!String.IsNullOrEmpty(password)))

        req.Credentials = new NetworkCredential(username.Trim(), password);

    XmlDocument doc = new XmlDocument();


    return doc;


Notice how we set the HTTP method based on the function requirements. It is worth mentioning that a status should not exceed 140 UTF-8-encoded characters.

Encoding URIs

Have you noticed the previous code? It tries to post the update "hello from the API". Because the text is included with the URI, special handling to the text should be carried. This special handling for text included in URIs is usually called Percent-encoding or URL Encoding. This encoding replaces unsafe characters with their hexadecimal values preceded by percentage (%) signs. Unsafe characters are those somewhat conflicted with URI special characters. For example, if we would encode the text "hello from the API" we would end up with "hello%20from%20the%20API".

There are many unsafe characters that should be percent-encoded including $, +, &, :, and =. A nice discussion of URL Encoding can be found in the article URL Encoding by Brian Wilson.

Once we get the idea, we can create our percent-encoding class that encodes/decodes strings:

private static string[,] _chars = new string[,]


{ "%", "%25" },     // this is the first one

{ "$" , "%24" },

{ "&", "%26" },

{ "+", "%2B" },

{ ",", "%2C" },

{ "/", "%2F" },

{ ":", "%3A" },

{ ";", "%3B" },

{ "=", "%3D" },

{ "?", "%3F" },

{ "@", "%40" },

{ " ", "%20" },

{ "\"" , "%22" },

{ "<", "%3C" },

{ ">", "%3E" },

{ "#", "%23" },

{ "{", "%7B" },

{ "}", "%7D" },

{ "|", "%7C" },

{ "\\", "%5C" },

{ "^", "%5E" },

{ "~", "%7E" },

{ "[", "%5B" },

{ "]", "%5D" },

{ "`", "%60" } };

public static string EncodeUrl(string url)

    for (int i = 0; i < _chars.GetUpperBound(0); i++)

        url = url.Replace(_chars[i, 0], _chars[i, 1]);

    return url;


public static string DecodeUrl(string url)

    for (int i = 0; i < _chars.GetUpperBound(0); i++)

        url = url.Replace(_chars[i, 1], _chars[i, 0]);

    return url;


For clearness, we have included the encoded string of each character along with the character itself. You don't have to do this. You can convert the character to a number and just output the number in hex format.
Now we could change the code that updates the status to the following:

public static void Main()

    string uri;

    string text = UrlEncoder.EncodeUrl("hello from the API");

    uri = "http://api.twitter.com/1/statuses/update.xml?status=" + text;

    GetResponse(uri, "elsheimy", "b@zzwrd", true);


.NET includes a nice function that escapes (encodes) a URI, System.Uri.EscapeUriString() function. However, this function does not encode all unsafe characters.

Business Objects

Once you know the structure of the XML data returned, you can create your business objects that would encapsulate this data. The following are the three classes that would represent our three core objects, the user, the status, and the message.

public structure TwitterUser

     public long ID;

     public string Name;

     public string ScreenName;

     public string Location;

     public string Description;

     public string ProfileImage;

     public string Url;

     public bool IsProtected;

     public long FollowersCount;

     public long FriendsCount;

     public string CreatedAt;

     public long FavoritesCount;

     public bool Verified;

     public bool Following;

     public long StatusCount;


public structure TwitterStatus

     public string CreatedAt;

     public long ID;

     public string Text;

     public string Source;

     public bool Truncated;

     public long InReplyToStatusID;

     public long InReplyToUserID;

     public bool Favorited;

     public string InReplyToScreenName;

     public TwitterUser User;


public structure TwitterMessage

     public long ID;

     public long SenderID;

     public long SenderScreenName;

     public long RecipientID;

     public long RecipientScreenName;

     public string Text;

     public string CreatedAt;

     public TwitterUser Sender;

     public TwitterUser Recipient;


Retrieving Data

Now you can walk through the XML data and get that data inside your objects. The following code returns a list of statuses from your friends' timeline.

public static void Main()

    GetStatuses("elsheimy", "b@zzword");


public static List GetStatuses(string username, string password)

    XmlNode node = GetResponse("http://api.twitter.com/1/statuses/friends_timeline.xml",

        username, password, true);

    List lst = new List(node.ChildNodes.Count);

    foreach (XmlNode nd in node.ChildNodes)   // for each status


    return lst;


public static TwitterStatus HandleStatus(XmlNode nd)

    // HandleNumber, FormatText, HandleBool

    // are just functions that converts strings

    // to numbers, decoded strings, and bool

    TwitterStatus status = new TwitterStatus(











    return status;


public static TwitterUser HandleUser(XmlNode nd)

    // HandleNumber, FormatText, HandleBool

    // are just functions that converts strings

    // to numbers, decoded strings, and bool

    long id = HandleNumber(nd["id"]);

    TwitterUser user;

    user = new TwitterUser(
















    return user;


twittoo, Sample Application

, is our WinForms sample application that utilizes the Twitter API. This is just a very simple application with basic functionalities.


The following are snapshots of the application:

Figure 2 - twitto 0

Figure 3 - twitto 1

Figure 4 - twitto 2

Figure 5 - twitto 3

Figure 6 - twitto 4

Figure 7 - twitto 5


This application was created using C# and WinForms 2.0 technology; it allows the user to navigate through his friends' timeline, mentions, direct messages, retweets, and friends, and to update his status, reply to tweets, retweets, and to direct messages. Data is not refreshed automatically, the user have to click the "refresh" button. (You can create your own routine that creates a timer that updates the data automatically.)


As you see, the application uses just the Windows Common Controls all around the application; no 3rd party controls were used.
To represent a status, message, or a user, the application overuses the System.Windows.Forms.TableLayoutPanel control to represent each status, message, or user. It consists of four columns and two rows. The following figure shows how the control is laid-out.

Figure 8 - TableLayoutPanel Status Template

URL Shortening

twittoo, has a very nice feature, it allows the user to insert a shortened URL into his tweets. For this to work, the application makes use of http://is.gd URL shortening service. The following is the function that utilizes the http://is.gd API:

public static string Shorten(string url)

    if (!System.Text.RegularExpressions.Regex.IsMatch(url, @"(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"))

        throw new FormatException("The URL you specificed is not in the current format.");

    url = Uri.EscapeUriString(url);

    string reqUri = String.Format(Properties.Settings.Default.Api_UrlShortner, url);

    WebRequest req = WebRequest.Create(reqUri);

    req.Timeout = 5000;

    using (System.IO.StreamReader reader = new System.IO.StreamReader(req.GetResponse().GetResponseStream()))

        return reader.ReadLine();




Download twittoo; our sample application

 Subscribe to Articles


Further Readings:

Author: Nikhil Kumar         Company URL: http://www.dotnetspark.com
Posted Date: May 31, 2010

nice article... keep it up
Author: Mohammad Elsheimy         Company URL: http://www.dotnetspark.com
Posted Date: June 13, 2010

Thanks :)

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend