Cross Platform C#

Be More Social: oAuth, Facebook and Xamarin

How to use Xamarin.Auth, Xamarin.Social, and the Facebook SDK for Android to interact with Facebook within a Xamarin.Android application.

It isn't breaking news that social networks are a big deal to your users. But what's the best way to add that functionality in the cross-platform development world? One of the best ways is through Xamarin, which provides a set of components that allows developers to concentrate on high-level programming and solving user problems. This article will look at some technologies available in Android -- as well as the iPhone -- to add social features to applications. It serves as a companion to my April article that covered oAuth, Twitter and the Linq to Twitter library.

Initial Login to Facebook
There are several mechanisms to connect to Facebook within a mobile application. Developers might call the exposed Web services directly and, while that's always the most flexible, most customers don't require this level of connectivity. Thankfully, Xamarin provides Xamarin.Auth. Xamarin.Auth is a library available via the Xamarin Component Store that provides the necessary APIs to authenticate via oAuth and connect to Facebook. An example is shown in Listing 1.

Listing 1: Connecting to Facebook, Processing the Callback and Storing the Connected User
string userToken; 
string AppId = "662869023780417"; // This is an example AppId that may change at any time
OAuth2Authenticator auth;
Button button, postButton, postViaFB, friendsList, personInfo;
protected override void OnCreate(Bundle bundle)
{
  base.OnCreate(bundle);
  SetContentView(Resource.Layout.Main);
  button = FindViewById<Button>(Resource.Id.MyButton);
  ostButton = FindViewById<Button>(Resource.Id.postButton);
  postButton.Click += postButton_Click;
  button.Click += delegate
  {
    auth = new OAuth2Authenticator(
      clientId: AppId,
      scope: "",
      authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
      redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));
    auth.Completed += auth_Completed;
    StartActivity(auth.GetUI(this));
  };
  postViaFB = FindViewById<Button>(Resource.Id.postViaFB);
  postViaFB.Click += postViaFB_Click;
  friendsList = FindViewById<Button>(Resource.Id.FriendsListFB);
  friendsList.Click += friendsList_Click;
  personInfo = FindViewById<Button>(Resource.Id.GetMyInfo);
  personInfo.Click += personInfo_Click;
}

void auth_Completed(object sender, AuthenticatorCompletedEventArgs e)
{
  if (e.Account != null)
  {
    userToken = e.Account.Properties["access_token"];
    AccountStore.Create(this).Save(e.Account, "Facebook");
  }
}

There are several things to notice in this code:

  • The parameters passed to the OAuth2Authenticator object are specific to Facebook.
  • The Completed method will handle what happens after the user logs in.
  • StartActivity(auth.GetUI(this)) will start the login process. The authenticator object's GetUI method provides the UI, which is an Activity that loads the Web interface for logging into Facebook.
  • Within the auth_Completed method, the user token is extracted. This is part of the e.Account.Properties dictionary. In this situation, the code retrieves the access_token property for later use. The access_token will be used later in this article.
  • Finally, the user account information can be stored locally on the device. This is done via the AccountStore class. This information can be stored for later use, so that the user isn't required to log in each time he uses the application.

The login screen for Facebook is shown in Figure 1. Once the login scenario is completed with Xamarin.Auth, the program will have the necessary values to perform further actions with Facebook.

[Click on image for larger view.] Figure 1. Facebook Login on Gennymotion Emulator

Introducing Xamarin.Social
Many times, an application needs to post to a user's wall in Facebook. This can be done with the Xamarin.Social library, which allows for users to post status updates and links to Web pages, pictures and other media (see Listing 2>). Xamarin.Social has been tested with Facebook, Flickr, Twitter and App.Net social networks.

Listing 2: Code for Using the Xamarin.Social Library to Post to Facebook

void postButton_Click(object sender, EventArgs e)
{
  var facebook = new Xamarin.Social.Services.FacebookService()
  {
    ClientId = AppId,
    RedirectUrl = new System.Uri("http://www.facebook.com/connect/login_success.html")
  };
  var item = new Xamarin.Social.Item { Text = 
    "Thanks to Wallace B. McClure, VSM and Xamarin for their help with programming Facebook." };
  item.Links.Add(new Uri("http://www.morewally.com/"));
  var bm = Android.Graphics.BitmapFactory.DecodeResource(
    this.Resources, Resource.Drawable.wallyimage);
  var id = new Xamarin.Social.ImageData(bm);
  item.Images.Add(id);
  var shareController = facebook.GetShareUI(this, item, result =>
  {
    if (result.HasFlag(Xamarin.Social.ShareResult.Done))
    {
      Toast.MakeText(this, "Posted", ToastLength.Long).Show();
    }
    if(result.HasFlag(Xamarin.Social.ShareResult.Cancelled))
    {
      Toast.MakeText(this, "Cancelled", ToastLength.Long).Show();
    }
  });
  StartActivity(shareController);
}

