Пример #1
0
 public static TweetCollection GetTimeline(string userName, int num, Hashtable properties)
 {
     //recommended properties: include_rts=true
     string rUrl = "https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + userName + "&count=" + num;
     foreach (DictionaryEntry property in properties)
     {
         rUrl += "&" + property.Key + "=" + property.Value;
     }
     XmlDocument rDoc = new XmlDocument();
     rDoc.LoadXml(Twitter.ExecuteRequest(rUrl));
     XmlNode root = rDoc.DocumentElement;
     XmlNodeList nodeList = root.SelectNodes("status");
     TweetCollection twColl = new TweetCollection();
     foreach (XmlNode node in nodeList)
     {
         try
         {
             if (node.SelectSingleNode("retweeted_status") == null)
             {
                 twColl.Add(new Tweet(node.SelectSingleNode("user/screen_name").InnerText, node.SelectSingleNode("user/id").InnerText, node.SelectSingleNode("user/profile_image_url").InnerText, node.SelectSingleNode("text").InnerText));
             }
             else if (node.SelectSingleNode("retweeted_status") != null)
             {
                 twColl.Add(new Tweet(node.SelectSingleNode("retweeted_status/user/screen_name").InnerText, node.SelectSingleNode("retweeted_status/user/id").InnerText, node.SelectSingleNode("retweeted_status/user/profile_image_url").InnerText, node.SelectSingleNode("retweeted_status/text").InnerText));
             }
         }
         catch (Exception e)
         {
             throw new Exception("Failed to retrieve timeline.", e);
         }
     }
     return twColl;
 }
        public TweetCollection GetTweets()
        {
            TweetCollection tweets = new TweetCollection();
            Tweet           tweet  = new Tweet();

            if (twitter == null)
            {
                tweet.Text = "Please setup your user/password and url in the connection settings.";
                tweets.Add(tweet);
                return(tweets);
            }
            try
            {
                //if (_lastId == null)
                tweets = twitter.GetFriendsTimeline();

                /*else
                 *  tweets = twitter.GetFriendsTimeline(_lastId.ToString());
                 * if (tweets != null && tweets.Count > 0)
                 * {
                 *  _lastId = String.Format("{0:0}", tweets[0].Id);
                 * }
                 * else
                 * {
                 *  tweet.Text = "sent " + _lastId;
                 *  tweets.Add(tweet);
                 * }*/
                return(tweets);
            }
            catch (System.Net.WebException we)
            {
                twitter.TwitterServerUrl = twitter.TwitterServerUrl.Replace("https://", "http://");
                try
                {
                    return(twitter.GetFriendsTimeline());
                }
                catch (Exception err)
                {
                    tweet.Text = err.Message;
                    tweets.Add(tweet);
                    return(tweets);
                }
            }
            catch (Exception err)
            {
                tweet.Text = err.Message;
                tweets.Add(tweet);
                return(tweets);
            }
        }
