Share photos on Facebook from Windows Phone app

Share photos on Facebook from Windows Phone app

Sharing photos on Facebook from your Windows Phone app is one of the scenarios for which you need Facebook inside your app. In my last article, I wrote about the first step of creating a Facebook enabled app, which is authentication. After the user is successfully authenticated, you can start doing things like sharing and uploading photos. This article will show you the simplest way to do it!

Let’s start with my last article - Facebook authentication from Windows Phone app. Finishing with implementing code from that article, I will assume that you have acquired AccessToken and UserID and serialized it to isolated storage. The class used for it was:

public class FacebookAccess  
{
    public string AccessToken { get; set; }
    public string UserId { get; set; }
}

I will also assume that the information is saved in a file called FacebookAccess. To share the photo, first of all you will need to load the information from isolated storage. Here is the method for it:

public static T LoadSetting<T>(string fileName)  
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (!store.FileExists(fileName))
            return default(T);
            try
            {
                using (var stream = store.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                {
                    var serializer = new DataContractSerializer(typeof(T));
                    return (T)serializer.ReadObject(stream);
                }
            }
            catch (Exception e)
            {
                Deployment.Current.Dispatcher.BeginInvoke(
                    () => MessageBox.Show(e.Message));
                return default(T);
            }
    }
}

It’s a generic method and you’ll use it to get back FacebookAccess object. You can skip that step if you already have the AccessToken in memory.

var file = SerializeHelper.LoadSetting("FacebookAccess");  
SharePhoto(file, message.Text);  

file is the FacebookAccess object with authentication details, and message is a textbox with the message you’d like to share with the photo. SharePhoto method assumes that you have a WriteableBitmap photo defined and called LoadedPhoto. There are many ways you can get it – from PhotoChooserTask, CameraCaptureTask, isolated storage etc. It’s not important as long as you have the object. You start by creating a FacebookClient object from Facebook C# SDK (see the last article to learn how to get it in your project).

void SharePhoto(FacebookAccess file, string message)  
{
    var fb = new FacebookClient(file.AccessToken);

After that, create a PostCompleted handler – what happens after the photo is posted (actually, after the request is done – the photo may not have been uploaded, an error might have occurred in the process).

fb.PostCompleted += (o, args) =>  
{
    if (args.Error != null)
    {
        if (args.Error.Message.StartsWith("(OAuthException - #190)"))
        {
        Dispatcher.BeginInvoke(() =>
        {
            // Error 190 means that the token has expired. You need to ask the user to get the token again before continuing. Handle this error gracefully here.
        });
    }
    else
    {
        Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show(args.Error.Message, "Error", MessageBoxButton.OK);
        });
    }
    return;
    }
    else
    {
        Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show("POSTED");
        }
    );
}
};

If there was an error, you need to handle it correctly. If error 190 happened, that means that the token has expired (learn more about expired tokens here: https://developers.facebook.com/docs/authentication/access-token-expiration/ ) and you need to get it again. Redirect user to the Facebook site and get the token again like I described in the previous article. If some other error happened, display the information to the user. Otherwise, the photo was posted successfully.

You will be posting your photo in the form of a FacebookMediaObject, object from Facebook C# SDK. You give it a name of your choice, and set the type (jpeg if photo is jpeg type)

var fbUpl = new Facebook.FacebookMediaObject  
{
    FileName = "TempPhoto.jpg",
    ContentType = "image/jpg"
};

Create a byte array from your photo (assuming it’s called LoadedPhoto). Then just call the SetValue method on FacebookMediaObject object with that byte array as a parameter:

using (MemoryStream ms = new MemoryStream()  
{
    LoadedPhoto.SaveJpeg(ms, app.LoadedPhoto.PixelWidth, app.LoadedPhoto.PixelHeight, 0, 95);
    ms.Seek(0, 0);
    byte[] data = new byte[ms.Length];
    ms.Read(data, 0, data.Length);
    ms.Close();

    fbUpl.SetValue(data);
}

Now you have both the message and the photo. You just have to create a dictionary with those elements to be used as parameters for request, and start the asynchronous request:

var parameters = new Dictionary<string,object>();  
parameters["message"] = message;  
parameters["file"] = fbUpl;

fb.PostAsync("me/photos", parameters);  

That’s it. Depending on the size, you have to wait a bit before the photo gets uploaded… You can notify the user that the photo is uploading by using performance progress bar, for example. This is what the sharing page will look like in my app Photo Light in a few days after it passes the certification.


fbshare

In conclusion, I’d like to add that it could really take just 20 lines of code to share photo on Facebook. It takes more though if you wish to handle all the errors properly.

Igor Ralic

igor ralic

View Comments
Microsoft Certified Solutions Developer: Windows Store Apps in C#