Example #1
0
        private async Task <MainViewModel> PreloadServiceData()
        {
            TaskScheduler uiTaskSheduler = TaskScheduler.FromCurrentSynchronizationContext();
            MainViewModel vm             = null;
            Exception     exception      = null;

            try
            {
                vm = new MainViewModel(true);

                var loadTrends = TwitterHelper.GetTrendsAsync()
                                 .ContinueWith(loadTask =>
                {
                    if (exception != null)
                    {
                        return;
                    }

                    exception = loadTask.Exception;
                    if (exception != null)
                    {
                        return;
                    }

                    try
                    {
                        var trendsCollection = loadTask.Result
                                               .Where(trend => trend.Name.StartsWith("#"))
                                               .Take <TwitterTrendViewModel>(10);

                        using (var db = new TwitterContext())
                        {
                            foreach (var t in trendsCollection)
                            {
                                if (db.Trends.Any(tt => tt.TrendName == t.Name))
                                {
                                    continue;
                                }

                                db.Trends.Add(new TwitterTrend
                                {
                                    TrendName = t.Name
                                });
                                db.SaveChanges();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                    }
                });


                var loadTweets = vm.LoadPostsAsync(uiTaskSheduler);
#if X
                TwitterHelper.GetTweetsAsync(40, null)// 1200112449287905280 - 1) // null)

                .ContinueWith(loadTask =>
                {
                    if (exception != null)
                    {
                        return;
                    }

                    exception = loadTask.Exception;
                    if (exception != null)
                    {
                        return;
                    }

                    try
                    {
                        var tweetsCollection = loadTask.Result;//.Take(10);

                        using (var db = new TwitterContext())
                        {
                            using (var transaction = db.Database.BeginTransaction())
                            {
                                try
                                {
                                    var users = db.Users.ToDictionary(u => u.UserName);
                                    foreach (var tw in tweetsCollection)
                                    {
                                        if (vm.PostMinId == null || vm.PostMinId.Value > tw.Id)
                                        {
                                            vm.PostMinId = tw.Id;
                                        }

                                        TwitterUser user;
                                        if (!users.TryGetValue(tw.User.UserName, out user))
                                        {
                                            user = new TwitterUser()
                                            {
                                                UserName        = tw.User.UserName,
                                                UserScreenName  = tw.User.UserScreenName,
                                                FavouritesCount = tw.User.FavouritesCount,
                                                FollowersCount  = tw.User.FollowersCount,
                                                FriendsCount    = tw.User.FriendsCount,
                                                Description     = tw.User.Description,
                                                ProfileImageUrl = tw.User.ProfileImageUrl
                                            };
                                            users.Add(tw.User.UserName, user);
                                            db.Users.Add(user);
                                        }

                                        user.Posts.Add(
                                            new TwitterPost
                                        {
                                            TwitterId    = tw.Id,
                                            Text         = tw.Text,
                                            CreatedDate  = tw.CreatedDate,
                                            RetweetCount = tw.RetweetCount
                                        });
                                    }

                                    db.SaveChanges();
                                    transaction.Commit();
                                }
                                catch
                                {
                                    transaction.Rollback();
                                    throw;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                    }
                }, uiTaskSheduler);
#endif

                var loadUserInfo = TwitterHelper.GetUserInfoAsync()
                                   .ContinueWith(loadTask =>
                {
                    if (exception != null)
                    {
                        return;
                    }

                    exception = loadTask.Exception;
                    if (exception != null)
                    {
                        return;
                    }

                    try
                    {
                        var userInfo = loadTask.Result;
                        if (userInfo != null)
                        {
                            vm.User = userInfo;
                        }
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                    }
                });

                await Task.WhenAll(loadTrends, loadTweets, loadUserInfo); // три задачи в параллель!!!
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception == null)
            {
                return(vm);
            }
            else
            {
                string error;
                if (exception is TwitterException)
                {
                    error = string.Format("Произошло специфическое исключение {0}:\n\t{1}", exception.GetType().Name, exception.Message);
                }
                else
                {
                    error = string.Format("Произошло исключение {0}:\n\t{1}", exception.GetType().Name, exception.Message);
                }
                MessageBox.Show(error, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                this.Close();
            }
            return(null);
        }