.NET Library for quick and easy Twitter integration

1 minute read

A few days ago I wanted to create a solution to automatically tweet new blog posts. Because I did not have enough time to write a custom component to communicate to twitter I started looking for a .NET Twitter library.

After some time I found a very simple and effective library named Twitterizer. With Twitterizer you can easily implement the OAuth security mechanism.

After adding the reference to the Twitterizer library I created a ItemEventReceiver that starts on the ItemAdded event. In that event I post the title and the url to twitter.

public override void ItemAdded(SPItemEventProperties properties)
{
    base.ItemAdded(properties);

    string message = string.Format(CultureInfo.InvariantCulture, "New post #msftplayground :{0} - {1}", ToTinyURLS(properties.Web.Site.Url, properties.ListItem), properties.ListItem.Title);

    //TODO Get OAuth from web
    OAuthTokens tokens = GetTwitterToken(properties);
    TwitterResponse<TwitterStatus> response = TwitterStatus.Update(tokens, message);
}

private OAuthTokens GetTwitterToken(SPItemEventProperties properties)
{
    OAuthTokens retVal = null;
    
    string consumerKeySecret = EncryptionUtility.DecryptedString(properties.Web.GetPropertyBagProperty(Constants.PropertyBagKeyConsumerKeySecret, string.Empty));
    string consumerKey = EncryptionUtility.DecryptedString(properties.Web.GetPropertyBagProperty(Constants.PropertyBagKeyConsumerKey, string.Empty));
    string accessToken = EncryptionUtility.DecryptedString(properties.Web.GetPropertyBagProperty(Constants.PropertyBagKeyAccessToken, string.Empty));
    string accessTokenSecret = EncryptionUtility.DecryptedString(properties.Web.GetPropertyBagProperty(Constants.PropertyBagKeyAccessTokenSecret, string.Empty));

    if (!string.IsNullOrEmpty(consumerKeySecret) | !string.IsNullOrEmpty(consumerKey) | !string.IsNullOrEmpty(accessToken) | !string.IsNullOrEmpty(accessTokenSecret))
    {
        retVal  = new OAuthTokens();
        retVal.AccessToken = accessToken;
        retVal.AccessTokenSecret = accessTokenSecret;
        retVal.ConsumerKey = consumerKey;
        retVal.ConsumerSecret = consumerKeySecret;
    }
    return retVal;

}