Skip to main content

C# Console app that displays twitter feed using Linq To Twitter (using Single User Authorization)


I recently had to add a twitter feed to my existing ASP.NET MVC 4 application. All I had to do was pull the last 10 tweets for a given user. It took me a while (shamefully, 3 hours) to get it working so I thought of writing a simple tutorial that explains how to pull a twitter feed for a console app using LINQ to Twitter.

LINQ to Twitter is an open source 3rd party LINQ Provider for the Twitter micro-blogging service. It uses standard LINQ syntax for queries and includes method calls for changes via the Twitter API

What took me long to figure out was the way twitter has implemented authentication using OAuth. Before you do anything, make sure you read the Learning to use OAuth document.

In my example, I used Single User Authorization. Single User Authorization is designed for scenarios where you'll only ever have one account accessing Twitter. i.e. if your Web site does periodic Twitter updates, regardless of user or you have a server that monitors general information. 

Before we begin coding, we'll need to set-up this authorization scheme on twitter & generate certain tokens as shown below:

Start by creating a twitter account that your application will be using to access Twitter. This is easy-peasy. Log on to https://twitter.com/ and setup your account. I've created a dummy account for this (_roehit).

Once your account is setup, navigate to https://dev.twitter.com and sign in with your twitter credentails. 

You now need to create an application. This can be done at https://dev.twitter.com/apps by clicking "Create a new application".



You need to enter your application details. You need a Name, Description & a Website (Your application's publicly accessible home page). You can add a Callback URL but its not really required. (Note: The name can't include the word "twitter".)



Remember to agree to the terms and conditions.

You should now get directed to the application page. By default, the first tab ("Details" tab) is visible. You must click the "Api Keys" tab and then click the "Create my access token" button (you will need to scroll down). This in turn generates the access tokens (you may need to refresh the page). Your Keys and Access Tokens should now be available for use.







Once created, navigate to the "OAutth tool" tab to view your OAuth Settings. We will need the generated tokens for our applications. (Note: My tokens are crossed out to maintain their integrity.)

Take note of the following tokens as we will need these later:
  • Consumer key
  • Consumer secret
  • Access token
  • Access token secret


Now we begin coding. In this example we've created a simple C# console application.

Start by creating a new project. Choose the "Console Application" template. 

Use NuGet to add the linqtotwitter package to our application. 



And now add the code shown below:
/// <summary>
/// Controls the flow of the program.
/// </summary>
/// <param name="args">The args.</param>
static void Main(string[] args)
{
// This is a super simple example that
// retrieves the latest tweets of a given
// twitter user.

// SECTION A: Initialise local variables
Console.WriteLine("SECTION A: Initialise local variables");

// Access token goes here .. (Please generate your own)
const string accessToken = "Access token goes here .. (Please generate your own)";
// Access token secret goes here .. (Please generate your own)
const string accessTokenSecret = "Access token secret goes here .. (Please generate your own)";

// Api key goes here .. (Please generate your own)
const string consumerKey = "Api key goes here .. (Please generate your own)";
// Api secret goes here .. (Please generate your own)
const string consumerSecret = "Api secret goes here .. (Please generate your own)";

// The twitter account name goes here
const string twitterAccountToDisplay = "roeburg";


// SECTION B: Setup Single User Authorisation
Console.WriteLine("SECTION B: Setup Single User Authorisation");
var authorizer = new SingleUserAuthorizer
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
OAuthToken = accessToken,
OAuthTokenSecret = accessTokenSecret
}
};

// SECTION C: Generate the Twitter Context
Console.WriteLine("SECTION C: Generate the Twitter Context");
var twitterContext = new TwitterContext(authorizer);

// SECTION D: Get Tweets for user
Console.WriteLine("SECTION D: Get Tweets for user");
var statusTweets = from tweet in twitterContext.Status
where tweet.Type == StatusType.User &&
tweet.ScreenName == twitterAccountToDisplay &&
tweet.IncludeContributorDetails == true &&
tweet.Count == 10 &&
tweet.IncludeEntities == true
select tweet;

// SECTION E: Print Tweets
Console.WriteLine("SECTION E: Print Tweets");
PrintTweets(statusTweets);
Console.ReadLine();
}

/// <summary>
/// Prints the tweets.
/// </summary>
/// <param name="statusTweets">The status tweets.</param>
/// <exception cref="System.NotImplementedException"></exception>
private static void PrintTweets(IQueryable<Status> statusTweets)
{
foreach (var statusTweet in statusTweets)
{
Console.WriteLine(string.Format("\n\nTweet From [{0}] at [{1}]: \n-{2}",
statusTweet.ScreenName,
statusTweet.CreatedAt,
statusTweet.Text));

Thread.Sleep(1000);
}
}

This should now display the last 10 tweets for the specified user.

A copy of the project is available at http://1drv.ms/NPUIVW (download the Linq2Twitter zip). This is a Visual Studio 2013 Console Application with a target framework of .NET 4.5.1 using LinqToTwitter package verison 3.0.2.

Disclaimer: The code shown above is quite crude & includes no error handling of any sort. This is just to give you a starting point. You can extend the functionality as you desire.





