0

When I execute the code I developed to call an Async method of the linq2Twitter, I am getting a System.Aggregate Exception, the code is below:

static async Task<List<myTwitterStatus>> getRetweets(ulong tweetID, TwitterContext twitterCtx)        
{
    List<myTwitterStatus> reTweets = new List<myTwitterStatus>();

    var publicTweets =
        await
        (from tweet in twitterCtx.Status
         where tweet.Type == StatusType.Retweets &&
               tweet.ID == tweetID
         select tweet)
         .ToListAsync();

    if (publicTweets != null)
        publicTweets.ForEach(tweet =>
        {
            if (tweet != null && tweet.User != null)
            {
                myTwitterStatus tempStatus = new myTwitterStatus();
                tempStatus.Country = tweet.Place.Country;
                tempStatus.createdAt = tweet.CreatedAt;
                tempStatus.FavoriteCount = long.Parse(tweet.FavoriteCount.ToString());
                tempStatus.ID = tweet.ID;
                tempStatus.isTruncated = tweet.Truncated;
                tempStatus.Lang = tweet.Lang;
                tempStatus.MaxID = tweet.MaxID;
                tempStatus.PlaceFullname = tweet.Place.FullName;
                tempStatus.RetweetCount = tweet.RetweetCount;
                tempStatus.ScreenName = tweet.ScreenName;
                tempStatus.Text = tweet.Text;
                tempStatus.UserFriends = tweet.User.FriendsCount;
                tempStatus.UserCreated = tweet.User.CreatedAt;
                tempStatus.UserFollowers = tweet.User.FollowersCount;
                tempStatus.UserFavorities = tweet.User.FavoritesCount;
                tempStatus.UserFriends = tweet.User.FriendsCount;
                tempStatus.UserLocation = tweet.User.Location;
                tempStatus.UserName = tweet.User.Name;
                tempStatus.UserTweetCount = tweet.User.StatusesCount;
                reTweets.Add(tempStatus);
            }
        });
        return reTweets;    
    }

The issue is when I called the method

var authorizer = new SingleUserAuthorizer
{
    CredentialStore = new InMemoryCredentialStore
    {
        ConsumerKey = SM.Default.Consumer_key2.ToString(),
        ConsumerSecret = SM.Default.Consumer_secret2.ToString(),
        OAuthToken = SM.Default.Access_token2.ToString(),
        OAuthTokenSecret = SM.Default.Access_secret2.ToString()
    }
};
TwitterContext twitterCtx = new TwitterContext(authorizer);

Task<List<myTwitterStatus>> task = Task<List<myTwitterStatus>>.Factory.StartNew(() => getRetweets(ulong.Parse(tweet.StringId), twitterCtx).Result);
task.Wait();                    
List<myTwitterStatus> tempList = task.Result.ToList<myTwitterStatus>();

