Issue Intializing new Type. System.InvalidCastException error

Dec 3, 2009 at 2:02 PM
Edited Dec 4, 2009 at 11:51 AM

Why do I get an error attempting to initialize a new type in the following snippet.

 

This way works:

=======================================

tc = new twittercontext(auth);
List<TwitterUser> retFriends = new List<TwitterUser>();

using (tc) //implement dispose
{
var currentUsers = from users in tc.User
where users.Type == UserType.Friends && users.ID == userId
&& users.Page == page
select users;

foreach(User u in currentUsers.ToArray())
{
TwitterUser tu = new TwitterUser();
tu.Description = u.Description;
tu.ScreenName = u.ScreenName;
tu.TwitterUserId = u.UserID;

retFriends.Add(tu);

}

}

===============================================

But this throws: 

Unable to cast object of type 'System.Collections.Generic.List`1[LinqToTwitter.Status]' to type 'System.Collections.Generic.IEnumerable`1[MyApplication.ModelLib.TwitterUser]
      

 

 IEnumerable<TwitterUser> currentUsers = null;

//get all friends by page, gets 100 per request see API: statuses/friends
currentUsers = from users in tc.User
where users.Type == UserType.Friends && users.ID == userId
&& users.Page == page
select new TwitterUser
{
Description = users.Description,
Following = users.Following,
Location = users.Location,
Name = users.Name,
Protected = users.Protected,
ScreenName = users.ScreenName,
ProfileImageURL = users.ProfileImageUrl,
TwitterUserId = users.UserID,
URL = users.URL
};


retFriends = currentUsers.ToList<TwitterUser>(); // this blows up...

The error is triggered in the TwitterQueryProvider class.

Here is the trace:

 

Source Error:

Line 92:                 typeof(TResult).Name == "IEnumerable";
Line 93: 
Line 94:             return (TResult)Context.Execute(expression, isEnumerable);
Line 95:         }
Line 96:     }


Source File: E:\projects\Linq2Twtr\LinqToTwitter\TwitterQueryProvider.cs    Line: 94

Stack Trace:

[InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[LinqToTwitter.Status]' to type 'System.Collections.Generic.IEnumerable`1[MyApp.ModelLib.TwitterUser]'.]
   LinqToTwitter.TwitterQueryProvider.Execute(Expression expression) in E:\projects\Linq2Twtr\LinqToTwitter\TwitterQueryProvider.cs:94
   LinqToTwitter.TwitterQueryable`1.GetEnumerator() in E:\projects\Linq2Twtr\LinqToTwitter\TwitterQueryable.cs:102
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +7665318
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +61
   MyApp.BAL.UserBLL.GetAllFriendsForUser(String userId, TwitterContext tc) in E:\projects\MyApp\BAL\UserBLL.cs:70
   MyApp._Default.btnTestMsg_Click(Object sender, EventArgs e) in E:\projects\MyApp\Default.aspx.cs:449
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565


Version Information: Microsoft .NET Framework Version:2.0.50727.3603; ASP.NET Version:2.0.50727.3082 

 

Any help would be appreciated.  I've done this type of initialization to new type before without issue, that's why it seems strange to me.

Dec 5, 2009 at 1:39 AM

Nevermind.  I think maybe this has been fixed with:

 

60405
by JoeMayo
Oct 23<abbr></abbr> at
2:58 PM<abbr></abbr>
2 Added cursor support for User and Social Graph APIs. Fixed type mismatch bug in post-processing.

 

Downloading latest version may fix this...

Coordinator
Dec 5, 2009 at 2:25 AM

Hi soupreme,

Yes, that's it.  Twitter deprecated paging on User and Social Graph APIs.  I put an obsolete warning on the Page property for that Oct 23rd check-in, but will change it to an error soon so that people know they should use cursors.  Just to let you know, page wasn't deprecated on all APIs, just User and Social Graph. You can find cursor examples in Program.cs.

Joe

Dec 5, 2009 at 1:53 PM

Joe -

Yep! That fixed everything.  Thanks for your help. BTW props to you and everyone involved in this...its very cool.

 

If anyone is interested, this is how I ended up returning all Friends or Followers for a user.  It prob needs to be cleaned-up/re-factored, but it works...

 

 /// <summary>
        /// Get all Friends or Followers for provided userId. Cursor based
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tc"></param>
        /// <returns></returns>
        public static List<TwitterUser> GetAllUsersForUser(string userId, TwitterContext tc, UserType userType)
        {
            List<TwitterUser> retUsers = new List<TwitterUser>();

            using (tc) //implement dispose
            {
                try
                {
                    string strCursor = "-1";

                    while (strCursor != "0")
                    {
                        //get all friends or followers using cursor, gets 100 per request see API: statuses/friends
                        var currentUsers = from users in tc.User
                                           where users.Type == userType && users.ID == userId
                                           && users.Cursor == strCursor
                                           select users;                                           

                        User[] cUsers = currentUsers.ToArray();
                
                        //if page returned users
                        if (Util.isPopulated(cUsers)) //not really sure this is necessary...
                        {
                            bool cursorSet = false;

                            foreach (User u in cUsers)
                            {
                                if (!cursorSet)
                                {
                                    strCursor = u.CursorMovement.Next;
                                    cursorSet = true;
                                }

                                TwitterUser tu = new TwitterUser();

                                tu.FollowersCount = u.FollowersCount;
                                tu.FriendsCount = u.FriendsCount;                                
                                tu.Following = u.Following;
                                tu.Location = u.Location;
                                tu.Name = u.Name;
                                tu.ProfileImageURL = u.ProfileImageUrl;
                                tu.Protected = u.Protected;
                                tu.Description = u.Description;
                                tu.ScreenName = u.Identifier.ScreenName;
                                tu.TwitterUserId = u.Identifier.ID;
                                tu.URL = u.URL;                               

                                retUsers.Add(tu);
                            }
                        }
                        else
                        {
                            strCursor = "0";
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    string test = ex.Message;
                }
            }
            return retUsers;
        }

 

Also after downloading newest code update, the initialization to new type thru Linq query works fine although I didn't see an easy way to do this and also set the next cursor value for the loop, but no errors occur:

 

      //get all friends or followers using cursor, gets 100 per request see API: statuses/friends
                        var currentUsers = from users in tc.User
                                           where users.Type == userType && users.ID == userId
                                           && users.Cursor == strCursor
                                           select new TwitterUser
                                          {
                                              Description = users.Description,
                                              Following = users.Following,
                                              Location = users.Location,
                                              Name = users.Name,
                                              Protected = users.Protected,
                                              ScreenName = users.Identifier.ScreenName,
                                              ProfileImageURL = users.ProfileImageUrl,
                                              TwitterUserId = users.Identifier.ID,
                                              URL = users.URL
                                          };