public static void PublicTimeline()
        {
            TwitterStatusCollection timeline = TwitterTimeline.PublicTimeline().ResponseObject;

            Assert.IsNotNull(timeline);
            Assert.IsNotEmpty(timeline);

            Assert.That(timeline.Count > 0 && timeline.Count <= 20, "Timeline should contain between 0 and 20 items.");
        }
예제 #2
0
        public void ProcessTweetsCallback(TwitterAsyncResponse <TwitterStatusCollection> ee)
        {
            TwitterStatusCollection tweets = ee.ResponseObject;

            if (tweets == null)
            {
                Global.DeckForm.TweetFailure(ee.Content);
                return;
            }
            for (int i = tweets.Count - 1; i >= 0; i--)
            {
                InsertTweet(flowColumn, tweets[i]);
            }
        }
예제 #3
0
        private void prefetch(UserDatabase.User usr)
        {
            TwitterStatusCollection prefetch = usr.tweetStack.Twitter.GetTweets();

            foreach (TwitterStatus status in prefetch)
            {
                TweetElement element = new TweetElement(this, status, usr, ImageCache.GetImage(status.User.Id, status.User.ProfileImageLocation));
                element.polyOpacity = polygonOpacity;
                this.TweetElements.Items.Add(element);

                if (this.TweetElements.Items.Count > o3o.Properties.Settings.Default.amountOfTWeetsToDisplay)
                {
                    TweetElement el = (TweetElement)this.TweetElements.Items[this.TweetElements.Items.Count - 1];
                    this.TweetElements.Items.Remove(el);
                    el.Dispose();
                }
            }

            TwitterStatusCollection prefetchMentions = usr.tweetStack.Twitter.GetMentions();

            foreach (TwitterStatus status in prefetchMentions)
            {
                TweetElement element = new TweetElement(this, status, usr, ImageCache.GetImage(status.User.Id, status.User.ProfileImageLocation));
                element.polyOpacity = polygonOpacity;
                this.TweetMentions.Items.Add(element);

                if (this.TweetElements.Items.Count > o3o.Properties.Settings.Default.amountOfTWeetsToDisplay)
                {
                    TweetElement el = (TweetElement)this.TweetMentions.Items[this.TweetMentions.Items.Count - 1];
                    this.TweetMentions.Items.Remove(el);
                    el.Dispose();
                }
            }

            TwitterDirectMessageCollection fetchmessages = usr.tweetStack.Twitter.GetMessages();

            foreach (TwitterDirectMessage message in fetchmessages)
            {
                DMElement element = new DMElement(this, message, usr, ImageCache.GetImage(message.SenderId, message.Sender.ProfileImageLocation));
                element.polyOpacity = polygonOpacity;
                this.TweetMessages.Items.Add(element);

                if (this.TweetMessages.Items.Count > o3o.Properties.Settings.Default.amountOfTWeetsToDisplay)
                {
                    DMElement el = (DMElement)this.TweetMessages.Items[this.TweetMessages.Items.Count - 1];
                    this.TweetMessages.Items.Remove(el);
                    el.Dispose();
                }
            }
        }
예제 #4
0
        public static TwitterStatusCollection GetMention(int count = 1)
        {
            TimelineOptions TLoption = new TimelineOptions();
            TLoption.Proxy = proxy;
            TLoption.Count = count;

            TwitterStatusCollection statusCollection = new TwitterStatusCollection();

            TwitterResponse<TwitterStatusCollection> userResponse = TwitterTimeline.Mentions(tokens, TLoption);
            if (userResponse.Result == RequestResult.Success)
            {
                foreach (TwitterStatus tempstatus in userResponse.ResponseObject)
                {
                    tempstatus.Text = System.Web.HttpUtility.HtmlDecode(tempstatus.Text);
                    statusCollection.Add(tempstatus);
                }
            }
            //System.Threading.Thread.Sleep(10000); //模拟网络状态不良用
            MemoryMap.SerializeTwitterStatusCollection("WidgetwitLite-MemoryMappedFile-Connect", statusCollection);
            return statusCollection;
        }