Comments

  1. This worked. I'd been struggling with the PIN-based OAuth flow but SingleUserAuthorizer is what I needed. Thanks!

    ReplyDelete
  2. "Timestamp out of bounds" in "foreach (var statusTweet in statusTweets)". You know what's wrong?

    ReplyDelete
  3. hi,
    I have used WebAuthorizer from LinqToTwitter, & added all the following things:
    accessToken, accessTokenSecret, consumerKey, consumerSecret
    But this is working for my login only.
    How do i get twitter login form? Can u plz guide me?

    ReplyDelete
    Replies
    1. Hi Shruti, Apologies for my tardy response but (and I might be wrong) I think what you're looking for is Pin Based authorisation. Have a look .. http://linqtotwitter.codeplex.com/discussions/468301 https://linqtotwitter.codeplex.com/wikipage?title=Implementing%20OAuth%20for%20Desktop%20Applications

      Delete
  4. Something changed in the package. "Credentials " does not work in the following example

    Credentials = new InMemoryCredentials
    {
    ConsumerKey = consumerKey,
    ConsumerSecret = consumerSecret,
    OAuthToken = accessToken,
    AccessToken = accessTokenSecret
    }

    ReplyDelete
    Replies
    1. Looks like with the newer version of LinqToTwitter the API has changed. This should now work ..

      var authorizer = new SingleUserAuthorizer
      {
      CredentialStore = new InMemoryCredentialStore
      {
      ConsumerKey = consumerKey,
      ConsumerSecret = consumerSecret,
      OAuthToken = accessToken,
      OAuthTokenSecret = accessTokenSecret
      }
      };

      Delete
  5. Hi
    not working
    incompatible project error..... :(

    ReplyDelete
  6. I have updated the post to work with LinqToTwitter 3.0.2.

    A copy of the project source code is available at http://1drv.ms/NPUIVW (download the Linq2Twitter zip). This is a Visual Studio 2013 Console Application with a target framework of .NET 4.5.1 using LinqToTwitter package verison 3.0.2.

    Note: Please use your own api keys.

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. How do I post a new tweet using this lib/?

    ReplyDelete
  9. Thanks, worked perfect! Got me started with LinqToTwitter :-)

    ReplyDelete
  10. Thank you very much! I was trying to display tweets from a protected account and this did the trick!

    ReplyDelete
  11. System.AggregateException in the foreach :(
    Help Me please

    ReplyDelete
    Replies
    1. Did you find a solution? I'm having the same problem.

      Delete
  12. What a lifesaver! Exactly what I needed. And I wasted time on Twitterizer (that doesn't seem to work with API 2 at the moment) and other overcomplicated solutions.
    Thanks a lot, Rohit!

    ReplyDelete
  13. How to follow user using another account(who is logged in)ie. key is for X
    have to follow for y->z

    ReplyDelete

Post a Comment

Popular posts from this blog

Internet Information Services(IIS) reveals its real or internal IP Address

In the ever changing world of global data communications, inexpensive Internet connections, and fast-paced software development, security is becoming more and more of an issue. Security is now a basic requirement because global computing is inherently insecure.

Keeping that in mind, we recently ran our flagship product through a security audit. It was such a helpful exercise in tying-off any remaining lose ends in our application in terms of application security. 
Based on the security audit report, there was a relatively minor issue that appeared when accessing the /images directory of our application. Turns out that the Location response header of the 301 request returns an Internal IP address. The issue is detailed below.

Issue reportedInternet Information Services (IIS) may reveal its real or internal IP address in the Location header via a request to the /images directory. The value returned whilst pen testing is https://10.0.0.10/images.

The riskInformation regarding internal IP add…

IIS Request Filtering to block HTTP Verbs (For example Trace)

The issueRequest Filtering is a built-in security feature that was introduced in Internet Information Services (IIS) 7.0. This can be used to block specific verbs like "Trace".

When request filtering blocks an HTTP request, IIS 7 will return an HTTP 404 error to the client and log the HTTP status with a unique substatus that identifies the reason that the request was denied. Verb Denied.

HTTP SubstatusDescription404.5URL Sequence Denied404.6Verb Denied404.7File Extension Denied404.8Hidden Namespace404.1Request Header Too Long404.11URL Double Escaped404.12URL Has High Bit Chars404.13Content Length Too Large

Unit Testing HttpContext.Current.Session in MVC3 .NET

We recently changed some functionality where during the "CREATE" process, we go through a wizard to save application data. This data is saved only to the session in the final step when the user clicks the final submit.

This was easy enough to implement but when I started writing unit tests for my static methods that Add, Update, Delete or Modify the contents of our application data in the session, I got the following error:
System.NullReferenceException: Object reference not set to an instance of an object.

Turns out I had forgotten to setup the HttpContext.
The following "TestInitialise" method fixed my problem :)

[TestInitialize]
public void TestSetup()
{
// We need to setup the Current HTTP Context as follows:

// Step 1: Setup the HTTP Request
var httpRequest = new HttpRequest("", "http://localhost/", "");

// Step 2: Setup the HTTP Response
var httpResponce = new HttpResponse(new StringWriter());

// Step 3: Se…