The UI for posting via Xamarin.Social is shown in Figure 2.

[Click on image for larger view.] Figure 2. The UI for Posting to Facebook via Xamarin Social

The key things to note in this code:

  • A Facebook service object is created. This object will be used to add text, links, images and other file types to Facebook.
  • A Xamarin.Social.Item object will be instantiated. There will be various properties that will be set on it. In this example, text, a link and a graphic will be added.
  • An Activity is created by calling the GetShare method and passing the created item to it.
  • The Activity is started by calling the Android StartActivity method to perform the post. The activity that's passed is a UI from the FacebookService GetShareUI method.
  • The last step is to process some code on the return from posting. In this situation, a toast is displayed, but nearly anything can be done.

(Note: The code is set to post a gratuitous image of the author along with text. This is for a test only to demonstrate that the code works. Please make sure that you change this code before running, unless you want pictures of the author, as well as links to his blog, posted on your Facebook timeline.)

Facebook SDK
Xamarin.Social is a great tool for user-centric posting. There are situations where more control is necessary, as well as more complicated scenarios and usage requirements. Realistically, this requires an SDK to make calls against the defined APIs.

Note No. 1: The userToken in this section is the access_token property obtained in the section with Xamarin.Auth.

Note No. 2: These samples were taken from the Facebook SDK documentation on the Xamarin site and modified to work with Xamarin.Android and Xamarin.Auth.

The first method to look at is the method to post to the user's wall (see Listing 3). The items to note:

  • The FacebookClient object is instantiated, then the userToken value is passed in. This demonstrates the interoperability of these solutions.
  • Posting to a user's wall is done by calling the PostTaskAsync method and passing the "me/feed" value in the first parameter.
  • The second parameter of the PostTaskAsync is an object. The parameters in that object appear to match the ones expected by the Facebook SDK.
  • Calling PostTaskAsync doesn't require user intervention to post.
Listing 3: The PostToMyWall Method Posts to a Facebook Wall via the Facebook SDK
void PostToMyWall()
{
  FacebookClient fb = new FacebookClient(userToken);
  string myMessage = "Posted via the Facebook SDK, Wally McClure, VSM, and Xamarin.";
  fb.PostTaskAsync("me/feed", new { message = myMessage }).ContinueWith(t =>
  {
    if (!t.IsFaulted)
    {

      string message = "Message posted to wall.";
      Console.WriteLine(message);
    }
  });
}

To get information from the user, it can be done against the "me" method of Facebook. When the method returns in the example, a Dictionary object is created. From this dictionary, the standard Facebook parameters can be returned. These may be seen in the Output window in Facebook when the example application writes this via the call to Console.WriteLine, as shown in Listing 4.

Listing 4: The GetMyInfo Method
void GetMyInfo()
{
  // This uses Facebook Graph API
  // See https://developers.facebook.com/docs/reference/api/ for more information.
  FacebookClient fb = new FacebookClient(userToken);
  fb.GetTaskAsync("me").ContinueWith(t =>
  {
    if (!t.IsFaulted)
    {
      var result = (IDictionary<string, object>)t.Result;
      Console.WriteLine(result);
    }
  });
}

It's possible to make other calls against the Facebook API. Listing 5 returns the number of friends of the logged-in user, as well as producing a list of these friends in the Visual Studio output window.

Listing 5: The PrintFriendsNames Method
void PrintFriendsNames()
{
  // This uses Facebook Query Language
  // See https://developers.facebook.com/docs/technical-guides/fql/ for more information.
  var query = string.Format("SELECT uid,name,pic_square FROM user WHERE uid IN (
    SELECT uid2 FROM friend WHERE uid1={0}) ORDER BY name ASC", "me()");
  FacebookClient fb = new FacebookClient(userToken);

  fb.GetTaskAsync("fql", new { q = query }).ContinueWith(t =>
  {
    if (!t.IsFaulted)
    {
      var result = (IDictionary<string, object>)t.Result;
      var data = (IList<object>)result["data"];
      var count = data.Count;
      var message = string.Format("You have {0} friends", count);
      Console.WriteLine(message);

      foreach (IDictionary<string, object> friend in data)
        Console.WriteLine((string)friend["name"]);
    }
  });
}

Wrapping Up
Integrating with social network sites is very important for mobile applications. In this article, I've looked at how to log in to Facebook, post updates to a user's Facebook wall and integrate with other Facebook API calls. This code is just a start. With these samples, you can add social networking functionality to mobile applications easily. By adding social networking features, a user will have easier access to his friends and share information while remaining within an existing application, while you can get higher ratings for your apps. Everyone can win.

comments powered by Disqus
Most   Popular
Upcoming Events

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.