예제 #5
0
        /// <summary>
        /// Get the tweets from the Twitter object
        /// </summary>
        /// <param name="PageNumber"></param>
        /// <returns></returns>
        private TwitterStatusCollection FetchTweets(int PageNumber)
        {
            TwitterStatusCollection tweets = new TwitterStatusCollection();

            //cache the tweets here
            if (Page.Cache[string.Format("Tweet-{0}-{1}", PageNumber, this.ScreenName)] == null)
            {
                //set the tokens here
                OAuthTokens tokens = new OAuthTokens();
                tokens.ConsumerKey       = this.ConsumerKey;
                tokens.ConsumerSecret    = this.ConsumerSecret;
                tokens.AccessToken       = this.AccessToken;
                tokens.AccessTokenSecret = this.AccessTokenSecret;


                UserTimelineOptions options = new UserTimelineOptions();
                options.Count      = this.TweetCount * PageNumber;
                options.Page       = 1;
                options.ScreenName = this.ScreenName;


                //now hit the twitter and get the response
                tweets = TwitterTimeline.UserTimeline(tokens, options).ResponseObject;

                if (PageNumber == 1)
                {
                    HttpContext.Current.Cache.Add(string.Format("Tweet-{0}-{1}", PageNumber, this.ScreenName), tweets, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, CacheRemovedCallBack);
                }
                else
                {
                    HttpContext.Current.Cache.Insert(string.Format("Tweet-{0}-{1}", PageNumber, this.ScreenName), tweets, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                }
            }
            else
            {
                tweets = HttpContext.Current.Cache[string.Format("Tweet-{0}-{1}", PageNumber, this.ScreenName)] as TwitterStatusCollection;
            }

            return(tweets);
        }
예제 #6
0
        private List <Message> MapMessage(TwitterStatusCollection statusCollection)
        {
            if (statusCollection == null)
            {
                return(null);
            }

            List <Message> messageCollection = new List <Message>();

            foreach (TwitterStatus status in statusCollection)
            {
                TwitterMessage message = new TwitterMessage();
                message.PostedOn     = status.CreatedDate;
                message.Source       = SocialNetworks.Twitter;
                message.Text         = status.LinkifiedText();
                message.UserName     = status.User.Name;
                message.UserImageUrl = status.User.ProfileImageLocation;

                messageCollection.Add(message);
            }

            return(messageCollection.OrderByDescending(msg => msg.PostedOn).ToList());
        }
예제 #7
0
        /// <summary>
        /// Generates the tweet table
        /// </summary>
        /// <param name="PageNumber"></param>
        /// <returns></returns>
        private Table CreateTweetTable(int PageNumber, TwitterStatusCollection tweets)
        {
            int i = 0;
            bool isTweetOnlyText = true;
            Table mainTable, innerTable;
            TableRow tr;
            TableCell tc, tcImage, tcText;
            HyperLink imgHyperLink;
            string strSource;
            Label lblContent;

            mainTable = new Table();
            mainTable.Width = Unit.Percentage(100);
            mainTable.CellSpacing = 0;
            mainTable.CellPadding = 0;
            this.Controls.Add(mainTable);

            if (tweets.Count > 0)
            {
                foreach (TwitterStatus tweet in tweets)
                {
                    isTweetOnlyText = true;
                    innerTable = new Table();
                    innerTable.CssClass = "ms-viewlsts";
                    innerTable.Width = Unit.Percentage(100);

                    if (i <= this.TweetCount * PageNumber)
                    {
                        tr = new TableRow();
                        mainTable.Rows.Add(tr);

                        tc = new TableCell();
                        tc.Width = Unit.Percentage(10);

                        tr.CssClass = " ms-WPBorderBorderOnly , twitBorderBottom";

                        #region UserImage
                        //Showing the user image
                        if (this.EnableShowImage)
                        {
                            imgHyperLink = new HyperLink();
                            imgHyperLink.ImageUrl = tweet.User.ProfileImageLocation;
                            imgHyperLink.NavigateUrl = "http://twitter.com/" + tweet.User.ScreenName;
                            imgHyperLink.Attributes.Add("target", "_blank");
                            tc.Controls.Add(imgHyperLink);
                            tc.CssClass = "twitHeaderImage";
                            tr.Cells.Add(tc);
                        }
                        #endregion

                        tc = new TableCell();
                        tc.Controls.Add(innerTable);
                        tr.Controls.Add(tc);

                        tr = new TableRow();
                        innerTable.Rows.Add(tr);

                        #region TwitPic
                        //Code for showing the image on the webpart
                        if (tweet.Entities.Count > 0)
                        {
                            int tweetCount = Convert.ToInt32(tweet.Entities.Count);

                            for (int tweetEntityCount = 0; tweetEntityCount < tweetCount; tweetEntityCount++)
                            {
                                //Check if the tweet is having the Picture
                                if (tweet.Entities[tweetEntityCount].ToString().Equals("Twitterizer.Entities.TwitterMediaEntity"))
                                {
                                    if (!string.IsNullOrEmpty(((Twitterizer.Entities.TwitterMediaEntity)(tweet.Entities[tweetEntityCount])).MediaUrl.ToString()))
                                    {
                                        //Create a new table to add the image and corresponding text
                                        tc = new TableCell();
                                        tr.Cells.Add(tc);
                                        Table tb = new Table();
                                        tb.Width = Unit.Percentage(100);
                                        tc.Controls.Add(tb);
                                        TableRow trinner = new TableRow();

                                        //get the image URL
                                        string ImageURL = ((Twitterizer.Entities.TwitterMediaEntity)(tweet.Entities[tweetEntityCount])).MediaUrl.ToString();

                                        tcImage = new TableCell();

                                        HyperLink imgTweet = new HyperLink();
                                        imgTweet.NavigateUrl = ImageURL;
                                        imgTweet.Attributes.Add("target", "_blank");

                                        //Added the HTMLImage Control to resize the image
                                        HtmlImage htmlImage = new HtmlImage();
                                        htmlImage.Src = ImageURL;
                                        htmlImage.Height = 100;
                                        htmlImage.Width = 137;
                                        htmlImage.Border = 0;
                                        imgTweet.Controls.Add(htmlImage);
                                        tcImage.Width = 137;
                                        tcImage.Controls.Add(imgTweet);
                                        //tcImage.Attributes.Add("style", "padding-top:0.5%");
                                        trinner.Cells.Add(tcImage);

                                        //Add the linkfied text
                                        lblContent = new Label();
                                        lblContent.Text = tweet.LinkifiedText();
                                        lblContent.ForeColor = Color.Black;

                                        //Show the text next to the Image
                                        tcText = new TableCell();
                                        tcText.Controls.Add(lblContent);
                                        trinner.Cells.Add(tcText);

                                        isTweetOnlyText = false;

                                        tb.Rows.Add(trinner);
                                    }
                                }
                            }
                        }
                        #endregion

                        #region Show Tweet
                        //If only the text is there in the image
                        if (isTweetOnlyText)
                        {
                            tc = new TableCell();
                            tr.Cells.Add(tc);

                            lblContent = new Label();
                            lblContent.Text = tweet.LinkifiedText();
                            lblContent.ForeColor = Color.Black;

                            tc.Controls.Add(lblContent);
                            tc.CssClass = "ms-vb2";
                        }
                        #endregion

                        #region Show Description
                        if (this.EnableShowDesc)
                        {
                            tr = new TableRow();
                            innerTable.Rows.Add(tr);
                            tc = new TableCell();
                            tr.Cells.Add(tc);

                            if (tweet.Source.StartsWith("<"))
                                strSource = tweet.Source.Substring(tweet.Source.IndexOf('>') + 1, tweet.Source.LastIndexOf('<') - tweet.Source.IndexOf('>') - 1);
                            else
                                strSource = tweet.Source;

                            tc.Text = relativeTime(tweet.CreatedDate.ToString()) + " via " + strSource;
                            tc.CssClass = "ms-vb2";
                            tc.ForeColor = Color.Gray;
                        }
                        #endregion
                    }
                    else
                    {
                        break;
                    }
                    i++;
                }

                imgbtnNext.Visible = true;
                imgNoTweet.Visible = false;
            }
            else
            {
                imgbtnNext.Visible = false;
                imgNoTweet.Visible = true;

                tr = new TableRow();
                mainTable.Rows.Add(tr);

                tc = new TableCell();
                tc.Width = Unit.Percentage(100);
                tc.CssClass = "ms-vb2";
                tc.HorizontalAlign = HorizontalAlign.Center;
                tc.ForeColor = Color.Gray;
                tr.Cells.Add(tc);

                tc.Text = string.Format("{0} hasn't tweeted yet.", this.ScreenName);

            }
            // if the number of tweet response is less than the number of tweets demanded than there are no more tweets : show grey tweet
            if (tweets.Count < this.TweetCount * PageNumber)
            {
                imgbtnNext.Visible = false;
                imgNoTweet.Visible = true;
            }
            return mainTable;
        }
예제 #8
0
        private IEnumerable<TwitterStatus> GetRelatedStatuses(TwitterStatus status)
        {
            Contract.Requires<ArgumentNullException>(status != null);

            TwitterStatusCollection result = new TwitterStatusCollection();
            TwitterStatus temp = status;

            while (temp.InReplyToStatusId.HasValue)
            {
                var inReplyTo = TwitterStatus.Show(temp.InReplyToStatusId.Value).ResponseObject;
                result.Add(inReplyTo);
                temp = inReplyTo;
            }
            return result;
        }
예제 #9
0
 private List<TwitterStatus> SortTimeline(TwitterStatusCollection timeline)
 {
     List<TwitterStatus> sortedTimeline =
         new List<TwitterStatus>(
             timeline.Count
         );
     foreach (TwitterStatus status in timeline) {
         sortedTimeline.Add(status);
     }
     sortedTimeline.Sort(
         (a, b) => (a.CreatedDate.CompareTo(b.CreatedDate))
     );
     return sortedTimeline;
 }
예제 #10
0
        private List<Message> MapMessage(TwitterStatusCollection statusCollection)
        {
            if (statusCollection == null)
                return null;

            List<Message> messageCollection = new List<Message>();

            foreach (TwitterStatus status in statusCollection)
            {
                TwitterMessage message = new TwitterMessage();
                message.PostedOn = status.CreatedDate;
                message.Source = SocialNetworks.Twitter;
                message.Text = status.LinkifiedText();
                message.UserName = status.User.Name;
                message.UserImageUrl = status.User.ProfileImageLocation;

                messageCollection.Add(message);
            }

            return messageCollection.OrderByDescending(msg => msg.PostedOn).ToList();
        }
        internal static CommandResult GetTimelines(decimal[] ids, bool resume)
        {
            if (!IsInitiated)
            {
                return(CommandResult.NotInitiated);
            }

            foreach (var id in ids)
            {
                if (id == 0)
                {
                    continue;
                }

                var UserToProcess = (new TwitterContext()).Users.FirstOrDefault(u => u.Id == id);

                if (UserToProcess == null)
                {
                    Form.AppendLineToOutput(string.Format("User with id {0} does not exist in the database.", id), Color.DarkSlateBlue);
                    continue;
                }
                //else continue and get user's timeline

                string  ScreenName       = UserToProcess.ScreenName;
                decimal IdNumber         = UserToProcess.Id;
                long    NumberOfStatuses = UserToProcess.NumberOfStatuses;

                TwitterContext db = null;
                try
                {
                    //var _friendshipContext = new TwitterEntitiesForFriendship();

                    TwitterResponse <TwitterStatusCollection> TimelineResponse;
                    int numTweets            = 0;
                    int duplicatesFoundTotal = 0;

                    Form.AppendLineToOutput(string.Format("Attempt to save timeline for {0} ({1} tweets).", ScreenName, NumberOfStatuses), Color.DarkSlateBlue);

                    decimal EarliestTweetId = 0;

                    if (resume)
                    {
                        EarliestTweetId = GetEarliestTweetId(id);
                    }
                    do
                    {
                        TimelineResponse = TwitterTimeline.UserTimeline(
                            Tokens,
                            new UserTimelineOptions
                        {
                            UserId = IdNumber,
                            Count  = MaxNumberOfTweets,
                            //SkipUser = false, //get the user's full details so it matches the User object in our db context.
                            SkipUser        = true,
                            MaxStatusId     = EarliestTweetId,
                            IncludeRetweets = true
                        }
                            );

                        if (TimelineResponse.Result == RequestResult.Success)
                        {
                            TwitterStatusCollection tweets = TimelineResponse.ResponseObject;
                            int duplicates = 0;
                            if (tweets == null || tweets.Count == 0)
                            {
                                break;
                            }
                            else
                            {
                                foreach (TwitterStatus tweet in tweets)
                                {
                                    //refresh context
                                    db = new TwitterContext();
                                    db.Configuration.AutoDetectChangesEnabled = false;

                                    if (!db.Tweets.Any(t => t.Id == tweet.Id)) //only continue if the tweet doesn't already exist
                                    {
                                        SaveTweet(tweet);

                                        numTweets++;
                                    }
                                    else
                                    {
                                        duplicates++;;
                                    }
                                }

                                duplicatesFoundTotal += duplicates;
                                EarliestTweetId       = tweets.LastOrDefault().Id - 1;
                            }

                            Form.AppendLineToOutput(string.Format("{0} tweets now saved for {1} (id:{2}). {3} duplicate {4} not saved.", numTweets, ScreenName, IdNumber, duplicatesFoundTotal, duplicatesFoundTotal == 1 ? "tweet" : "tweets"), Color.DarkSlateBlue);

                            //if we are getting no more new tweets then assume saved timeline is now up to date.
                            if (duplicates == tweets.Count)
                            {
                                break;
                            }
                        }
                        else if (TimelineResponse.Result == RequestResult.RateLimited)
                        {
                            WaitForRateLimitReset(TimelineResponse);

                            Form.AppendLineToOutput("Resuming GetTimelines command", Color.DarkSlateBlue);
                            continue;
                        }
                        else if (TimelineResponse.Result == RequestResult.Unauthorized || TimelineResponse.Result == RequestResult.FileNotFound)
                        {
                            /**
                             * Attempt to fix a bug discovered on 2012-06-21: user no longer exists so Twitter returns a
                             * FileNotFound error ('sorry the page no longer exists'). Because of the hack above which
                             * forces the loop to continue it keeps looping and getting the same error until all 350 calls
                             * are exhausted then repeats and repeats :(
                             *
                             * Attempted fix/change is: added "|| timelineResponse.Result == RequestResult.FileNotFound"
                             * treat no-longer-existant users the same as protected users.
                             **/
                            Form.AppendLineToOutput(string.Format("User {0} is now private or no longer exists.", ScreenName), Color.DarkSlateBlue);

                            //Set user to protected.
                            using (var tmpDb = new TwitterContext())
                            {
                                var u = tmpDb.Users.Find(IdNumber);
                                u.IsProtected = true;
                                tmpDb.SaveChanges();
                            }

                            break; //give up with current user
                        }
                        else
                        {
                            HandleTwitterizerError <TwitterStatusCollection>(TimelineResponse);

                            //log that this user should be retried later
                            File.AppendAllText(@".\users-to-retry.txt", IdNumber.ToString() + Environment.NewLine);

                            break; //give up with current user for now
                        }
                    } while (TimelineResponse.ResponseObject != null && TimelineResponse.ResponseObject.Count > 0);
                }
                catch (Exception e)
                {
                    Exception current = e;
                    Form.AppendLineToOutput(string.Format("Unexpected exception : {0}", e.Message), Color.DarkSlateBlue);

                    while (current.InnerException != null)
                    {
                        Form.AppendLineToOutput(string.Format("Inner exception : {0}", current.InnerException.Message), Color.DarkSlateBlue);
                        current = current.InnerException;
                    }

                    //log that this user should be retried later
                    File.AppendAllText(@".\users-to-retry.txt", IdNumber.ToString() + Environment.NewLine);

                    continue; //give up with current user
                }
                finally
                {
                    if (db != null)
                    {
                        db.Dispose();
                    }
                }
            }

            return(CommandResult.Success);
        }
        public static CommandResult GetRepliedToTweets(decimal[] ids)
        {
            if (!IsInitiated)
            {
                return(CommandResult.NotInitiated);
            }

            Form.AppendLineToOutput(string.Format("Attempt to get tweets which were replied to"), Color.DarkMagenta);

            int numTweets = 0;
            int notAdded  = 0;

            for (int i = 0; i < ids.Length; i += 100)
            {
                TwitterIdCollection idsToLookup = new TwitterIdCollection(ids.Skip(i).Take(100).ToList());

                TwitterContext db = null;
                try
                {
                    TwitterResponse <TwitterStatusCollection> result = null;

                    result = TwitterStatus.Lookup(Tokens, new LookupStatusesOptions
                    {
                        StatusIds = idsToLookup
                    });

                    if (result.Result == RequestResult.Success)
                    {
                        TwitterStatusCollection tweets = result.ResponseObject;

                        //refresh context
                        db = new TwitterContext();
                        db.Configuration.AutoDetectChangesEnabled = false;

                        foreach (TwitterStatus tweet in tweets)
                        {
                            try
                            {
                                numTweets++;

                                TwitterUser userInDb = db.Users.FirstOrDefault(u => u.Id == tweet.User.Id);
                                if (userInDb != null)
                                {
                                    tweet.User = userInDb;
                                }

                                tweet.RetweetedStatus = null;
                                tweet.QuotedStatus    = null;

                                db.Tweets.Add(tweet);
                                db.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                //Form.AppendLineToOutput(string.Format("{0} -ERROR- {1}", tweet.Id, ex.Message), Color.DarkMagenta);
                                //Form.AppendLineToOutput(ex.StackTrace, Color.DarkMagenta);

                                db        = new TwitterContext();
                                notAdded += 1;
                            }
                        }



                        Form.AppendLineToOutput(string.Format("{0} tweets processed. {1} duplicate {2} not saved.", numTweets, notAdded, notAdded == 1 ? "tweet" : "tweets"), Color.DarkMagenta);
                    }
                    else if (result.Result == RequestResult.RateLimited)
                    {
                        WaitForRateLimitReset(result);

                        Form.AppendLineToOutput("Resuming get replied-to-tweets command", Color.DarkMagenta);
                        continue;
                    }
                }
                catch (Exception e)
                {
                    Exception current = e;
                    Form.AppendLineToOutput(string.Format("Unexpected exception : {0}", e.Message), Color.DarkMagenta);

                    while (current.InnerException != null)
                    {
                        Form.AppendLineToOutput(string.Format("Inner exception : {0}", current.InnerException.Message), Color.DarkMagenta);
                        current = current.InnerException;
                    }

                    db = new TwitterContext();

                    continue; //give up with current batch
                }
                finally
                {
                    if (db != null)
                    {
                        db.Dispose();
                    }
                }
            }

            return(CommandResult.Success);
        }
예제 #13
0
        private TwitterStatusCollection getTwittergotchiDirectedOwnerTweets(String ownerName, String twittergotchiName)
        {
            TwitterStatusCollection directedToTwittergotchiTweets = new TwitterStatusCollection();

            UserTimelineOptions options = new UserTimelineOptions();
            options.ScreenName = ownerName;
            TwitterResponse<TwitterStatusCollection> userTimeline = TwitterTimeline.UserTimeline(options);
            TwitterStatusCollection userStatusCollection = userTimeline.ResponseObject;
            foreach(TwitterStatus userStatus in userStatusCollection)
            {
                if(userStatus.InReplyToScreenName == twittergotchiName) {
                    directedToTwittergotchiTweets.Add(userStatus);
                }
            }
            return directedToTwittergotchiTweets;
        }
예제 #14
0
 public HomeViewModel(TwitterStatusCollection mattTweets, TwitterStatusCollection christyTweets)
 {
     MattTweets = mattTweets;
     ChristyTweets = christyTweets;
 }
예제 #15
0
 public static void TwitterRest(Guid unqiueID, TweetListType TweetType, Decimal TwitterAccountID, RefreshTypes RefreshType, Action initialCallback, string SearchTerm = null, Decimal InReplyToID = 0M, Decimal LastUpdateID = 0M, Decimal OldestTweetID = 0M, bool ListRetweets = true)
 {
     Func<string> MessengerToken = (Func<string>)(() => ((object)ViewModelMessages.RestUpdate).ToString() + unqiueID.ToString());
     Action<Task<TwitterResponse<SearchResult>>> continuationAction1 = (Action<Task<TwitterResponse<SearchResult>>>)(searchResponse =>
     {
         Action local_0 = initialCallback;
         try
         {
             TwitterStatusCollection local_1 = searchResponse.Result.ResponseObject.Statuses ?? new TwitterStatusCollection();
             Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)new MetroRestResponse<TwitterStatusCollection>()
             {
                 Tweets = local_1,
                 RefreshType = RefreshType,
                 RequestResult = searchResponse.Result.Result,
                 Error = searchResponse.Result.Errors
             }), (object)MessengerToken());
             Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(-1), (object)ViewModelMessages.ProgressVisible);
             App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, searchResponse.Result.RateLimiting, "");
         }
         catch
         {
         }
         finally
         {
             if (local_0 != null)
             {
                 local_0();
                 local_0 = null;
             }
         }
     });
     Action<Task<TwitterResponse<TwitterStatusCollection>>> continuationAction2 = (Action<Task<TwitterResponse<TwitterStatusCollection>>>)(response =>
     {
         Action local_0 = initialCallback;
         try
         {
             TwitterStatusCollection local_1 = response.Result.ResponseObject ?? new TwitterStatusCollection();
             Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)new MetroRestResponse<TwitterStatusCollection>()
             {
                 Tweets = local_1,
                 RefreshType = RefreshType,
                 RequestResult = response.Result.Result,
                 Error = response.Result.Errors
             }), (object)MessengerToken());
             Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(-1), (object)ViewModelMessages.ProgressVisible);
             App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, response.Result.RateLimiting, "");
         }
         catch
         {
         }
         finally
         {
             if (local_0 != null)
                 local_0();
         }
     });
     try
     {
         Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(1), (object)ViewModelMessages.ProgressVisible);
         TimelineOptions timelineOptions = MetroTwitTwitterizer.TimelineOptions;
         if (TweetType != TweetListType.Search && TweetType != TweetListType.DirectMessages && TweetType != TweetListType.Favourites && TweetType != TweetListType.Conversation)
         {
             if (RefreshType != RefreshTypes.ForeverScroll)
                 timelineOptions.SinceStatusId = LastUpdateID;
             else
                 timelineOptions.MaxStatusId = OldestTweetID;
         }
         Action action1;
         switch (TweetType)
         {
             case TweetListType.FriendsTimeline:
                 Timelines.HomeTimelineAsync(App.AppState.Accounts[TwitterAccountID].Tokens, timelineOptions).ContinueWith(continuationAction2);
                 break;
             case TweetListType.DirectMessages:
                 DirectMessagesOptions directMessageOptions = MetroTwitTwitterizer.DirectMessageOptions;
                 DirectMessagesSentOptions sentMessageOptions = MetroTwitTwitterizer.DirectSentMessageOptions;
                 if (RefreshType != RefreshTypes.ForeverScroll)
                 {
                     directMessageOptions.SinceStatusId = LastUpdateID;
                     sentMessageOptions.SinceStatusId = LastUpdateID;
                 }
                 else
                 {
                     directMessageOptions.MaxStatusId = OldestTweetID;
                     sentMessageOptions.MaxStatusId = OldestTweetID;
                 }
                 try
                 {
                     DirectMessages.SentAsync(App.AppState.Accounts[TwitterAccountID].Tokens, sentMessageOptions).ContinueWith((Action<Task<TwitterResponse<TwitterDirectMessageCollection>>>)(directMessagesSentResponse =>
                     {
                         if (directMessagesSentResponse.Result.Result == RequestResult.Success)
                         {
                             DirectMessages.ReceivedAsync(App.AppState.Accounts[TwitterAccountID].Tokens, directMessageOptions).ContinueWith((Action<Task<TwitterResponse<TwitterDirectMessageCollection>>>)(directMessagesReceived =>
                             {
                                 if (directMessagesReceived.Result.Result == RequestResult.Success && directMessagesReceived.Result.ResponseObject != null && directMessagesSentResponse.Result.ResponseObject != null)
                                 {
                                     IOrderedEnumerable<TwitterDirectMessage> local_0 = Enumerable.OrderByDescending<TwitterDirectMessage, DateTime>(Enumerable.Union<TwitterDirectMessage>((IEnumerable<TwitterDirectMessage>)directMessagesReceived.Result.ResponseObject, (IEnumerable<TwitterDirectMessage>)directMessagesSentResponse.Result.ResponseObject), (Func<TwitterDirectMessage, DateTime>)(s => s.CreatedDate)) ?? (IOrderedEnumerable<TwitterDirectMessage>)new TwitterDirectMessageCollection();
                                     Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)new MetroRestResponse<IEnumerable<TwitterDirectMessage>>()
                                     {
                                         Tweets = (IEnumerable<TwitterDirectMessage>)local_0,
                                         RefreshType = RefreshType,
                                         RequestResult = directMessagesReceived.Result.Result
                                     }), (object)MessengerToken());
                                     Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(-1), (object)ViewModelMessages.ProgressVisible);
                                     if (initialCallback != null)
                                     {
                                         initialCallback();
                                         initialCallback = (Action)null;
                                     }
                                     App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, directMessagesSentResponse.Result.RateLimiting, "S");
                                     App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, directMessagesReceived.Result.RateLimiting, "R");
                                 }
                                 else
                                 {
                                     IEnumerable<TwitterError> local_3 = directMessagesReceived.Result.Errors;
                                     if (local_3 != null)
                                     {
                                         Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)new MetroRestResponse<IEnumerable<TwitterDirectMessage>>()
                                         {
                                             Tweets = (IEnumerable<TwitterDirectMessage>)new TwitterDirectMessageCollection(),
                                             RefreshType = RefreshType,
                                             Error = local_3,
                                             RequestResult = directMessagesReceived.Result.Result
                                         }), (object)MessengerToken());
                                         Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(-1), (object)ViewModelMessages.ProgressVisible);
                                     }
                                     if (initialCallback != null)
                                     {
                                         Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)null), (object)MessengerToken());
                                         initialCallback();
                                         initialCallback = (Action)null;
                                     }
                                     App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, directMessagesReceived.Result.RateLimiting, "R");
                                 }
                             }));
                         }
                         else
                         {
                             IEnumerable<TwitterError> local_0 = directMessagesSentResponse.Result.Errors;
                             if (local_0 != null)
                             {
                                 Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)new MetroRestResponse<IEnumerable<TwitterDirectMessage>>()
                                 {
                                     Tweets = (IEnumerable<TwitterDirectMessage>)new TwitterDirectMessageCollection(),
                                     RefreshType = RefreshType,
                                     Error = local_0,
                                     RequestResult = directMessagesSentResponse.Result.Result
                                 }), (object)MessengerToken());
                                 Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(-1), (object)ViewModelMessages.ProgressVisible);
                             }
                             if (initialCallback != null)
                             {
                                 Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)null), (object)MessengerToken());
                                 initialCallback();
                                 initialCallback = (Action)null;
                             }
                             App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, directMessagesSentResponse.Result.RateLimiting, "S");
                         }
                     }));
                     break;
                 }
                 catch
                 {
                     break;
                 }
             case TweetListType.Search:
                 SearchOptions searchOptions = MetroTwitTwitterizer.SearchOptions;
                 if (RefreshType != RefreshTypes.ForeverScroll)
                     searchOptions.SinceId = (Decimal)(long)LastUpdateID;
                 else
                     searchOptions.MaxId = (Decimal)(long)OldestTweetID;
                 Search.SearchAsync(App.AppState.Accounts[TwitterAccountID].Tokens, SearchTerm, searchOptions).ContinueWith(continuationAction1);
                 break;
             case TweetListType.UserTimeline:
                 UserTimelineOptions userTimelineOptions1 = MetroTwitTwitterizer.UserTimelineOptions;
                 userTimelineOptions1.IncludeRetweets = true;
                 if (RefreshType != RefreshTypes.ForeverScroll)
                     userTimelineOptions1.SinceStatusId = LastUpdateID;
                 else
                     userTimelineOptions1.MaxStatusId = OldestTweetID;
                 userTimelineOptions1.ScreenName = SearchTerm.Replace("@", "").Trim();
                 Timelines.UserTimelineAsync(App.AppState.Accounts[TwitterAccountID].Tokens, userTimelineOptions1).ContinueWith(continuationAction2);
                 break;
             case TweetListType.List:
                 ListStatusesOptions listStatusesOptions = MetroTwitTwitterizer.ListStatusesOptions;
                 listStatusesOptions.IncludeRetweets = ListRetweets;
                 if (RefreshType != RefreshTypes.ForeverScroll)
                     listStatusesOptions.SinceId = (Decimal)(long)LastUpdateID;
                 else
                     listStatusesOptions.MaxId = (Decimal)(long)OldestTweetID;
                 string[] strArray = SearchTerm.Split(new char[1]
     {
       '/'
     });
                 Lists.StatusesAsync(App.AppState.Accounts[TwitterAccountID].Tokens, strArray[1], strArray[0].Replace("@", ""), listStatusesOptions).ContinueWith(continuationAction2);
                 break;
             case TweetListType.MentionsMyTweetsRetweeted:
                 Task<TwitterResponse<TwitterStatusCollection>> mentionsresponse = Timelines.MentionsAsync(App.AppState.Accounts[TwitterAccountID].Tokens, timelineOptions);
                 mentionsresponse.Wait();
                 Action action2 = initialCallback;
                 if (mentionsresponse.Result.Result == RequestResult.Success)
                 {
                     RetweetsOfMeOptions retweetsOfMeOptions = MetroTwitTwitterizer.RetweetsOfMeOptions;
                     if (RefreshType != RefreshTypes.ForeverScroll)
                         retweetsOfMeOptions.SinceStatusId = (Decimal)(long)LastUpdateID;
                     else
                         retweetsOfMeOptions.MaxStatusId = (Decimal)(long)OldestTweetID;
                     Task<TwitterResponse<TwitterStatusCollection>> task = Timelines.RetweetsOfMeAsync(App.AppState.Accounts[TwitterAccountID].Tokens, retweetsOfMeOptions);
                     task.Wait();
                     if (task.Result.Result == RequestResult.Success && task.Result.ResponseObject != null && mentionsresponse.Result.ResponseObject != null)
                     {
                         if (mentionsresponse.Result.ResponseObject.Count > 0)
                         {
                             foreach (Status status in Enumerable.Where<Status>((IEnumerable<Status>)Enumerable.ToArray<Status>((IEnumerable<Status>)task.Result.ResponseObject), (Func<Status, int, bool>)((x, r) => x.Id < Enumerable.Last<Status>((IEnumerable<Status>)mentionsresponse.Result.ResponseObject).Id)))
                                 task.Result.ResponseObject.Remove(status);
                         }
                         IOrderedEnumerable<Status> orderedEnumerable = Enumerable.OrderByDescending<Status, DateTime>(Enumerable.Union<Status>((IEnumerable<Status>)mentionsresponse.Result.ResponseObject, (IEnumerable<Status>)task.Result.ResponseObject), (Func<Status, DateTime>)(s => s.CreatedDate));
                         if (Enumerable.Count<Status>((IEnumerable<Status>)orderedEnumerable) > 0)
                         {
                             TwitterStatusCollection statusCollection = new TwitterStatusCollection();
                             statusCollection.AddTwitterRange<Status>(orderedEnumerable.ToList<Status>());
                             // statusCollection, (IEnumerable<Status>) Enumerable.ToList<Status>((IEnumerable<Status>) orderedEnumerable));
                             Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)new MetroRestResponse<TwitterStatusCollection>()
                             {
                                 Tweets = statusCollection,
                                 RefreshType = RefreshType,
                                 RequestResult = task.Result.Result
                             }), (object)MessengerToken());
                             Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(-1), (object)ViewModelMessages.ProgressVisible);
                         }
                         else
                             continuationAction2(mentionsresponse);
                         App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, mentionsresponse.Result.RateLimiting, "M");
                         App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, task.Result.RateLimiting, "R");
                     }
                     else
                     {
                         continuationAction2(mentionsresponse);
                         IEnumerable<TwitterError> errors = task.Result.Errors;
                         if (errors != null)
                         {
                             Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)new MetroRestResponse<TwitterStatusCollection>()
                             {
                                 Tweets = new TwitterStatusCollection(),
                                 RefreshType = RefreshType,
                                 Error = errors,
                                 RequestResult = task.Result.Result
                             }), (object)MessengerToken());
                             Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(-1), (object)ViewModelMessages.ProgressVisible);
                         }
                         App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, task.Result.RateLimiting, "R");
                     }
                 }
                 else
                 {
                     IEnumerable<TwitterError> errors = mentionsresponse.Result.Errors;
                     if (errors != null)
                     {
                         Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)new MetroRestResponse<TwitterStatusCollection>()
                         {
                             Tweets = new TwitterStatusCollection(),
                             RefreshType = RefreshType,
                             Error = errors,
                             RequestResult = mentionsresponse.Result.Result
                         }), (object)MessengerToken());
                         Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(-1), (object)ViewModelMessages.ProgressVisible);
                     }
                     App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, mentionsresponse.Result.RateLimiting, "M");
                 }
                 if (action2 == null)
                     break;
                 action2();
                 action1 = (Action)null;
                 break;
             case TweetListType.MyTweets:
                 UserTimelineOptions userTimelineOptions2 = MetroTwitTwitterizer.UserTimelineOptions;
                 userTimelineOptions2.IncludeRetweets = true;
                 if (RefreshType != RefreshTypes.ForeverScroll)
                     userTimelineOptions2.SinceStatusId = LastUpdateID;
                 else
                     userTimelineOptions2.MaxStatusId = OldestTweetID;
                 Timelines.UserTimelineAsync(App.AppState.Accounts[TwitterAccountID].Tokens, userTimelineOptions2).ContinueWith(continuationAction2);
                 break;
             case TweetListType.Favourites:
                 ListFavoritesOptions favoritesOptions = MetroTwitTwitterizer.ListFavoritesOptions;
                 if (RefreshType != RefreshTypes.ForeverScroll)
                     favoritesOptions.SinceStatusId = (Decimal)(long)LastUpdateID;
                 else
                     favoritesOptions.MaxStatusId = (Decimal)(long)OldestTweetID;
                 Favorites.ListAsync(App.AppState.Accounts[TwitterAccountID].Tokens, favoritesOptions).ContinueWith(continuationAction2);
                 break;
             case TweetListType.Conversation:
                 Decimal statusId1 = TweetType != TweetListType.Conversation || !(InReplyToID == new Decimal(0)) ? InReplyToID : LastUpdateID;
                 if (!(statusId1 > new Decimal(0)))
                     break;
                 Task<TwitterResponse<Status>> task1 = Tweets.ShowAsync(App.AppState.Accounts[TwitterAccountID].Tokens, statusId1, MetroTwitTwitterizer.Options);
                 task1.Wait();
                 Action action3 = initialCallback;
                 try
                 {
                     Status responseObject1 = task1.Result.ResponseObject;
                     TwitterStatusCollection statusCollection1 = new TwitterStatusCollection();
                     if (responseObject1 != null)
                         statusCollection1.Add(responseObject1);
                     Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)new MetroRestResponse<TwitterStatusCollection>()
                     {
                         Tweets = statusCollection1,
                         RefreshType = RefreshType,
                         RequestResult = task1.Result.Result,
                         Error = task1.Result.Errors
                     }), (object)MessengerToken());
                     App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, task1.Result.RateLimiting, "");
                     if (responseObject1 != null)
                     {
                         Decimal statusId2 = responseObject1.InReplyToStatusId;
                         while (statusId2 > new Decimal(0))
                         {
                             if (statusId2 > new Decimal(0))
                             {
                                 Task<TwitterResponse<Status>> task2 = Tweets.ShowAsync(App.AppState.Accounts[TwitterAccountID].Tokens, statusId2, MetroTwitTwitterizer.Options);
                                 task2.Wait();
                                 try
                                 {
                                     Status responseObject2 = task2.Result.ResponseObject;
                                     TwitterStatusCollection statusCollection2 = new TwitterStatusCollection();
                                     if (responseObject2 != null)
                                         statusCollection2.Add(responseObject2);
                                     Messenger.Default.Send<GenericMessage<object>>(new GenericMessage<object>((object)new MetroRestResponse<TwitterStatusCollection>()
                                     {
                                         Tweets = statusCollection2,
                                         RefreshType = RefreshType,
                                         RequestResult = task2.Result.Result,
                                         Error = task2.Result.Errors
                                     }), (object)MessengerToken());
                                     statusId2 = responseObject2 == null ? new Decimal(0) : responseObject2.InReplyToStatusId;
                                     App.AppState.Accounts[TwitterAccountID].UpdateRateLimits(TweetType, task2.Result.RateLimiting, "");
                                 }
                                 catch
                                 {
                                     Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(-1), (object)ViewModelMessages.ProgressVisible);
                                 }
                             }
                         }
                     }
                 }
                 catch
                 {
                     Messenger.Default.Send<GenericMessage<int>>(new GenericMessage<int>(-1), (object)ViewModelMessages.ProgressVisible);
                 }
                 finally
                 {
                     if (action3 != null)
                     {
                         action3();
                         action1 = (Action)null;
                     }
                 }
                 break;
             case TweetListType.RetweetUsers:
                 Tweets.RetweetsAsync(App.AppState.Accounts[TwitterAccountID].Tokens, Decimal.Parse(SearchTerm), MetroTwitTwitterizer.RetweetsOptions).ContinueWith(continuationAction2);
                 break;
             case TweetListType.Followers:
                 Friendship.FollowersIdsAsync(App.AppState.Accounts[TwitterAccountID].Tokens, new UsersIdsOptions()
                 {
                     ScreenName = SearchTerm
                 }).ContinueWith((Action<Task<TwitterResponse<UserIdCollection>>>)(r => Users.LookupAsync(App.AppState.Accounts[TwitterAccountID].Tokens, new LookupUsersOptions()
                 {
                     UserIds = (TwitterIdCollection)r.Result.ResponseObject
                 }).Wait()));
                 break;
         }
     }
     catch
     {
     }
 }