Пример #3
0
        public void Tweet_added_to_collection_unsorted()
        {
            TweetCollection tweets = new TweetCollection(SortOrder.None);
            Tweet tweet1 = new Tweet() { DateCreated = DateTime.Now, Id = 1 };
            Tweet tweet2 = new Tweet() { DateCreated = tweet1.DateCreated.Value.Subtract(TimeSpan.FromMinutes(5)), Id = 2 };
            Tweet tweet3 = new Tweet() { DateCreated = tweet1.DateCreated.Value.Subtract(TimeSpan.FromMinutes(2)), Id = 2 };

            tweets.Add(tweet1);
            tweets.Add(tweet2);
            tweets.Add(tweet3);
            Assert.That(tweets[0], Is.EqualTo(tweet1));
            Assert.That(tweets[1], Is.EqualTo(tweet2));
            Assert.That(tweets[2], Is.EqualTo(tweet3));
        }
        public TweetCollection GetTweets()
        {
            TweetCollection tweets = new TweetCollection();
            Tweet tweet = new Tweet();
            if (twitter == null)
            {
                tweet.Text = "Please setup your user/password and url in the connection settings.";
                tweets.Add(tweet);
                return tweets;
            }
            try
            {
                //if (_lastId == null)
                tweets = twitter.GetFriendsTimeline();
                /*else
                    tweets = twitter.GetFriendsTimeline(_lastId.ToString());
                if (tweets != null && tweets.Count > 0)
                {
                    _lastId = String.Format("{0:0}", tweets[0].Id);
                }
                else
                {
                    tweet.Text = "sent " + _lastId;
                    tweets.Add(tweet);
                }*/
                return tweets;
            }
            catch (System.Net.WebException we)
            {
                twitter.TwitterServerUrl = twitter.TwitterServerUrl.Replace("https://","http://");
                try
                {
                    return twitter.GetFriendsTimeline();
                }
                catch (Exception err)
                {
                    tweet.Text = err.Message;
                    tweets.Add(tweet);
                    return tweets;
                }

            }
            catch (Exception err)
            {
                tweet.Text = err.Message;
                tweets.Add(tweet);
                return tweets;
            }
        }
 private void ProcessTweetMessages(object obj, DownloadStringCompletedEventArgs args)
 {
     try
     {
         System.Diagnostics.Debug.WriteLine(args.Result);
         StockTwits_Stream_Symbol s = JsonConvert.DeserializeObject <StockTwits_Stream_Symbol>(args.Result);
         Cursor = s.cursor;
         foreach (StockTwits_Message m in s.messages)
         {
             TweetCollection.Add(new TweetItemViewModel()
             {
                 Author = m.user.name + " (" + m.user.username + ")", Content = m.body, PubDate = m.created_at
             });
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.Message);
         System.Diagnostics.Debug.WriteLine(ex.Source);
         System.Diagnostics.Debug.WriteLine(ex.StackTrace);
     }
     if (ProgressBar != null)
     {
         ProgressBar.IsVisible = false;
     }
     this.IsDataLoaded = true;
 }
Пример #6
0
        public TweetCollection GetSearchResults(string searchText, IWebProxy webProxy)
        {
            TweetCollection tweets = new TweetCollection();

            string tweetscanUrl = "http://tweetscan.com/trss.php?s=" + searchText;

            HttpWebRequest request = WebRequest.Create(tweetscanUrl) as HttpWebRequest;

            // Add configured web proxy
            request.Proxy = webProxy;

            //try
            //{
            // Get the Web Response
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream
                StreamReader reader = new StreamReader(response.GetResponseStream());

                // Load the response data into a XmlDocument
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);

                // Get statuses with XPath
                XmlNodeList nodes = doc.SelectNodes("/rss/channel/item");

                foreach (XmlNode node in nodes)
                {
                    Tweet tweet = new Tweet();
                    tweet.Id   = double.Parse(node.SelectSingleNode("tweetid").InnerText);
                    tweet.Text = HttpUtility.HtmlDecode(node.SelectSingleNode("text").InnerText);

                    string dateString = node.SelectSingleNode("pubdate").InnerText;
                    if (!string.IsNullOrEmpty(dateString))
                    {
                        tweet.DateCreated = DateTime.Parse(dateString);
                    }

                    User user = new User();

                    user.Name       = node.SelectSingleNode("username").InnerText;
                    user.ScreenName = node.SelectSingleNode("screenname").InnerText;
                    user.ImageUrl   = node.SelectSingleNode("image").InnerText;

                    tweet.User = user;

                    tweets.Add(tweet);
                }

                tweets.SaveToDisk();
            }
            //}
            //catch {
            ////TODO: not sure what kind of errors are thrown by tweetcan
            //    // eat it.
            //}

            return(tweets);
        }
