Search code examples
c#linqlinq-to-twitter

c# LinqtoTwitter getting ScreenName/UserID from connection context


I've read nearly every post with a code example in the LinqToTwitter documentation. I want to get the UserID or the User's ScreenName to make a call like this for the user who is logged in.

var friendList =
            await
            (from friend in twitterCtx.Friendship
             where friend.Type == FriendshipType.FriendIDs &&
                   friend.ScreenName == "JoeMayo"
             select friend)
            .SingleOrDefaultAsync();

But all I can find are queries like above who have a hardcoded string for ScreenName.

Where can I get my own ScreenName/UserID out of the twitterCtx?

Cheers,

Chris


Solution

  • When you first authorize, the ScreenName and UserID of the IAuthorizer will be populated:

             var credentials = auth.CredentialStore; 
             string oauthToken = credentials.OAuthToken; 
             string oauthTokenSecret = credentials.OAuthTokenSecret; 
             string screenName = credentials.ScreenName; 
             ulong userID = credentials.UserID; 
    

    If you're pre-loading all 4 credentials, LINQ to Twitter short-circuits to save time, bandwidth, and user annoyance by not going through the authorization process again. The side-effect is that you don't get the ScreenName and UserID, because those are a product of authorization. So, if you save someone's keys after initial authorization, so you can use them again on subsequent queries, then grab ScreenName and UserID at that time too.

    Of course you have another way to obtain ScreenName and UserID. You can do a VerifyCredentials query, like this:

            try
            {
                var verifyResponse =
                    await
                        (from acct in twitterCtx.Account
                         where acct.Type == AccountType.VerifyCredentials
                         select acct)
                        .SingleOrDefaultAsync();
    
                if (verifyResponse != null && verifyResponse.User != null)
                {
                    User user = verifyResponse.User;
    
                    Console.WriteLine(
                        "Credentials are good for {0}.",
                        user.ScreenNameResponse); 
                }
            }
            catch (TwitterQueryException tqe)
            {
                Console.WriteLine(tqe.Message);
            }
    

    The ScreenName and UserID are in the User entity of the User property on the Account entity returned from the VerifyCredentials query. They are named ScreenNameResponse and **UserIDResponse** properties, respectively.