예제 #16
0
        /// <summary>
        /// Generates the tweet table
        /// </summary>
        /// <param name="PageNumber"></param>
        /// <returns></returns>
        private Table CreateTweetTable(int PageNumber, TwitterStatusCollection tweets)
        {
            int       i = 0;
            bool      isTweetOnlyText = true;
            Table     mainTable, innerTable;
            TableRow  tr;
            TableCell tc, tcImage, tcText;
            HyperLink imgHyperLink;
            string    strSource;
            Label     lblContent;

            mainTable             = new Table();
            mainTable.Width       = Unit.Percentage(100);
            mainTable.CellSpacing = 0;
            mainTable.CellPadding = 0;
            this.Controls.Add(mainTable);


            if (tweets.Count > 0)
            {
                foreach (TwitterStatus tweet in tweets)
                {
                    isTweetOnlyText     = true;
                    innerTable          = new Table();
                    innerTable.CssClass = "ms-viewlsts";
                    innerTable.Width    = Unit.Percentage(100);

                    if (i <= this.TweetCount * PageNumber)
                    {
                        tr = new TableRow();
                        mainTable.Rows.Add(tr);

                        tc       = new TableCell();
                        tc.Width = Unit.Percentage(10);

                        tr.CssClass = " ms-WPBorderBorderOnly , twitBorderBottom";

                        #region UserImage
                        //Showing the user image
                        if (this.EnableShowImage)
                        {
                            imgHyperLink             = new HyperLink();
                            imgHyperLink.ImageUrl    = tweet.User.ProfileImageLocation;
                            imgHyperLink.NavigateUrl = "http://twitter.com/" + tweet.User.ScreenName;
                            imgHyperLink.Attributes.Add("target", "_blank");
                            tc.Controls.Add(imgHyperLink);
                            tc.CssClass = "twitHeaderImage";
                            tr.Cells.Add(tc);
                        }
                        #endregion

                        tc = new TableCell();
                        tc.Controls.Add(innerTable);
                        tr.Controls.Add(tc);

                        tr = new TableRow();
                        innerTable.Rows.Add(tr);

                        #region TwitPic
                        //Code for showing the image on the webpart
                        if (tweet.Entities.Count > 0)
                        {
                            int tweetCount = Convert.ToInt32(tweet.Entities.Count);

                            for (int tweetEntityCount = 0; tweetEntityCount < tweetCount; tweetEntityCount++)
                            {
                                //Check if the tweet is having the Picture
                                if (tweet.Entities[tweetEntityCount].ToString().Equals("Twitterizer.Entities.TwitterMediaEntity"))
                                {
                                    if (!string.IsNullOrEmpty(((Twitterizer.Entities.TwitterMediaEntity)(tweet.Entities[tweetEntityCount])).MediaUrl.ToString()))
                                    {
                                        //Create a new table to add the image and corresponding text
                                        tc = new TableCell();
                                        tr.Cells.Add(tc);
                                        Table tb = new Table();
                                        tb.Width = Unit.Percentage(100);
                                        tc.Controls.Add(tb);
                                        TableRow trinner = new TableRow();

                                        //get the image URL
                                        string ImageURL = ((Twitterizer.Entities.TwitterMediaEntity)(tweet.Entities[tweetEntityCount])).MediaUrl.ToString();

                                        tcImage = new TableCell();

                                        HyperLink imgTweet = new HyperLink();
                                        imgTweet.NavigateUrl = ImageURL;
                                        imgTweet.Attributes.Add("target", "_blank");

                                        //Added the HTMLImage Control to resize the image
                                        HtmlImage htmlImage = new HtmlImage();
                                        htmlImage.Src    = ImageURL;
                                        htmlImage.Height = 100;
                                        htmlImage.Width  = 137;
                                        htmlImage.Border = 0;
                                        imgTweet.Controls.Add(htmlImage);
                                        tcImage.Width = 137;
                                        tcImage.Controls.Add(imgTweet);
                                        //tcImage.Attributes.Add("style", "padding-top:0.5%");
                                        trinner.Cells.Add(tcImage);

                                        //Add the linkfied text
                                        lblContent           = new Label();
                                        lblContent.Text      = tweet.LinkifiedText();
                                        lblContent.ForeColor = Color.Black;

                                        //Show the text next to the Image
                                        tcText = new TableCell();
                                        tcText.Controls.Add(lblContent);
                                        trinner.Cells.Add(tcText);

                                        isTweetOnlyText = false;

                                        tb.Rows.Add(trinner);
                                    }
                                }
                            }
                        }
                        #endregion

                        #region Show Tweet
                        //If only the text is there in the image
                        if (isTweetOnlyText)
                        {
                            tc = new TableCell();
                            tr.Cells.Add(tc);

                            lblContent           = new Label();
                            lblContent.Text      = tweet.LinkifiedText();
                            lblContent.ForeColor = Color.Black;

                            tc.Controls.Add(lblContent);
                            tc.CssClass = "ms-vb2";
                        }
                        #endregion

                        #region Show Description
                        if (this.EnableShowDesc)
                        {
                            tr = new TableRow();
                            innerTable.Rows.Add(tr);
                            tc = new TableCell();
                            tr.Cells.Add(tc);

                            if (tweet.Source.StartsWith("<"))
                            {
                                strSource = tweet.Source.Substring(tweet.Source.IndexOf('>') + 1, tweet.Source.LastIndexOf('<') - tweet.Source.IndexOf('>') - 1);
                            }
                            else
                            {
                                strSource = tweet.Source;
                            }

                            tc.Text      = relativeTime(tweet.CreatedDate.ToString()) + " via " + strSource;
                            tc.CssClass  = "ms-vb2";
                            tc.ForeColor = Color.Gray;
                        }
                        #endregion
                    }
                    else
                    {
                        break;
                    }
                    i++;
                }

                imgMoreTweet.Visible = true;
                imgNoTweet.Visible   = false;
            }
            else
            {
                imgMoreTweet.Visible = false;
                imgNoTweet.Visible   = true;

                tr = new TableRow();
                mainTable.Rows.Add(tr);

                tc                 = new TableCell();
                tc.Width           = Unit.Percentage(100);
                tc.CssClass        = "ms-vb2";
                tc.HorizontalAlign = HorizontalAlign.Center;
                tc.ForeColor       = Color.Gray;
                tr.Cells.Add(tc);

                tc.Text = string.Format("{0} hasn't tweeted yet.", this.ScreenName);
            }
            // if the number of tweet response is less than the number of tweets demanded than there are no more tweets : show grey tweet
            if (tweets.Count < this.TweetCount * PageNumber)
            {
                imgMoreTweet.Visible = false;
                imgNoTweet.Visible   = true;
            }
            return(mainTable);
        }