Пример #7
0
        public TweetCollection GetSearchResults(string searchText, IWebProxy webProxy)
        {
            TweetCollection tweets = new TweetCollection();

            string tweetscanUrl = "http://tweetscan.com/trss.php?s=" + searchText;

            HttpWebRequest request = WebRequest.Create(tweetscanUrl) as HttpWebRequest;

            // Add configured web proxy
            request.Proxy = webProxy;

            //try
            //{
                // Get the Web Response
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    // Load the response data into a XmlDocument
                    XmlDocument doc = new XmlDocument();
                    doc.Load(reader);

                    // Get statuses with XPath
                    XmlNodeList nodes = doc.SelectNodes("/rss/channel/item");

                    foreach (XmlNode node in nodes)
                    {
                        Tweet tweet = new Tweet();
                        tweet.Id = double.Parse(node.SelectSingleNode("tweetid").InnerText);
                        tweet.Text = HttpUtility.HtmlDecode(node.SelectSingleNode("text").InnerText);

                        string dateString = node.SelectSingleNode("pubdate").InnerText;
                        if (!string.IsNullOrEmpty(dateString))
                        {
                            tweet.DateCreated = DateTime.Parse(dateString);
                        }

                        User user = new User();

                        user.Name = node.SelectSingleNode("username").InnerText;
                        user.ScreenName = node.SelectSingleNode("screenname").InnerText;
                        user.ImageUrl = node.SelectSingleNode("image").InnerText;

                        tweet.User = user;

                        tweets.Add(tweet);
                    }

                    tweets.SaveToDisk();
                }
            //}
            //catch {
            ////TODO: not sure what kind of errors are thrown by tweetcan
            //    // eat it.
            //}

            return tweets;
        }
Пример #8
0
 public void Tweet_added_to_empty_collection_succeeds()
 {
     TweetCollection tweets = new TweetCollection();
     Tweet tweet = new Tweet() { DateCreated = DateTime.Now, Id = 1 };
     tweets.Add(tweet);
     Assert.That(tweets.Contains(tweet));
     Assert.That(tweets.Count == 1);
 }
Пример #9
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            TweetScanHelper ts            = new TweetScanHelper();
            TweetCollection searchREsults = ts.GetSearchResults(SearchTextBox.Text);

            foreach (Tweet t in searchREsults)
            {
                tweets.Add(t);
            }
        }
Пример #10
0
        public void Tweet_added_to_empty_collection_succeeds()
        {
            TweetCollection tweets = new TweetCollection();
            Tweet           tweet  = new Tweet()
            {
                DateCreated = DateTime.Now, Id = 1
            };

            tweets.Add(tweet);
            Assert.That(tweets.Contains(tweet));
            Assert.That(tweets.Count == 1);
        }
Пример #11
0
        public void Tweet_added_to_collection_in_sorted_order_with_ascending_sort()
        {
            TweetCollection tweets = new TweetCollection(SortOrder.Ascending);
            Tweet           tweet1 = new Tweet()
            {
                DateCreated = DateTime.Now, Id = 1
            };
            Tweet tweet2 = new Tweet()
            {
                DateCreated = tweet1.DateCreated.Value.Subtract(TimeSpan.FromMinutes(5)), Id = 2
            };
            Tweet tweet3 = new Tweet()
            {
                DateCreated = tweet1.DateCreated.Value.Subtract(TimeSpan.FromMinutes(2)), Id = 2
            };

            tweets.Add(tweet1);
            tweets.Add(tweet2);
            tweets.Add(tweet3);
            Assert.That(tweets[0], Is.EqualTo(tweet2));
            Assert.That(tweets[1], Is.EqualTo(tweet3));
            Assert.That(tweets[2], Is.EqualTo(tweet1));
        }
