In this tutorial, we will talk about how to interact with the Facebook API, and all the tools you need in order to connect with it. Specifically, the app that we are going to make will be able to connect with the user's Facebook account and update their status. Let’s get started!
Step 1: Visual Studio Project Creation
First of all, we need to create a new project with Visual Studio. We'll just be building a simple app, so select the "Windows Phone App" option:
If you are using Visual Studio 2012 with the new WP8 SDK, you are going to be asked the Target Windows Phone OS Version. If that's the case, then just select the 7.1 OS.
Step 2: Adding the UI
With the project already 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="Facebook" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel>
Now in our ContentPanel Grid, we will add two Rows, one for a TextBox where the user will input the new status, and the other one 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>
And then just add a TextBox on the first Row with the name of "Message", and a button on the second:
<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"/> <Button Grid.Row="1" Content="Post"/> </Grid>
At the end you should have this:
Step 3: Creating Developer Accounts
Facebook has a very comprehensive API for enabling interaction between apps and the site. The API allows your app to connect and interact with the user's FB account.
In order to connect our app to facebook, we'll need to register as a Facebook Developer. To create a Facebook developer account, go to the Facebook Developer Site,
then login with your facebook account or create one if you don't have one already. Once you've already logged in, click on the "Register Button" and follow the instructions.
Step 4: Registering a New App
Now, create a new App by going to your Apps menu, and then select the "Create New App" button.
After you have created your app, you will see your App settings page, and on it an App ID/API Key number.
Copy this number, return to the project, and inside of the "MainPage.xaml.cs" file, create a new global constant string on top of your constructor:
private const string FBApi = "YOUR API KEY GOES HERE"; // Constructor public MainPage() { InitializeComponent(); }
Step 5: Choosing the Facebook C# SDK
Facebook has some great SDK's for iOS, and Android, but sadly none for WP7, so in order to connect with Facebook from a WP7 App, we have two options: (1) create all the calls manually, or (2) use the Facebook C# SDK, a non-official SDK made specifically for C# apps.
For this tutorial, we'll use the C# SDK. It has every method from the Facebook API already integrated, so it will make our task a lot easier!
Step 6: Downloading the SDK
This SDK is only available through NuGet, so in case your Visual Studio doesn't include the NugGet Package manager,
you will need to download it from the NuGet hompage.
In order to download the package, open the Package Manager Console on Visual Studio (Tools>Library Package Manager>Package Manager Console), and enter the following command:Install-Package Facebook
. In case you are having troubles with the downloaded version, then try using this command: Install-Package Facebook -version 6.0.24
Step 7: Add the FB SDK to Your App
Now that we have the SDK, we will add it to our project. Add a new import on the "MainPage.xaml.cs" file:
using Facebook;
Step 8: Adding a Browser
In order for a user to connect to Facebook, he has to first give us access and permission to his FB account. This is done through the Facebook webpage, and therefore we need to add a web browser into our application. The browser should cover most of the page, so initially it will be collapsed, and then it will change to be visible just when the user needs to login. On 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"/> <Button Grid.Row="1" Content="Post"/> </Grid> <phone:WebBrowser Name="Browser" Grid.Row="1" Background="Aqua" Width="450" Height="600" Visibility="Collapsed"/>
Step 9: Connecting with Facebook
With everything correctly set, we can now start to code our application. Create a new FacebookClient variable, and name it just client. This is where all the connections will be made. Also, initiate the variable inside of the constructor:
private FacebookClient client; // Constructor public MainPage() { InitializeComponent(); client = new FacebookClient(); }
Step 10: Adding the Click Event
In order to actually post something, the user has to click on the "Post" button. Let's go and add a click event to that button:
<Button Grid.Row="1" Content="Post" Click="PostClicked"/>
On the code side, when the user clicks the button, he has to login with Facebook and authorize accept our App. For this process, we need to make the browser visible and navigate to a url that the client will give us, but before that we need to send some initial parameters:
private void PostClicked(object sender, RoutedEventArgs e) { //Client Parameters var parameters = new Dictionary<string, object>(); parameters["client_id"] = FBApi; parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html"; parameters["response_type"] = "token"; parameters["display"] = "touch"; //The scope is what give us the access to the users data, in this case //we just want to publish on his wall parameters["scope"] = "publish_stream"; Browser.Visibility = System.Windows.Visibility.Visible; Browser.Navigate(client.GetLoginUrl(parameters)); }
If you run your code right now and click on the Post button, the browser should appear, showing the Facebook login page:
Step 11: Adding a Navigation Event
After the user has logged in on Facebook, the browser will be navigated to a URL which will contain our access token for API calls. Once we retrieve it, we just have to assign it to our client. One thing to take into consideration is that there are many pages to which the browser could navigate (wrong password, user rejected our app, etc.), so we need to try to get the token just when we are sure that we are on the correct page.
Add the navigated event to the web browser:
<phone:WebBrowser Name="Browser" Grid.Row="1" Background="Aqua" Width="450" Height="600" Visibility="Collapsed" Navigated="BrowserNavitaged"/>
Then add the following lines to the event handler:
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e) { FacebookOAuthResult oauthResult; //Making sure that the url actually has the access token if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult)) { return; } //Checking that the user successfully accepted our app, otherwise just show the error if (oauthResult.IsSuccess) { //Process result client.AccessToken = oauthResult.AccessToken; //Hide the browser Browser.Visibility = System.Windows.Visibility.Collapsed; PostToWall(); } else { //Process Error MessageBox.Show(oauthResult.ErrorDescription); Browser.Visibility = System.Windows.Visibility.Collapsed; } }
Step 12: Adding a Post Method
Now that we have access, we can go on and actually post to the user's wall. Create a new private void method called postToWall, and add the following lines:
private void PostToWall() { var parameters = new Dictionary<string, object>(); parameters["message"] = Message.Text; client.PostAsync("me/feed", parameters); }
The only parameter that we need to send to this call is the message that we are going to post on the user's wall. The message that we will send will be the text from our TextBox called "Message". The message will be posted asynchronously, so the PostCompleted event will be called once the task is finished, therefore we need no add an event handler for it.
Step 13: PostCompleted Event Handler
Since we just want to add the event handler once, we will add it on the constructor, just after our client is initialized. Inside the handler, check if the post was successfully completed or if there were errors during the operations, then notify the user:
// Constructor public MainPage() { InitializeComponent(); client = new FacebookClient(); client.PostCompleted += (o, args) => { //Checking for errors if (args.Error != null) { Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message)); } else { Dispatcher.BeginInvoke(() =>MessageBox.Show("Message posted successfully")); } }; }
Step 14: Testing the Code
With this code, our App should already be able to post a message through the user's Facebook account.
Run the App in the emulator, try to post any test message that you want, and at the end you should receive a message telling you: "Message successfully posted".
Now open the Facebook account on a web browser, and you should see the message that you just posted:
Congratulations! You now have an app that is able to connect to Facebook, but there's still some things that we could improve. For example, we could try saving the access token, so users don't have to login every time they open the app.
Step 15: Saving the Acces Token
We are going to save the token for the application settings, but in order to do this, we must first import the IsolatedStorage library:
using System.IO.IsolatedStorage;
With this library we can now just go on and create the method:
private void SaveToken(String token) { //If it is the first save, create the key on ApplicationSettings and save the token, otherwise just modify the key if (!IsolatedStorageSettings.ApplicationSettings.Contains("token")) IsolatedStorageSettings.ApplicationSettings.Add("token", token); else IsolatedStorageSettings.ApplicationSettings["token"] = token; IsolatedStorageSettings.ApplicationSettings.Save(); }
Step 16: Retrieving with the Saved Token
Now we need to get the token from IsolatedStorage:
private string GetToken() { //If there's no Token on memory, just return null, otherwise return the token as string if (!IsolatedStorageSettings.ApplicationSettings.Contains("token")) return null; else return IsolatedStorageSettings.ApplicationSettings["token"] as string; }
Step 17: Logging with the Saved Token
With these two methods, we can now retrieve the token and assign it to our client each time the app is opened:
// Constructor public MainPage() { InitializeComponent(); client = new FacebookClient(); client.PostCompleted += (o, args) => { //Checking for errors if (args.Error != null) { Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message)); } else { Dispatcher.BeginInvoke(() =>MessageBox.Show("Message posted successfully")); } }; //Checking for saved token if (GetToken() != null) client.AccessToken = GetToken(); }
Step 18: Checking Expired Tokens
Another thing to take into account is that the user may reject the permissions of our App, so we need to detect this and ask for permissions again. This detection should be done on our PostCompleted handler, since that's where Facebook will notify us of a problem with our post. Add the following lines to our PostCompleted handler:
client.PostCompleted += (o, args) => { //Checking for errors if (args.Error != null) { //Authorization error if (args.Error is FacebookOAuthException) { Dispatcher.BeginInvoke(() => MessageBox.Show("Authorization Error")); //Remove the actual token since it doesn't work anymore. SaveToken(null); client.AccessToken = null; } else { Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message)); } } else { Dispatcher.BeginInvoke(() =>MessageBox.Show("Message posted successfully")); } };
Step 19: Modify the Back Button
Just as a last step, we must give the user the option to close the browser whenever desired.
This action should be given to the back button, so we just need to modify the event handler to achieve it.
Add the following method to your code:
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { //If browser is visible, hide it and cancel the navigation event if (Browser.Visibility == System.Windows.Visibility.Visible) { Browser.Visibility = System.Windows.Visibility.Collapsed; e.Cancel = true; } base.OnBackKeyPress(e); }
Step 20: The Final Product
Test your app once again, now you have a fully operational Facebook app!
Where to Go From Here
Facebook isn't just about updating your status. There's many other thing that you could add to your App, like sharing Photos, sending app recommendations to friends, etc. The Facebook C# SDK offers many possibilities for Facebook integration. To learn more about it, go and check out their web page and start working on making your app more social!
Comments