예제 #17
0
        /// <summary>
        /// Creates the header and footer
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="userInfo"></param>
        /// <param name="ShowHeaderImage"></param>
        /// <param name="ShowFollowUs"></param>
        /// <returns></returns>
        public static Table CreateHeaderFooter(string Type, TwitterStatusCollection tweets, bool ShowHeaderImage, bool ShowFollowUs)
        {
            Table     tbHF;
            TableRow  trHF;
            TableCell tcHF;

            tbHF = new Table();

            if (!ShowHeaderImage)
            {
                tbHF.CellSpacing = 0;
                tbHF.CellPadding = 4;
            }
            else
            {
                tbHF.CellPadding = 0;
                tbHF.CellSpacing = 0;
            }

            tbHF.Width = Unit.Percentage(100);
            trHF       = new TableRow();
            tcHF       = new TableCell();

            #region Header
            if (Type.Equals("Header"))
            {
                Table tbinner = new Table();
                tbinner.Width = Unit.Percentage(100);
                TableRow  trinner = new TableRow();
                TableCell tcinner = new TableCell();

                //Adding the Header Image
                if (ShowHeaderImage)
                {
                    HtmlImage image = new HtmlImage();
                    image.Src    = tweets[0].User.ProfileImageLocation;
                    image.Height = 22;
                    image.Width  = 35;
                    image.Border = 0;
                    HyperLink hplnkImage = new HyperLink();
                    if (tweets.Count > 0)
                    {
                        hplnkImage.NavigateUrl = "http://twitter.com/" + tweets[0].User.ScreenName;
                    }
                    hplnkImage.Attributes.Add("target", "_blank");
                    hplnkImage.Controls.Add(image);
                    tcinner.Controls.Add(hplnkImage);
                    tcinner.CssClass = "twitHeaderImage";
                    tcinner.Width    = Unit.Percentage(4);
                    trinner.Cells.Add(tcinner);
                }

                //Creating the name hyperlink in header
                tcinner = new TableCell();
                HyperLink hplnkName = new HyperLink();
                if (tweets.Count > 0)
                {
                    hplnkName.Text        = tweets[0].User.Name;
                    hplnkName.NavigateUrl = "http://twitter.com/" + tweets[0].User.ScreenName;
                }
                hplnkName.Attributes.Add("target", "_blank");
                tcinner.Controls.Add(hplnkName);
                tcinner.VerticalAlign = VerticalAlign.Middle;
                tcinner.CssClass      = "twitHeaderText";
                trinner.Cells.Add(tcinner);

                tcinner = new TableCell();
                HtmlImage imgHeaderTwitter = new HtmlImage();
                imgHeaderTwitter.Src    = SPContext.Current.Web.Url + "/_layouts/Brickred.OpenSource.Twitter/twitterbird.png";
                imgHeaderTwitter.Height = 22;
                imgHeaderTwitter.Border = 0;
                tcinner.Controls.Add(imgHeaderTwitter);
                tcinner.HorizontalAlign = HorizontalAlign.Right;
                if (ShowHeaderImage)
                {
                    tcinner.CssClass = "padding-align-right";
                }
                trinner.Cells.Add(tcinner);

                //Adding controls to the main table
                tbinner.Rows.Add(trinner);
                tcHF.Controls.Add(tbinner);
                tcHF.CssClass = "twitHeaderBorder";
                trHF.Cells.Add(tcHF);
            }
            #endregion

            #region Footer
            else if (Type.Equals("Footer"))
            {
                HyperLink hplnk = new HyperLink();
                hplnk.ImageUrl    = SPContext.Current.Web.Url + "/_layouts/Brickred.OpenSource.Twitter/twitterlogo.png";
                hplnk.NavigateUrl = "https://twitter.com";
                hplnk.Attributes.Add("target", "_blank");
                tcHF.Controls.Add(hplnk);
                tcHF.CssClass = "twitFooterBorder";
                trHF.Cells.Add(tcHF);

                if (ShowFollowUs)
                {
                    tcHF = new TableCell();
                    HyperLink hplnkJoinus = new HyperLink();
                    hplnkJoinus.Text      = "Follow Us";
                    hplnkJoinus.ForeColor = Color.White;
                    if (tweets.Count > 0)
                    {
                        hplnkJoinus.NavigateUrl = "https://twitter.com/" + tweets[0].User.ScreenName;
                    }
                    hplnkJoinus.Attributes.Add("target", "_blank");
                    tcHF.Controls.Add(hplnkJoinus);
                    tcHF.CssClass = "padding-align-right , twitFooterBorder";
                    trHF.Cells.Add(tcHF);
                    trHF.Cells.Add(tcHF);
                }

                tbHF.CssClass = "twitFooterBorder";
            }
            #endregion


            tbHF.Rows.Add(trHF);
            return(tbHF);
        }
