예제 #1
0
    protected void VerifyButton_Click(object sender, EventArgs e)
    {
        ResultLabel.Visible = true;

        OAuthTokens tokens = new OAuthTokens()
        {
            AccessToken       = AKTextBox.Text,
            AccessTokenSecret = ASTextBox.Text,
            ConsumerKey       = CKTextBox.Text,
            ConsumerSecret    = CSTextBox.Text
        };

        TwitterResponse <TwitterUser> twitterResponse = TwitterAccount.VerifyCredentials(tokens);

        if (twitterResponse.Result == RequestResult.Success)
        {
            ResultLabel.Text     = string.Format("Success! Verified as {0}", twitterResponse.ResponseObject.ScreenName);
            ResultLabel.CssClass = "ResultLabelSuccess";
        }
        else
        {
            ResultLabel.Text     = string.Format("Failed! \"{0}\"", twitterResponse.ErrorMessage ?? "Not Authorized.");
            ResultLabel.CssClass = "ResultLabelFailed";
        }
    }
예제 #2
0
        public override void Execute(IEmailItem emailItem = null, int?lastExitCode = null)
        {
            if (AppliesTo(emailItem, lastExitCode))
            {
                if (null != emailItem &&
                    null != emailItem.Message &&
                    null != emailItem.Message.From
                    )
                {
                    OAuthTokens oAuthTokens;
                    if (GetOAuthToken(out oAuthTokens))
                    {
                        var    fromEmailRecipient = emailItem.Message.From;
                        string from = !string.IsNullOrEmpty(fromEmailRecipient.DisplayName) ? fromEmailRecipient.DisplayName : !string.IsNullOrEmpty(fromEmailRecipient.NativeAddress) ? fromEmailRecipient.NativeAddress : fromEmailRecipient.SmtpAddress;
                        TwitterResponse <TwitterStatus> response = TwitterStatus.Update(oAuthTokens, string.Format("[{0}] New mail from {1}", DateTime.Now, from));
                    }
                }

                if (null != Handlers && Handlers.Count > 0)
                {
                    foreach (IHandler handler in Handlers)
                    {
                        handler.Execute(emailItem, lastExitCode);
                    }
                }
            }
        }
예제 #3
0
파일: UserModel.cs 프로젝트: swinghu/Ocell
        void ReceiveBlock(TwitterUser usr, TwitterResponse response)
        {
            string successMsg = "", errorMsg = "";

            if (!Blocked)
            {
                successMsg = String.Format(Resources.UserIsNowUnblocked, User.ScreenName);
                errorMsg   = String.Format(Resources.CouldntUnblock, User.ScreenName);
            }
            else
            {
                successMsg = String.Format(Resources.UserIsNowBlocked, User.ScreenName);
                errorMsg   = String.Format(Resources.CouldntBlock, User.ScreenName);
            }

            IsLoading = false;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                MessageService.ShowLightNotification(successMsg);
                Blocked = !Blocked;
                block.RaiseCanExecuteChanged();
                unblock.RaiseCanExecuteChanged();
            }
            else
            {
                MessageService.ShowError(errorMsg);
            }
        }
예제 #4
0
        public static void PostTweet()
        {
            try
            {
                //get approval from user
                OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerSecret, "oob");
                string             url          = String.Format("http://twitter.com/oauth/authorize?oauth_token={0}", requestToken.Token);
                Process.Start(url);

                //get PIN & access-token from user
                string             pin         = "1234";
                OAuthTokenResponse accessToken = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerKey, requestToken.Token, pin);

                //post tweet
                OAuthTokens tokens = new OAuthTokens();
                tokens.AccessToken       = accessToken.Token;
                tokens.AccessTokenSecret = accessToken.TokenSecret;
                tokens.ConsumerKey       = ConsumerKey;
                tokens.ConsumerSecret    = ConsumerSecret;

                TwitterResponse <TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, SampleTweet);
                if (tweetResponse.Result == RequestResult.Success)
                {
                }
            }
            catch (Exception exception)
            {
                Log.Error(exception);
            }
        }
예제 #5
0
        private void shareImageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tweet tweet = new Tweet(GetImageFromSelection());

            tweet.TweetSubmitted += (s, args) => {
                string msg      = args.GetTweet();
                Image  img      = args.GetImage();
                string fileName = Path.GetTempFileName();
                img.Save(fileName, ImageFormat.Png);
                TwitterClient twitterClient = new TwitterClient(new OAuth(
                                                                    consumerKey,
                                                                    consumerSecret,
                                                                    accessToken,
                                                                    accessTokenSecret
                                                                    ));
                TwitterResponse tweetResponse = twitterClient.SendTweetWithMedia(msg, fileName);
                if (tweetResponse.Failed)
                {
                    Console.WriteLine("Failed to post tweet");
                    Console.Write(tweetResponse.FailedMessage);
                }
                else
                {
                    Console.WriteLine("Successfully posted tweet and media");
                }
            };
            tweet.Show(this);
        }
