Thursday, 17 October 2013

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

Introduction

This article explains how quickly and easily it is possible to post a status or a status with media to Twitter via TweetSharp. At the time of this article, TweetSharp version 2.3.1 was the latest. Make sure that you have the full package added to your project. TweetSharp has a dependancy on Newtonsoft.Json and it also works with Hammock Client Profile.

If you would like to know how to use NuGet libraries in your projects, please refer NuGet Overview.
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 TweetSharp in the opening window otherwise go here and download the .dll files explained in the introduction above. Add references of these files to your project. If you are working on web sites instead, drag the downloaded .dll files to your site's bin folder. At this stage you should have the following three references within your application bin.
    • Hammock.ClientProfile
    • Newtornsoft.Json
    • TweetSharp

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.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using System.Drawing;
    using TweetSharp;
    
    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var oauth_consumer_key = "replace this with your twitter application consumer key";
            var oauth_consumer_secret = "replace this with your twitter application consumer key";
    
            string dbToken = string.Empty;
            string dbSecret = string.Empty;
    
            //the assumption here is your application has members
            //check whether an authenticated member has twitter access token and secret within our local database; 
            //for now let's say there is no in db ==> hasTokensInDb = false
            bool hasTokensInDb = false; //GetMembersTwitterTokenFromDb(ref string dbToken, ref string dbSecret);
            var service = new TwitterService(oauth_consumer_key, oauth_consumer_secret);
    
            if (hasTokensInDb)
            {
                service.AuthenticateWith(dbToken, dbSecret);
                DoWhatThisAppNeedToDo(ref service); 
            }
            else
            {
                //if oauth_token is null (i.e. if we haven't sent a token request to twitter yet, 
                //then send a get token request by addressing the this page as a callback (Request.Url.AbsoluteUri)
    
                if (Request["oauth_token"] == null)
                {               
                    OAuthRequestToken requestToken = service.GetRequestToken(Request.Url.AbsoluteUri);
                    Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}", requestToken.Token));
                   
                }
                else
                {
                    string requestToken = Request["oauth_token"].ToString();
                    string pin = Request["oauth_verifier"].ToString();
                    // Using the values Twitter sent back, get an access token from Twitter
                    var accessToken = service.GetAccessToken(new OAuthRequestToken { Token = requestToken }, pin);
                    // Use that access token and send a tweet on the user's behalf
                    if (accessToken != null && !string.IsNullOrEmpty(accessToken.Token) && !string.IsNullOrEmpty(accessToken.TokenSecret))
                    {
                        service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
                        UpdateDatabase(accessToken.Token, accessToken.TokenSecret);
                        DoWhatThisAppNeedToDo(ref service);                                             
                    }
                }
            }
        }
    
        private void UpdateDatabase(string token, string secret)
        { 
            //do database updates
        }
        private void DoWhatThisAppNeedToDo(ref TwitterService tService)
        {
            //if you want status update only uncomment the below line of code instead
            //var result = tService.SendTweet(new SendTweetOptions { Status = Guid.NewGuid().ToString() });
            Bitmap img = new Bitmap(Server.MapPath("~/test.jpg"));
            if (img != null)
            {
                MemoryStream ms = new MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Seek(0, SeekOrigin.Begin);
                Dictionary<string, Stream> images = new Dictionary<string, Stream>{{"mypicture", ms}};
                //Twitter compares status contents and rejects dublicated status messages. 
                //Therefore in order to create a unique message dynamically, a generic guid has been used
    
                var result = tService.SendTweetWithMedia(new SendTweetWithMediaOptions { Status = Guid.NewGuid().ToString(), Images = images });
                if (result != null && result.Id > 0)
                {
                    Response.Redirect("https://twitter.com");
                }
                else
                {
                    Response.Write("fails to update status");
                }
            }
        }
    
    }
    
  4. That is it! Run your page and see what happens. Don’t forget TweetSharp requires .net Framework 4
  5. Download 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:

  1. Hello,

    Thank you for this article, I know it's not friendly to do that, but I have a little problem with tweetsharp.

    I use "tweetsharp" last year, with vesrion of the time and not the latest version 2.5.1

    I try to obtain last version of dll on framework 2.0 and 3.5 but I work with VS Studio 2008.

    Could you send me these files (only dll and dll dependacy as json......) for framework 2.0 and 3.5.

    my mail is JP_BELMONDO_59 AT Yahoo.fr

    Thanks to help me :-)

    ReplyDelete