예제 #18
0
        /// <summary>
        /// Displays the Count of the followers/following
        /// </summary>
        /// <param name="Type"> enter the type as Followers/Following</param>
        /// <param name="twitterResponse">Twiiter object from which count can be retrieved</param>
        /// <param name="userInfo">Twiiter object from which user info can be retrieved</param>
        /// <returns></returns>
        public static Table ShowDisplayCount(string Type, TwitterResponse <TwitterUserCollection> twitterResponse, TwitterStatusCollection tweets)
        {
            Table tb = new Table();

            tb.Width = Unit.Percentage(100);
            TableRow  tr = new TableRow();
            TableCell tc = new TableCell();

            #region Followers
            if (Type.Equals("Followers"))
            {
                int   followersCount          = Convert.ToInt32(twitterResponse.ResponseObject.Count);
                Label lblDisplayFollowerCount = new Label();
                lblDisplayFollowerCount.Text      = " has " + followersCount + " followers ";
                lblDisplayFollowerCount.ForeColor = Color.Black;

                Label lblScreenName = new Label();
                lblScreenName.Text      = "@" + tweets[0].User.Name;
                lblScreenName.Font.Bold = true;
                lblScreenName.Font.Size = FontUnit.XXSmall;
                lblScreenName.ForeColor = Color.Black;

                tc.Controls.Add(lblScreenName);
                tc.Controls.Add(lblDisplayFollowerCount);
            }
            #endregion

            #region Following
            else if (Type.Equals("Following"))
            {
                int followCount = Convert.ToInt32(twitterResponse.ResponseObject.Count);

                Label lblScreenName = new Label();
                lblScreenName.Text      = "@" + tweets[0].User.Name;
                lblScreenName.Font.Bold = true;
                lblScreenName.Font.Size = FontUnit.XXSmall;
                lblScreenName.ForeColor = Color.Black;

                Label lblDisplayFollowerCount = new Label();
                lblDisplayFollowerCount.Text      = " is following " + followCount + " people";
                lblDisplayFollowerCount.ForeColor = Color.Black;

                tc.Controls.Add(lblScreenName);
                tc.Controls.Add(lblDisplayFollowerCount);
            }
            #endregion

            tc.CssClass = "twitDisplayCount";
            tr.Cells.Add(tc);
            tb.Rows.Add(tr);

            return(tb);
        }
