For most Windows Phone apps, sharing a status message on Twitter is quite simple. This is achieved by using the ShareStatusTask class in Microsoft.Phone.Tasks namespace, where the user can tweet from the Twitter account set up on the device. There could be a scenario where different users would need to login to that application. For instance, you play a game on a friend’s Windows Phone device and want to tweet your score. Since your Twitter account may not be setup on your friends device, the application could allow you to login with your Twitter id and tweet your score. This would require the application to authenticate the user before their score is tweeted.

Through this post I will illustrate how to integrate Twitter into your WP7 app, so that you can authenticate a user using OAuth and allow the authenticated user to send tweets.

Authenticating a user:

1.   To get started you would need to register your app on Twitter. You can get that done at https://dev.twitter.com/apps . You will need to fill in details like application name, description of application, application website and also the Call Back Url (DO NOT leave this field empty). Once you’ve created the application, give your application Read and Write access, by selecting ‘Read and Write’ from the ‘Application Type’ section in the settings tab of Application Description, so that you can tweet from your app. On completion you will receive a Consumer Key and Consumer Secret.

2.   Go to your Windows Phone application project or create a new one if required. Add the consumer key and secret to a class. For example, create a class called TwitterSettings.cs. Also add the call back url, that you would have entered while registering your app on Twitter, in the previous step, to this class.

3.   Use the Package Manager Console and add the TweetSharp package to your project from http://nuget.org/packages/TweetSharp. A simple way to do this is to type the command PM> Install-Package TweetSharp  in your Package Manager Console(go to ‘Tools’ in the Visual Studio menu bar, and select Package Manager Console under Library Package Manager).This command will add the required packages to your project. The Package Manager will also add any dependencies such as Hammock and Newtonsoft.Json.

4.   To your xaml page add Login button with name ‘btnLogin’, and web browser control with name ‘webBrowser1′, from the ToolBox. Set the Visibility property of the web browser control to ‘Collapsed’, so that we can make the browser visible only when the Login button is clicked.

5.   In the Login button click event, add code to make the web browser control visible, and to start the twitter authentication process. I have shown this below:

[sourcecode language=”csharp”]
private OAuthRequestToken requestToken;
private TwitterService twitterService;
public string AccessToken { get; set; }
public string AccessTokenSecret { get; set; }

private void btnLogin_Click(object sender, EventArgs e)
{
webBrowser1.Visibility = Visibility.Visible;
btnLogin.Visibility = Visibility.Collapsed;

var cb = new Action<OAuthRequestToken, TwitterResponse>(CallBackToken);
twitterService = new TwitterService(TwitterSettings.TwitterConsumerKey, TwitterSettings.TwitterConsumerSecret);
twitterService.GetRequestToken(TwitterSettings.TwitterCallbackUrl, CallBackToken);
}
[/sourcecode]

Then you define the callback method which you’ll use for getting the authentication URI and      navigate the browser to it. We can then call the GetRequestToken method and callback method      to get the request token. The callback method gets the required authentication URI and then            opens that URI in the web browser control. When we get the access token, access token       secret and the browser re-directs to the twitter website after successful authentication, we can       display a message that the user had been authenticated and can proceed.

[sourcecode language=”csharp”]
private void CallBackToken(OAuthRequestToken rt, TwitterResponse response)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
MessageBox.Show("Unable to connect to twitter!");
return;
}
Uri uri = twitterService.GetAuthorizationUri(rt);
requestToken = rt;
webBrowser1.Dispatcher.BeginInvoke(() => webBrowser1.Navigate(uri));
}

void CallBackVerifiedResponse(OAuthAccessToken at, TwitterResponse response)
{
if (at != null)
{
AccessToken = at.Token;
if (string.IsNullOrEmpty(AccessToken))
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Unable to authenticate");
return;
});
}
AccessTokenSecret = at.TokenSecret;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Authentication succesful!");
});
}
}

private void webBrowser1_Navigated(object sender, NavigationEventArgs e)
{
if (e.Uri.ToString().Contains(TwitterSettings.TwitterCallbackUrl+"?oauth_token"))
{
var cb = new Action<OAuthAccessToken, TwitterResponse>(CallBackVerifiedResponse);
var values = ParseQueryString(e.Uri.AbsoluteUri);
string verifier = values["oauth_verifier"];
twitterService.GetAccessToken(requestToken, verifier, CallBackVerifiedResponse);
webBrowser1.Visibility = Visibility.Collapsed;
return;
}
}

public static IDictionary<string, string> ParseQueryString(string query)
{
if (query.StartsWith("?")) query = query.Substring(1);
if (query.Equals(string.Empty))
{
return new Dictionary<string, string>();
}

var parts = query.Split(new[] { ‘&’ });

return parts.Select(
part => part.Split(new[] { ‘=’ })).ToDictionary(
pair => pair[0], pair => pair[1]
);
}
[/sourcecode]

Sending tweets:

1. Once the user has been authenticated, we can use TweetSharp library classes and the same AccessToken and AccessTokenSecret retrieved above to allow the user to tweet the message.

2. On the xaml page, we can add a textbox named ‘txtTweet’ and a button ‘btnTweet’. The user can enter the message to be tweeted in the textbox, and on the click event of the button       ‘btnTweet’ we can use the TwitterService method to send the tweet.

[sourcecode language=”csharp”]
private void btnTweet_Click(object sender, EventArgs e)
{
var service = new TwitterService(TwitterSettings.TwitterConsumerKey, TwitterSettings.TwitterConsumerSecret);
SendTweetOptions tweetOptions = new SendTweetOptions();
tweetOptions.Status = txtTweet.Text;
service.AuthenticateWith(AccessToken, AccessTokenSecret);
service.SendTweet(new SendTweetOptions { Status = txtTweet.Text }, (tweet, response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("You have successfully tweeted the message!");
});
}
});
}
[/sourcecode]

The acquiring of the access token and access token secret after a successful authentication is primary. These two keys can be used to perform all the Twitter related operations from your application, such as getting the user tweets, user mentions, user followers and so on.