public async Task InitTweetViewModel()
        {
            var auth = new ApplicationOnlyAuthorizer()
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = "dYNbMI3KFn4zFrHIaAKIWCFYQ",
                    ConsumerSecret = "mQhDSmPov7bbJXb8jPwaVghBbUbgELpQqyHG2QRyf89CsQWKyb",
                },
            };
            await auth.AuthorizeAsync();

            var ctx = new TwitterContext(auth);

            var searchResponse = await
                (from search in ctx.Search
                 where search.Type == SearchType.Search &&
                       search.Query == "\"LINQ to Twitter\""
                 select search)
                .SingleAsync();

            Tweets =
                (from tweet in searchResponse.Statuses
                 select new Tweet
                 {
                     StatusID = tweet.StatusID,
                     ScreenName = tweet.User.ScreenNameResponse,
                     Text = tweet.Text,
                     ImageUrl = tweet.User.ProfileImageUrl
                 })
                .ToList();
        }
    public async Task LoadTweetsCommand(string search)
    {
      if (IsBusy)
        return;

      IsBusy = true;
      try
      {

        Tweets.Clear();
        var auth = new ApplicationOnlyAuthorizer()
        {
          CredentialStore = new InMemoryCredentialStore
          {
            ConsumerKey = "ZTmEODUCChOhLXO4lnUCEbH2I",
            ConsumerSecret = "Y8z2Wouc5ckFb1a0wjUDT9KAI6DUat5tFNdmIkPLl8T4Nyaa2J",
          },
        };
        await auth.AuthorizeAsync();

        var twitterContext = new TwitterContext(auth);
       
        var queryResponse = await
          (from tweet in twitterContext.Search
           where tweet.Type == SearchType.Search &&
             tweet.Query == search &&
             tweet.Count == 100
           select tweet).SingleOrDefaultAsync();

        if (queryResponse == null || queryResponse.Statuses == null)
          return;


        var tweets =
          (from tweet in queryResponse.Statuses
           select new Tweet
           {
             StatusID = tweet.StatusID,
             ScreenName = tweet.User.ScreenNameResponse,
             Text = tweet.Text,
             CurrentUserRetweet = tweet.CurrentUserRetweet,
             CreatedAt = tweet.CreatedAt,
             Url = string.Format("https://m.twitter.com/{0}/status/{1}", tweet.User.ScreenNameResponse, tweet.StatusID),
             Image = (tweet.RetweetedStatus != null && tweet.RetweetedStatus.User != null ?
                            tweet.RetweetedStatus.User.ProfileImageUrl.Replace("http://", "https://") : tweet.User.ProfileImageUrl.Replace("http://", "https://"))
           }).ToList();

        foreach (var tweet in tweets)
        {
          Tweets.Add(tweet);
        }
      }
      catch
      {
      }

      IsBusy = false;
    }
Esempio n. 3
0
        public override List<Result> Search(string pKeyWords)
        {
            string twitterConsumerKey = ConfigurationManager.AppSettings["twitter-consumer-key"];
            string twitterConsumerSecret = ConfigurationManager.AppSettings["twitter-consumer-secret"];

            if (string.IsNullOrWhiteSpace(twitterConsumerKey) || string.IsNullOrWhiteSpace(twitterConsumerSecret))
                throw new Exception("App was unable to find Twitter credentials on the current settings file. Please add twitter-consumer-key and twitter-consumer-secret to the appSettings section.");

            ApplicationOnlyAuthorizer authorization = new ApplicationOnlyAuthorizer()
            {
                Credentials = new InMemoryCredentials()
                {
                    ConsumerKey = twitterConsumerKey,
                    ConsumerSecret = twitterConsumerSecret
                }
            };

            authorization.Authorize();

            if(!authorization.IsAuthorized)
                throw new Exception("Twitter authorizaton was unsuccessful. Please review your Twitter key and secret.");

            TwitterContext twitterContext = new TwitterContext(authorization);

            LinqToTwitter.Search twitterSearch =
                (from search in twitterContext.Search
                 where search.Type == SearchType.Search &&
                       search.Query == pKeyWords &&
                       search.Count == this.MaxResultSearch
                 select search)
                .SingleOrDefault();

            IEnumerable<Status> tweets =
                from status in twitterSearch.Statuses
                orderby status.CreatedAt descending
                select status;

            List<Result> domainResults = new List<Result>();

            foreach (Status status in tweets)
            {
                domainResults.Add(
                    new Result()
                    {
                        CreatedDate = status.CreatedAt,
                        Type = SourceType.Twitter,
                        Text = status.Text,
                        Title = status.Text.Length > 50? string.Format("{0}...",status.Text.Substring(0, 47)) : status.Text,
                        URL = string.Format("http://twitter.com/{0}", status.User.Identifier.ScreenName)
                    }
                );
            }

            return domainResults;
        }
Esempio n. 4
0
 private static ITwitterAuthorizer DoApplicationOnly()
 {
     var auth = new ApplicationOnlyAuthorizer()
                {
                    Credentials = new InMemoryCredentials
                                  {
                                      ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
                                      ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
                                  },
                };
     auth.Authorize();
     return auth;
 }
		public async static Task<IAuthorizer> GetAuth()
		{
			var auth = new ApplicationOnlyAuthorizer
			{
				CredentialStore = new InMemoryCredentialStore()
				{
					ConsumerKey = Secrets.twitterConsumerKey,
					ConsumerSecret = Secrets.twitterConsumerSecret
				}
			};

			await auth.AuthorizeAsync();
			return auth;
		}
Esempio n. 6
0
 public static async Task<ApplicationOnlyAuthorizer> Authorize()
 {
     throw new NotImplementedException("Enter API key & secret below");
     var auth = new ApplicationOnlyAuthorizer
     {
         CredentialStore = new InMemoryCredentialStore()
         {
             ConsumerKey = "",
             ConsumerSecret = ""
         }
     };
     await auth.AuthorizeAsync();
     return auth;
 }
        private async Task InitializeTwitterContextAsync()
        {
            var auth = new ApplicationOnlyAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey = "wamG84e3GpkPjVp08UwsfAZIG",
                    ConsumerSecret = "9lCkCpXJ2FJFINs7329p06alOowqvWNJ2wwFPSTP9MaNu1xGyL"
                }
            };

            await auth.AuthorizeAsync().ConfigureAwait(false);
            Context = new TwitterContext(auth);
        }
        public void EncodeCredentials_Returns_Valid_Credentials()
        {
            const string ExpectedEncodedCredentials = "eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJnNmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==";
            var auth = new ApplicationOnlyAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "xvz1evFS4wEEPTGEFPHBog",
                    ConsumerSecret = "L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg"
                }
            };

            auth.EncodeCredentials();

            Assert.Equal(ExpectedEncodedCredentials, auth.BasicToken);
        }
Esempio n. 9
0
        async private void button1_Click(object sender, EventArgs e)
        {
            var authorizer = new ApplicationOnlyAuthorizer
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = "KQrJnO8Sxc6098dm6OMSbQeoU",
                    ConsumerSecret = "gs7cQhxsMnNGukBnYmCoCPRgIXVTwEPDIjnwOfLUBY9smwsGVv"
                }
            };

            await authorizer.AuthorizeAsync();
            var ctx = new TwitterContext(authorizer);

            string searchString = searchText.Text;

            var searchResponse =
                await
                (from search in ctx.Search
                 where search.Type == SearchType.Search &&
                       search.Query == searchString &&
                       search.Count == 100
                 select search)
                .SingleOrDefaultAsync();

            var tweets =
                (from tweet in searchResponse.Statuses
                 select new TweetViewModel
                 {
                     ImageUrl = tweet.User.ProfileImageUrl,
                     ScreenName = tweet.User.ScreenNameResponse,
                     Text = tweet.Text
                 })
                .ToList();

            string result = "";
            foreach(TweetViewModel tweet in tweets)
            {
                result += tweet.Text + "\n";
            }
            label1.Text = result;

        }
Esempio n. 10
0
        async void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            var authorizer = new ApplicationOnlyAuthorizer
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = "",
                    ConsumerSecret = ""
                }
            };

            await authorizer.AuthorizeAsync();
            var ctx = new TwitterContext(authorizer);

            string searchString = searchText.Text;

            var searchResponse =
                await
                (from search in ctx.Search
                 where search.Type == SearchType.Search &&
                       search.Query == searchString
                 select search)
                .SingleOrDefaultAsync();

            var tweets =
                (from tweet in searchResponse.Statuses
                 select new TweetViewModel
                 {
                     ImageUrl = tweet.User.ProfileImageUrl,
                     ScreenName = tweet.User.ScreenNameResponse,
                     Text = tweet.Text
                 })
                .ToList();

            tweetListView.ItemsSource = new ObservableCollection<TweetViewModel>(tweets);
        }
        public IHttpActionResult GetUserInfo(string query, int count = 20, string resultType = "recent", string language = null, string geo = null)
        {
            try
            {
                var auth = new ApplicationOnlyAuthorizer
                {
                    CredentialStore = new SingleUserInMemoryCredentialStore
                    {
                        ConsumerKey = TwitterKeys.consumerKey,
                        ConsumerSecret = TwitterKeys.consumerSecret,
                        AccessToken = TwitterKeys.accessToken,
                        AccessTokenSecret = TwitterKeys.accessTokenSecret
                    }
                };

                var authSync = auth.AuthorizeAsync();
                authSync.Wait();

                var twitterCtx = new TwitterContext(auth);

                var resultadoBusca = (from search in twitterCtx.Search
                                      where search.Type == SearchType.Search &&
                                            search.Query == query &&
                                            search.Count == count &&
                                            search.ResultType == ResultType.Recent &&
                                            search.SearchLanguage == "pt"
                                      select search)
                                     .ToList();

                return Ok(resultadoBusca[0].Statuses);
            }
            catch (Exception ex)
            {
                throw new Exception("Não conseguimos processar a requisição. Por favor verifique a conexão com a internet ou tente mais tarde.");
            }
        }
        private async Task<List<Status>> GetLatestsTwittersWithHashtag(string hashtag, long laterThanThisID = 0)
        {
            try
            {

                hashtag = !hashtag.Contains("#") ? "#" + hashtag : hashtag;

                var authorizer = new ApplicationOnlyAuthorizer
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey = Services.Settings["TwitterConsumerKey"],
                        ConsumerSecret = Services.Settings["TwitterConsumerSecret"],
                    }
                };

                await authorizer.AuthorizeAsync();
                var twitterCtx = new TwitterContext(authorizer);

                var query = twitterCtx.Search.Where(x => x.Type == SearchType.Search && x.Query == hashtag && x.Count == 100);

                if (laterThanThisID > 0)
                {
                    query = query.Where(x => x.SinceID == (ulong)laterThanThisID);
                }

                var searchresponse = query.FirstOrDefault();

                return searchresponse.Statuses;

            }
            catch (Exception ex)
            {
                return new List<Status>();
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Demonstrates how to use ApplicationOnlyAuthorizer
        /// </summary>
        /// <param name="twitterCtx"></param>
        private static void HandleApplicationOnlyAuthentication()
        {
            var auth = new ApplicationOnlyAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]
                }
            };

            auth.Authorize();
            //auth.Invalidate();

            var twitterCtx = new TwitterContext(auth);

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

            Console.WriteLine("\nQuery: {0}\n", srch.SearchMetaData.Query);
            srch.Statuses.ForEach(entry =>
                Console.WriteLine(
                    "ID: {0, -15}, Source: {1}\nContent: {2}\n",
                    entry.StatusID, entry.Source, entry.Text));
        }
Esempio n. 14
0
        protected override void render(Graphics g)
        {
            if (W != 1059 || H != 94)
                Global.error("Drawing WidgetTwitter in unknown frame size: " + W + "x" + H);
            g.DrawImage(new Bitmap(Global.appData("1059x94 twitter.png")), new Rectangle(0, 0, W, H));

            if (handles == null) return;

            var auth = new ApplicationOnlyAuthorizer();
            auth.Credentials = new InMemoryCredentials { // @weatherfnord/multitweeterer
                ConsumerKey = "vTTLuEldRiVwqdBv97q6Q",
                ConsumerSecret = "4pLpDAjDAqovaY4DzQW7wj8ow9MeMmJ10nLlVED5zk"
            };
            auth.Authorize();
            var ctx = new TwitterContext(auth);
            var res =
                from search in ctx.Search
                where search.Type == SearchType.Search &&
                    search.Query == "LINQ to Twitter"
                select search;

            Search srch = res.Single();

            IEnumerable<Status> tweets = Enumerable.Empty<Status>();
            foreach (string h in handles.Split()) {
                string handle = h;
                if (h[0] == '@') handle = handle.Substring(1);

                try {
                    var response =
                        (from tweet in ctx.Status
                         where tweet.Type == StatusType.User &&
                               tweet.ScreenName == handle &&
                               tweet.Count == 5
                         select tweet)
                        .ToList();
                    tweets = tweets.Concat(response);
                } catch { }
            }
            tweets = tweets.OrderByDescending(item => item.CreatedAt);
            string text = "";
            foreach (Status tweet in tweets) {
                text = tweet.ScreenName + ": " + tweet.Text.Replace("\n", " ");
                break;
            }

            fitText(g, Color.Black, "Calibri", text, new RectangleF(100, 16, 945, 54));
        }
Esempio n. 15
0
        public async Task<string> Get()
        {
            
            try
            {
                

                var tweets = new List<Tweet>();
                var tweetsObj = cache.GetValue("tweets");

                if(tweetsObj != null)
                    tweets = tweetsObj as List<Tweet>;

                if (tweets == null)
                    tweets = new List<Tweet>();

                if (tweets.Count > 0)
                    return Newtonsoft.Json.JsonConvert.SerializeObject(tweets);

                

                var auth = new ApplicationOnlyAuthorizer()
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
                        ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
                    },
                };
                await auth.AuthorizeAsync();

                var twitterContext = new TwitterContext(auth);

                var queryResponse = await
                    (from tweet in twitterContext.Search
                     where tweet.Type == SearchType.Search &&
                         (tweet.Query == "#XamarinEvolve") &&
                         tweet.Count == 100
                     select tweet).SingleOrDefaultAsync();

                if (queryResponse == null || queryResponse.Statuses == null)
                    return string.Empty;

                tweets =
                    (from tweet in queryResponse.Statuses
                     where tweet.RetweetedStatus.StatusID == 0 && !tweet.PossiblySensitive && !censor.HasCensoredWord(tweet.Text)
                     select new Tweet
                     {
                         TweetedImage = tweet.Entities?.MediaEntities.Count > 0 ? tweet.Entities?.MediaEntities?[0].MediaUrlHttps ?? string.Empty : string.Empty,
                         ScreenName = tweet.User?.ScreenNameResponse ?? string.Empty,
                         Text = tweet.Text,
                         Name = tweet.User.Name,
                         CreatedDate = tweet.CreatedAt,
                         Url = string.Format("https://twitter.com/{0}/status/{1}", tweet.User.ScreenNameResponse, tweet.StatusID),
                         Image = (tweet.RetweetedStatus != null && tweet.RetweetedStatus.User != null ?
                                 tweet.RetweetedStatus.User.ProfileImageUrl.Replace("http://", "https://") : tweet.User.ProfileImageUrl.Replace("http://", "https://"))
                     }).Take(15).ToList();


                cache.Add("tweets", tweets, DateTimeOffset.UtcNow.AddMinutes(1));
               
                return Newtonsoft.Json.JsonConvert.SerializeObject(tweets);
            }
            catch
            {

            }


            return string.Empty;
        }
Esempio n. 16
0
        static IAuthorizer DoApplicationOnlyAuth()
        {
            var auth = new ApplicationOnlyAuthorizer()
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
                },
            };

            return auth;
        }
Esempio n. 17
0
		private async void ExecuteLoadTweetsCommand ()
		{
			if (IsBusy)
				return;

			IsBusy = true;
			try {

				Tweets.Clear ();
				var auth = new ApplicationOnlyAuthorizer () {
					CredentialStore = new InMemoryCredentialStore {
						ConsumerKey = "ZTmEODUCChOhLXO4lnUCEbH2I",
						ConsumerSecret = "Y8z2Wouc5ckFb1a0wjUDT9KAI6DUat5tFNdmIkPLl8T4Nyaa2J",
					},
				};
				await auth.AuthorizeAsync ();

				var twitterContext = new TwitterContext (auth);

#if !WINDOWS_PHONE
        IQueryable<LinqToTwitter.Status> queryResponse =
					(from tweet in twitterContext.Status
					where tweet.Type == StatusType.User &&
					  tweet.ScreenName == "shanselman" &&
					  tweet.Count == 100 &&
					  tweet.IncludeRetweets == true &&
					  tweet.ExcludeReplies == true
					select tweet);
					
				var queryTweets = queryResponse.ToList ();
				var tweets =
					(from tweet in queryTweets
					select new Tweet {
						StatusID = tweet.StatusID,
						ScreenName = tweet.User.ScreenNameResponse,
						Text = tweet.Text, 
						CurrentUserRetweet = tweet.CurrentUserRetweet, 
						CreatedAt = tweet.CreatedAt
					}).ToList ();
#else

				var tweets =
					await (from tweet in twitterContext.Status
					where tweet.Type == StatusType.User &&
					  tweet.ScreenName == "shanselman" &&
					  tweet.Count == 100 &&
					  tweet.IncludeRetweets == true &&
					  tweet.ExcludeReplies == true
                 select new Tweet
                 {
                   StatusID = tweet.StatusID,
                   ScreenName = tweet.User.ScreenNameResponse,
                   Text = tweet.Text,
                   CurrentUserRetweet = tweet.CurrentUserRetweet,
                   CreatedAt = tweet.CreatedAt
                 }).ToListAsync();

#endif

        foreach (var tweet in tweets) {
					Tweets.Add (tweet);
				}
			} catch (Exception ex) {
				var page = new ContentPage();
				page.DisplayAlert ("Error", "Unable to load twitter.", "OK", null);
			}

			IsBusy = false;
		}
Esempio n. 18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Initialize object for paging
        pds = new PagedDataSource();
        pds.AllowPaging = true;
        pds.PageSize = 5;

        // In v1.1, all API calls require authentication
        // Authentication
        auth = new ApplicationOnlyAuthorizer
        {
            Credentials = new InMemoryCredentials
            {
                ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],  // Custom Custom Consumer Key
                ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"] // Custom Consumer Secret
            }
        };

        // Authorize
        auth.Authorize();

        // Instantiate a LinqToTwitter object
        twitterCtx = new TwitterContext(auth);

        // On first load
        if(! Page.IsPostBack){

            // Initialize viewstate variables
            this.ViewState["CurrentPageIndex"] = 0;
            this.ViewState["PageCount"] = 0;

            // Invoke twitter databind
            TwitterDataBind();

            // Set timer interval
            Timer1.Interval = REFRESHRATE * 1000;

        } // end if IsPostBack
    }
Esempio n. 19
0
        public async Task ExecuteLoadTweetsCommand()
        {
            if (IsBusy)
                return;

            IsBusy = true;
            LoadTweetsCommand.ChangeCanExecute();
            var error = false;
            try
            {

                Tweets.Clear();
                var auth = new ApplicationOnlyAuthorizer()
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey = "ZTmEODUCChOhLXO4lnUCEbH2I",
                        ConsumerSecret = "Y8z2Wouc5ckFb1a0wjUDT9KAI6DUat5tFNdmIkPLl8T4Nyaa2J",
                    },
                };
                await auth.AuthorizeAsync();

                var twitterContext = new TwitterContext(auth);

                var queryResponse = await
                  (from tweet in twitterContext.Status
                   where tweet.Type == StatusType.User &&
                     tweet.ScreenName == "shanselman" &&
                     tweet.Count == 100 &&
                     tweet.IncludeRetweets == true &&
                     tweet.ExcludeReplies == true
                   select tweet).ToListAsync();

                var tweets =
                  (from tweet in queryResponse
                   select new Tweet
                   {
                       StatusID = tweet.StatusID,
                       ScreenName = tweet.User.ScreenNameResponse,
                       Text = tweet.Text,
                       CurrentUserRetweet = tweet.CurrentUserRetweet,
                       CreatedAt = tweet.CreatedAt,
                       Image = tweet.RetweetedStatus != null && tweet.RetweetedStatus.User != null ?
                                      tweet.RetweetedStatus.User.ProfileImageUrl.Replace("http://", "https://") : (tweet.User.ScreenNameResponse == "shanselman" ? "scott159.png" : tweet.User.ProfileImageUrl.Replace("http://", "https://"))
                   }).ToList();
                foreach (var tweet in tweets)
                {
                    Tweets.Add(tweet);
                }

                if (Device.OS == TargetPlatform.iOS)
                {
                    // only does anything on iOS, for the Watch
                    DependencyService.Get<ITweetStore>().Save(tweets);
                }



            }
            catch
            {
                error = true;
            }

            if (error)
            {
                var page = new ContentPage();
                await page.DisplayAlert("Error", "Unable to load tweets.", "OK");
            }

            IsBusy = false;
            LoadTweetsCommand.ChangeCanExecute();
        }
Esempio n. 20
0
        static IAuthorizer DoApplicationOnlyAuth()
        {
            var auth = new ApplicationOnlyAuthorizer()
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = Environment.GetEnvironmentVariable(OAuthKeys.TwitterConsumerKey),
                    ConsumerSecret = Environment.GetEnvironmentVariable(OAuthKeys.TwitterConsumerSecret)
                },
            };

            return auth;
        }