Sunday 20 October 2013

Working with Twitter's REST API V1.1 Using LinqToTwitter

Introduction

This article explains how quickly and easily it is possible to post a status or a status with media to Twitter via LINQ to Twitter. At the time of this article, LINQ to Twitter version 2.1.9 was the latest.

Let's kick off and see some practical examples.

Step 1: Creating Twitter App

If you have done this before and if you are confident about application configurations, you can jump to Step 2.

Creating the app

Go to http://dev.twitter.com/apps and sign in.
Once you signed in, click on "Create a new application" button.
create a new application

Fill the application's details and click on "Create your Twitter Application" button right at the bottom of the page.
application detail
If you've created your twitter app successfully, you should see a page like below. The two important values that we need for our project development, Consumer Key and Consumer Secret values, can be found under Details tab oAuth Settings section.


Click on the Settings tab, and make sure that you filled the Callback URL(can be any link to start with), select Read and write Application Type and tick Allow this application to be used to sign in with Twitter and save (Update this Twitter application's settings) from the settings section.
settings
update settings

Step 2: Creating the Project (Visual Studio)

  1. Create an AsplNet Empty Web Application or Empty Web Site whichever is convenient for you.
  2. If you are on VS 2012, go to Tool > Library Package Manager > Package Manager Console and type Install-Package linqtotwitter in the opening window otherwise go here and download LinqToTwitter.dll file. Add a reference of this file to your project. If you are working on web sites instead, drag the downloaded .dll file to your site's bin folder. At this stage, you should have the following reference within your application bin.
    • LinqToTwitter.dll

Step 3: Adding a Test Page and an Image

  1. Add a new page and name it "Test.aspx"
  2. Add an image to your application root and name it test.jpg
  3. Go to the code behind page (Test.aspx.cs) and modify the code as follows.

    Code

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Globalization;
    using LinqToTwitter;
    namespace TwitterRestAPITest
    {
        public partial class Test : System.Web.UI.Page
        {
            private WebAuthorizer auth;
            private TwitterContext twitterCtx;
            protected void Page_Load(object sender, EventArgs e)
            {           
                IOAuthCredentials credentials = new SessionStateCredentials();
    
                if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
                {
                    credentials.ConsumerKey = "your consumer key";
                    credentials.ConsumerSecret = "your consumer secret";
                }
                if (Request.QueryString["oauth_token"] != null)
                {
                        string requestToken = Request["oauth_token"].ToString();
                        string pin = Request["oauth_verifier"].ToString();
                    
                }
                
                auth = new WebAuthorizer
                {                 
                    Credentials = credentials,
                    PerformRedirect = authUrl => Response.Redirect(authUrl),
                    
    
                };
                if (!Page.IsPostBack)
                {
                    auth.CompleteAuthorization(Request.Url);
                }
    
                if (Request.QueryString["oauth_token"] == null)
                {
                    auth.BeginAuthorization(Request.Url);
                }
                var twitterCtx = new TwitterContext(auth);
                string status = "Testing TweetWithMedia #Linq2Twitter " +
                DateTime.Now.ToString(CultureInfo.InvariantCulture);
                const bool PossiblySensitive = false;
                const decimal Latitude = StatusExtensions.NoCoordinate; 
                const decimal Longitude = StatusExtensions.NoCoordinate; 
                const bool DisplayCoordinates = false;
    
                string ReplaceThisWithYourImageLocation = Server.MapPath("~/test.jpg");
    
                var mediaItems =
                    new List
                    {
                        new Media
                        {
                            Data = Utilities.GetFileBytes(ReplaceThisWithYourImageLocation),
                            FileName = "test.jpg",
                            ContentType = MediaContentType.Jpeg
                        }
                    };
    
                Status tweet = twitterCtx.TweetWithMedia(
                    status, PossiblySensitive, Latitude, Longitude,
                    null, DisplayCoordinates, mediaItems, null);
    
                Response.Write("Your tweet has been published successfully: " + tweet.Text);
            }
           
        }
    }
    
    
  4. That is it! Run your page and see what happens. Don’t forget LinqToTwitter requires .net Framework 4
  5. Downlaod the Solution

Issues

If you encounter a problem or an error, go back to http://dev.twitter.com/apps and check whether your Twitter application settings are exactly as stated as step 1.


1 comment: