How can I Get the Current User Info without given SceenName/ID?

Sep 21, 2011 at 9:06 PM
Edited Sep 21, 2011 at 9:08 PM

I want to fetch the user info who has been authenticated. How can I Get the Current User Info without giving SceenName/ID after the user has been redirected from the twitter?

Coordinator
Sep 21, 2011 at 9:51 PM

Hi,

You can use User/Show, but you still must provide the ScreenName or ID of the current user.  The ScreenName or UserID are required by the Twitter API.  That said, here's a quick work-around.  It's based on the fact that LinqToTwitter keeps information about the authenticated user after authentication:

        /// <summary>
        /// shows how to query authenticated user
        /// </summary>
        /// <param name="twitterCtx">TwitterContext</param>
        private static void UserShowForAuthenticatedUser(TwitterContext twitterCtx)
        {
            string screenName = twitterCtx.AuthorizedClient.ScreenName;

            var user =
                (from usr in twitterCtx.User
                 where usr.Type == UserType.Show &&
                       usr.ScreenName == screenName
                 select usr)
                .SingleOrDefault();

            var name = user.Name;
            var lastStatus = user.Status == null ? "No Status" : user.Status.Text;

            Console.WriteLine("\nName: {0}, Last Tweet: {1}\n", name, lastStatus);
        }

The AuthorizedClient property of the TwitterContext instance, twitterCtx, contains the OAuth provider instance used to authenticate the user.  It has a ScreenName property you can use. It also has a UserID property if you prefer that.

Joe 

 

Sep 21, 2011 at 10:06 PM

awesome :)thank you very much.  you rock

Aug 10, 2012 at 7:51 PM

Hello Joe,

I was bugging you over twitter regarding the screenName. I tried both the Timeline as well as the UserInfo samples. Both get correct data but don't seem to have UserID or screenName populated in the AuthorizedClient object. I am authenticating and giving permission to the client. I also put the Pin in as returned by the web view.

Is there anything else I can try?

My environment is:

- Win8 RP
- VS2012 RC
- Linq2Twitter.dll version 2.0.28.0

Thanks and Regards,

Sumit.

Aug 11, 2012 at 12:57 AM

Okay, I have been working on this and I have a small update. I downloaded the code and tried to build the Linq2TweeterRT project and it failed viz. because of changes in the IsolatedStorage namespace for WinRT. It's basically gone (ref: http://msdn.microsoft.com/en-us/library/windows/apps/br230302%28v=vs.110%29.aspx#storage) . Also Long, Double etc. .ToString() doesn't take Culture enum any more. So removed those. That got it to build but still I am not getting UserID and ScreenName.

Going to dig deeper now by stepping through code.

Joe,

if you are waiting on Win8 final release before you update the the RT version of the dll it's fine. Else I could submit a pull request (gotta figure it out first ;-)...)

 

Thanks and Regards,

Sumit.

Aug 11, 2012 at 1:34 AM

Okay, nailed it.

        void AuthenticatePinButton_Click(object sender, RoutedEventArgs e)
        {
            auth.CompleteAuthorize(
                PinTextBox.Text,
                completeResp => Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    switch (completeResp.Status)
                    {
                        case TwitterErrorStatus.Success:
                            auth.UserId = completeResp.State.UserID; //newly added
                            auth.ScreenName = completeResp.State.ScreenName; //newly added
                            SuspensionManager.SessionState["Authorizer"] = auth;
                            Frame.Navigate(typeof(MainPage));
                            break;
                        case TwitterErrorStatus.RequestProcessingException:
                        case TwitterErrorStatus.TwitterApiError:
                            new MessageDialog(completeResp.Error.ToString(), completeResp.Message).ShowAsync().AsTask().Wait();
                            break;
                    }
                }).AsTask().Wait());
        }

I had to explicitly add the UserId and ScreenName values from the Response.State object. Not sure if this happens automatically in other Authorizers, but the PinAuthorizer didn't seem to have this baked in. The above change is required for the first code snippet (as shown by Joe above) to work.

Thanks and Regards,

Sumit.

Aug 11, 2012 at 9:11 AM

I can confirm this issue. Worked around by saving UserID and ScreenName separately to IsolatedStorage (on WIndows Phone).

Coordinator
Aug 17, 2012 at 4:08 AM

Sumit,

I checked in an update to the LinqToTwitterRT yesterday that fixed these issues.

Livven,

Correct, that's a good way to do it.

Joe

Aug 17, 2012 at 12:13 PM

Thanks Joe,

I was going to submit a pull request ;-), now I'll get latest.

Regards,

Sumit.

Aug 17, 2012 at 10:30 PM
Edited Aug 17, 2012 at 10:37 PM

Joe,

After the latest pull I see the entire IsolatedStorageCredentials.cs is wrapped in an #if !NETFX_CORE. Essentially making it unavailable for WinRT. I am putting the following code in the #else, please review and include if deemed fit. I am using IsolatedStorageCredentials successfully in WinRT using the code below.

using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Foundation;
//using System.IO.IsolatedStorage;
using Windows.Storage;

namespace LinqToTwitter
{
    public class IsolatedStorageCredentials : IOAuthCredentials
    {
        const int ConsumerKeyIdx = 0;
        const int ConsumerSecretIdx = 1;
        const int OAuthTokenIdx = 2;
        const int AccessTokenIdx = 3;
        const int ScreenNameIdx = 4;
        const int UserIdIdx = 5;

        readonly string[] credentials = new string[6];

        public IsolatedStorageCredentials()
        {
            LoadCredentialsFromIsolatedStorageAsync();
        }

        public void Load(string credentialsString)
        {
            string[] tempCredentials = credentialsString.Split(',');

            for (int i = 0; i < tempCredentials.Length; i++)
            {
                credentials[i] = tempCredentials[i];
            }

            SaveCredentialsToIsolatedStorage();
        }