예제 #19
0
        /// <summary>
        /// Creates the header and footer
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="userInfo"></param>
        /// <param name="ShowHeaderImage"></param>
        /// <param name="ShowFollowUs"></param>
        /// <returns></returns>
        public static Table CreateHeaderFooter(string Type, TwitterStatusCollection tweets, bool ShowHeaderImage, bool ShowFollowUs)
        {
            Table tbHF;
            TableRow trHF;
            TableCell tcHF;
            tbHF = new Table();

            if (!ShowHeaderImage)
            {
                tbHF.CellSpacing = 0;
                tbHF.CellPadding = 4;
            }
            else
            {
                tbHF.CellPadding = 0;
                tbHF.CellSpacing = 0;
            }

            tbHF.Width = Unit.Percentage(100);
            trHF = new TableRow();
            tcHF = new TableCell();

            #region Header
            if (Type.Equals("Header"))
            {
                Table tbinner = new Table();
                tbinner.Width = Unit.Percentage(100);
                TableRow trinner = new TableRow();
                TableCell tcinner = new TableCell();

                //Adding the Header Image
                if (ShowHeaderImage)
                {
                    HtmlImage image = new HtmlImage();
                    image.Src = tweets[0].User.ProfileImageLocation;
                    image.Height = 22;
                    image.Width = 35;
                    image.Border = 0;
                    HyperLink hplnkImage = new HyperLink();
                    if (tweets.Count > 0)
                    {
                        hplnkImage.NavigateUrl = "http://twitter.com/" + tweets[0].User.ScreenName;
                    }
                    hplnkImage.Attributes.Add("target", "_blank");
                    hplnkImage.Controls.Add(image);
                    tcinner.Controls.Add(hplnkImage);
                    tcinner.CssClass = "twitHeaderImage";
                    tcinner.Width = Unit.Percentage(4);
                    trinner.Cells.Add(tcinner);
                }

                //Creating the name hyperlink in header
                tcinner = new TableCell();
                HyperLink hplnkName = new HyperLink();
                if (tweets.Count > 0)
                {
                    hplnkName.Text = tweets[0].User.Name;
                    hplnkName.NavigateUrl = "http://twitter.com/" + tweets[0].User.ScreenName;
                }
                hplnkName.Attributes.Add("target", "_blank");
                tcinner.Controls.Add(hplnkName);
                tcinner.VerticalAlign = VerticalAlign.Middle;
                tcinner.CssClass = "twitHeaderText";
                trinner.Cells.Add(tcinner);

                tcinner = new TableCell();
                HtmlImage imgHeaderTwitter = new HtmlImage();
                imgHeaderTwitter.Src = SPContext.Current.Web.Url + "/_layouts/Brickred.OpenSource.Twitter/twitterbird.png";
                imgHeaderTwitter.Height = 22;
                imgHeaderTwitter.Border = 0;
                tcinner.Controls.Add(imgHeaderTwitter);
                tcinner.HorizontalAlign = HorizontalAlign.Right;
                if (ShowHeaderImage)
                    tcinner.CssClass = "padding-align-right";
                trinner.Cells.Add(tcinner);

                //Adding controls to the main table
                tbinner.Rows.Add(trinner);
                tcHF.Controls.Add(tbinner);
                tcHF.CssClass = "twitHeaderBorder";
                trHF.Cells.Add(tcHF);

            }
            #endregion

            #region Footer
            else if (Type.Equals("Footer"))
            {
                HyperLink hplnk = new HyperLink();
                hplnk.ImageUrl = SPContext.Current.Web.Url + "/_layouts/Brickred.OpenSource.Twitter/twitterlogo.png";
                hplnk.NavigateUrl = "https://twitter.com";
                hplnk.Attributes.Add("target", "_blank");
                tcHF.Controls.Add(hplnk);
                tcHF.CssClass = "twitFooterBorder";
                trHF.Cells.Add(tcHF);

                if (ShowFollowUs)
                {
                    tcHF = new TableCell();
                    HyperLink hplnkJoinus = new HyperLink();
                    hplnkJoinus.Text = "Follow Us";
                    hplnkJoinus.ForeColor = Color.White;
                    if (tweets.Count > 0)
                    {
                        hplnkJoinus.NavigateUrl = "https://twitter.com/" + tweets[0].User.ScreenName;
                    }
                    hplnkJoinus.Attributes.Add("target", "_blank");
                    tcHF.Controls.Add(hplnkJoinus);
                    tcHF.CssClass = "padding-align-right , twitFooterBorder";
                    trHF.Cells.Add(tcHF);
                    trHF.Cells.Add(tcHF);
                }

                tbHF.CssClass = "twitFooterBorder";
            }
            #endregion

            tbHF.Rows.Add(trHF);
            return tbHF;
        }