foreach (var ret in tempList)
{
    un = file.RemoveSpecialCharacters(ret.UserName);
    sn = file.RemoveSpecialCharacters(ret.ScreenName);

    tweets.AppendLine(account + "," + getWE(ret.createdAt) + "," + Text + "," + un + "," + sn + "," + ret.createdAt + "," +
    file.RemoveSpecialCharacters(ret.UserLocation) + ",,,1,," + ret.UserTweetCount + "," +
    ret.RetweetCount + "," + ret.FavoriteCount + "," + ret.UserFollowers);

I would appreciate any kind of assistance about it, I have no idea how to solve it.

Craig W.
  • 17,838
  • 6
  • 49
  • 82
  • What is the actual contents of the exception? – Craig W. Apr 22 '15 at 17:30
  • It is "An exception of type 'System.AggregateException' occurred in mscorlib.dll but was not handled in user code" if I use a Try-catch I need to loop thru the exception messages – Rod Barrantes Apr 22 '15 at 18:56
  • @RodBarrantes Need a stack trace for more info. You should also use async/await pattern, rather than Task.Wait() or Task.Result - otherwise, bad things happen. See "Don't Block on Async Code" by Steven Cleary: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html – Joe Mayo Apr 22 '15 at 19:58
  • On the async method I used the await (Task> getRetweets) but in this synch call I am not allowed to use it. This it the error's output The thread 0x32b0 has exited with code 259 (0x103). The thread 0x494 has exited with code 259 (0x103). The thread 0x31b8 has exited with code 0 (0x0). The thread 0x1bd8 has exited with code 259 (0x103). – Rod Barrantes Apr 22 '15 at 20:31
  • My bad: `code` at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) – Rod Barrantes Apr 22 '15 at 20:40
  • One or more errors occurred. at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task`1.get_Result() at Engaged_Twitter.frmMain.getRetweets(TwitterStatus tweet) in c:\Users\rodolfo.barrantes\Documents\Visual Studio 2013\Projects\Engaged_Twitter\Engaged_Twitter\frmMain.cs:line 625 – Rod Barrantes Apr 22 '15 at 22:13
  • I think you missed the point of my question. An AggregateException is just that, a collection of other exceptions that have occurred. You need to dig in and inspect what those other exceptions are. Look at the `InnerException` and/or `InnerExceptions` properties to find out what the underlying cause of the exception is. The AggregateException is not the underlying cause. My guess is once you know that you'll have your answer. – Craig W. Apr 23 '15 at 14:21

2 Answers2

0

Can you add a try/catch so see what the inner exception is.

try
{
    //Perform your operation here
}
catch (AggregateException aex)
{
    //Dive into inner exception
}
Cody
  • 149
  • 5
  • This should be a comment not an answer. – Craig W. Apr 22 '15 at 17:30
  • Hello, thank you for the prompt reply, due to the fact that I am getting an Aggregate Exception a try-catch might not be the best answer here, I am guessing that the Exception is produced while feeding the List that is returned. – Rod Barrantes Apr 22 '15 at 18:03
0

Thanks to all for the help, I activate the breakpoints for the specific exception and an additional validation was added, the issue was not in the async process, it was because it was trying to handle a null as an string, to hendle this error this line was modified sn = file.RemoveSpecialCharacters(ret.ScreenName ?? string.Empty);

The full code is below:

   private void getRetweets(TwitterStatus tweet)
    {
        Text = file.RemoveSpecialCharacters(tweet.Text);
        tweetID = tweet.StringId;

        #region Get retweets
        RetweetsOptions retOpt = new RetweetsOptions();
        if (int.Parse(tweet.RetweetCountString.ToString()) > 1)
                retOpt.Count = int.Parse(tweet.RetweetCountString.ToString()) + 1;
            else
                retOpt.Count = 1;

        String errorText = "";

        DateTime fromDate, toDate;
        if (radDate.Checked == true)
        {
            fromDate = dtpFrom.Value;
            toDate = dtpTo.Value;
        }
        else
        {
            fromDate = tweet.CreatedDate;
            toDate = DateTime.Now;
        }

        TwitterResponse<TwitterStatusCollection> retweet = null;

        if (int.Parse(tweet.RetweetCountString.ToString()) > 100)
        {                                
            var authorizer = new SingleUserAuthorizer
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = SM.Default.Consumer_key2.ToString(),
                    ConsumerSecret = SM.Default.Consumer_secret2.ToString(),
                    OAuthToken = SM.Default.Access_token2.ToString(),
                    OAuthTokenSecret = SM.Default.Access_secret2.ToString()
                }
            };
            TwitterContext twitterCtx = new TwitterContext(authorizer);

            //HELPER: https://www.youtube.com/watch?v=IONqMWGn9-w                                
            try
            {                        
                Task<List<myTwitterStatus>> task = null;
                Parallel.Invoke(
                    () =>
                    {
                        task = getRetweets(ulong.Parse(tweet.StringId), twitterCtx);
                        while (!task.IsCompleted)
                        {
                            Thread.Sleep(250);
                        }
                    });



                List<myTwitterStatus> tempList = task.Result.ToList<myTwitterStatus>();

                foreach (var ret in tempList)
                {
                    un = file.RemoveSpecialCharacters(ret.UserName);
                    sn = file.RemoveSpecialCharacters(ret.ScreenName ?? string.Empty);

                    tweets.AppendLine(account + "," + getWE(ret.createdAt) + "," + Text + "," + un + "," + sn + "," + ret.createdAt + "," +
                            file.RemoveSpecialCharacters(ret.UserLocation) + ",,,1,," + ret.UserTweetCount + "," +
                            ret.RetweetCount + "," + ret.FavoriteCount + "," + ret.UserFollowers);
                }
            }catch(Exception ex){
                Console.WriteLine("Error: " + ex.Message+ Environment.NewLine + ex.StackTrace);
            }
            return;
        }
        else
            retweet= TwitterStatus.Retweets(tokensRet, Decimal.Parse(tweet.Id.ToString()), retOpt);


        if (retweet.Result.ToString() == "Success" && retweet.ResponseObject.Count > 0 && retweet!=null)
        {                
            int retPages = int.Parse(tweet.RetweetCountString.ToString()) + 1 / 20;

            for (int page = 0; page <= retPages; page++)
            {
                try
                {
                    //List<TwitterStatus> retList = new List<TwitterStatus>(retweet.ResponseObject.Page = page);                    
                    retweet.ResponseObject.Page = page;
                    List<TwitterStatus> retList = retweet.ResponseObject.ToList<TwitterStatus>();

                    foreach (var ret in retList)
                    {

                        try
                        {
                            if (ret.CreatedDate.CompareTo(fromDate) >= 0 && ret.CreatedDate.CompareTo(toDate) <= 0)
                            {
                                #region Get UN Sync
                                getUN(ret, ref un, ref sn);
                                #endregion

                                tweets.AppendLine(account + "," + getWE(ret.CreatedDate) + "," + Text + "," + un + "," + sn + "," + ret.CreatedDate + "," +
                                    file.RemoveSpecialCharacters(ret.User.Location.ToString()) + ",,,1,," + ret.User.NumberOfStatuses.ToString() + "," +
                                    ret.RetweetCount + "," + ret.User.NumberOfFavorites.ToString() + "," + ret.User.NumberOfFollowers.ToString());

                            }
                            else if (tweet.CreatedDate.CompareTo(toDate) <= 0)//if the tweet's created date is lower than the from's date, exits the loop
                                break;
                        }
                        catch (NullReferenceException ex)
                        {
                            errorText = ex.Source + Environment.NewLine + ex.StackTrace;
                            continue;
                        }

                    }
                }
                catch (Exception ex)
                {
                    errorText = ex.Source + Environment.NewLine + ex.StackTrace;
                    //MessageBox.Show(ex.Message + Environment.NewLine + "Rate Limit was reached!" + Environment.NewLine +
                    //    "Wait an hour or try a shorter date range", "Rate Limit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
        }
        else if (error == false && retweet.Result.ToString() != "Success")
        {
            errorText = retweet.Result.ToString();
            MessageBox.Show("Retweets: Something went wrong!" + Environment.NewLine + errorText, "Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            error = true;
        }
    #endregion
    }