The C# Facebook SDK is a very nice utility for working from Facebook within Windows 8, Windows Phone 8, or the web. I’m going to demo how to use the Login control for Windows 8, which is very easy to use. You can find an existing tutorial on this control here. I’m going to examine my usability of the control within a Windows Store app.
To begin, we need the Facebook and Facebook Client Controls, available from Nuget via:
– Install-Package Facebook
– Install-Package Facebook.Client -pre
Find the view you want to add the login button to. Add the following namespace in XAMl:
xmlns:fbc="using:Facebook.Client.Controls"
Add a fbc:LoginButton to the page:
<fbc:LoginButton x:Name="LoginButton" Width="200" Height="40" Foreground="White" Visibility="{Binding Path=LoginVisibility}" AuthenticationError="LoginButton_AuthenticationError" SessionStateChanged="LoginButton_SessionStateChanged" />
In order for the Facebook login to work, you need a Facebook application. Create one from the following URL: developers.facebook.com/apps. I like to assign this from code, so I can store the application ID in a constant. You have to give the Facebook issued app ID to the Login control though, which I do in code (yes I know, not very XAML’y).
LoginButton.ApplicationId = SocialConstants.FacebookAppID;
The SessionStateChanged event is the main event that receives focus on various actions. When you click Login, the framework opens a popup dialog that navigates to Facebook, asking for authentication information. Once authenticated, control returns to the application, whereby the current user’s information and current session information is available to you (via CurrentUser and CurrentSession properties of the LoginButton control).
Once we have the current session, we have an authenticated token, and can make a REST request to get the user’s current information. I currently do that using the following REST request:
var fb = new FacebookClient(session.AccessToken); //loginbutton control's session in a variable var response = await fb.GetTaskAsync<IDictionary>("/me");
Notice I grab the information as a dictionary, so it’s easy to grab the information like “first_name”, “last_name”, “name”, “email”, “uid” for the user’s ID, etc. This is where the Facebook documentation can come in handy. For instance, this information coincides with the user table in the FQL documentation (Facebook Query Language).
Pretty easy to use. Next we’ll examine how we can use this feature for Android and iOS as well.