Wednesday 19 June 2013

Twitter API Authentication -- OAuth v 1.1

You can use following class to get the Tweets from from Twitter API v 1.1 using the oAuth.  you should perform following steps.

 Step1:

Login your Developer account on twitter website by using following link.

https://dev.twitter.com/user/login

Step2:

Click on the My Applications on the user profile as shown in following pic.

 



Step3:

Click on the Create New Application button. Fill the form and save the information as shown in following figure

 



Step4:

It will display the list of your created applications as shown in following figure.. so select your application so select your application , it will show the consumer key and consumer secret as shown in following figure.




Step5:

 Use following code to get tweets.

Twitter OAuth is based on four tokens generally referred to as consumer key and consumer secret



public class ManageTweets
    {
        public string OAuthConsumerKey { get; set; }
        public string OAuthConsumerSecret { get; set; }
        public string OAuthUrl { get; set; }
                     
        public DataTable GetTweetsListFromTwitter()
        {

            DataTable dataTable =TweetsDataTable();
            var timeLineJson = string.Empty;
            var oAuthConsumerKey = OAuthConsumerKey;
            var oAuthConsumerSecret = OAuthConsumerSecret;
            var oAuthUrl = OAuthUrl;
           
          
            //var screenname = "yourscreenname";
            // Do the Authenticate
            var authHeaderFormat = "Basic {0}";

            var authHeader = string.Format(authHeaderFormat,
                 Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
                        Uri.EscapeDataString((oAuthConsumerSecret)))
                        ));

            var postBody = "grant_type=client_credentials";

            System.Net.HttpWebRequest authRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(oAuthUrl);
                        authRequest.Headers.Add("Authorization", authHeader);
            authRequest.Method = "POST";
            authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            authRequest.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate;

            using (System.IO.Stream stream = authRequest.GetRequestStream())
            {
                byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
                stream.Write(content, 0, content.Length);
            }

            authRequest.Headers.Add("Accept-Encoding", "gzip");

            System.Net.WebResponse authResponse = authRequest.GetResponse();
            // // deserialize into an object
            TwitAuthenticateResponse twitAuthResponse;
            using (authResponse)
            {
                using (var reader = new System.IO.StreamReader(authResponse.GetResponseStream()))
                {
                    var objectText = reader.ReadToEnd();
                    //objectText = objectText.Replace("{\"","");
                    //string[] arr = objectText.Split(':');
                    System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
                    twitAuthResponse = js.Deserialize<TwitAuthenticateResponse>(objectText);
                }
            }

            // Do the timeline
            var timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5";
            timelineUrl = string.Format(timelineFormat, screenname);

          

            System.Net.HttpWebRequest timeLineRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(
timelineUrl );
            if (!string.IsNullOrEmpty(ProxyURL))
            {
                timeLineRequest.Proxy = webproxy;
            }
            var timelineHeaderFormat = "{0} {1}";
            timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
            timeLineRequest.Method = "Get";
            System.Net.WebResponse timeLineResponse = timeLineRequest.GetResponse();

            using (authResponse)
            {
                using (var reader = new System.IO.StreamReader(timeLineResponse.GetResponseStream()))
                {
                    timeLineJson = reader.ReadToEnd();
                }

                Newtonsoft.Json.Linq.JArray jsonDat = Newtonsoft.Json.Linq.JArray.Parse(timeLineJson);

                for (int x = 0; x < jsonDat.Count(); x++)
                {
                    Newtonsoft.Json.Linq.JObject tweet = Newtonsoft.Json.Linq.JObject.Parse(jsonDat[x].ToString());
                    string created_at = tweet["created_at"].ToString();
                    string tweettext = tweet["text"].ToString();
                    string profile_image_url_https = tweet["user"]["profile_image_url_https"].ToString() ;
                    dataTable.Rows.Add(tweettext.Replace("\"", ""), profile_image_url_https.Replace("\"", ""), created_at.Replace("\"", ""));
                    //whatever else you want to look up
                }

            }
            return dataTable;
        }
      
        private DataTable TweetsDataTable()
        {
            DataTable tweetsTable = new DataTable();
            tweetsTable.Columns.Add("Tweet_Text", typeof(string));
            tweetsTable.Columns.Add("Department_Logo", typeof(string));
            tweetsTable.Columns.Add("createdAt", typeof(string));
            return tweetsTable;
        }

        public class TwitAuthenticateResponse
        {
            public string token_type { get; set; }
            public string access_token { get; set; }
        }
    }