Getting the Album ID with the Facebook C# SDK

I really shouldn’t drink & post like last night… Anyways, cynicism and rantiness wane as sobriety returns, and here’s some code that illustrates uploading a photo to a specific album:


// This is directly out of the Facebook C# SDK sample code (FacebookInfoDialog.cs)
private void btnPostPicture_Click(object sender, EventArgs e)
{
    var ofd = new OpenFileDialog
                  {
                      Filter = "JPEG Files|*.jpg",
                      Title = "Select picture to upload"
                  };
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        var picture = File.ReadAllBytes(ofd.FileName);

        var fb = new FacebookClient(_accessToken);

        fb.PostCompleted +=
            (o, args) =>
            {
                if (args.Error == null)
                {
                    FacebookClient tmpClient = (FacebookClient)o;
                    Console.WriteLine(args.GetResultData().ToString());
                    JsonObject jo = (JsonObject)args.GetResultData();

                    Console.WriteLine((string)jo["link"]);

                    MessageBox.Show("Picture posted to wall successfully.");
                }
                else
                {
                    MessageBox.Show(args.Error.Message);
                }
            };

        dynamic parameters = new ExpandoObject();
        parameters.caption = txtMessage.Text;
        parameters.method = "facebook.photos.upload";
        // See below for how to get the album ID value:
        parameters.aid = "123456"; // <== This is the album ID.

        var mediaObject = new FacebookMediaObject
                              {
                                  FileName = Path.GetFileName(ofd.FileName),
                                  ContentType = "image/jpeg"
                              };
        mediaObject.SetValue(picture);
        parameters.source = mediaObject;

        fb.PostAsync(parameters);
    }
}

// PARTIAL SNIPPET
// This shows a quick & dirty way to get the album ID:

dynamic jobj = arraySerializer.Deserialize(json, typeof(object));
int counter = 0;
Dictionary<string, string> albums = new Dictionary<string, string>();
// This loop is a sin, but don't get side-tracked.
while (true)
{
    try
    {
        // The link to the album has it's ID:
        string link = Convert.ToString(jobj.data[counter].link);
        // Convert that to a URI:
        Uri url = new Uri(link);
        // Get the query string:
        string query = url.Query;
        // Put the query string into a quick & easy collection:
        NameValueCollection nvc = HttpUtility.ParseQueryString(query);
        // Extract the album ID using the literal variable name, "aid":
        string aid = nvc["aid"]; // <== The correct album ID.
        // Add the album ID (aid) and the album name to a dictionary:
        albums.Add(aid, jobj.data[counter].name);
        // If you were to do this, you wouldn't have an album ID that you can use
        // because the "id" in the JSON doesn't return the album:
        // albums.Add(jobj.data[counter].id, jobj.data[counter].name);
    }
    catch
    {
        break;
    }
    counter++;
}

It’s not hard at all. But the lack of decent documentation makes it painful at best.

I’ve been harping on this for a long time: In software components, the real product isn’t *just* the component… It’s the documentation.  The best software in the world is no better than the worst if you can’t use it effectively. That’s what documentation is for.

I hope that helps save someone some time.

Cheers,

Ryan

Share

Written by:

276 Posts

View All Posts
Follow Me :

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 thoughts on “Getting the Album ID with the Facebook C# SDK

  1. Hello Cynic,

    Very informative blog you have here – thank you, and I too realized this dilemma. Perhaps my dev skills arent where they should be yet, but I can’t piece together the puzzle before this code snippit. Would you mind filling in the gap if you have time later?THank you

    ^
    ^
    dynamic jobj = arraySerializer.Deserialize(json, typeof(object));
    int counter = 0;
    Dictionary albums = new Dictionary();

    1. I’m glad it’s been useful for someone. 🙂

      When you already have the json response object, that code snippet there simply puts the json into a dynamic typed object.

      The counter is used to iterate through it.

      The dictionary is used to store the album IDs and names.

      The part below loops over the json dynamic object. When it finds an album, it stores it in the dictionary.

      Does that answer the question?

  2. More about Facebook SDK C# for

    from me and other users:

    post to wall,
    post photo to album,
    download photos from album

    share post with another user (maybe send messages)
    share photo with another user (maybe send messages)
    share page with another user

    do like and unlike to a post
    do like and unlike to a page

    from me
    delete post
    delete photo from album

    delete album
    create new album