Implementing oauth twitter search in C# and JSON


To implement twitter search in C# that uses oauth for authentication, first we need a C# oauth implementation, and a JSON parser for extracting results. For oauth implementation I’m using Twitter oAuth with .NET by Shannon whitley and for parsing the results JSON parser by Procurious and i have to say that this post is just a bit refined implementation of Parsing Twitter JSON data in C# by Jamie’s Digital Blog.

To get started with twitter needs you to authenticate your application before you could use twitter API’s search feature, to authenticate an application needs to initialize a oAuthTwitter object so that it is accessible through out the class like

oAuthTwitter oauth = new oAuthTwitter();
//Replace the vlues with the one's provided by twitter
oauth.ConsumerKey = "Your-twitter-oauth-consumerkey";
oauth.ConsumerSecret = "Your-twitter-oauth-consumersecret";
//Launches your default browser for requesting //authentication
System.Diagnostics.Process.Start(oauth.AuthorizationLinkGet());
//Copy the pin provided after you authenticating and save to a string
//I am assuming you store it in a string twitterpin
//Now the real authentication takes place
//you will exchange the authtoken and pin for Access token
oauth.AccessTokenGet(oauth.OAuthToken, twitterpin);
//remember twitterpin is the object in which we stored the //pin value

Now since we have obtained the authentication we can use this oAuth to search twitter

//Replace the term search_keyword with a term you want to search
//rpp=100 in the url means results per page is 100, and lang=en means
//Language is english
string result = oauth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://search.twitter.com/search.json", "q=" + search_keyword + "&rpp=100&lang=en");

Now we have the 100 search results stored in a string result in JSON format, we will use JSON parser for extracting the values of each tweet

//The following code is a straight copy from jamiedigi.com
HashTable jsonHash = (Hashtable)JSON.JsonDecode(jsonCode);
ArrayList jsonResults = (ArrayList)jsonHash["results"];
foreach (object objResult in jsonResults)
{
Hashtable jsonResult = (Hashtable)objResult;
System.Diagnostics.Debug.WriteLine("User ID: "
+ jsonResult["from_user_id"].ToString());
System.Diagnostics.Debug.WriteLine("Tweet text: "
+ jsonResult["text"].ToString());
System.Diagnostics.Debug.WriteLine("Tweet date: "
+ jsonResult["created_at"].ToString());
System.Diagnostics.Debug.WriteLine("User name: "
+ jsonResult["from_user"].ToString());
System.Diagnostics.Debug.WriteLine("Language: "
+ jsonResult["iso_language_code"].ToString())
}

You can download the complete source code along with oauth and JSON parser implementations from https://sites.google.com/site/coderbuddy/myReserach.zip?attredirects=0&d=1

You may need to make some modifications to the code like providing the consumer key and consumer secret before working with the code

8 thoughts on “Implementing oauth twitter search in C# and JSON

  1. Thanks a lot, this works! But it only works with the popup window that shows the PIN end then I enter the PIN manually into the program.

    Now I want to get it working without the PIN, but by directly using the Token and the TokenSecret:

    oAuthTwitter oauth = new oAuthTwitter();

    oauth.ConsumerKey = “HFb…”;
    oauth.ConsumerSecret = “1XRu…”;

    oauth.Token = “19305…”;
    oauth.TokenSecret = “ZJfOx6l…”;

    Tweets tweets = new Tweets(oauth);

    tweets.UpdateStatus(Tweets.ResponseFormat.XML, “My first tweet…”, null);

    Is that possible?
    Thx a lot!

    Like

    • PIN, is a necessary step in twitter OAUTH authentication, if you want to avoid it use XAUTH, it is not possible to avoid PIN using twitter oauth

      Like

  2. I am using oAuth only, If I click on “Allow” but after giving the username and password. The twitter does not show me the PIN instead of it goes to the call back URL mentioned or passed through arguments.

    But, it works fine for me for the first time without getting the PIN. It throws the exception as “401 unauthorized” when try to send the tweet to the twitter.

    Will you just give me the right information about getting the PIN?

    Like

    • You have not mentioned the type of your application, is it a desktop application ?, if it is a desktop application then select the application type as Client in your application settings at dev.twitter.com and remove the callback url, this will stop the twitter from redirecting the browser to the callback url, instead it will take you to the page where the pin will be displayed to you.

      However, if you want to use a callback url, for desktop applications you can do so by using oauth_callback=oob parameter.

      Reply back if you got anymore doubts

      Thank for sharing your thoughts, subscribe to this blogs feed if you like it

      Like

  3. Sorry for the inconvenient details provided by me.

    I am just creating a web application.

    Thanks for your information.

    I implemented all the functions without any errors.

    I stored the consumer key and the consumer secret from the registered application in Twitter.

    I got the access token and access token verifier from the query string received after clicking on “Allow” button giving my valid twitter account details and it returned back to my call back URL with a query consists oauth_token as well oauth_token_verifier and stored these values for later purpose.

    If I use the oauth_token and oauth_token_verifier for later for sending the tweets or after the first time verification. Get the exception as “401 unauthorized”. I know I did a small mistake but do not know where.

    Will you just explain me the basic details should be collected and stored for later purpose to avoid the authorization process again and again else avoiding the error “401 unauthorize”.

    I tried the followings also to diagnose the error and rectify it.

    1. Initially, I set http://localhose:xxxx/thepagename.aspx through code. It just over writes the call back URL set at the app setting in the twitter. I just removed this and executed also with the registered application in the www but exception arises.

    2. I just stored the nonce also since it is generated randomly and referred at the future access, but the exception arises even.

    So, I would like to know what details can be stored exactly for future references to avoid the authentication repeatedly unless the user revokes me from his twitter.

    Like

    • Have you url encoded the tweet before posting it, can you post the complete source code, so that I can suggest you a solution. If you don’t want to post it online, you can mail me personally to chowdarysway[at the rate]gmail.com.

      Like

Comments are closed.