Search code examples
c#twitterwindows-phonelinq-to-twitter

Get all followings using LINQ to Twitter


I've just started a Windows Phone app, and I need to get all the user's followings. I tried this :

SharedState.Authorizer = pinAuth;
ITwitterAuthorizer auth = SharedState.Authorizer;
TwitterContext twitterCtx = new TwitterContext(auth);

var friendList =
    (from friend in twitterCtx.SocialGraph
        where friend.Type == SocialGraphType.Friends && friend.ScreenName == "_TDK"
        select friend)
    .SingleOrDefault();

List<String> Followings;
foreach (var id in friendList.ScreenName)
{
    Followings.Add(id.ToString());
}

But friendlist is always null and, obviously, the foreach does not like that and throws an exception.

Could someone help me ?

Thanks.


Solution

  • I think you need to iterate over the IDs collection, like this:

    foreach (var id in friendList.IDs)
    {
        Followings.Add(id.ToString());
    }
    

    You need to make async calls with Silverlight-based apps, including Windows Phone. Here's an example of how you can refactor the query:

    var twitterCtx = new TwitterContext(auth);
    
    (from social in twitterCtx.SocialGraph
     where social.Type == SocialGraphType.Followers &&
           social.ScreenName == "JoeMayo"
     select social)
    .MaterializedAsyncCallback(asyncResponse =>
         Dispatcher.BeginInvoke(() =>
         {
             if (asyncResponse.Status != TwitterErrorStatus.Success)
             {
                  MessageBox.Show(
                      "Error during query: " + 
                      asyncResponse.Exception.Message);
                  return;
             }
    
             SocialGraph social = asyncResponse.State.SingleOrDefault();
    
             SocialListBox.ItemsSource = social.IDs;
         }));
    

    The MaterializedAsyncCallback manages the callback from Twitter. Notice how I use Dispatcher.BeginInvoke to marshal the call back onto the UI thread as the callback is on a worker thread. On the asyncResponse callback parameter, use Status to see if there is an error and use State to get the data if the query is successful.