예제 #20
0
        /// <summary>
        /// Displays the Count of the followers/following
        /// </summary>
        /// <param name="Type"> enter the type as Followers/Following</param>
        /// <param name="twitterResponse">Twiiter object from which count can be retrieved</param>
        /// <param name="userInfo">Twiiter object from which user info can be retrieved</param>
        /// <returns></returns>
        public static Table ShowDisplayCount(string Type, TwitterResponse<TwitterUserCollection> twitterResponse, TwitterStatusCollection tweets)
        {
            Table tb = new Table();
            tb.Width = Unit.Percentage(100);
            TableRow tr = new TableRow();
            TableCell tc = new TableCell();

            #region Followers
            if (Type.Equals("Followers"))
            {
                int followersCount = Convert.ToInt32(twitterResponse.ResponseObject.Count);
                Label lblDisplayFollowerCount = new Label();
                lblDisplayFollowerCount.Text = " has " + followersCount + " followers ";
                lblDisplayFollowerCount.ForeColor = Color.Black;

                Label lblScreenName = new Label();
                lblScreenName.Text = "@" + tweets[0].User.Name;
                lblScreenName.Font.Bold = true;
                lblScreenName.Font.Size = FontUnit.XXSmall;
                lblScreenName.ForeColor = Color.Black;

                tc.Controls.Add(lblScreenName);
                tc.Controls.Add(lblDisplayFollowerCount);
            }
            #endregion

            #region Following
            else if (Type.Equals("Following"))
            {
                int followCount = Convert.ToInt32(twitterResponse.ResponseObject.Count);

                Label lblScreenName = new Label();
                lblScreenName.Text = "@" + tweets[0].User.Name;
                lblScreenName.Font.Bold = true;
                lblScreenName.Font.Size = FontUnit.XXSmall;
                lblScreenName.ForeColor = Color.Black;

                Label lblDisplayFollowerCount = new Label();
                lblDisplayFollowerCount.Text = " is following " + followCount + " people";
                lblDisplayFollowerCount.ForeColor = Color.Black;

                tc.Controls.Add(lblScreenName);
                tc.Controls.Add(lblDisplayFollowerCount);
            }
            #endregion

            tc.CssClass = "twitDisplayCount";
            tr.Cells.Add(tc);
            tb.Rows.Add(tr);

            return tb;
        }
