2

I have been searching for the most current method for posting a tweet on behalf of a user in Webforms. Most of the information I've come across dates to around 2010 and involves Twitterizer, which is no longer supported by the Twitter API. My question is, is there any updated documentation or examples, tutorials on the subject?

I've created my app, have the consumer key and secret, but most of the code I'm coming across is in php. Any help would be appreciated.

Rex_C
  • 2,436
  • 7
  • 32
  • 54
  • 1
    I've posted an answer on how to authenticate and use their api. May be of some use to you. http://stackoverflow.com/questions/17067996/authenticate-and-request-a-users-timeline-with-twitter-api-1-1-oauth/17071447#17071447 – hutchonoid Nov 26 '13 at 20:32
  • Are you using WebForms or MVC? I support LINQ to Twitter: https://linqtotwitter.codeplex.com/ which lets you use any type of OAuth offered by Twitter. I can answer with an example of how it works once I know what you're using. – Joe Mayo Nov 27 '13 at 05:43
  • The site was built with webforms. – Rex_C Nov 27 '13 at 17:18

1 Answers1

1

Since you're using WebForms (via your reply in comments), here's an example of tweeting on another user's behalf with LINQ to Twitter. Other examples might show you how to add a signature to an authorization header, but you'll still have to manage the OAuth workflow. This should give you an idea of how that workflow can be managed in WebForms.

LINQ to Twitter uses different authorizers to manage the process of producing OAuth signatures, managing credentials, and supporting OAuth workflow. First, instantiate a WebAuthorizer, like this:

public partial class _Default : 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 = ConfigurationManager.AppSettings["twitterConsumerKey"];
            credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
        }

        auth = new WebAuthorizer
        {
            Credentials = credentials,
            PerformRedirect = authUrl => Response.Redirect(authUrl)
        };

The WebAuthorizer only needs your ConsumerKey and ConsumerSecret, which can be saved in web.config. The authorization process is divided into two parts because you have to send the user to Twitter to authorize your app and then Twitter redirects the user back to your page to collect the other two tokens, which are oauth_token and access_token. That means you need logic to handle the callback from Twitter, which could look like this:

        if (!Page.IsPostBack && Request.QueryString["oauth_token"] != null)
        {
            auth.CompleteAuthorization(Request.Url);
        }

This goes after you instantiate WebAuthorizer and makes sure you're processing a Twitter callback before performing completion. After you call CompleteAuthorize, go into auth.Credentials and grab the new user credentials and save them for the logged in user. On subsequent queries, you can then load all 4 credentials into WebAuthorizer and LINQ to Twitter will work without requiring the user to authorize your application again.

After you have credentials, you can instantiate a TwitterContext, which gives you access to the Twitter API. Here's an example that does that and performs a query:

        if (auth.IsAuthorized)
        {
            twitterCtx = new TwitterContext(auth);

            var search =
                (from srch in twitterCtx.Search
                 where srch.Type == SearchType.Search &&
                       srch.Query == "LINQ to Twitter"
                 select srch)
                .SingleOrDefault();

            TwitterListView.DataSource = search.Statuses;
            TwitterListView.DataBind(); 
        }

This code follows the call to auth.CompleteAuthorize to make sure all credentials are populated. The auth.IsAuthorized verifies that all 4 credentials are present.

That was the completion and instantiation of the TwitterContext part, but you'll first need to start the oauth process. Here's a button click handler that does that:

    protected void authorizeTwitterButton_Click(object sender, EventArgs e)
    {
        auth.BeginAuthorization(Request.Url);
    }

Just call BeginAuthorization, which executes the callback assigned to the PerformRedirect property of WebAuthorizer, sending the user to Twitter to authorize your app. As mentioned earlier, Twitter redirects the user back to your page and CompleteAuthorization executes to finish the authorization process. I typically put the OAuth logic on a separate page to simplify things.

Once the user authorizes your app, you can execute any query you want, such as the method below that tweets some text for the user:

    protected void postUpdateButton_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;
        }

        twitterCtx.UpdateStatus(updateBox.Text);
        updateBox.Text = string.Empty;
    }

Tip: the SessionStateCredentials stores credentials in session state. So, you want to make sure you're using state server, SQL server, but definitely not InProc.

There's documentation on the LINQ to Twitter site at CodePlex.com and a working demo in the LinqToTwitterWebFormsDemo in the downloadable source code.

Joe Mayo
  • 7,501
  • 7
  • 41
  • 60
  • Say that this functionality was to go into a service, how would you handle the redirects in that case? – Rex_C Dec 02 '13 at 17:57
  • OAuth was intrinsically built for the Web (allowing users to authorize your app to operate on their behalf). So, other schemes need a different approach. In the case of a service (Web or Windows), my use case is normally single-user. So, you can use SingleUserAuthorizer or ApplicationOnlyAuthorizer, both requiring all 4 OAuth tokens. The redirects only need to happen the first time the user authorizes your app. If you don't go with the previous options, you can then save the tokens and send the tokens to the service. – Joe Mayo Dec 02 '13 at 23:38
  • Are there any examples that you could link me to in relation to this? – Rex_C Dec 03 '13 at 19:56
  • You can download the source code at https://linqtotwitter.codeplex.com/ - the LinqToTwitterDemos project has examples of all the authorizers. Most are also documented. In addition to L2T documentation, the Twitter dev site at https://dev.twitter.com/docs/auth has more explanations of which OAuth method to use too and more. – Joe Mayo Dec 04 '13 at 03:45