Twitter has long since announced that they will close down its old API in favor of a new one. Unfortunately, it made it a little harder for those of us who only want to search or look at a user’s tweets. Fortunately, there are two solutions on how to authenticate a app against Twitter, one of these, Application-only authentication, are easier to implement.

In this example, I will show how to search tweets and read a user’s timeline. This is implemented in a Portable Class Library so that it can be used on multiple platforms, especially Windows 8 and Windows Phone.

  1. Create an application key for your app with Twitter https://dev.twitter.com/apps and obtain:
    Customer key
    Customer secret
  2. Create a new solution for Windows 8 or Windows Phone 8.
  3. Add a Portable Class Library project named TwitterClientCore.
  4. Use NuGet with TwitterClientCore in order to add the Microsoft HTTP Client Libraries. (Search for Microsoft.Net.Http)
  5. Create a new class of TwitterClientCore called Twitter.
  6. Copy the code below.
  7. Add yours key and secret.
  8. Create a button in your Windows 8 or Windows Phone 7 project.
  9. Call Twitter. Search() in the buttons click event.

Code

public class Twitter
{
    public static async Task<Tuple<List<ExpandoObject>, List<ExpandoObject>>> Search()
    {
        Tuple<List<ExpandoObject>, List<ExpandoObject>> _return =
            new Tuple<List<ExpandoObject>, List<ExpandoObject>>(new List<ExpandoObject>(), new List<ExpandoObject>());

        const string oauthConsumerKey = "<your customer key>";
        const string oauthConsumerSecret = "<your customer secret>";
        string accessToken;

        // get authentication token
        HttpMessageHandler handler = new HttpClientHandler();
        HttpClient httpClient = new HttpClient(handler);
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://api.twitter.com/oauth2/token ");
        var customerInfo = Convert.ToBase64String(new UTF8Encoding().GetBytes(oauthConsumerKey + ":" + oauthConsumerSecret));
        request.Headers.Add("Authorization", "Basic " + customerInfo);
        request.Content = new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded");

        HttpResponseMessage response = await httpClient.SendAsync(request);

        var s = await response.Content.ReadAsStringAsync();
        var returnJson = JValue.Parse(s);
        accessToken = returnJson["access_token"].ToString();

        // get timeline for user buzzfrog
        HttpRequestMessage requestUserTimeline = new HttpRequestMessage(HttpMethod.Get, "https://api.twitter.com//1.1/statuses/user_timeline.json?count=100&screen_name=buzzfrog");
        requestUserTimeline.Headers.Add("Authorization", "Bearer " + accessToken);
        HttpResponseMessage responseUserTimeLine = await httpClient.SendAsync(requestUserTimeline);
        var returnJsonUserTimeline = JValue.Parse(await responseUserTimeLine.Content.ReadAsStringAsync());

        List<ExpandoObject> timeLineResult = _return.Item1;
        foreach (var token in returnJsonUserTimeline)
        {
            dynamic twitterObject = new ExpandoObject();
            twitterObject.from_user = token["user"]["name"].ToString();
            twitterObject.profile_image_url = token["user"]["profile_image_url"].ToString();
            twitterObject.text = token["text"].ToString();
            timeLineResult.Add(twitterObject);
        }

        // search for the string "wpdev"
        HttpRequestMessage requestSearch = new HttpRequestMessage(HttpMethod.Get, "https://api.twitter.com/1.1/search/tweets.json?count=100&q=wpdev");
        requestSearch.Headers.Add("Authorization", "Bearer " + accessToken);
        HttpResponseMessage responseSearch = await httpClient.SendAsync(requestSearch);
        var returnJsonSearch = JValue.Parse(await responseSearch.Content.ReadAsStringAsync());

        List<ExpandoObject> searchResult = _return.Item2;
        foreach (var token in returnJsonSearch["statuses"])
        {
            dynamic twitterObject = new ExpandoObject();
            twitterObject.from_user = token["user"]["name"].ToString();
            twitterObject.profile_image_url = token["user"]["profile_image_url"].ToString();
            twitterObject.text = token["text"].ToString();
            searchResult.Add(twitterObject);
        }

        return _return;
    }
}

I will not go through the code so closely. But here are some comments on it:

  • In this example I played with the Tuple class to be able to return two results from the method.
  • I also used dynamic to create objects on the fly. For me this was the fastest way to create the result.
  • I do three calls to twitter: 1) to get the authentication token 2) get info from a users timeline 3) do a search

Source Code for the example