Пример #12
0
        public void ShowGetTweetDialog()
        {
            int    count;
            string screenName;

            var settings = new MetroDialogSettings()
            {
                AnimateHide = true,
                AnimateShow = true
            };

            var dlg = new GetTweetDialog();

            dlg.OKButton.Click += async(s, e) =>
            {
                count      = Convert.ToInt32(dlg.CountBox.Value);
                screenName = dlg.ScreenNameBox.Text;

                if (!string.IsNullOrWhiteSpace(screenName))
                {
                    dynamic json = await twitterAuth.GetJson($"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={screenName}&count={count}", "GET");

                    if (json == null)
                    {
                        return;
                    }

                    collection.Clear();
                    RetweetCountBlock.Text     = "Unselected";
                    TweetListView.SelectedItem = null;
                    foreach (var obj in json)
                    {
                        Tweet t = new Tweet(obj);
                        collection.Add(t);
                    }
                    if (TweetListView.Items.Count > 0)
                    {
                        TweetListView.ScrollIntoView(TweetListView.Items[0]);
                    }
                }

                await this.HideMetroDialogAsync(dlg, settings);
            };
            dlg.CancelButton.Click += (s, e) =>
            {
                this.HideMetroDialogAsync(dlg, settings);
            };

            DialogManager.ShowMetroDialogAsync(this, dlg, settings);
        }
 public TweetCollection FetchByScreenName(string screenName, int max)
 {
     Logger.Log("FetchByScreenName: " + screenName, System.Diagnostics.TraceEventType.Information);
     var collection = new TweetCollection();
     collection.Add(new Tweet()
     {
         TweetID = 1,
         LocationText = "Milwaukee, WI",
         ProfileImageUrl = String.Empty,
         ScreenName = screenName,
         TweetText = "First tweet!",
         TweetCreated = DateTime.Now.AddMinutes(-10)
     });
     collection.Add(new Tweet()
     {
         TweetID = 1,
         LocationText = "Milwaukee, WI",
         ProfileImageUrl = String.Empty,
         ScreenName = screenName,
         TweetText = "Second tweet!",
         TweetCreated = DateTime.Now.AddMinutes(-5)
     });
     return collection;
 }
Пример #14
0
        private void PopUpNotify(TweetCollection newTweets)
        {
            TweetCollection popUpTweets = new TweetCollection();
            
            foreach (var tweet in newTweets)
            {
                if (ShouldPopUp(tweet))
                    popUpTweets.Add(tweet);
            }

            if (popUpTweets.Count > Double.Parse(AppSettings.MaximumIndividualAlerts))
            {
                Popup p = new Popup("New Tweets", BuiltNewTweetMessage(popUpTweets), twitter.CurrentlyLoggedInUser.ImageUrl, 0);
                SetupPopupProps(p);
                p.Show();
            }
            else
            {
                int index = 0;
                foreach (Tweet tweet in popUpTweets)
                {
                    Popup p = new Popup(tweet, index++);
                    SetupPopupProps(p);
                    p.Show();
                }
            }
        }