        public override string ToString()
        {
            if (credentials == null)
            {
                LoadCredentialsFromIsolatedStorageAsync();
            }

            return string.Join(",", credentials);
        }

        public void Save()
        {
            SaveCredentialsToIsolatedStorage();
        }

        public void Clear()
        {
            for (int i = 0; i < credentials.Length; i++)
            {
                credentials[i] = string.Empty;
            }

            SaveCredentialsToIsolatedStorage();
        }

        ///Commented out by Sumit
        //void LoadCredentialsFromIsolatedStorage()
        //{
        //    string tempCredentialsString = null;

        //    IsolatedStorageFile credentialsStore = IsolatedStorageFile.GetUserStoreForApplication();

        //    using (var isoFileStream = new IsolatedStorageFileStream("Linq2TwitterCredentials.txt", FileMode.OpenOrCreate, credentialsStore))
        //    {
        //        using (var isoFileReader = new StreamReader(isoFileStream))
        //        {
        //            tempCredentialsString = isoFileReader.ReadLine();
        //        }
        //    }

        //    if (tempCredentialsString != null)
        //    {
        //        string[] tempCredentialsArr = tempCredentialsString.Split(',');

        //        for (int i = 0; i < tempCredentialsArr.Length; i++)
        //        {
        //            credentials[i] = tempCredentialsArr[i];
        //        }
        //    }
        //}

        /// <summary>
        /// Modified by Sumit to use the Release Preview version
        /// of the WinRT library for IsolatedStorage
        /// </summary>
        void LoadCredentialsFromIsolatedStorageAsync()
        {
            try
            {
                var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
                Task<StorageFile> sampleFile = localFolder.GetFileAsync("Linq2TwitterCredentials.txt").AsTask<StorageFile>();
                sampleFile.Wait();
                Task<string> readTask = FileIO.ReadTextAsync(sampleFile.Result).AsTask<string>();
                readTask.Wait();
                string tempCredentialsString = readTask.Result;
                if (tempCredentialsString != null)
                {
                    string[] tempCredentialsArr = tempCredentialsString.Split(',');

                    for (int i = 0; i < tempCredentialsArr.Length; i++)
                    {
                        credentials[i] = tempCredentialsArr[i];
                    }
                }
            }
            catch (Exception ex)
            {
                // TODO: Report this/Log This
            }
            return;
        }

        /// <summary>
        /// Modified by Sumit to use the Release Preview version
        /// of the WinRT library for IsolatedStorage
        /// </summary>
        async void SaveCredentialsToIsolatedStorage()
        {
            var credentialsString = string.Join(",", credentials);
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            // Write data to a file
            StorageFile sampleFile = await localFolder.CreateFileAsync("Linq2TwitterCredentials.txt", CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteTextAsync(sampleFile, credentialsString);
        }

        /// Commented out by Sumit
        //void SaveCredentialsToIsolatedStorage()
        //{
        //    var credentialsString = string.Join(",", credentials);

        //    IsolatedStorageFile credentialsStore = IsolatedStorageFile.GetUserStoreForApplication();

        //    using (var isoFileStream = new IsolatedStorageFileStream("Linq2TwitterCredentials.txt", FileMode.OpenOrCreate, credentialsStore))
        //    {
        //        using (var isoFileWriter = new StreamWriter(isoFileStream))
        //        {
        //            isoFileWriter.WriteLine(credentialsString);
        //        }
        //    }
        //}

        public string AccessToken
        {
            get
            {
                if (credentials[AccessTokenIdx] == null)
                {
                    LoadCredentialsFromIsolatedStorageAsync();
                }

                return credentials[AccessTokenIdx];
            }
            set
            {
                credentials[AccessTokenIdx] = value;
            }
        }

        public string ConsumerSecret
        {
            get
            {
                if (credentials[ConsumerSecretIdx] == null)
                {
                    LoadCredentialsFromIsolatedStorageAsync();
                }

                return credentials[ConsumerSecretIdx];
            }
            set
            {
                credentials[ConsumerSecretIdx] = value;
            }
        }

        public string OAuthToken
        {
            get
            {
                if (credentials[OAuthTokenIdx] == null)
                {
                    LoadCredentialsFromIsolatedStorageAsync();
                }

                return credentials[OAuthTokenIdx];
            }
            set
            {
                credentials[OAuthTokenIdx] = value;
            }
        }

        public string ConsumerKey
        {
            get
            {
                if (credentials[ConsumerKeyIdx] == null)
                {
                    LoadCredentialsFromIsolatedStorageAsync();
                }

                return credentials[ConsumerKeyIdx];
            }
            set
            {
                credentials[ConsumerKeyIdx] = value;
            }
        }

        /// <summary>
        /// Added by Sumit to enable Serialization of ScreenName
        /// </summary>
        public string ScreenName
        {
            get
            {
                if (credentials[ScreenNameIdx] == null)
                {
                    LoadCredentialsFromIsolatedStorageAsync();
                }
                return credentials[ScreenNameIdx];
            }
            set
            {
                credentials[ScreenNameIdx] = value;
            }
        }

        /// <summary>
        /// Added by Sumit to enable serialization of UserId 
        /// </summary>
        public string UserId
        {
            get
            {
                if (credentials[UserIdIdx] == null)
                {
                    LoadCredentialsFromIsolatedStorageAsync();
                }
                return credentials[UserIdIdx];
            }
            set
            {
                credentials[UserIdIdx] = value;
            }
        }
    }
}

Coordinator
Aug 17, 2012 at 10:34 PM

Wonderful, Thank You.

Joe

Coordinator
Aug 17, 2012 at 10:35 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.