Knowledge is power. We love to share it.

News related to Mono products, services and latest developments in our community.

mzilic

Using Twitter APIs from MonoX and ASP.NET

05/19/2012Categories: MonoX

Intro

In my last blog I've demonstrated how to use LinkedIn APIs. This time I'd like to demonstrate how to use another great tool which allows you to implement Twitter Integration.

If you head over to Twitter developers site you will see that you have several libraries at your disposal. Components I researched were:
LINQ to Twitter
Topsy's Otter API
Twitterizer
Twitterizer caught my attention for the very same reasons as LinkedIn Developer Toolkit, which we used for our LinkedIn integration. If you're curious about the reasons why we chose to use the LinkedIn Developer Toolkit, then please head over to the Using LinkedIn API from ASP.NET and MonoX article and read the section "Why choose LinkedIn Developer Toolkit?".

Also note that there is another library worth mentioning (which is equally good) called TweetSharp. I recommend that you check it out once you read this article.

Tweets and Twitter APIs introduction

Twitter can be described as a social networking service that enables its users to send text-based messages known as tweets. Tweets can be up to 140 characters long, so have that in mind when you tweet something from your application. Twitter uses OAuth protocol for authentication and it also supports REST HTTP requests.

Be sure to check out Twitters REST API. REST is an acronym for Representational State Transfer, however explaining REST in full detail is beyond the scope of this article.

Registering new Twitter application

Go to Twitter developers site and log in using your account.
Select My Applications option from the dropdown menu.
twitter
Click on the Create New Application button on the next screen and enter information about your application. Copy the Consumer Key and Consumer Secret Key. Make sure to keep these keys a secret.

Retrieving Access Token

Before we're able to do anything with our users account, we need to ask the user for permission to access their account. In order for us to do that, we need to build an authentication Url and redirect the user to the Twitter login page. Twitterizer handles this for us, we only need to pass on a few parameters such as the Consumer Key and Consumer Secret Key which we've obtained earlier while registering our application.

We also need to have in mind that we're going to tell Twitter to return us to the same page. Having that in mind, we need to differentiate initial request with a Twitter callback. So we handle that in the following sample by appending a query parameter to the callback Url:
public bool IsTwitterCallback
{
    get
    {
        bool isCallback = false;
        if (Request.QueryString["isCallback"] != null)
            bool.TryParse(Request.QueryString["isCallback"], out isCallback);
        return isCallback;
    }
}
 
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    try
    {
        if (!IsTwitterCallback)
        {
            // append the isCallback parameter
            OAuthTokenResponse tokenResponse = OAuthUtility.GetRequestToken(ApplicationSettings.TwitterAPIKey, ApplicationSettings.TwitterSecretKey, Request.Url.AbsoluteUri.Append("isCallback", true));
            Uri authenticationUri = OAuthUtility.BuildAuthorizationUri(tokenResponse.Token);
            Response.Redirect(authenticationUri.ToString());
        }
        else
        {
            // Get access token during callback and store it in session
            OAuthTokenResponse tokenResponse = OAuthUtility.GetAccessTokenDuringCallback(ApplicationSettings.TwitterAPIKey, ApplicationSettings.TwitterAPIKey);
            Session["TokenKey"] = tokenResponse.Token;
            Session["TokenSecretKey"] = tokenResponse.TokenSecret;           
            // redirect back to default page
            Response.Redirect("/Default.aspx");
        }
    }
    catch (Exception ex)
    {
        LogUtility log = new LogUtility();
        log.Error(ex);
    }
}

Posting a tweet

Once we have the access tokens it is pretty easy to post a tweet, just remember that the content must not exceed 140 characters. Here's how you can post a tweet:
private OAuthTokens GetAuthToken()
{
    if (Session["TokenKey"] != null &&
            Session["TokenSecretKey"] != null)
    {
        OAuthTokens authorization = new OAuthTokens();
        authorization.ConsumerKey = ApplicationSettings.TwitterAPIKey;
        authorization.ConsumerSecret = ApplicationSettings.TwitterSecretKey;
        authorization.AccessToken = Session["TokenKey"].ToString();
        authorization.AccessTokenSecret = Session["TokenSecretKey"].ToString();
        return authorization;
    }
    return null;
}
 
void tweet_Click(object sender, EventArgs e)
{
    OAuthTokens authorization = this.GetAuthToken();
    if (authorization != null)
    {
        try
        {
            var result = TwitterStatus.Update(authorization, "This is a test tweet");
            bool isPosted = result.Result == RequestResult.Success;
            if (isPosted)
            {
                // do action
            }
        }
        catch (Exception ex)
        {
            LogUtility log = new LogUtility();
            log.Error(ex);
        }
    }
}

Fetching user data

The profile data is returned in the JSON format so we need to deserialize it. Let's see how we can do that (this code sample fetches your own profile):
// fetch current users profile
OAuthTokens authorization = this.GetAuthToken();
if (authorization != null)
{
    var userData = TwitterAccount.VerifyCredentials(authorization);
    if (userData != null && userData.Result == RequestResult.Success)
    {
        // deserialize object                   
        TwitterUser user = Newtonsoft.Json.JsonConvert.DeserializeObject<TwitterUser>(userData.Content);
        // do something with data
    }
}

Conclusion

Twitterizer is a powerful tool which will save you a lot of time, while allowing you to use the full power of the Twitter APIs.
Rated 3.78, 9 vote(s). 
Can you share full code??
mzilic
Hello, I've updated the post with a sample project based on the blog post.

Regards,
Mario