Пример #15
0
        /// <summary>
        /// The Main function for interfacing with the Twitter API
        /// </summary>
        /// <returns>Collection of Tweets. Twitter limits the max to 20.</returns>
        private TweetCollection RetrieveTimeline(Timeline timeline, string since, string userId)
        {
            TweetCollection tweets = new TweetCollection();

            string timelineUrl;

            switch (timeline)
            {
                case Timeline.Public:
                    timelineUrl = PublicTimelineUrl;
                    break;
                case Timeline.Friends:
                    timelineUrl = FriendsTimelineUrl;
                    break;
                case Timeline.User:
                    timelineUrl = UserTimelineUrl;
                    break;
                case Timeline.Replies:
                    timelineUrl = RepliesTimelineUrl;
                    break;
                default:
                    timelineUrl = PublicTimelineUrl;
                    break;
            }

            if (!string.IsNullOrEmpty(userId))
                timelineUrl += "/" + userId + Format;
            else
                timelineUrl += Format;

            if (!string.IsNullOrEmpty(since))
            {
                DateTime sinceDate;
                DateTime.TryParse(since, out sinceDate);

                // Go back a minute to compensate for latency.
                sinceDate = sinceDate.AddMinutes(-1);
                string sinceDateString = sinceDate.ToString(twitterSinceDateFormat);
                timelineUrl = timelineUrl + "?since=" + sinceDateString;
            }

            // Create the web request
            HttpWebRequest request = CreateTwitterRequest(timelineUrl);

            // moved this out of the try catch to use it later on in the XMLException
            // trying to fix a bug someone report
            XmlDocument doc = new XmlDocument();
            try
            {
                // Get the Web Response
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    // Load the response data into a XmlDocument
                    doc.Load(reader);
                    // Get statuses with XPath
                    XmlNodeList nodes = doc.SelectNodes("/statuses/status");

                    foreach (XmlNode node in nodes)
                    {
                        Tweet tweet = new Tweet();
                        tweet.Id = double.Parse(node.SelectSingleNode("id").InnerText);
                        tweet.Text = HttpUtility.HtmlDecode(node.SelectSingleNode("text").InnerText);
                        string source = HttpUtility.HtmlDecode(node.SelectSingleNode("source").InnerText);
                        if (!string.IsNullOrEmpty(source))
                            tweet.Source = Regex.Replace(source, @"<(.|\n)*?>", string.Empty);

                        string dateString = node.SelectSingleNode("created_at").InnerText;
                        if (!string.IsNullOrEmpty(dateString))
                        {
                            tweet.DateCreated = DateTime.ParseExact(
                                dateString,
                                twitterCreatedAtDateFormat,
                                CultureInfo.GetCultureInfoByIetfLanguageTag("en-us"), DateTimeStyles.AllowWhiteSpaces);
                        }
                        string replyTo = HttpUtility.HtmlDecode(node.SelectSingleNode("in_reply_to_status_id").InnerText);
                        if (!string.IsNullOrEmpty(replyTo))
                        {
                            tweet.InReplyTo = double.Parse(HttpUtility.HtmlDecode(node.SelectSingleNode("in_reply_to_status_id").InnerText));

                        }
                        XmlNode userNode = node.SelectSingleNode("user");
                        User user = CreateUser(userNode);
                        tweet.User = user;
                        tweet.Timeline = timeline;
                        tweet.IsReply = IsReplyTweet(this.CurrentlyLoggedInUser.ScreenName, tweet);

                        tweets.Add(tweet);
                    }

                    tweets.SaveToDisk();
                }
            }
            catch (XmlException exXML)
            {
                // adding the XML document data to the exception so it will get logged
                // so we can debug the issue
                exXML.Data.Add("XMLDoc", doc);
                throw;
            }
            catch (WebException webExcp)
            {
                ParseWebException(webExcp, timeline, userId);
            }
            return tweets;
        }
Пример #16
0
        public TweetCollection GetConversation(double id)
        {
            TweetCollection tweets = new TweetCollection();
            Tweet tweet = RetrieveTweet(id);
            while (tweet.InReplyTo != null)
            {
                tweets.Add(tweet);
                id = (double)tweet.InReplyTo;
                tweet = RetrieveTweet(id);
            }

            tweets.Add(tweet);
            return tweets;
        }
Пример #17
0
        private void UpdateRepliesInterface(TweetCollection newReplies)
        {
            repliesLastUpdated = DateTime.Now;
            StatusTextBlock.Text = "Replies Updated: " + repliesLastUpdated.ToLongTimeString();

            UpdateExistingTweets(replies);
            TweetCollection addedReplies = new TweetCollection();

            for (int i = newReplies.Count - 1; i >= 0; i--)
            {
                Tweet reply = newReplies[i];
                if (!replies.Contains(reply))
                {
                    replies.Insert(0, reply);
                    reply.Index = replies.Count;
                    reply.IsNew = true;
                    addedReplies.Add(reply);
                }
            }

            if (addedReplies.Count > 0)
            {
                if (AppSettings.DisplayNotifications && !(bool)this.IsActive)
                    NotifyOnNewTweets(addedReplies, "reply");

                if (AppSettings.PlaySounds)
                {
                    // Author: Keith Elder
                    // I wrapped a try catch around this and added logging.
                    // I found that the Popup screen and this were causing 
                    // a threading issue.  At least that is my theory.  When
                    // new items would come in, and play a sound as well as 
                    // pop a new message there was no need to recreate and load
                    // the wave file.  InitializeSoundPlayer() was added on load
                    // to do that just once.
                    try
                    {
                        // Play tweets found sound for new tweets
                        _player.Play();
                    }
                    catch (Exception ex)
                    {
                        App.Logger.Error("Error playing sound", ex);
                    }
                }
            }

            StopStoryboard("Fetching");
        }
