Monday, April 21, 2014

Consuming the Twitter API v1.1

A short tutorial on Consuming the Twitter API 1.1
Consuming Twitter API in Dot Net c#, using this you can collect tweets aggregate it to do some data-mining or for a simple widget on your website to display your recent tweets or tweets about any particular topic or entity. Here I shall show a simple way to search for tweets of a particular entity and display it on a GridView of a ASP.Net Application.



Twitter is an online social networking and microblogging service  that enables users to send and read short 140-character text messages, called "tweets"

Companies have already started using twitter as it is the new way to promote, connect and brand a company.
Why?? – Connecting with customers, InstantFeedBack, Latest News, Marketing etc

Why Twitter Analytics are Imp?
Analyzing your followers, your own activity, and what other people are talking about online are all smart ways to make sure you’re getting the most benefit out of your social media presence.
see what users are saying about your business or products, and monitor Twitter feedback as best as possible.




Twitter API v1.1 

Twitter bases its application programming interface (API) off the Representational StateTransfer (REST) architecture. 
By allowing third-party developers partial access to its API, Twitter allows them to create programs that incorporate Twitter's services.


Twitter supports a few authentication methods and with a range of OAuth authentication styles you may be wondering which method you should be using. When choosing which authentication method to use you should understand the way that method will affect your users experience and the way you write your application.




Initially Twitter had API v1 which was pretty much straight forward 
Where you constructed the url and pinged it to return ur result in JSON or XML

Then when the API was updated to v1.1 many third party apps were affected coz of it.
There are many reasons for this, like request limitations to prevent the abuse of the service.


In this article I shall focus on getting the data of a twitter home-timeline or a twitter search.

If you use the...
Send...
REST API
Streaming API

What can it do?


Steps
Create an twitter account
Head to dev.twitter.com/apps/ and log in using your Twitter ID and password. 

Click the Create a new application button and enter the name and description of your application. The website should be a page where you can download your code but, since you’re still writing it, enter your home page URL and change it later. Leave the callback URL blank.



Next
•Create an Access Token
Click the Create my access token button at the bottom of the Details tab on your application’s page. You’ll now see various strings against:

•OAuth: Consumer key
•OAuth: Consumer secret
•Token: Access token
•Token: Access token secret


Now coming to Visual Studio

Hope you got nugget Manager if not install it from extension manager

Create a ASP Application Project.

Go to Nuget Package Manager-> Package Manager Console

In the console that will appear at the bottom of VS type in
Install-Package TweetSharp

TweetSharpis a Twitter API library that greatly simplifies the task of adding Twitter to your desktop, web, and mobile applications. You can build simple widgets, or complex application suites using TweetSharp.


using TweetSharp; // In v1.1, all API calls require authentication

var service = new TwitterService(_consumerKey, _consumerSecret);
service.AuthenticateWith(_accessToken, _accessTokenSecret); 

Here we see we need to replace the keys and tokens which we had generated earlier from the twitter website.

var tweets = service.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions());
foreach (var tweet in tweets)
{
Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
}
You can try out this simple app on console, that will get all the statuses from your current timeLine


Here is my app , 
A simple web app with a gridView to hold the tweets. All tweets that contains "Bruce Wayne" are searched from twitter and displayed here.



The code:
Default.aspx.cs

using TweetSharp;


namespace Tweetz
{
    public class TweetAttribs {

        public string imageUrl { getset; }
        public string userName { getset; }
        public string tweetText { getset; }


}

    public partial class _Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            List<TweetAttribs> tweetsList = new List<TweetAttribs>();
            var service = new TwitterService("oHLA""OgKbtiOg");
            service.AuthenticateWith("22fwghS7T""HMEB5jvSVve");
            var options = new SearchOptions { Q = "Bruce Wayne"  };

            var tweets = service.Search(options);
            foreach (var tweet in tweets.Statuses)
            {
                TweetAttribs taObj = new TweetAttribs();
                taObj.userName = tweet.User.ScreenName;
                taObj.imageUrl = tweet.User.ProfileImageUrl;
                taObj.tweetText = tweet.Text;
                tweetsList.Add(taObj);
            }

            GridView1.DataSource= tweetsList.ToList();
           // GridView1.BackImageUrl = "http://9to5mac.files.wordpress.com/2012/07/screen-shot-2012-07-08-at-8-45-25-pm.png";
            GridView1.DataBind();

        }
    }
}

note:  The keys used are samples, please generate your own and then run the code.

Default.aspx
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:ImageField DataImageUrlField="imageUrl" HeaderText="Pic">
                </asp:ImageField>
                <asp:BoundField DataField="userName" HeaderText="ScreenName" />
                <asp:BoundField DataField="tweetText" HeaderText="Tweet" />
            </Columns>

        </asp:GridView>

References:
So just with a few lines of code and with some major help from tweet sharp we were able to fetch the info we wanted.
TweetSharp simplifies things a lot.         

No comments: