protected void Page_Load(object sender, EventArgs e)
    {
        IOAuthCredentials creds = new SessionStateCredentials();
        creds.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
        creds.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
        creds.AccessToken = ConfigurationManager.AppSettings["twitterAccessToken"];
        creds.OAuthToken = ConfigurationManager.AppSettings["twitterOauthToken"];
        //Auth Object With Credentials
        var auth = new WebAuthorizer
        {
            Credentials = creds
        };     
        var twitterCtx = new TwitterContext(auth);

        var users =
            (from user in twitterCtx.Status
             where user.Type == StatusType.User &&
                   user.ScreenName == "JoeMayo" &&
                   user.Count == 200
             select user)
            .ToList();

        UserListView.DataSource = users;
        UserListView.DataBind();
    }
        public void BeginAuthorize_Requires_Credentials()
        {
            const string RequestUrl = "https://api.twitter.com/";
            var webAuth = new WebAuthorizer();

            var ex = Assert.Throws<ArgumentNullException>(() => webAuth.BeginAuthorization(new Uri(RequestUrl)));

            Assert.Equal("Credentials", ex.ParamName);
        }
        public void BeginAuthorize_Does_Not_Require_A_Uri()
        {
            var webAuth = new WebAuthorizer {Credentials = new InMemoryCredentials()};
            var oAuthMock = new Mock<IOAuthTwitter>();
            webAuth.OAuthTwitter = oAuthMock.Object;
            string authUrl = string.Empty;
            webAuth.PerformRedirect = url => authUrl = url;

            webAuth.BeginAuthorization(null);
            Assert.Null(authUrl);
        }
Beispiel #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        IOAuthCredentials credentials = new SessionStateCredentials();

        if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
        {
            credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
            credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
        }

        auth = new WebAuthorizer
        {
            Credentials = credentials,
            PerformRedirect = authUrl => Response.Redirect(authUrl)
        };

        if (!Page.IsPostBack && Request.QueryString["oauth_token"] != null)
        {
            auth.CompleteAuthorization(Request.Url);
        }

        if (string.IsNullOrWhiteSpace(credentials.ConsumerKey) ||
            string.IsNullOrWhiteSpace(credentials.ConsumerSecret))
        {
            // The user needs to set up the web.config file to include Twitter consumer key and secret.
            PrivateDataMultiView.SetActiveView(SetupTwitterConsumer);
        }
        else if (auth.IsAuthorized)
        {
            screenNameLabel.Text = auth.ScreenName;
            PrivateDataMultiView.SetActiveView(ViewPrivateUpdates);
            updateBox.Focus();
        }
        else
        {
            PrivateDataMultiView.SetActiveView(AuthorizeTwitter);
        }

        if (auth.IsAuthorized)
        {
            twitterCtx = new TwitterContext(auth);

            var search =
                (from srch in twitterCtx.Search
                 where srch.Type == SearchType.Search &&
                       srch.Query == "LINQ to Twitter"
                 select srch)
                .SingleOrDefault();

            TwitterListView.DataSource = search.Statuses;
            TwitterListView.DataBind(); 
        }
    }
        public void BeginAuthorization_Calls_PerformRedirect()
        {
            const string RequestUrl = "https://api.twitter.com/";
            var webAuth = new WebAuthorizer {Credentials = new InMemoryCredentials()};
            var oAuthMock = new Mock<IOAuthTwitter>();
            oAuthMock.Setup(oauth => oauth.FilterRequestParameters(It.IsAny<Uri>())).Returns(RequestUrl);
            webAuth.OAuthTwitter = oAuthMock.Object;
            string authUrl = string.Empty;
            webAuth.PerformRedirect = url => authUrl = url;

            webAuth.BeginAuthorization(new Uri(RequestUrl));

            Assert.Null(authUrl);
        }
        public void BeginAuthorization_Gets_Request_Token()
        {
            const string RequestUrl = "https://api.twitter.com/";
            var webAuth = new WebAuthorizer {Credentials = new InMemoryCredentials()};
            var oAuthMock = new Mock<IOAuthTwitter>();
            webAuth.OAuthTwitter = oAuthMock.Object;
            oAuthMock.Setup(oauth => oauth.FilterRequestParameters(It.IsAny<Uri>())).Returns(RequestUrl);
            string authUrl = string.Empty;
            webAuth.PerformRedirect = url => authUrl = url;

            webAuth.BeginAuthorization(new Uri(RequestUrl));

            oAuthMock.Verify(oAuth => oAuth.AuthorizationLinkGet(It.IsAny<string>(), It.IsAny<string>(), RequestUrl, false, AuthAccessType.NoChange), Times.Once());
            Assert.Null(authUrl);
        }
Beispiel #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //var twitterCtx = new TwitterContext();

            IOAuthCredentials credentials = new SessionStateCredentials();

            if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
            {
                credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
                credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
            }

            auth = new WebAuthorizer
            {
                Credentials = credentials,
                PerformRedirect = authUrl => Response.Redirect(authUrl)
            };

            if (!Page.IsPostBack)
            {
                auth.CompleteAuthorization(Request.Url);
            }

            else if (auth.IsAuthorized)
            {
                Label1.Text = "Congratulations, you're authorized";

            }

            var twitterCtx = new TwitterContext(auth);
            //twitterCtx = auth.IsAuthorized ? new TwitterContext(auth) : new TwitterContext();

            UserId = credentials.UserId;
            string token = credentials.OAuthToken;
            string sec = credentials.AccessToken;

            ////// show token and secret in index page after Authorization
            Label2.Text = token;
            Label3.Text = sec;
            Label4.Text = credentials.UserId;

            ////// creat twtUser object to store the info about the user
            TwitterUser twt = new TwitterUser(UserId, token, sec);

            ////// move user's info to another page throw Session
            Session["objTwt"] = twt;
        }
        void OAuthForm_Load(object sender, EventArgs e)
        {
            auth = new WebAuthorizer
            {
                // Get the ConsumerKey and ConsumerSecret for your app and load them here.
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = Twitter.ConsumerKey,
                    ConsumerSecret = Twitter.ConsumerSecret
                },
                Callback = new Uri("http://livesplit.org/twitter/"),
                // Note: GetPin isn't used here because we've broken the authorization
                // process into two parts: begin and complete
                PerformRedirect = pageLink =>
                    OAuthWebBrowser.Navigate(new Uri(pageLink, UriKind.Absolute))
            };

            auth.BeginAuthorization(new Uri("http://livesplit.org/twitter/"));
        }
        public void CompleteAuthorization_Gets_Access_Token()
        {
            string screenName = "JoeMayo";
            string userID = "123";
            const string Verifier = "1234567";
            const string AuthToken = "token";
            const string AuthLink = "https://authorizationlink?oauth_token=" + AuthToken + "&oauth_verifier=" + Verifier;
            var webAuth = new WebAuthorizer {Credentials = new InMemoryCredentials()};
            var oAuthMock = new Mock<IOAuthTwitter>();
            oAuthMock.Setup(oauth => oauth.GetUrlParamValue(It.IsAny<string>(), "oauth_verifier")).Returns(Verifier);
            oAuthMock.Setup(oauth => oauth.GetUrlParamValue(It.IsAny<string>(), "oauth_token")).Returns(AuthToken);
            oAuthMock.Setup(oAuth => oAuth.AuthorizationLinkGet(It.IsAny<string>(), It.IsAny<string>(), "https://authorizationlink", false, AuthAccessType.NoChange))
                     .Returns(AuthLink);
            oAuthMock.Setup(oAuth => oAuth.AccessTokenGet(AuthToken, Verifier, It.IsAny<string>(), string.Empty, out screenName, out userID));
            webAuth.OAuthTwitter = oAuthMock.Object;

            webAuth.CompleteAuthorization(new Uri(AuthLink));

            oAuthMock.Verify(oauth => oauth.AccessTokenGet(AuthToken, Verifier, It.IsAny<string>(), string.Empty, out screenName, out userID), Times.Once());
            Assert.Equal(screenName, webAuth.ScreenName);
            Assert.Equal(userID, webAuth.UserId);
        }
Beispiel #10
0
        /// <summary>
        /// Gets a Twitter search result.
        /// </summary>
        /// <param name="query">Search query.
        /// API docs: https://dev.twitter.com/docs/api/1.1/get/search/tweets
        /// </param>
        /// <returns>Tweets found by search, or null if no results.</returns>
        public List<Status> GetTweetsBySearch(string query)
        {
            var auth = new WebAuthorizer
            {
                Credentials = new SessionStateCredentials()
            };

            var twitterCtx = new TwitterContext(auth);

            var searchResults =
                from search in twitterCtx.Search
                where search.Type == SearchType.Search && search.Query == query
                select search;

            var searched = searchResults.SingleOrDefault();

            if (searched != null)
            {
                return searched.Statuses;
            }

            return null;
        }
Beispiel #11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        IOAuthCredentials credentials = new InMemoryCredentials();
        string authString = Session[OAuthCredentialsKey] as string;

        if (authString == null)
        {
            credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
            credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];

            Session[OAuthCredentialsKey] = credentials.ToString();
        }
        else
        {
            credentials.Load(authString);
        }

        auth = new WebAuthorizer
        {
            Credentials = new InMemoryCredentials
            {
                ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]
            },
            PerformRedirect = authUrl => Response.Redirect(authUrl)
        };

        if (string.IsNullOrEmpty(credentials.ConsumerKey) ||
            string.IsNullOrEmpty(credentials.ConsumerSecret) ||
            !auth.IsAuthorized)
        {
            // Authorization occurs only on the home page.
            Response.Redirect("~/");
        }

        updateBox.Focus();
    }
 public MvcOAuthActionResult(WebAuthorizer webAuth)
 {
     this.webAuth = webAuth;
 }
    private List<SessionsResult> SessionsToTweetAfterSignup(out StringBuilder sbText)
    {
        //DateTime compareDateTime = DateTime.Now.Subtract(new TimeSpan(0, 1, 0, 0));
        // do a max of 2 at a time.  these go every 30 minutes
        var sessionsToTweet = SessionsManager.I.Get(new SessionsQuery
                                                        {
                                                            TweetLineTweeted = false,
                                                            WithSpeakers = true,
                                                            WithSchedule = true,
                                                            CodeCampYearId = Utils.CurrentCodeCampYear
                                                        }).Where(
                                                            a =>
                                                            a.Createdate != null &&
                                                            a.Createdate.Value.CompareTo(
                                                                DateTime.Now.Subtract(new TimeSpan(0, 48, 0, 0))) <
                                                            0).
            OrderByDescending(a => a.Id).Take(_tweetsToProcessAtOnce).ToList();

        sbText = new StringBuilder();
        foreach (var session in sessionsToTweet)
        {
            var speakers = Utils.GetSpeakersBySessionId(session.Id);
            var sb = new StringBuilder();
            foreach (var speaker in speakers)
            {
                string speakerName = string.Format("{0} {1},", speaker.UserFirstName, speaker.UserLastName);
                sb.Append(speakerName);
            }
            string speakerList = sb.ToString();
            if (speakerList.Length > 0 && speakerList.EndsWith(","))
            {
                speakerList = speakerList.Substring(0, speakerList.Length - 1);
            }

            string sessionUrl = String.Format("http://siliconvalley-codecamp.com/Sessions.aspx?sessionid={0}",
                                              session.Id);
            string sessionUrlShort = API.Bit(_bitLyApiUsername, _bitLyApiKey,
                                             HttpContext.Current.Server.HtmlEncode(sessionUrl), "Shorten");

            string template = "NEW SESSION: {0}  Speaker: {1} #svcc Title: \"{2}\"";
            if (speakerList.Length > 0 && speakers.Count > 1)
            {
                template = "NEW SESSION: {0}  Speakers: {1} #svcc Title: \"{2}\"";
            }

            string tweet = String.Format(template, sessionUrlShort, speakerList, session.Title);
            if (tweet.Length > 139)
            {
                tweet = tweet.Substring(0, 136) + "...";
            }

            // finally, do the tweet
            string credentialString = _twitterCredential;

            var credentials = new SessionStateCredentials();
            credentials.Load(credentialString);

            var auth = new WebAuthorizer
                           {
                               Credentials = credentials
                           };

            var twitterCtx = new TwitterContext(auth);
            const decimal lattitude = (decimal) 37.362056;
            const decimal longitude = (decimal) 122.131056;
            if (!testMode)
            {
                Status tweetInfo = twitterCtx.UpdateStatus(tweet, lattitude, longitude);
                Label1.Text = tweetInfo.Text; // not sure if this helps
            }

            sbText.AppendLine(tweet);

            // update
            session.TweetLine = tweet;
            session.TweetLineTweetedDate = DateTime.Now;
            session.TweetLineTweeted = true;
            if (!testMode)
            {
                SessionsManager.I.Update(session);
            }

            // finally, send the emails.
            foreach (var rec in speakers)
            {
                SendEmailToSpeaker(rec.UserFirstName, rec.UserLastName, rec.Email, session.Title, tweet);
            }
        }
        return sessionsToTweet;
    }
Beispiel #14
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            var auth = new WebAuthorizer
            {
                Credentials = new SessionStateCredentials()
            };

            var twitterCtx = new TwitterContext(auth);

            /////////////////////////////////
            ///// get this user's tweets ////
            string name = TextBoxUser.Text; //twt.getScreenName(); //"mishari11";
            /////////////////////////////////
            /////////////////////////////////

            ////// show token and secret and Screen Name in page
            Label1.Text = twt.getToken();
            Label2.Text = twt.getTokenSecret();
            Label4.Text = twt.getTwitterID();

            //// 111111111111111111111111111111111111111111111111111111111
            ///  first API requst before the while loop to get the "maxID"
            var statusTweets =
              from tweet in twitterCtx.Status
              where tweet.Type == StatusType.User
                    && tweet.ScreenName == name         /// get this user's tweets
                    && tweet.Count == 200               /// number of tweets to retrieve in single requst  // max is 200
                    && tweet.ExcludeReplies == true     /// do not show replies
                    && tweet.IncludeMyRetweet == false  /// do not show my retweet
                    && tweet.IncludeRetweets == false   /// do not show other pepole retweet
              select tweet;

            ////// (ahmed) this is for the userID for each tweet i do not if you need it or not (you wrote it)
            //var test3 = statusTweets.Select(tweet => tweet.UserID).ToArray();
            //List<String> test10 = new List<string>();
            //test10.AddRange(test3);

            ////// store tweets and RTConut in var
            var tmepTweet = statusTweets.Select(tweet => tweet.Text).ToArray();
            var tempRetweetCount = statusTweets.Select(tweet => tweet.RetweetCount).ToArray();

            ///// add tweet and RTCount to temp lists
            List<String> lstTempTweet = new List<string>();
            lstTempTweet.AddRange(tmepTweet);

            List<int> lstTempRTCount = new List<int>();
            lstTempRTCount.AddRange(tempRetweetCount);

            //// to store the Status that retrieve each time from the API   (Status conteant evry thing about the tweet "text" "RTCount" etc..)
            var statusList = new List<Status>(); ;

            //// 22222222222222222222222222222222222222222222222222222
            //// the rest of APT requsts (up to 3200 tweets including replies and retweets)
            int intcall = 1;        // counter for number of requst to twitter API
            while (statusTweets.Count() != 0)
            {

                //// get the ID of last tweet retrieved -1
                ulong maxID = statusTweets.Min(status => ulong.Parse(status.StatusID)) - 1;

                statusTweets =
                  from tweet in twitterCtx.Status
                  where tweet.Type == StatusType.User
                        && tweet.ScreenName == name         /// get this user's tweets
                        && tweet.Count == 200               /// number of tweets to retrieve in single requst  // max is 200
                        && tweet.ExcludeReplies == true     /// do not show replies
                        && tweet.IncludeMyRetweet == false  /// do not show my retweet
                        && tweet.IncludeRetweets == false   /// do not show other pepole retweet
                        && tweet.MaxID == maxID             /// retrieve before this ID
                  select tweet;

                //// store the Status and add 1 to requst counter
                statusList.AddRange(statusTweets);
                intcall++;

            } /// end while loop

            ////// store tweets and RTConut in var
            tmepTweet = statusList.Select(tweet => tweet.Text).ToArray();
            tempRetweetCount = statusList.Select(tweet => tweet.RetweetCount).ToArray();

            ///// add tweet and RTCount to temp lists
            lstTempTweet.AddRange(tmepTweet);
            lstTempRTCount.AddRange(tempRetweetCount);

            //// add tweet and RTCount twtUser object "twt"
            twt.setLstTwts(lstTempTweet);
            twt.setLstTwtsRT(lstTempRTCount);

            /////////////   print all tweets    ///////////////////////////////

            List<String> tempTWT = new List<string>();
            tempTWT = twt.getarrTwts();

            List<int> tempRT = new List<int>();
            tempRT = twt.getarrTwtsRT();

            for (int k = 0; k < tempTWT.Count; k++)
            {
                classes.DBConnection NewConnection = new classes.DBConnection();
                NewConnection.AddTweetInDB(tempTWT[k], " ", TextBoxUser.Text, " ");
                TextBox3.Text += tempTWT[k] + "\n\n" + "#RT:  " + tempRT[k] + "\n\n-----------------------------------------------------\n";

            }

            Label3.Text = tempTWT.Count.ToString();
            Label11.Text = intcall.ToString();

            var lists =
                (from list in twitterCtx.List
                 where list.Type == ListType.Lists &&
                       list.ScreenName == twt.getScreenName()
                 select list)
                .ToList();
            TextBox1.Text = "";
            TextBox2.Text = "";
            foreach (var list in lists)
            {
                 TextBox1.Text = TextBox1.Text + " " +list.ListIDResult+" - " + list.SlugResult + " - " +  list.Description + "\n";
            }
            //---------------------------------
            foreach (var Mylists in lists)
            {
                var lists1 =
                    (from list in twitterCtx.List
                     where list.Type == ListType.Members &&
                     //list.ListID == "88244464"
                     list.ListID == Mylists.ListIDResult
                     select list).First();

                TextBox2.Text = TextBox2.Text + "\n" + Mylists.SlugResult + "( " + Mylists.Description + " ) " + " : " + "\n";
                //TextBox2.Text = lists1.Users.First().Name.ToString();//(i).Users.ToList();
                foreach (var UsersOfList in lists1.Users)
                {
                    TextBox2.Text = TextBox2.Text + UsersOfList.Identifier.ID + " - " + UsersOfList.Name.ToString() + "\n";
                }
            }
            //----------------------------------- end
        }
 public MvcOAuthActionResult(WebAuthorizer webAuth)
 {
     this.webAuth = webAuth;
 }
    private List<SessionsResult> SessionsToTweetBeforeBigEvent(out StringBuilder sbText)
    {
        var codeCampYearResult = CodeCampYearManager.I.Get(new CodeCampYearQuery {Id = Utils.CurrentCodeCampYear}).FirstOrDefault();
        if (codeCampYearResult != null)
        {
            DateTime startTweetsAfter =
                codeCampYearResult.
                    CampStartDate.Subtract(new TimeSpan(12, 0, 0, 0));

            if (startTweetsAfter.CompareTo(DateTime.Now) > 0)
            {
                sbText = new StringBuilder("No Tweeting because too soon for SessionsToTweetBeforeBigEvent()");
                return new List<SessionsResult>();
            }
        }
        else
        {
            sbText = new StringBuilder("No Tweeting because no code camp year found");
            return new List<SessionsResult>();
        }

        // if got here, then we should start tweeting all sessions again

        var sessionsToTweet =
            SessionsManager.I.Get(new SessionsQuery
                                      {
                                          TweetLineTweetedPreCamp = false,
                                          WithSchedule = true,
                                          WithSpeakers = true,
                                          CodeCampYearId = Utils.CurrentCodeCampYear
                                         // Id = 953 // test for just scottgu and email comes to me
                                      }).Where(a => !a.SessionTime.Equals("Agenda Not Set Yet")).
                                      OrderBy(a => a.SessionTimesResult.StartTime.HasValue ? a.SessionTimesResult.StartTime.Value : DateTime.Now).Take(_tweetsToProcessAtOnce).
                ToList();

        sbText = new StringBuilder();
        foreach (var session in sessionsToTweet)
        {

            DateTime sessionTime;
            string sessionTimeFriendly;
            string speakerNames;
            string speakerHandles;
            string hashTags;
            Utils.GetSessionHandlesHashTagsTime(session, out speakerNames, out speakerHandles,out hashTags, out sessionTime, out sessionTimeFriendly);
            string sessionTitle = Utils.ClearSpecialCharacters(session.Title);

            string sessionUrl = String.Format("http://siliconvalley-codecamp.com/Sessions.aspx?sessionid={0}",
                                              session.Id);
            string sessionUrlShort = API.Bit(_bitLyApiUsername, _bitLyApiKey,
                                             HttpContext.Current.Server.HtmlEncode(sessionUrl), "Shorten");

            // "at 9:45AM 10/6 Speaker Douglas Crockford @dougc Title: Gonads and Ponads  #svcc #json http://dkfjdkf
            string template = "{0}  {1} {2} \"{{0}}\" #svcc {3} {4} ReTweet!";

            string tweetFirstPart =
                String.Format(template, sessionTimeFriendly, speakerNames, speakerHandles, hashTags,
                              sessionUrlShort).Trim();
            int spaceLeftForTitle = 130 - tweetFirstPart.Length;
            int titleLen = Math.Min(sessionTitle.Length, spaceLeftForTitle);

            string tweet = String.Format(tweetFirstPart, sessionTitle.Substring(0, titleLen)).Trim();

            // finally, do the tweet
            string credentialString = _twitterCredential;

            var credentials = new SessionStateCredentials();
            credentials.Load(credentialString);

            var auth = new WebAuthorizer
            {
                Credentials = credentials
            };

            var twitterCtx = new TwitterContext(auth);
            const decimal lattitude = (decimal)37.362056;
            const decimal longitude = (decimal)122.131056;
            if (!testMode)
            {
                Status tweetInfo = twitterCtx.UpdateStatus(tweet, lattitude, longitude);
                Label1.Text = tweetInfo.Text; // not sure if this helps
            }
            sbText.AppendLine(tweet);

            // update
            session.TweetLinePreCamp = tweet;
            session.TweetLineTweetedDatePreCamp = DateTime.Now;
            session.TweetLineTweetedPreCamp = true;

            if (!testMode)
            {
                SessionsManager.I.Update(session);
            }

            // finally, send the emails.
            foreach (var rec in session.SpeakersList)
            {
                SendEmailToSpeakerJustBeforeEvent(rec.UserFirstName, rec.UserLastName, rec.Email, session.Title, tweet);
            }
        }
        return sessionsToTweet;
    }
        public void CompleteAuthorization_Requires_Credentials()
        {
            const string AuthLink = "https://authorizationlink";
            var webAuth = new WebAuthorizer();

            var ex = Assert.Throws<ArgumentNullException>(() => webAuth.CompleteAuthorization(new Uri(AuthLink)));

            Assert.Equal("Credentials", ex.ParamName);
        }
        public void CompleteAuthorization_Requires_A_Uri()
        {
            var webAuth = new WebAuthorizer {Credentials = new InMemoryCredentials()};
            var oAuthMock = new Mock<IOAuthTwitter>();
            webAuth.OAuthTwitter = oAuthMock.Object;

            var ex = Assert.Throws<ArgumentNullException>(() => webAuth.CompleteAuthorization(null));

            Assert.Equal("callback", ex.ParamName);
        }