Пример #18
0
        private void GetUserTimeline(string userId)
        {
            try
            {
                // Schedule the update function in the UI thread.
                LayoutRoot.Dispatcher.BeginInvoke(
                    DispatcherPriority.Background,
                    new OneArgDelegate(UpdateUsersTimelineInterface), twitter.GetUserTimeline(userId));
            }

            // Jason Follas: Added the following UI feedback behavior for when users weren't found.
            catch (UserNotFoundException userNotFoundEx)
            {

                TweetCollection fakeTweets = new TweetCollection();
                fakeTweets.Add(new Tweet());
                fakeTweets[0].Id = -1;
                fakeTweets[0].Text = userNotFoundEx.Message;
                fakeTweets[0].Source = "Witty Error Handler";
                fakeTweets[0].User = new User();
                fakeTweets[0].User.ScreenName = "@" + userNotFoundEx.UserId;
                fakeTweets[0].User.Description = userNotFoundEx.Message;


                StopStoryboard("Fetching");

                this.UserContextMenu.IsEnabled = false;

                UpdateUsersTimelineInterface(fakeTweets);

            }
            catch (System.Security.SecurityException ex)
            {
                App.Logger.DebugFormat("User not allowed to get protected tweets from {0}. Exception details: {1}", userId, ex.ToString());
                StatusTextBlock.Text = userId + "'s updates are protected.";
                StopStoryboard("Fetching");
            }
            catch (WebException ex)
            {
                App.Logger.DebugFormat("There was a problem fetching the user's timeline from Twitter.com: {0}", ex.ToString());
            }
            catch (ProxyAuthenticationRequiredException ex)
            {
                App.Logger.Error("Incorrect proxy configuration.");
                MessageBox.Show("Proxy server is configured incorrectly.  Please correct the settings on the Options menu.");
            }
            catch (ProxyNotFoundException ex)
            {
                App.Logger.Error("Incorrect proxy configuration.");
                MessageBox.Show(ex.Message);
            }

        }
Пример #19
0
        private void UpdateUserInterface(TweetCollection newTweets)
        {
            DateTime lastUpdated = DateTime.Now;
            StatusTextBlock.Text = "Last Updated: " + lastUpdated.ToLongTimeString();

            AppSettings.LastUpdated = lastUpdated.ToString();
            AppSettings.Save();

            FilterTweets(newTweets, true);
            HighlightTweets(newTweets);
            UpdateExistingTweets();

            TweetCollection addedTweets = new TweetCollection();

            //prevents huge number of notifications appearing on startup
            bool displayPopups = !(tweets.Count == 0);

            // Add the new tweets
            for (int i = newTweets.Count - 1; i >= 0; i--)
            {
                Tweet tweet = newTweets[i];

                if (tweets.Contains(tweet) || HasBehavior(tweet, UserBehavior.Ignore) || IsTruncatedTweet(tweet))
                    continue;

                tweets.Add(tweet);
                tweet.Index = tweets.Count;
                tweet.IsNew = true;
                addedTweets.Add(tweet);
            }

            // tweets listbox ScrollViewer.CanContentScroll is set to "False", which means it scrolls more smooth,
            // However it disables Virtualization
            // Remove tweets pass 100 should improve performance reasons.
            if (AppSettings.KeepLatest != 0)
            {
                if (tweets.Count > AppSettings.KeepLatest)
                    lastTruncatedTweetTime = tweets[AppSettings.KeepLatest - 1].DateCreated;

                tweets.TruncateAfter(AppSettings.KeepLatest);
            }

            if (addedTweets.Count > 0)
            {
                if (AppSettings.DisplayNotifications && !(bool)this.IsActive)
                    NotifyOnNewTweets(addedTweets, "tweet");

                if (AppSettings.PlaySounds)
                {
                    // Author: Keith Elder
                    // I wrapped a try catch around this and added logging.
                    // I found that the Popup screen and this were causing 
                    // a threading issue.  At least that is my theory.  When
                    // new items would come in, and play a sound as well as 
                    // pop a new message there was no need to recreate and load
                    // the wave file.  InitializeSoundPlayer() was added on load
                    // to do that just once.
                    try
                    {
                        // Play tweets found sound for new tweets
                        _player.Play();
                    }
                    catch (Exception ex)
                    {
                        App.Logger.Error("Error playing sound", ex);
                    }
                }
            }

            StopStoryboard("Fetching");
        }