예제 #21
0
        /// <summary>
        /// Get the tweets from the Twitter object
        /// </summary>
        /// <param name="PageNumber"></param>
        /// <returns></returns>
        private TwitterStatusCollection FetchTweets(int PageNumber)
        {
            TwitterStatusCollection tweets = new TwitterStatusCollection();

            //cache the tweets here
            if (Page.Cache[string.Format("Tweet-{0}-{1}", PageNumber,this.ScreenName)] == null)
            {
                //set the tokens here
                OAuthTokens tokens = new OAuthTokens();
                tokens.ConsumerKey = this.ConsumerKey;
                tokens.ConsumerSecret = this.ConsumerSecret;
                tokens.AccessToken = this.AccessToken;
                tokens.AccessTokenSecret = this.AccessTokenSecret;

                UserTimelineOptions options = new UserTimelineOptions();
                options.Count = this.TweetCount * PageNumber;
                options.Page = 1;
                options.ScreenName = this.ScreenName;

                //now hit the twitter and get the response
                tweets = TwitterTimeline.UserTimeline(tokens, options).ResponseObject;

                if (PageNumber == 1)
                {
                    HttpContext.Current.Cache.Add(string.Format("Tweet-{0}-{1}", PageNumber,this.ScreenName), tweets, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, CacheRemovedCallBack);
                }
                else
                {
                    HttpContext.Current.Cache.Insert(string.Format("Tweet-{0}-{1}", PageNumber,this.ScreenName), tweets, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                }
            }
            else
            {
                tweets = HttpContext.Current.Cache[string.Format("Tweet-{0}-{1}", PageNumber,this.ScreenName)] as TwitterStatusCollection;
            }

            return tweets;
        }