Introduction
This article explains how to fetch data of a particular Hashtag from Twitter using TweetSharp API in ASP.NET.
Background
- VS2013
- C#
Before moving forward we have to create an app in Twitter using the following steps:
Step 1: Login to twitter and go to
https://apps.twitter.com/ and you can see your apps if you have any, else click on
Create New App button
. You will be able to see application management window to create a new app. Here's the screenshot:
I have filled the form as per my requirements. You can change this as per your.
Accept the agreement and click
Create Your Twitter Application.
Step 2: Go to
Keys and Access Tokens Tab and you will see
Consumer Key (API Key) and
Consumer Secret (API Secret). Here's the screenshoot.
Step 3: Now scroll down and click on
Create my access token. You will see
Access Token and
Access Token Secret.
Step 4: I am showing data in console application.
- Go to Visual Studio and create a console application.
- Click Manage NuGet Packages.
- Search for tweetsharp and install it as per the following image:
Step 5: Add the following code in your class with main method. Refer the comments for better understanding.
- public static string _consumerKey = "my key";
- public static string _consumerSecret = "my key";
- public static string _accessToken = "my key";
- public static string _accessTokenSecret = "my key";
-
- static void Main(string[] args)
- {
- TwitterService twitterService = new TwitterService(_consumerKey, _consumerSecret);
- twitterService.AuthenticateWith(_accessToken, _accessTokenSecret);
-
- int tweetcount = 1;
- var tweets_search = twitterService.Search(new SearchOptions { Q = "#ItCanWait", Resulttype = TwitterSearchResultType.Popular });
-
- List<TwitterStatus> resultList = new List<TwitterStatus>(tweets_search.Statuses);
- foreach (var tweet in tweets_search.Statuses)
- {
- try
- {
-
-
-
-
-
-
-
-
-
-
-
-
- Console.WriteLine("Sr.No: " + tweetcount + "\n" + tweet.User.Name + "\n" + tweet.User.ScreenName + "\n" + "https://twitter.com/intent/retweet?tweet_id=" + tweet.Id);
- tweetcount++;
- }
- catch { }
- }
- Console.ReadLine();
- }
Now run the code you will see only 15 results.
You can change code line-12 as per the following code to get 100 results.
- var tweets_search = twitterService.Search(new SearchOptions { Q = "#ItCanWait", Resulttype = TwitterSearchResultType.Popular, Count = 100 });
Sometimes you may find the following error: Arithmetic operation resulted in an overflow because the count parameter has Integer value as per TweetSharp API and the Tweet Count is more than integer range in your hash tag.
To get over it remove Resulttype and Count.
Note:
- #ItCanWait is my hashtag as per my code, you can change it as per your requirement.
- Twitter API allows maximum 100 data at a time and 15 is the default.
- Change the Keys as per your Twitter App.