With Twitter integration, users can share app content on their timeline. For example, on multimedia apps a user can tweet the song he is listening to, or if the app is a game, a new unlocked achievement can be tweeted. Integrating Twitter to your app will help it stand out and enable users to promote it.
Step 1: Visual Studio Project Creation
To begin, we need to create a new project on Visual Studio. For this tutorial we need a simple app, so select the “Windows Phone App” option:
If you are using Visual Studio 2012 with the new WP8 SDK, you will be asked about the Target Windows Phone OS Version. If that’s the case, select the 7.1 OS.
Step 2: Building the UI
Now that the project is created, open the “MainPage.xaml” file, if it isn’t already open, and change the default application and page name text box:
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="WP7 Tutorial" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="Twitter" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel>
Now in the ContentPanel Grid add two rows, one for a TextBox where the user will input the new status, and the other for the button to submit the status:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition Height="auto"/> </Grid.RowDefinitions> </Grid>
Then add a TextBox on the first row with the name “Message” and a button on the second row:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition Height="auto"/> </Grid.RowDefinitions> <TextBox Grid.Row="0" Height="150" Name="Message" TextWrapping="Wrap"/> <Button Grid.Row="1" Content="Tweet"/> </Grid>
At the end you should have this:
Step 3: Creating a Twitter Developer Account
In order to connect to Twitter, you will first need a developer account. Go to the Twitter developer homepage and login with your Twitter account, or create one if you don’t have one already.
Step 4: Registering the New App
Once you are logged in, go to the “My Applications” page, and then click on the “Create a new application” button. On the following page fill in the Application Details, and if you already have a web site, input your site at the Website and Callback URL fields. Otherwise, use a placeholder like “http://www.google.com”. After this step a new page will appear giving you two tokens, the “Access token” and the “Access token secret”. Copy these codes and add them as constant strings on top of your “MainPage.xaml.cs” constructor:
private const string consumerKey = "your key here"; private const string consumerSecret = "your secret here"; // Constructor public MainPage() { InitializeComponent(); }
Step 5: Introduction to Tweetsharp
Twitter has a complete API that allows you to connect your app to the service in several ways. It is clear and easy to follow, so it is a great add-on to any app. Note that the authentication API is built using OAuth, which makes it very safe, but gives developers trouble connecting to the API. The steps to connect to the API are explained on the OAuth Documentation of the API. There are different ways to connect, but in this tutorial we are going to use the 3 legged authorization. This method asks for a Request Token, then takes the user to a login page and collects the AccessToken. This process can be a little bit complicated, especially if you are trying to add just one or two features of the API. Fortunately, there is a library developed by Daniel Crenna called Tweetsharp. Tweetsharp is a great tool that will simplify communication between your WP7 Apps and Twitter. It is very simple to use and gives you access to the entire Twitter API from just one library:
TweetSharp is a Twitter API library that simplifies the task of adding Twitter to your desktop, web, and mobile applications. You can build simple widgets or complex application suites using TweetSharp.
You can find more information about the project by going to their website and looking through the hosted example projects.
Step 6: Downloading Tweetsharp
The library is only available through NuGet, so in case your Visual Studio doesn’t include the NugGet Package manager, you need to download it from the NuGet homepage. In order to download the package, open the Package Manager Console in Visual Studio (Tools>Library Package Manager>Package Manager Console), and enter the following command:Install-Package TweetSharp
.
Step 7: Adding Tweetsharp to the Project
Now that we have the library, we can add it to our project. Add a new import on the “MainPage.xaml.cs” file:
using Tweetsharp
Step 8:Adding a Browser
In order to connect an app to a user’s Twitter account, we must first be given access and permission to the Twitter account. This is done through Twitter’s webpage. Therefore, we need to add a web browser. The browser should cover most of the page, so initially it will be collapsed, and then change to visible only when the user needs to login. In the “MainPage.xaml” file add a new WebBrowser just below the ContentPanel:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition Height="auto"/> </Grid.RowDefinitions> <TextBox Grid.Row="0" Height="150" Name="Message" TextWrapping="Wrap"/> <Button Grid.Row="1" Content="Tweet"/> </Grid> <phone:WebBrowser Name="Browser" Grid.Row="1" Background="Aqua" Width="450" Height="600" Visibility="Collapsed"/>
Step 9: Connecting to Twitter
Now that we have added Tweetsharp and the web browser, we can continue and connect our app to Twitter. The connection is done through a TwitterService object. Therefore we need to create a private global variable and initialize it on the constructor:
private TwitterService client; // Constructor public MainPage() { InitializeComponent(); client = new TwitterService(consumerKey, consumerSecret); }
Step 10: Adding the Click Event
The first time that a user clicks on your “Tweet” button, you must send him to the Twitter login page so he can give you the necessary permission for your app. To do this, ask for a RequestToken. Once you have the token, go to the login page. First, you need to add the click event on your Click button:
<Button Grid.Row="1" Content="Tweet" Click="tweetClick" />
Now add that method to the code:
private void tweetClick(object sender, RoutedEventArgs e) { // Ask for the token }
Before we can add the code for the token we need two things, a boolean variable telling us if the user is already logged in, and a variable that will save the RequestToken. Let’s add this to the code above the constructor:
private OAuthRequestToken requestToken; private bool userAuthenticated = false;
Step 11: Processing the RequestToken
With the variables ready, we can go and create the method for processing our RequestedToken. This will check for errors. If everything was done correctly, then save the token and take the user to the login URL from the RequestToken:
private void processRequestToken(OAuthRequestToken token, TwitterResponse response) { if (token == null) Dispatcher.BeginInvoke(() => { MessageBox.Show("Error getting request token"); }); else { requestToken = token; Dispatcher.BeginInvoke(() => { Browser.Visibility = System.Windows.Visibility.Visible; Browser.Navigate(client.GetAuthorizationUri(requestToken)); }); } }
Now add the code to request the Token inside the Click event method:
//If user is already logged in, just send the tweet, otherwise get the RequestToken if (userAuthenticated) //send the Tweet, this is just a placeholder, we will add the actual code later Dispatcher.BeginInvoke(() => { MessageBox.Show("Placeholder for tweet sending"); }); else client.GetRequestToken(processRequestToken);
Step 12: Adding Navigated Event
After the user logs in and accepts our app, Twitter will take us to a URL containing a verifier code that we need in order to request the AccessToken. Let’s add this event method to our browser
<phone:WebBrowser Name="Browser" Grid.Row="1" Background="Aqua" Width="450" Height="600" Visibility="Collapsed" Navigated="browserNavigated"/>
Use the event code:
private void browserNavigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { }
In order to retrieve the verifier code from the URL we need a parser, which in this case is a method that is on the Hammock extensions library. Copy this code and add it to your project:
// From Hammock.Extensions.StringExtensions.cs public static IDictionary<string, string> ParseQueryString(string query) { // [DC]: This method does not URL decode, and cannot handle decoded input 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] ); }
With this method we can go and get the verifier code on the browserNavigated event method:
private void browserNavigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { if (e.Uri.AbsoluteUri.Contains("oauth_verifier")) { var values = ParseQueryString(e.Uri.AbsoluteUri); string verifier = values["oauth_verifier"]; //getTheAccessToken Dispatcher.BeginInvoke(() => { Browser.Visibility = System.Windows.Visibility.Collapsed; }); } }
Step 13: Processing the AccessToken
Just like with the RequestToken, we have to create a method that handles the result of the AccessToken request. Once we receive the result we must check for errors. If the request was done successfully, we then authenticate the user, and send the Tweet:
private void processAccessToken(OAuthAccessToken token, TwitterResponse response) { if (token == null) Dispatcher.BeginInvoke(() => { MessageBox.Show("Error obtaining Access token"); }); else { client.AuthenticateWith(token.Token, token.TokenSecret); userAuthenticated = true; //Send the Tweet, we will add this code later } }
With this completed, go to the browserNavigated method and change the getTheAccessToken comment with the following line:
client.GetAccessToken(requestToken, verifier, processAccessToken);
Step 14: Handling a Tweet Response
When we send a Tweet we want to know if it was successfully sent. That’s why we need another method to handle a Tweet. Here’s the code that we need to add:
private void tweetResponse(TwitterStatus tweet, TwitterResponse response) { if (response.StatusCode == HttpStatusCode.OK) Dispatcher.BeginInvoke(() => { MessageBox.Show("Tweet posted successfully"); }); else Dispatcher.BeginInvoke(() => { MessageBox.Show("Error, please try again later"); }); }
Finally, go and change the Send Tweet comment on the processAccessToken and tweetClick methods with the following line:
Dispatcher.BeginInvoke(() => client.SendTweet(Message.Text, tweetResponse));
Step 15: Testing Your App
Right now your app should be completely functional, so go and test it. Enter any message click on the “Tweet” button and the following screen should appear.
After that, a message saying “Tweet posted successfully” should appear:
If you go to the Twitter account, you should also be able to see the Tweet you just sent:
Congratulations! You now have an app that can connect to Twitter! But we haven’t finished yet. There are some areas we can improve.
Step 16: Saving the AccessToken
Every time a user opens your app, he will have to go through the Twitter login page. This is something users don’t like. They want to register once and be able to Tweet without trouble. This problem is easy to solve. We need to save the AccessToken that we obtained the first time the user logs in. Once that is completed, it’s saved on IsolatedStorage and will always be accessible. This can be done by using the following method:
private void saveAccessToken(OAuthAccessToken token) { if (IsolatedStorageSettings.ApplicationSettings.Contains("accessToken")) IsolatedStorageSettings.ApplicationSettings["accessToken"] = token; else IsolatedStorageSettings.ApplicationSettings.Add("accessToken", token); IsolatedStorageSettings.ApplicationSettings.Save(); }
And importing the IsolatedStorage library:
using System.IO.IsolatedStorage;
Now we can save the obtained AccessToken from the processAccessToken method:
private void processAccessToken(OAuthAccessToken token, TwitterResponse response) { if (token == null) Dispatcher.BeginInvoke(() => { MessageBox.Show("Error obtaining Access token"); }); else { client.AuthenticateWith(token.Token, token.TokenSecret); saveAccessToken(token); userAuthenticated = true; Dispatcher.BeginInvoke(() => client.SendTweet(Message.Text, tweetResponse)); } }
Step 17: Retrieving the AccessToken
With the token already on IsolatedStorage, we need a method to retrieve it. Go ahead and add the following method:
private OAuthAccessToken getAccessToken() { if (IsolatedStorageSettings.ApplicationSettings.Contains("accessToken")) return IsolatedStorageSettings.ApplicationSettings["accessToken"] as OAuthAccessToken; else return null; }
This function should be called from the constructor because we want to be logged in from the very beginning:
// Constructor public MainPage() { InitializeComponent(); client = new TwitterService(consumerKey, consumerSecret); //Chek if we already have the Autehntification data var token = getAccessToken(); if (token != null) { client.AuthenticateWith(token.Token, token.TokenSecret); userAuthenticated = true; } }
Step 18: Checking Expired Tokens
Additionally take into account that the user may reject the permission of our app, so we need to detect this and ask for permission again. This detection should be done on our tweetResponse method, since that’s where Twitter notifies you of any problem with your post. Change the code from tweetResponse to the following:
private void tweetResponse(TwitterStatus tweet, TwitterResponse response) { if (response.StatusCode == HttpStatusCode.OK) { Dispatcher.BeginInvoke(() => { MessageBox.Show("Tweet posted successfully"); }); } else { if (response.StatusCode == HttpStatusCode.Unauthorized) { saveAccessToken(null); userAuthenticated = false; Dispatcher.BeginInvoke(() => { MessageBox.Show("Authentication error"); }); } else Dispatcher.BeginInvoke(() => { MessageBox.Show("Error, please try again later"); }); } }
Step 19: Modify the Back Button
One last feature to add to your app is to allow the user to close the browser if he wants to. Right now if the browser appears, the only way to close it is by logging in or with an error. You can give the user this option by using the back button:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { if (Browser.Visibility == System.Windows.Visibility.Visible) { Browser.Visibility = System.Windows.Visibility.Collapsed; e.Cancel = true; } base.OnBackKeyPress(e); }
Where to Go From Here
This tutorial is a short explanation of what you can do with Tweetsharp and Twitter. If you are interested in increasing the functionality of your app, like getting mentions, retweets, direct messages, and several other features, go to Tweetsharp’s website and you will find everything that you need to start developing a great app. I hope you enjoyed this tutorial and that it will be useful for your future projects.