Пример #20
0
        /// <summary>
        /// The Main function for interfacing with the Twitter API
        /// </summary>
        /// <returns>Collection of Tweets. Twitter limits the max to 20.</returns>
        private TweetCollection RetrieveTimeline(Timeline timeline, string since, string userId)
        {
            if (!IsLoggedIn()) return null;

            var tweets = new TweetCollection();

            ITwitterLeafNode request;

            switch (timeline)
            {
                case Timeline.Public:
                    request = CreateRequest().Statuses().OnPublicTimeline();
                    break;
                case Timeline.Friends:
                    request = CreateRequest().Statuses().OnFriendsTimeline();
                    break;
                case Timeline.User:
                    request = CreateRequest().Statuses().OnUserTimeline().For(userId);
                    break;
                case Timeline.Replies:
                    request = CreateRequest().Statuses().Mentions();
                    break;
                default:
                    request = CreateRequest().Statuses().OnPublicTimeline();
                    break;
            }

            if (!string.IsNullOrEmpty(since))
            {
                DateTime sinceDate;
                DateTime.TryParse(since, out sinceDate);

                // Go back a minute to compensate for latency.
                sinceDate = sinceDate.AddMinutes(-1);

                //TODO: Need to make use of since information
            }

            foreach (TwitterStatus result in request.Request().AsStatuses())
            {
                tweets.Add(GetTweetFromTwitterStatus(result));
            }

            tweets.SaveToDisk();
            return tweets;
        }
Пример #21
0
        private void AddTweet(string tweetText)
        {
            try
            {
                //bgriswold: Keeping check in place in case final character string is URL and it wasn't reformatted on the fly.
                if (tweetText.Length > TwitterNet.CharacterLimit) 
                {
                    ParseTextHereAndTinyUpAnyURLsFound(ref tweetText);
                }

                var addedTweets = new TweetCollection();

                string[] statuses = TweetSplitter.SplitTweet(tweetText);
                foreach (string status in statuses)
                {
                    if (isReplyMessage)
                    {
                        addedTweets.Add(twitter.AddTweet(status, SelectedTweet.Id));
                    }
                    else 
                    {
                        addedTweets.Add(twitter.AddTweet(status));
                    }
                }

                if (statuses.Length > 0)
                {
                    ScheduleUpdateFunctionInUIThread(addedTweets);
                }

            }
            catch (WebException ex)
            {
                UpdateTextBlock.Text = "Update failed.";
                App.Logger.Debug(String.Format("There was a problem fetching new tweets from Twitter.com: {0}", ex.ToString()));
            }
            catch (ProxyAuthenticationRequiredException ex)
            {
                App.Logger.Error("Incorrect proxy configuration.");
                MessageBox.Show("Proxy server is configured incorrectly.  Please correct the settings on the Options menu.");
            }
            catch (ProxyNotFoundException ex)
            {
                App.Logger.Error("Incorrect proxy configuration.");
                MessageBox.Show(ex.Message);
            }

        }