Invalid CastException Was Unhandled-Collection of common programming errors

I am getting the following error when trying to run code from http://facebooksdk.blogspot.co.uk/2011/04/facebook-groups.html

The error is “Invalid CastException Was Unhandled” and “Specified Cast Is Not Valid”

I am using the Facebook C# SDK and I am using the following code…

    public Dictionary GetGroups()
    {
        string accessToken = _accessToken;
        FacebookClient facebookClient = new FacebookClient(accessToken);
        JsonObject resul = facebookClient.Get("https://graph.facebook.com/me/groups?access_token=" + accessToken) as JsonObject;
        Dictionary dicGroups = new Dictionary();
        foreach (JsonObject item in (((KeyValuePair)(resul[0])).Value as JsonArray))
        {
            comboBox1.Items.Add(item["id"].ToString());
        }
        return dicGroups;
    }

Could anyone help? I am trying to get a list of all the users groups and add them to a combobox. Thanks

  1. I looked into the Facebook C# SDK more, and the api returns a json string of groups. You need to loop through each object in the json string to get what you want.

    JsonObject groups = facebookClient.Get("me/groups") as JsonObject;
    foreach(var group in (JsonArray)groups["data"])
    {
        comboBox1.Items.Add(item["id"].ToString());
        ...
    }
    

    Note: You need to prompt the user for the user_groups extended permission to be able to retrieve groups. Follow this link for an example of prompting for extended permissions. I don’t have a Facebook app, so I can’t test prompting for the permissions and retrieving group information.

Originally posted 2013-11-27 05:08:38.