예제 #6
0
        /// <summary>
        /// Gets last 20 users
        /// </summary>
        /// <param name="search">Search string</param>
        /// <returns>TwitterUserInfo list</returns>
        public List <TwitterUserInfo> FindUsers(string search)
        {
            const int pageRowCount = 20;
            const int pageNumber   = 0;

            try
            {
                Twitterizer.OAuthTokens tokens = GetOAuthTokens();

                UserSearchOptions options = new UserSearchOptions();
                options.Page          = pageNumber;
                options.NumberPerPage = pageRowCount;

                TwitterResponse <TwitterUserCollection> userResponse = TwitterUser.Search(tokens, search, options);
                if (userResponse.Result == RequestResult.Success)
                {
                    TwitterUserCollection collection = userResponse.ResponseObject;
                    return(MapUsers(userResponse.ResponseObject));
                }
                else
                {
                    throw CreateException(userResponse.Result, userResponse.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
예제 #7
0
        private static void ReceiveFriends(TwitterCursorList <TwitterUser> friends, TwitterResponse response, UserToken user)
        {
            if (friends == null || response.StatusCode != HttpStatusCode.OK)
            {
                return;
            }

            if (dicUsers.ContainsKey(user))
            {
                dicUsers[user] = dicUsers[user].Union(friends.Select(x => x.ScreenName)).ToList();
            }
            else
            {
                dicUsers[user] = friends.Select(x => x.ScreenName).ToList();
            }

            if (friends.NextCursor != null && friends.NextCursor != 0)
            {
                ServiceDispatcher.GetService(user).ListFriends(new ListFriendsOptions {
                    ScreenName = user.ScreenName, Cursor = (long)friends.NextCursor
                }, (l, r) => ReceiveFriends(l, r, user));
            }
            else
            {
                finishedUsers[user] = true;
                SaveUserCache(user, dicUsers[user]);
            }
        }
예제 #8
0
        /// <summary>
        /// Gets current user (defined by access token) home timeline
        /// </summary>
        /// <param name="messageCount">Message count</param>
        /// <returns>Message list</returns>
        public List <Message> GetUserHomeTimeLine(int messageCount)
        {
            try
            {
                Twitterizer.OAuthTokens tokens = GetOAuthTokens();

                Twitterizer.UserTimelineOptions options = new Twitterizer.UserTimelineOptions();
                options.Count           = messageCount;
                options.IncludeRetweets = true;

                TwitterResponse <TwitterStatusCollection> statusResponse = TwitterTimeline.HomeTimeline(tokens, options);

                if (statusResponse.Result == RequestResult.Success)
                {
                    return(MapMessage(statusResponse.ResponseObject));
                }

                else
                {
                    throw CreateException(statusResponse.Result, statusResponse.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
예제 #9
0
        /// <summary>
        /// Gets tweets posted by specified user
        /// </summary>
        /// <param name="messageCount">Message count</param>
        /// <returns>Message list</returns>
        public List <Message> GetUserTweets(decimal?userID, string screenName, int messageCount)
        {
            try
            {
                Twitterizer.OAuthTokens tokens = GetOAuthTokens();

                Twitterizer.UserTimelineOptions options = new Twitterizer.UserTimelineOptions();
                options.ScreenName = screenName;
                if (userID.HasValue)
                {
                    options.UserId = userID.Value;
                }
                options.IncludeRetweets = true;
                options.Count           = messageCount;

                TwitterResponse <TwitterStatusCollection> statusResponse = TwitterTimeline.UserTimeline(tokens, options);

                if (statusResponse.Result == RequestResult.Success)
                {
                    return(MapMessage(statusResponse.ResponseObject));
                }

                else
                {
                    throw CreateException(statusResponse.Result, statusResponse.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw;
            }
        }
        public static void Tweet(string message)
        {
            throw new NotSupportedException("Remove this when you're ready to Tweet!");
            try
            {
                if (ConfigManager.CurrentUserSpecific.IsValidated)
                {
                    return;
                }
                if (ConfigManager.CurrentUserSpecific.IsEnabled == false)
                {
                    return;
                }
                var         currConfig = ConfigManager.CurrentUserSpecific;
                OAuthTokens tokens     = new OAuthTokens
                {
                    ConsumerKey       = ConsumerKey,
                    ConsumerSecret    = ConsumerSecret,
                    AccessToken       = currConfig.AccessToken,
                    AccessTokenSecret = currConfig.AccessSecret
                };

                TwitterResponse <TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, message);
                if (tweetResponse.Result == RequestResult.Success)
                {
                    // Tweet posted successfully!
                }
                else
                {
                    // Something bad happened
                }
            } catch // Very silent
            {
            }
        }
예제 #11
0
        public void FollowersIds()
        {
            OAuthTokens tokens = Configuration.GetTokens();

            TwitterResponse <UserIdCollection> response = TwitterFriendship.FollowersIds(tokens, new UsersIdsOptions
            {
                ScreenName = "twitterapi"
            });

            Assert.IsNotNull(response, "response is null");
            Assert.IsTrue(response.Result == RequestResult.Success, response.ErrorMessage ?? response.Result.ToString());
            Assert.IsNotNull(response.ResponseObject, response.ErrorMessage ?? response.Result.ToString());
            Assert.IsTrue(response.ResponseObject.Count > 0, response.ErrorMessage ?? response.Result.ToString());

            decimal firstId = response.ResponseObject[0];

            response = TwitterFriendship.FollowersIds(tokens, new UsersIdsOptions {
                ScreenName = "twitterapi", Cursor = response.ResponseObject.NextCursor
            });
            Assert.IsNotNull(response, "response is null");
            Assert.IsTrue(response.Result == RequestResult.Success, response.ErrorMessage ?? response.Result.ToString());
            Assert.IsNotNull(response.ResponseObject, response.ErrorMessage ?? response.Result.ToString());
            Assert.IsTrue(response.ResponseObject.Count > 0, response.ErrorMessage ?? response.Result.ToString());
            Assert.AreNotEqual(response.ResponseObject[0], firstId, response.ErrorMessage ?? response.Result.ToString());
        }
예제 #12
0
        public void Button1_Click(object sender, EventArgs e)
        {
            string Input  = TextBox1.Text;
            string method = Input.Split('(')[0];
            int    x      = Input.Length - 1 - (Input.IndexOf('(') + 1);
            string value  = Input.Substring(Input.IndexOf('(') + 1, x);

            UserTimelineOptions userOptions = new UserTimelineOptions();

            userOptions.APIBaseAddress = "https://api.twitter.com/1.1/";                                            // <-- needed for API 1.1
            userOptions.Count          = 5;
            userOptions.UseSSL         = true;                                                                      // <-- needed for API 1.1
            userOptions.ScreenName     = value;                                                                     //<-- replace with yours
            TwitterResponse <TwitterStatusCollection> timeline = TwitterTimeline.UserTimeline(tokens, userOptions); // collects first 20 tweets from our account
            int i = 1;
            //TwitterResponse<TwitterTrendCollection> timelineres = TwitterTrend.Trends(tokens,1);

            TwitterResponse <TwitterUser> followers = TwitterUser.Show(tokens, value);

            if (followers.Result == RequestResult.Success)
            {
                TextBox2.Text = "Number of followers for " + followers.ResponseObject.ScreenName + " is " + followers.ResponseObject.NumberOfFollowers + Environment.NewLine;
            }

            //if (showUserResponse.Result == RequestResult.Success)
            //    {
            //    string screenName = showUserResponse.ResponseObject.ScreenName;
            //    Response.Write(screenName);
            //    Response.Write("<br>");
            //    Response.Write(showUserResponse.ResponseObject.NumberOfFollowers);
            //    }
            //FollowersOptions options = new FollowersOptions();
            //options.ScreenName = value;
            //options.UserId = 212250358;
            //options.UseSSL = true;
            //TwitterResponse<TwitterUserCollection> Followernames = TwitterFriendship.Followers(tokens, options);
            //TwitterResponse<TwitterUserCollection> followers = TwitterFriendship.Followers(options);
            //foreach (var follower in followers.ResponseObject.)
            //{
            //    TextBox2.Text += i + ")" + follower + Environment.NewLine;
            //    i++;
            //}
            foreach (TwitterStatus status in timeline.ResponseObject)
            {
                TextBox2.Text += i + ")" + status.Text + Environment.NewLine;
                i++;
            }

            //Getting trends from a location
            LocalTrendsOptions trendoptions = new LocalTrendsOptions();

            trendoptions.UseSSL = true;


            //  TwitterResponse<TwitterTrendCollection> tr = TwitterTrend.Trends(1);
            //foreach (TwitterTrend tnds in tr.ResponseObject)
            //{
            //    TextBox2.Text += tnds.ToString() + Environment.NewLine;
            //}
        }
        public static void Search()
        {
            SearchOptions options = new SearchOptions();

            options.NumberPerPage = 19;

            TwitterResponse <TwitterSearchResultCollection> searchResponse = TwitterSearch.Search("twitter", options);

            Assert.IsNotNull(searchResponse);
            Assert.That(searchResponse.Result == RequestResult.Success, searchResponse.ErrorMessage);
            Assert.IsNotNull(searchResponse.ResponseObject);
            Assert.That(searchResponse.ResponseObject.Count == 19);

            var request = Twitterizer.TwitterSearch.Search("twitter");

            Assert.IsNotNull(request);
            Assert.That(request.Result == RequestResult.Success, request.ErrorMessage);
            Assert.IsNotNull(request.ResponseObject);

            Assert.Greater(request.ResponseObject.MaxId, 0);
            Assert.Greater(request.ResponseObject.CompletedIn, 0);
            Assert.IsNotNullOrEmpty(request.ResponseObject.MaxIdStr);
            Assert.IsNotNullOrEmpty(request.ResponseObject.NextPage);
            Assert.Greater(request.ResponseObject.Page, 0);
            Assert.AreEqual("twitter", request.ResponseObject.Query);
            Assert.IsNotNullOrEmpty(request.ResponseObject.RefreshUrl);
        }
예제 #14
0
        private TwitterResponse <TwitterStatusCollection> GetTwitterStatus()
        {
            TwitterResponse <TwitterStatusCollection> userInfo = new TwitterResponse <TwitterStatusCollection>();

            //use cache here
            if (Page.Cache[string.Format("TweetWrite-{0}", this.ScreenName)] == null)
            {
                //create a authorization token of the user
                OAuthTokens tokens = new OAuthTokens();
                tokens.ConsumerKey       = this.ConsumerKey;
                tokens.ConsumerSecret    = this.ConsumerSecret;
                tokens.AccessToken       = this.AccessToken;
                tokens.AccessTokenSecret = this.AccessTokenSecret;

                //Set the query options

                UserTimelineOptions Useroptions = new UserTimelineOptions();
                Useroptions.ScreenName = this.ScreenName;

                //Get the account info
                userInfo = TwitterTimeline.UserTimeline(tokens, Useroptions);
                HttpContext.Current.Cache.Insert(string.Format("TweetWrite-{0}", this.ScreenName), userInfo, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            }
            else
            {
                userInfo = Page.Cache[string.Format("TweetWrite-{0}", this.ScreenName)] as TwitterResponse <TwitterStatusCollection>;
            }

            return(userInfo);
        }
        public void GetMembers()
        {
            OAuthTokens tokens = Configuration.GetTokens();

            TwitterResponse <TwitterList>           list           = TwitterList.Show(tokens, "ghc10-attendees");
            TwitterResponse <TwitterUserCollection> usersInTheList = TwitterList.GetMembers(tokens, "ghc", "ghc10-attendees");

            Assert.IsNotNull(usersInTheList);
            Assert.That(usersInTheList.Result == RequestResult.Success);

            int countedMembers = usersInTheList.ResponseObject.Count;

            // Attempt to page through the results.
            while (usersInTheList != null && usersInTheList.ResponseObject.Count > 0)
            {
                usersInTheList = TwitterList.GetMembers(tokens, "ghc", "ghc10-attendees", new GetListMembersOptions {
                    Cursor = usersInTheList.ResponseObject.NextCursor
                });

                if (usersInTheList != null)
                {
                    countedMembers += usersInTheList.ResponseObject.Count;
                }
            }

            Assert.That(countedMembers == list.ResponseObject.NumberOfMembers);
        }
        public static void HandleTwitterizerError <T>(TwitterResponse <T> response) where T : Twitterizer.Core.ITwitterObject
        {
            // Something bad happened, time to figure it out.
            string RawDataReturnedByTwitter      = response.Content;
            string ErrorMessageReturnedByTwitter = response.ErrorMessage;

            if (string.IsNullOrEmpty(ErrorMessageReturnedByTwitter))
            {
                ErrorMessageReturnedByTwitter = "No error given";
            }
            var ErrorMessage = "Error from twitter: " + ErrorMessageReturnedByTwitter + Environment.NewLine;

            // The possible reasons something went wrong
            switch (response.Result)
            {
            case RequestResult.FileNotFound:
                ErrorMessage += "\t This usually means the user doesn't exist.";
                break;

            case RequestResult.BadRequest:
                ErrorMessage += "\t An unknown error occurred (RequestResult = BadRequest).";
                break;

            case RequestResult.Unauthorized:
                ErrorMessage += "\t An unknown error occurred (RequestResult = Unauthorized).";
                break;

            case RequestResult.NotAcceptable:
                ErrorMessage += "\t An unknown error occurred (RequestResult = NotAcceptable).";
                break;

            case RequestResult.RateLimited:
                TimeSpan ttr = DateTime.Now.ToUniversalTime().Subtract(response.RateLimiting.ResetDate).Duration();
                ErrorMessage += "Rate limit of " + response.RateLimiting.Total + " reached; ";
                break;

            case RequestResult.TwitterIsDown:
                //
                break;

            case RequestResult.TwitterIsOverloaded:
                ErrorMessage += "\t Twitter is overloaded (or down)";
                //System.Threading.Thread.Sleep(_fiveSec);
                break;

            case RequestResult.ConnectionFailure:
                ErrorMessage += "\t An unknown error occurred (RequestResult = ConnectionFailure).";
                break;

            case RequestResult.Unknown:
                ErrorMessage += "\t An unknown error occurred (RequestResult = Unknown).";
                break;

            default:
                ErrorMessage += "\t An unknown error occurred.)";
                break;
            }

            Form.AppendLineToOutput(ErrorMessage);
        }
 private void tweetResponse(TwitterStatus tweet, TwitterResponse response)
 {
     if (response.StatusCode == HttpStatusCode.OK)
     {
         Dispatcher.BeginInvoke(() =>
         {
             MessageBox.Show("Successfully shared on Twitter");
             progbar1.IsIndeterminate = false;
             progbar1.Visibility      = Visibility.Collapsed;
             if (NavigationService.CanGoBack)
             {
                 NavigationService.GoBack();
             }
         });
     }
     else
     {
         if (response.StatusCode == HttpStatusCode.Unauthorized)
         {
             Dispatcher.BeginInvoke(() => { MessageBox.Show("Authentication error"); });
         }
         else
         {
             Dispatcher.BeginInvoke(() => { MessageBox.Show("Error, please try again later"); });
         }
     }
 }
예제 #18
0
        public void DisplayTweets(string value)
        {
            if (value != "")
            {
                UserTimelineOptions userOptions = new UserTimelineOptions();
                userOptions.APIBaseAddress = "https://api.twitter.com/1.1/";                                            // <-- needed for API 1.1
                userOptions.Count          = 20;
                userOptions.UseSSL         = true;                                                                      // <-- needed for API 1.1
                userOptions.ScreenName     = value;                                                                     //<-- replace with yours
                TwitterResponse <TwitterStatusCollection> timeline = TwitterTimeline.UserTimeline(tokens, userOptions); // collects first 20 tweets from our account
                int i = 1;

                foreach (TwitterStatus status in timeline.ResponseObject)
                {
                    TextBox2.Text += i + ")" + status.Text + Environment.NewLine;
                    i++;
                }

                TextBox2.Text += "-----------------------------------------------------------------------" + Environment.NewLine;
            }
            else
            {
                TextBox2.Text += "Invalid Screen Name";
            }
        }
예제 #19
0
        /// <summary>
        /// Create the Header and footer of the Webpart
        /// </summary>
        /// <param name="Type"></param>
        /// <returns></returns>
        private Table CreateHeaderFooter(string Type)
        {
            Table tbHF;

            tbHF             = new Table();
            tbHF.Width       = Unit.Percentage(100);
            tbHF.CellPadding = 0;
            tbHF.CellSpacing = 0;

            if (!string.IsNullOrEmpty(this.ScreenName) &&
                !string.IsNullOrEmpty(this.ConsumerKey) &&
                !string.IsNullOrEmpty(this.ConsumerSecret) &&
                !string.IsNullOrEmpty(this.AccessToken) &&
                !string.IsNullOrEmpty(this.AccessTokenSecret))
            {
                TwitterResponse <TwitterStatusCollection> userInfo = GetTwitterStatus();

                #region Header
                if (Type.Equals("Header"))
                {
                    tbHF = Common.CreateHeaderFooter("Header", userInfo.ResponseObject, this.ShowHeaderImage, this.ShowFollowUs);
                }
                #endregion

                #region Footer
                if (Type.Equals("Footer"))
                {
                    tbHF = Common.CreateHeaderFooter("Footer", userInfo.ResponseObject, this.ShowHeaderImage, this.ShowFollowUs);
                }
                #endregion
            }
            return(tbHF);
        }
예제 #20
0
파일: UserModel.cs 프로젝트: swinghu/Ocell
        void ReceiveFollow(TwitterUser usr, TwitterResponse response)
        {
            string successMsg = "", errorMsg = "";

            if (usr == null)
            {
                MessageService.ShowError(Resources.ErrorMessage);
                return;
            }

            if (!Followed)
            {
                successMsg = String.Format(Resources.NowYouFollow, usr.ScreenName);
                errorMsg   = String.Format(Resources.CouldntFollow, usr.ScreenName);
            }
            else
            {
                successMsg = String.Format(Resources.NowYouUnfollow, usr.ScreenName);
                errorMsg   = String.Format(Resources.CouldntUnfollow, usr.ScreenName);
            }

            IsLoading = false;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                MessageService.ShowLightNotification(successMsg);
                Followed = !Followed;
                followUser.RaiseCanExecuteChanged();
                unfollowUser.RaiseCanExecuteChanged();;
            }
            else
            {
                MessageService.ShowError(errorMsg);
            }
        }
예제 #21
0
        private void GetStatusReplied(TwitterStatus status)
        {
            if (status.InReplyToStatusId != null)
            {
                Interlocked.Increment(ref pendingCalls);
                service.GetTweet(new GetTweetOptions {
                    Id = (long)status.InReplyToStatusId
                }, (result, response) =>
                {
                    if (result == null || response.StatusCode != HttpStatusCode.OK)
                    {
                        RaiseCallback(new List <TwitterStatus>(), response); // report the error
                        TryFinish();
                        return;
                    }

                    okResponse = response;
                    if (!searchCache.Contains(result))
                    {
                        searchCache.Add(result);
                    }

                    RaiseCallback(new List <TwitterStatus> {
                        status, result
                    }, response);

                    GetConversationForStatus(result);

                    TryFinish();
                });
            }
        }
예제 #22
0
 private void Form3_Load(object sender, EventArgs e)
 {
     try
     {
         showUserResponse = TwitterUser.Show(oa, scr);
         TwitterUser user = showUserResponse.ResponseObject;
         pictureBox1.ImageLocation = user.ProfileImageLocation;
         Text = "UserViewer - " + user.ScreenName;
         label1.Text = user.Name;
         label2.Text = "@" + user.ScreenName;
         label3.Text = user.Location;
         linkLabel1.Text = user.Website;
         if (user.IsFollowing == true)
         {
             label4.Text = "Following";
         }
         else if (user.IsFollowing == false && user.FollowRequestSent == false)
         {
             label4.Text = "Not Following";
         }
         else
         {
             label4.Text = "Has Sent a Follow Request";
         }
         if (user.IsProtected == true) label5.Text = "Protected";
         button1.Text = (bool)user.IsFollowing ? "unfollow" : "follow";
         textBox1.Text = user.Description;
         
     }
     catch
     {
         MessageBox.Show("Some error happened. The user should not exists.");
         this.Close();
     }
 }
        public static void FollowersIds()
        {
            OAuthTokens tokens = Configuration.GetTokens();

            TwitterResponse <UserIdCollection> response = TwitterFriendship.FollowersIds(tokens, new UsersIdsOptions
            {
                ScreenName = "twitterapi"
            });

            Assert.IsNotNull(response);
            Assert.That(response.Result == RequestResult.Success);
            Assert.IsNotNull(response.ResponseObject);
            Assert.That(response.ResponseObject.Count > 0);

            decimal firstId = response.ResponseObject[0];

            response = TwitterFriendship.FollowersIds(tokens, new UsersIdsOptions {
                ScreenName = "twitterapi", Cursor = response.ResponseObject.NextCursor
            });
            Assert.IsNotNull(response);
            Assert.That(response.Result == RequestResult.Success);
            Assert.IsNotNull(response.ResponseObject);
            Assert.That(response.ResponseObject.Count > 0);
            Assert.AreNotEqual(response.ResponseObject[0], firstId);
        }
예제 #24
0
 private void RaiseCallback(IEnumerable <TwitterStatus> statuses, TwitterResponse response)
 {
     if (callback != null)
     {
         callback.Invoke(statuses, response);
     }
 }
예제 #25
0
        private void SearchCallback(TwitterSearchResult result, TwitterResponse response, TwitterStatus status)
        {
            if (result == null || response.StatusCode != HttpStatusCode.OK || result.Statuses == null)
            {
                RaiseCallback(new List <TwitterStatus>(), response); // report the error
                TryFinish();
                return;
            }

            okResponse = response;
            searchCache.BulkAdd(result.Statuses.Except(searchCache));

            if (result.Statuses.Count() >= 90)
            {
                // There are still more statuses to retrieve
                Interlocked.Increment(ref pendingCalls);
                service.Search(new SearchOptions {
                    Q = "to:" + status.AuthorName, SinceId = status.Id, MaxId = result.Statuses.Min(x => x.Id), Count = 100
                },
                               (rs, rp) => SearchCallback(rs, rp, status));
            }
            else
            {
                // Finished!
                AddCachedResult(status.AuthorName, status.Id);
            }

            RetrieveRepliesFromCache(status);

            TryFinish();
        }
예제 #26
0
        //
        // GET: /Home/

        public string AjaxSaveToDB()
        {
            if (Session["LoggedASP"] != null)
            {
                TimelineOptions options = new TimelineOptions();

                options.Count           = 200;
                options.IncludeRetweets = true;

                OAuthTokens token = new OAuthTokens();
                token.ConsumerKey       = ConfigurationManager.AppSettings["consumerKey"];
                token.ConsumerSecret    = ConfigurationManager.AppSettings["consumerSecret"];
                token.AccessToken       = ((User)Session["LoggedUser"]).TwitterToken;
                token.AccessTokenSecret = ((User)Session["LoggedUser"]).TwitterTokenSecret;

                TwitterResponse <TwitterStatusCollection> truc = TwitterTimeline.HomeTimeline(token, options);

                TweetEntity tweetEntity = new TweetEntity();

                tweetEntity.RemoveTweetFromOwner(((User)Session["LoggedUser"]).ID);

                foreach (var item in truc.ResponseObject)
                {
                    //int lol = ;

                    tweetEntity.AddTweet(item.Id, item.Text, item.User.ScreenName, item.User.ProfileImageLocation, ((User)Session["LoggedUser"]).ID, ((int)((TimeSpan)(item.CreatedDate - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime())).TotalSeconds));
                }
                return("Success");
            }
            else
            {
                return("Fail");
            }
        }
예제 #27
0
        /// <summary>
        /// Get the Twitter response object for the friends
        /// </summary>
        /// <returns></returns>
        private TwitterResponse <TwitterUserCollection> GetTwitterFriends()
        {
            TwitterResponse <TwitterUserCollection> twitterResponse = new TwitterResponse <TwitterUserCollection>();

            if (Page.Cache[string.Format("TwitterFriends-{0}", this.ScreenName)] == null)
            {
                //create a authorization token of the user
                OAuthTokens tokens = new OAuthTokens();
                tokens.ConsumerKey       = this.ConsumerKey;
                tokens.ConsumerSecret    = this.ConsumerSecret;
                tokens.AccessToken       = this.AccessToken;
                tokens.AccessTokenSecret = this.AccessTokenSecret;

                //Set the query options
                FriendsOptions Friendoptions = new FriendsOptions();
                Friendoptions.ScreenName = this.ScreenName;
                Friendoptions.Cursor     = -1;

                //get the Following Object from the Twitter
                twitterResponse = TwitterFriendship.Friends(tokens, Friendoptions);
                HttpContext.Current.Cache.Insert(string.Format("TwitterFriends-{0}", this.ScreenName), twitterResponse, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            }
            else
            {
                twitterResponse = Page.Cache[string.Format("TwitterFriends-{0}", this.ScreenName)] as TwitterResponse <TwitterUserCollection>;
            }

            return(twitterResponse);
        }
예제 #28
0
        public void Deserialize_UsesJsonProperties_True()
        {
            // Arrange
            var testResponse = new TestResponse()
            {
                id_str     = "123",
                created_at = "Sun Dec 16 20:56:33 +0000 2018",
                full_text  = "Wello Horld! http://www.Steve.com",
                truncated  = false,
            };
            var             serializer = new LambdaRestSerializer();
            var             stream     = new MemoryStream();
            TwitterResponse result     = null;

            // Act
            serializer.Serialize <TestResponse>(testResponse, stream);
            stream.Position = 0;
            result          = serializer.Deserialize <TwitterResponse>(stream);

            // Assert
            Assert.Equal(result.UID, testResponse.id_str);
            Assert.Equal(result.CreatedAt, new DateTimeOffset(2018, 12, 16, 20, 56, 33, new TimeSpan(0)));
            Assert.Equal(result.FullText, testResponse.full_text);
            Assert.Equal(result.Truncated, testResponse.truncated);
        }
        public void BypassCacheForRecentResults()
        {
            // Setup the cache
            var cachedResults = new TwitterSearchResultCollection();
            cachedResults.Add(new TwitterSearchResult() { Id = 1, Text = "This is just a #test" });
            _localCache.Stub(c => c.PageResults).Return(cachedResults);
            _localCache.Stub(c => c.PageNumber).Return(1);

            // Setup the Twitterizer response
            TwitterResponse<TwitterSearchResultCollection> response = new TwitterResponse<TwitterSearchResultCollection>();
            response.ResponseObject = new TwitterSearchResultCollection();
            response.ResponseObject.Add(new TwitterSearchResult() { Id = 1, Text = "This is just a #test" });
            response.ResponseObject.Add(new TwitterSearchResult() { Id = 2, Text = "This is just another #test" });
            _searchService
                .Expect(s => s.Search(Arg<string>.Is.Anything, Arg<SearchOptions>.Is.Anything))
                .Return(response);

            TwitterSearchClient client = new TwitterSearchClient(_localCache, _searchService);
            var results = client.Search("#test", 1, 10, true); //newSearch means ignore the cache
            Assert.IsFalse(AreEquivalent(cachedResults, results));
            Assert.IsTrue(AreEquivalent(response.ResponseObject, results));

            _searchService.VerifyAllExpectations();
            _localCache.VerifyAllExpectations();
        }
        public static void Friends()
        {
            OAuthTokens tokens = Configuration.GetTokens();

#pragma warning disable 618
            TwitterResponse <TwitterStatusCollection> response = TwitterTimeline.FriendTimeline(tokens, new TimelineOptions {
                Count = 2
            });
#pragma warning restore 618

            Assert.IsNotNull(response);
            Assert.That(response.Result == RequestResult.Success);
            Assert.IsNotNull(response.ResponseObject);
            Assert.That(response.ResponseObject.Count > 0);

            decimal firstId = response.ResponseObject[0].Id;

#pragma warning disable 618
            response = TwitterTimeline.FriendTimeline(tokens, new TimelineOptions {
                Page = ++response.ResponseObject.Page
            });
#pragma warning restore 618
            Assert.IsNotNull(response);
            Assert.That(response.Result == RequestResult.Success);
            Assert.IsNotNull(response.ResponseObject);
            Assert.That(response.ResponseObject.Count > 0);
            Assert.AreNotEqual(response.ResponseObject[0].Id, firstId);
        }
예제 #31
0
        void buttonTweet_Click(object sender, EventArgs e)
        {
            try
            {
                OAuthTokens tokens = new OAuthTokens();
                tokens.ConsumerKey       = this.ConsumerKey;
                tokens.ConsumerSecret    = this.ConsumerSecret;
                tokens.AccessToken       = this.AccessToken;
                tokens.AccessTokenSecret = this.AccessTokenSecret;

                TwitterResponse <TwitterStatus> Response = TwitterStatus.Update(tokens, textTweet.Text.Trim());
                if (Response.Result == RequestResult.Success)
                {
                    LblMessage.Text      = "Message tweeted sucessfully!!!";
                    LblMessage.ForeColor = Color.Green;
                }
                else
                {
                    LblMessage.Text      = Response.ErrorMessage;
                    LblMessage.ForeColor = Color.Red;
                }
            }
            catch (Exception Ex)
            {
                LblMessage.Text      = Ex.Message;
                LblMessage.ForeColor = Color.Red;
            }
        }
예제 #32
0
        protected override void OnPreRender(EventArgs e)
        {
            try
            {
                textTweet.Text = "";
                if (this.EnableShowUserName)
                    textTweet.Text = SPContext.Current.Web.CurrentUser.Name + " : ";

                if (!string.IsNullOrEmpty(this.ConsumerKey)
                    && !string.IsNullOrEmpty(this.ConsumerSecret)
                    && !string.IsNullOrEmpty(this.AccessToken)
                    && !string.IsNullOrEmpty(this.AccessTokenSecret))
                {
                    TwitterResponse<TwitterStatusCollection> userInfo = GetTwitterStatus();

                    if (userInfo.ResponseObject.Count < 10000)
                    {
                        lblTweets.Text = userInfo.ResponseObject.Count.ToString();
                    }
                    else
                    {
                        lblTweets.Text = "10000+";

                    }
                }

                //Get the Css Class
                this.Page.Header.Controls.Add(StyleSheet.CssStyle());
            }
            catch (Exception Ex)
            {
                LblMessage.Text = Ex.Message;
                LblMessage.ForeColor = Color.Red;
            }
        }
예제 #33
0
        /// <summary>
        /// Parsea a una colección de Tweets, si el arreglo de tweets está en una propiedad "statuses"
        /// usar este método
        /// </summary>
        /// <param name="twitterResponse"></param>
        /// <returns></returns>
        public static TwitterResponse<List<Tweet>> ParseTweetsCollection2(TwitterResponse<string> twitterResponse)
        {
            if (twitterResponse.Status == TwitterStatus.Success)
            {
                JArray json = JArray.Parse(JObject.Parse(twitterResponse.ObjectResponse)["statuses"].ToString());

                List<Tweet> listFavourited =
                    (
                        from tweets in json.AsEnumerable()
                        select new Tweet
                        {
                            Id = (decimal)tweets["id"],
                            Text = (string)tweets["text"],
                            CreatedAt = DateTime.ParseExact(tweets["created_at"].ToString(), "ddd MMM dd HH:mm:ss K yyyy", CultureInfo.InvariantCulture),
                            User = new TwitterUser
                            {
                                Id = (int)tweets["user"]["id"],
                                Description = (string)tweets["user"]["description"],
                                FavouritesCount = (int)tweets["user"]["favourites_count"],
                                FollowersCount = (int)tweets["user"]["followers_count"],
                                Location = (string)tweets["user"]["location"],
                                Name = (string)tweets["user"]["name"],
                                ProfileImageUrl = (string)tweets["user"]["profile_image_url"],
                                ScreenName = (string)tweets["user"]["screen_name"]
                            },
                            Entities = new TweetEntities
                            {
                                Urls =
                                (
                                        from url in tweets["entities"]["urls"].AsEnumerable()
                                        select new EntitieUrl
                                        {
                                            DisplayUrl = (string)url["url"],
                                            ExpandedUrl = (string)url["display_url"],
                                            Url = (string)url["expanded_url"]
                                        }
                                ).ToList<EntitieUrl>()
                            }
                        }
                    ).ToList<Tweet>();
                return new TwitterResponse<List<Tweet>>
                {
                    ObjectResponse = listFavourited,
                    Status = TwitterStatus.Success
                };
            }
            else
            {
                return new TwitterResponse<List<Tweet>>
                {
                    ObjectResponse = null,
                    Status = twitterResponse.Status
                };
            }
        }
예제 #34
0
        protected virtual void HandleAuthenticationRequestToken(OAuthRequestToken token, TwitterResponse response)
        {
            _requestToken = token; // Save the token
            
            while(!_browserLoaded)
            {
                Thread.Sleep(200);
            }

            Dispatcher.BeginInvoke(
                () => _browser.Navigate(_service.GetAuthorizationUri(_requestToken))
                );
        }
예제 #35
0
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         showUserResponse = TwitterUser.Show(oa, scr);
         user = showUserResponse.ResponseObject;
         if (user.IsFollowing == true)
         {
             TwitterResponse<TwitterUser> follow = TwitterFriendship.Delete(oa, user.ScreenName);
             update();
         }
         else if (user.IsFollowing == false)
         {
             TwitterResponse<TwitterUser> follow = TwitterFriendship.Create(oa, user.ScreenName);
             update();
         }
     }
     catch
     {
         MessageBox.Show("Some error happened");
     }
 }
        public void MaintainPaginationConsistency()
        {
            // Setup the cache
            _localCache.Expect(c => c.PageNumber).Return(10);
            _localCache.Expect(c => c.MaxId).Return(999);

            // Setup the Twitterizer response
            TwitterResponse<TwitterSearchResultCollection> response = new TwitterResponse<TwitterSearchResultCollection>();
            response.ResponseObject = new TwitterSearchResultCollection();
            response.ResponseObject.Add(new TwitterSearchResult() { Id = 1, Text = "This is just a #test" });
            response.ResponseObject.Add(new TwitterSearchResult() { Id = 2, Text = "This is just another #test" });
            _searchService
                .Expect(s => s.Search(Arg<string>.Is.Anything, Arg<SearchOptions>.Matches(so => so.MaxId == 999 && so.PageNumber == 2)))
                .Return(response);

            TwitterSearchClient client = new TwitterSearchClient(_localCache, _searchService);
            var results = client.Search("#test", 11, 10, false);
            Assert.IsTrue(AreEquivalent(response.ResponseObject, results));

            _searchService.VerifyAllExpectations();
            _localCache.VerifyAllExpectations();
        }
예제 #37
0
        private void HomeTimelineSet()
        {
            DateTime server_time = ServerTime();

            tlp_timeline = new LinkedList<TableLayoutPanel>();
            response_status_collection = twitter_login.GetHomeTimeline();
            tweet_cnt = response_status_collection.ResponseObject.Count;

            for(int i = 0; i < tweet_cnt; i++)
            {
                TwitterStatus tStatus = response_status_collection.ResponseObject[i];
                TimeSpan time_gap = (server_time - tStatus.CreatedDate);

                string _text = HttpUtility.HtmlDecode(tStatus.Text);

                string str_gap;
                if(time_gap.Days > 7) { str_gap = tStatus.CreatedDate.ToString("yyyy년 M월 d일"); }
                else if(time_gap.Days > 0) { str_gap = time_gap.Days.ToString() + "일 전"; }
                else if(time_gap.Hours > 0) { str_gap = time_gap.Hours.ToString() + "시간 전"; }
                else if(time_gap.Minutes > 0) { str_gap = time_gap.Minutes.ToString() + "분 전"; }
                else { str_gap = time_gap.Seconds.ToString() + "초 전"; }

                string label_text;
                int RT_check = _text.IndexOf("RT");
                if(RT_check > -1)
                {
                    string rt_org = _text.Substring(3, _text.IndexOf(":") - 3);

                    label_text =
                            tStatus.User.Name + " 님이 리트윗함\n" +
                            rt_org + " · " + str_gap + "\n" +
                            _text.Substring(_text.IndexOf(rt_org + ": ") + (rt_org + ": ").Length);
                }
                else
                {
                    label_text =
                            tStatus.User.Name + " @" + tStatus.User.ScreenName + " · " + str_gap + "\n" +
                            _text;
                }

                PictureBox pb_TweetProfileImage = TwitterContent.GetPictureBox(48, 48, 12, 9, tStatus.User.ProfileImageLocation);
                Label lb_Nickname = TwitterContent.GetLabel(new Point(70, 9), new Font("맑은 고딕", 14f, FontStyle.Bold, GraphicsUnit.Pixel), tStatus.User.Name);
                Label lb_ID = TwitterContent.GetLabel(new Point(78 + lb_Nickname.Width, 10), new Font("맑은 고딕", 13f, FontStyle.Regular, GraphicsUnit.Pixel), "@" + tStatus.User.ScreenName);
                Label lb_CreatedDate = TwitterContent.GetLabel(new Point(78 + lb_Nickname.Width + lb_ID.Width, 10), new Font("맑은 고딕", 13f, FontStyle.Regular, GraphicsUnit.Pixel), str_gap);
                Label label = TwitterContent.GetLabel(506, new Point(70, 9), new Font("맑은 고딕", 14f, FontStyle.Regular, GraphicsUnit.Pixel), label_text);
                TableLayoutPanel tlp;

                if(tlp_timeline.Count == 0)
                {
                    tlp = TwitterContent.GetTableLayoutPanel(588, label.Height, 10, 10, 2, 1);
                }
                else
                {
                    tlp = TwitterContent.GetTableLayoutPanel(588, label.Height, 10, tlp_timeline.First.Value.Location.Y + tlp_timeline.First.Value.Height, 2, 1);
                }

                tlp.Controls.Add(pb_TweetProfileImage);
                tlp.Controls.Add(label);

                tlp_timeline.AddFirst(tlp);
                pn_timeline.Controls.Add(tlp);
            }
        }
예제 #38
0
        private void DrawTweet()
        {
            try
            {
                timelineResponse = TwitterTimeline.Mentions(myOAuthTokens);
                string tweet = timelineResponse.ResponseObject[0].Text;

                if (tweet.Length > 50)
                {
                    tweet = tweet.Insert((int)(tweet.Length / 2), "\n");
                }
                if (tweet.Length > 100)
                {
                    tweet = tweet.Insert((int)(tweet.Length / 8), "\n");
                    tweet = tweet.Insert((int)(tweet.Length / 4), "\n");
                    tweet = tweet.Insert((int)(tweet.Length / 4) + (int)(tweet.Length / 8), "\n");
                    tweet = tweet.Insert((int)(tweet.Length / 2) + (int)(tweet.Length / 8), "\n");
                    tweet = tweet.Insert((int)(tweet.Length - (tweet.Length / 4)), "\n");
                }

                if (currentTweet != tweet)
                {
                    drawingTweet = true;
                    currentTweet = tweet;
                }
            }
            catch (TwitterizerException ex)
            {

            }
        }
예제 #39
0
 private void Login()
 {
     twitter_login = new TwitterEnter();
     response_user = twitter_login.GetUserData();
 }
예제 #40
0
 private static void ShowUserCompleted(TwitterResponse<TwitterUser> user)
 {
     Console.WriteLine(user.ResponseObject.Status.Text);
 }
예제 #41
0
        public void ProcessResponse(TwitterResponse response)
        {
            try
            {
                lock (responseLock)
                {
                    log.Info("Received Response: " + response);
                    if (response is GetFriendsResponse)
                    {
                        ProcessGetFriendsResponse(response as GetFriendsResponse);
                    }
                    else if (response is GetFollowersResponse)
                    {
                        ProcessGetFollowersResponse(response as GetFollowersResponse);
                    }
                    else if (response is UserInfoResponse)
                    {
                        ProcessUserInfoResponse(response as UserInfoResponse);
                    }
                    else if (response is ErrorResponse)
                    {
                        ProcessErrorResponse(response as ErrorResponse);
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException("response", "Unknown / unhandled response type: " + response.GetType().Name);
                    }

                    if (!Shutdown)
                    {
                        responseQueue.BeginReceive(); // next..
                    }
                }
            }
            catch (Exception ex)
            {
                log.Fatal("Unhandled exception while trying to process result.  This will hang up the ResponseQueue.BeginReceive() loop, attempting to terminate program.", ex);
                Shutdown = true;
                if (ShutdownResetEvent != null)
                {
                    ShutdownResetEvent.Set();
                }
            }
        }
예제 #42
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="twitterResponse"></param>
        /// <returns></returns>
        private TwitterResponse<List<TwitterUser>> ParseListUsers(TwitterResponse<string> twitterResponse)
        {
            if (twitterResponse.Status == TwitterStatus.Success)
            {
                JArray json = JArray.Parse(twitterResponse.ObjectResponse);

                List<TwitterUser> usersSearched =
                    (
                        from  user in json.AsEnumerable()
                        select new TwitterUser
                        {
                            Name = (string)user["name"],
                            Id = (int)user["id"],
                            Location = (string)user["location"],
                            Description = (string)user["description"],
                            ScreenName = (string)user["screen_name"],
                            FavouritesCount = (int)user["favourites_count"],
                            FollowersCount = (int)user["followers_count"],
                            ProfileImageUrl = (string)user["profile_image_url"],
                            Verified = (bool)user["verified"]
                        }
                    ).ToList<TwitterUser>();

                return new TwitterResponse<List<TwitterUser>>
                {
                    Status=TwitterStatus.Success,
                    ObjectResponse=usersSearched
                };
            }
            else
                return new TwitterResponse<List<TwitterUser>>
                {
                    Status = twitterResponse.Status,
                    ObjectResponse = null
                };
        }
예제 #43
0
        /// <summary>
        /// Get the Twitter response object for the friends
        /// </summary>
        /// <returns></returns>
        private TwitterResponse<TwitterUserCollection> GetTwitterFriends()
        {
            TwitterResponse<TwitterUserCollection> twitterResponse = new TwitterResponse<TwitterUserCollection>();

            if (Page.Cache[string.Format("TwitterFriends-{0}", this.ScreenName)] == null)
            {
                //create a authorization token of the user
                OAuthTokens tokens = new OAuthTokens();
                tokens.ConsumerKey = this.ConsumerKey;
                tokens.ConsumerSecret = this.ConsumerSecret;
                tokens.AccessToken = this.AccessToken;
                tokens.AccessTokenSecret = this.AccessTokenSecret;

                //Set the query options
                FriendsOptions Friendoptions = new FriendsOptions();
                Friendoptions.ScreenName = this.ScreenName;
                Friendoptions.Cursor = -1;

                //get the Following Object from the Twitter
                twitterResponse = TwitterFriendship.Friends(tokens, Friendoptions);
                HttpContext.Current.Cache.Insert(string.Format("TwitterFriends-{0}", this.ScreenName), twitterResponse, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            }
            else
            {
                twitterResponse = Page.Cache[string.Format("TwitterFriends-{0}", this.ScreenName)] as TwitterResponse<TwitterUserCollection>;
            }

            return twitterResponse;
        }
예제 #44
0
 public void Send(TwitterResponse response)
 {
     SendMessage(response);
 }
예제 #45
0
        private void ProcessIncomingTweets(TwitterResponse response, IEnumerable<TwitterStatus> statuses, Dispatcher dispatcher)
        {
            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(response.StatusCode.ToString());
            }

            foreach (var status in statuses)
            {
                var inline = status;
                var tweet = new Tweet(inline);

                dispatcher.BeginInvoke(() => _tweets.Items.Add(tweet));
            }
        }
예제 #46
0
        private void HandleAuthenticationAccessToken(OAuthAccessToken token, TwitterResponse response)
        {
            _accessToken = token;

            Dispatcher.BeginInvoke(
                ()=>
                    {
                        _browser.Visibility = Visibility.Visible;
                        _tweets.Visibility = Visibility.Collapsed;            
                    }
            );

            ServiceExample();
        }
예제 #47
0
 public ResponseReceivedEventArgs(TwitterResponse response)
 {
     TwitterResponse = response;
 }
예제 #48
0
 private void timer1_Tick(object sender, EventArgs e)
 {
     showUserResponse = TwitterUser.Show(oa, scr);
     user = showUserResponse.ResponseObject;
     if (user.IsFollowing == true)
     {
         label4.Text = "Following";
     }
     else if (user.IsFollowing == false && user.FollowRequestSent == false)
     {
         label4.Text = "Not Following";
     }
     else
     {
         label4.Text = "Has Sent a Follow Request";
     }
     button1.Text = (bool)user.IsFollowing ? "unfollow" : "follow";
 }
예제 #49
0
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
			try{
            showUserResponse = TwitterUser.Show(oa, scr);
            user = showUserResponse.ResponseObject;
            System.Diagnostics.Process.Start(user.Website);
			}
			catch
			{
			}
        }
예제 #50
0
 public void update()
 {
     showUserResponse = TwitterUser.Show(oa, scr);
     user = showUserResponse.ResponseObject;
     if (user.IsFollowing == true)
     {
         label4.Text = "Following";
     }
     else if (user.IsFollowing == false && user.FollowRequestSent == false)
     {
         label4.Text = "Not Following";
     }
     else
     {
         label4.Text = "Has Sent a Follow Request";
     }
     button1.Text = (bool)user.IsFollowing ? "unfollow" : "follow";
 }
예제 #51
0
        private TwitterResponse<TwitterStatusCollection> GetTwitterStatus()
        {
            TwitterResponse<TwitterStatusCollection> userInfo = new TwitterResponse<TwitterStatusCollection>();

            //use cache here
            if (Page.Cache[string.Format("TweetWrite-{0}", this.ScreenName)] == null)
            {
                //create a authorization token of the user
                OAuthTokens tokens = new OAuthTokens();
                tokens.ConsumerKey = this.ConsumerKey;
                tokens.ConsumerSecret = this.ConsumerSecret;
                tokens.AccessToken = this.AccessToken;
                tokens.AccessTokenSecret = this.AccessTokenSecret;

                //Set the query options

                UserTimelineOptions Useroptions = new UserTimelineOptions();
                Useroptions.ScreenName = this.ScreenName;

                //Get the account info
                userInfo = TwitterTimeline.UserTimeline(tokens, Useroptions);
                HttpContext.Current.Cache.Insert(string.Format("TweetWrite-{0}", this.ScreenName), userInfo, null, DateTime.Now.AddMinutes(Common.CACHEDURATION), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            }
            else
            {
                userInfo = Page.Cache[string.Format("TweetWrite-{0}", this.ScreenName)] as TwitterResponse<TwitterStatusCollection>;
            }

            return userInfo;
        }
예제 #52
0
        /// <summary>
        /// Get the Followers from Twitter
        /// </summary>
        /// <returns></returns>
        private Table GetFollowers(TwitterResponse<TwitterUserCollection> twitterUsers, TwitterResponse<TwitterStatusCollection> twitterStatus)
        {
            Table insideTable;
            TableRow tr;
            TableCell tc;

            insideTable = new Table();
            insideTable.CellPadding = 0;
            insideTable.CellSpacing = 0;
            insideTable.Width = Unit.Percentage(100);

            int r = 1;
            tr = new TableRow();
            if (twitterUsers.ResponseObject.Count > 0)
            {
                //Get the total number of followers
                int followersCount = Convert.ToInt32(twitterUsers.ResponseObject.Count);
                int c = 0;

                foreach (TwitterUser followerUsers in twitterUsers.ResponseObject)
                {
                    # region Create a new row if User column count limit exceeds
                    if (this.UsersColumnCount == c)
                    {
                        if (r < this.UsersRowCount)
                        {
                            tr = new TableRow();
                            r++;
                            c = 0;
                        }
                        else
                        {
                            break;
                        }
                    }
                    #endregion

                    //Create a new cell
                    tc = new TableCell();
                    tc.Attributes.Add("valign", "top");

                    //create a new table in a cell
                    Table tb = new Table();
                    tb.Width = Unit.Percentage(100);

                    #region Show Follower Image
                    HtmlImage imgFollower = new HtmlImage();
                    imgFollower.Src = followerUsers.ProfileImageLocation.ToString();
                    imgFollower.Border = 0;

                    //Show Follower Image
                    TableRow tr1 = new TableRow();
                    TableCell tc1 = new TableCell();
                    tc1.CssClass = "alignCenter";

                    if (this.ShowImageAsLink)
                    {
                        HyperLink lnkFollower = new HyperLink();
                        lnkFollower.NavigateUrl = "http://twitter.com/" + followerUsers.ScreenName;
                        lnkFollower.Attributes.Add("target", "_blank");
                        lnkFollower.Controls.Add(imgFollower);
                        lnkFollower.ToolTip = followerUsers.Name;
                        tc1.Controls.Add(lnkFollower);
                        tc1.VerticalAlign = VerticalAlign.Top;
                        tc1.Width = Unit.Percentage(100 / this.UsersColumnCount);
                    }
                    else
                    {
                        tc1.Controls.Add(imgFollower);
                        tc.ToolTip = followerUsers.Name;
                    }
                    #endregion

                    tr1.Controls.Add(tc1);
                    tb.Rows.Add(tr1);

                    #region Show Follower Name
                    //Show Follower Name
                    if (this.ShowFollowerScreenName)
                    {
                        Label lblFollower = new Label();

                        //If the user has entered only first name
                        if (followerUsers.Name.IndexOf(" ") != -1)
                            lblFollower.Text = followerUsers.Name.Substring(0, followerUsers.Name.IndexOf(" "));      //Get the first name only to display
                        else
                            lblFollower.Text = followerUsers.Name;

                        lblFollower.Font.Size = FontUnit.XXSmall;
                        TableRow tr2 = new TableRow();
                        TableCell tc2 = new TableCell();
                        tc2.CssClass = "alignCenter";
                        tc2.VerticalAlign = VerticalAlign.Top;
                        tc2.Width = Unit.Percentage(100 / this.UsersColumnCount);
                        tc2.Controls.Add(lblFollower);
                        tr2.Controls.Add(tc2);
                        tb.Rows.Add(tr2);
                    }
                    #endregion

                    tc.Controls.Add(tb);
                    tr.Cells.Add(tc);
                    insideTable.Rows.Add(tr);
                    c++;
                }
            }
예제 #53
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="twitterResponse"></param>
        /// <returns></returns>
        private TwitterResponse<TwitterUser> ParseUserInfo(TwitterResponse<string> twitterResponse)
        {
            if (twitterResponse.Status == TwitterStatus.Success)
            {
                JObject json = JObject.Parse(twitterResponse.ObjectResponse);

                TwitterUser user = new TwitterUser()
                {
                    Name = (string)json["name"],
                    Id = (int)json["id"],
                    Location = (string)json["location"],
                    Description = (string)json["description"],
                    ScreenName = (string)json["screen_name"],
                    FavouritesCount = (int)json["favourites_count"],
                    FollowersCount = (int)json["followers_count"],
                    ProfileImageUrl = (string)json["profile_image_url"],
                    Verified=(bool)json["verified"]
                };

                return new TwitterResponse<TwitterUser>()
                {
                    Status = TwitterStatus.Success,
                    ObjectResponse = user
                };
            }
            else
                return new TwitterResponse<TwitterUser>()
                {
                    Status = twitterResponse.Status,
                    ObjectResponse = null
                };
        }
예제 #54
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;
        }
예제 #55
0
 public void Send(TwitterResponse response)
 {
     SentResponses.Add(response);
 }
 private static void PerformCommonTimelineTests(TwitterResponse<TwitterStatusCollection> timelineResponse)
 {
     Assert.IsNotNull(timelineResponse);
     Assert.That(timelineResponse.Result == RequestResult.Success, timelineResponse.ErrorMessage);
     Assert.IsNotNull(timelineResponse.ResponseObject);
 }
예제 #57
0
        /// <summary>
        /// Get the following users
        /// </summary>
        /// <returns></returns>
        private Table GetFollowing(TwitterResponse<TwitterUserCollection> twitterUsers, TwitterResponse<TwitterStatusCollection> twitterStatus)
        {
            Table insideTable;
            TableRow tr = null;
            TableCell tc;

            insideTable = new Table();
            insideTable.CellPadding = 0;
            insideTable.CellSpacing = 0;
            insideTable.Width = Unit.Percentage(100);

            int r = 1;
            tr = new TableRow();

            if (twitterUsers.ResponseObject.Count > 0)
            {
                //Get the total number of followers
                int followersCount = Convert.ToInt32(twitterUsers.ResponseObject.Count);
                int c = 0;

                foreach (TwitterUser followingUsers in twitterUsers.ResponseObject)
                {
                    //Create a new row if Usercount limit exceeds
                    if (this.UsersColumnCount == c)
                    {
                        if (r < this.UsersRowCount)
                        {
                            tr = new TableRow();
                            r++;
                            c = 0;
                        }
                        else
                        {
                            break;
                        }
                    }

                    //Create a new cell
                    tc = new TableCell();
                    tc.Attributes.Add("valign", "top");

                    //create a new table in a cell
                    Table tb = new Table();
                    tb.Width = Unit.Percentage(100);

                    //Show Friend Image
                    HtmlImage imgFollower = new HtmlImage();
                    imgFollower.Src = followingUsers.ProfileImageLocation.ToString();
                    imgFollower.Border = 0;

                    TableRow tr1 = new TableRow();
                    TableCell tc1 = new TableCell();
                    tc1.CssClass = "alignCenter";

                    if (this.ShowImageAsLink)
                    {
                        HyperLink lnkFollower = new HyperLink();
                        lnkFollower.NavigateUrl = "http://twitter.com/" + followingUsers.ScreenName;
                        lnkFollower.Attributes.Add("target", "_blank");
                        lnkFollower.Controls.Add(imgFollower);
                        lnkFollower.ToolTip = followingUsers.Name;
                        tc1.Controls.Add(lnkFollower);
                        tc1.VerticalAlign = VerticalAlign.Top;
                        tc1.Width = Unit.Percentage(100 / this.UsersColumnCount);
                    }
                    else
                    {
                        tc1.Controls.Add(imgFollower);
                    }

                    tr1.Controls.Add(tc1);
                    tb.Rows.Add(tr1);

                    //Show Follower Name
                    if (this.ShowFollowingScreenName)
                    {
                        Label lblFollower = new Label();

                        if (followingUsers.Name.IndexOf(" ") != -1)
                            lblFollower.Text = followingUsers.Name.Substring(0, followingUsers.Name.IndexOf(" "));      //Get the first name only to display
                        else
                            lblFollower.Text = followingUsers.Name;

                        lblFollower.Font.Size = FontUnit.XXSmall;
                        TableRow tr2 = new TableRow();
                        TableCell tc2 = new TableCell();
                        tc2.CssClass = "alignCenter";
                        tc2.Width = Unit.Percentage(100 / this.UsersColumnCount);
                        tc2.Controls.Add(lblFollower);
                        tr2.Controls.Add(tc2);
                        tb.Rows.Add(tr2);
                    }

                    tc.Controls.Add(tb);
                    tr.Cells.Add(tc);
                    insideTable.Rows.Add(tr);
                    c++;
                }
            }
            else
            {
                // If there are no Friends

                insideTable = new Table();
                tr = new TableRow();
                tc = new TableCell();
                insideTable.Width = Unit.Percentage(100);
                insideTable.CellPadding = 5;

                //display grey tweet image
                HtmlImage imgGreyTweet = new HtmlImage();
                imgGreyTweet.Src = SPContext.Current.Web.Url + "/_layouts/Brickred.OpenSource.Twitter/Greytweet.png";
                imgGreyTweet.Border = 0;
                tc.Controls.Add(imgGreyTweet);
                tc.CssClass = "alignCenter";
                tc.VerticalAlign = VerticalAlign.Middle;
                tr.Cells.Add(tc);
                insideTable.Rows.Add(tr);

                //display message
                tr = new TableRow();
                tc = new TableCell();
                Label lblScreenName = new Label();
                lblScreenName.Text = "@" + twitterStatus.ResponseObject[0].User.Name;
                lblScreenName.Font.Size = FontUnit.Large;
                lblScreenName.ForeColor = Color.Gray;
                Label lblMessage = new Label();
                lblMessage.Text = " is not following anyone yet.";
                lblMessage.ForeColor = Color.Gray;
                lblScreenName.ForeColor = Color.Gray;
                tc.Controls.Add(lblScreenName);
                tc.Controls.Add(lblMessage);
                tc.CssClass = "alignCenter";
                tr.Cells.Add(tc);
                insideTable.Rows.Add(tr);
            }

            return insideTable;
        }
예제 #58
0
 private TwitterStatus HandleTwitterResponse(TwitterResponse<TwitterStatus> statusResponse)
 {
     if (statusResponse.Result == RequestResult.Success)
     {
         Console.WriteLine("Successfull");
         return statusResponse.ResponseObject as TwitterStatus;
     }
     else
     {
         Console.WriteLine("error: {0}", statusResponse.ErrorMessage);
         return null;
     }
 }
        public void StoreTweetsLocally()
        {
            TwitterResponse<TwitterSearchResultCollection> response = new TwitterResponse<TwitterSearchResultCollection>();
            response.ResponseObject = new TwitterSearchResultCollection();
            response.ResponseObject.Add(new TwitterSearchResult() { Id = 1, Text = "This is just a #test" });

            _searchService
                .Expect(s => s.Search(Arg<string>.Is.Anything, Arg<SearchOptions>.Is.Anything))
                .Return(response);

            _localCache.Expect(c => c.PageResults = response.ResponseObject);

            TwitterSearchClient client = new TwitterSearchClient(_localCache, _searchService);
            client.Search("#test", 1, 10, true);

            _searchService.VerifyAllExpectations();
            _localCache.VerifyAllExpectations();
        }
예제 #60
0
 private static void PerformCommonTimelineTests(TwitterResponse<TwitterStatusCollection> timelineResponse)
 {
     Assert.IsNotNull(timelineResponse, "timelineResponse is null");
     Assert.IsTrue(timelineResponse.Result == RequestResult.Success, timelineResponse.ErrorMessage ?? timelineResponse.Result.ToString());
     Assert.IsNotNull(timelineResponse.ResponseObject, timelineResponse.ErrorMessage ?? timelineResponse.Result.ToString());
 }