private void BindDemo() { ITwitterAuthorizer autentikasi = GetInformasiKredensial(); var TwitterDataContext = new TwitterContext(autentikasi); string _screen_name = "kicaubobotoh"; //screen name yang melakukan retweet var liststatus = (from tweet in TwitterDataContext.Status where tweet.Type == StatusType.RetweetedByUser && tweet.ScreenName == _screen_name select tweet.RetweetedStatus) .ToList(); System.Data.DataTable dt = new System.Data.DataTable(); dt.Columns.Add("name"); dt.Columns.Add("text"); foreach (Status item in liststatus) { dt.Rows.Add(item.User.Name, item.Text); } gvMain.DataSource = dt; gvMain.DataBind(); }
public List<LinqToTwitter.Status> GetTwitterData() { BTProgressHUD.Show(); //has the user already authenticated from a previous session? see AccountStore.Create().Save() later IEnumerable<Xamarin.Auth.Account> accounts = AccountStore.Create().FindAccountsForService("Twitter"); //check the account store for a valid account marked as "Twitter" and then hold on to it for future requests var cred = new LinqToTwitter.InMemoryCredentialStore(); cred.ConsumerKey = loggedInAccount.Properties["oauth_consumer_key"]; cred.ConsumerSecret = loggedInAccount.Properties["oauth_consumer_secret"]; cred.OAuthToken = loggedInAccount.Properties["oauth_token"]; cred.OAuthTokenSecret = loggedInAccount.Properties["oauth_token_secret"]; var auth = new LinqToTwitter.PinAuthorizer() { CredentialStore = cred, }; var TwitterCtx = new LinqToTwitter.TwitterContext(auth); Console.WriteLine(TwitterCtx.User); List<LinqToTwitter.Status> tl = (from tweet in TwitterCtx.Status where tweet.Type == LinqToTwitter.StatusType.Home select tweet).ToList(); BTProgressHUD.Dismiss(); return tl; //Console.WriteLine("Tweets Returned: " + tl.Count.ToString()); }
protected override IQueryable<Streaming> GetStreamQuery(TwitterContext context) { var selection = from stream in context.Streaming where stream.Type == StreamingType.Sample select stream; return selection; }
/// <summary> /// Run all error handling related demos /// </summary> /// <param name="twitterCtx">TwitterContext</param> public static void Run(TwitterContext twitterCtx) { //HandleQueryExceptionDemo(twitterCtx); //HandleSideEffectExceptionDemo(twitterCtx); //HandleSideEffectWithFilePostExceptionDemo(twitterCtx); //HandleTimeoutErrors(twitterCtx); }
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(); }
internal static async Task RunAsync(TwitterContext twitterCtx) { char key; do { ShowMenu(); key = Console.ReadKey(true).KeyChar; switch (key) { case '0': Console.WriteLine("\n\tShowing favorites...\n"); await ShowFavoritesAsync(twitterCtx); break; case '1': Console.WriteLine("\n\tFavoriting...\n"); await CreateFavoriteAsync(twitterCtx); break; case '2': Console.WriteLine("\n\tUnfavoriting...\n"); await DestroyFavoriteAsync(twitterCtx); break; case 'q': case 'Q': Console.WriteLine("\nReturning...\n"); break; default: Console.WriteLine(key + " is unknown"); break; } } while (char.ToUpper(key) != 'Q'); }
static async Task ShowFavoritesAsync(TwitterContext twitterCtx) { const int PerQueryFavCount = 200; // set from a value that you previously saved ulong sinceID = 1; var favsResponse = await (from fav in twitterCtx.Favorites where fav.Type == FavoritesType.Favorites && fav.Count == PerQueryFavCount select fav) .ToListAsync(); if (favsResponse == null) { Console.WriteLine("No favorites returned from Twitter."); return; } var favList = new List<Favorites>(favsResponse); // first tweet processed on current query ulong maxID = favList.Min(fav => fav.StatusID) - 1; do { favsResponse = await (from fav in twitterCtx.Favorites where fav.Type == FavoritesType.Favorites && fav.Count == PerQueryFavCount && fav.SinceID == sinceID && fav.MaxID == maxID select fav) .ToListAsync(); if (favsResponse == null || favsResponse.Count == 0) break; // reset first tweet to avoid re-querying the // same list you just received maxID = favsResponse.Min(fav => fav.StatusID) - 1; favList.AddRange(favsResponse); } while (favsResponse.Count > 0); favList.ForEach(fav => { if (fav != null && fav.User != null) Console.WriteLine( "Name: {0}, Tweet: {1}", fav.User.ScreenNameResponse, fav.Text); }); // save this in your db for this user so you can set // sinceID accurately the next time you do a query // and avoid querying the same tweets again. ulong newSinceID = favList.Max(fav => fav.SinceID); }
/// <summary> /// shows how to perform a twitter search, extract status, and search the status /// </summary> /// <param name="twitterCtx">TwitterContext</param> private static void SearchAndUseStatusTwitterDemo(TwitterContext twitterCtx) { var queryResult = (from search in twitterCtx.Search where search.Type == SearchType.Search && search.Query == "LINQ to Twitter" select search) .SingleOrDefault(); foreach (var entry in queryResult.Entries) { var statusID = entry.ID.Substring(entry.ID.LastIndexOf(":") + 1); var status = (from tweet in twitterCtx.Status where tweet.Type == StatusType.Show && tweet.ID == statusID select tweet) .SingleOrDefault(); Console.WriteLine( "ID: {0}, User: {1}\nTweet: {2}\n", status.ID, status.User.Name, status.Text); } }
protected void Page_Load(object sender, EventArgs e) { auth = new WebOAuthAuthorization(InMemoryTokenManager.Instance, InMemoryTokenManager.AccessToken); if (!Page.IsPostBack) { // try to complete a pending authorization in case there is one. string accessToken = auth.CompleteAuthorize(); if (accessToken != null) { // Store the access token in session state so we can get at it across page refreshes. // In a real app, you'd want to associate this access token with the user that is // logged into your app at this point. InMemoryTokenManager.AccessToken = accessToken; // Clear away the OAuth message so that users can refresh the page without problems. Response.Redirect(Page.Request.Path); } } if (string.IsNullOrEmpty(InMemoryTokenManager.Instance.ConsumerKey) || string.IsNullOrEmpty(InMemoryTokenManager.Instance.ConsumerSecret)) { // The user needs to set up the web.config file to include Twitter consumer key and secret. PrivateDataMultiView.SetActiveView(SetupTwitterConsumer); } else if (auth.CachedCredentialsAvailable) { auth.SignOn(); // acquire the screen name, and ensure the access token is still valid. screenNameLabel.Text = auth.ScreenName; PrivateDataMultiView.SetActiveView(ViewPrivateUpdates); updateBox.Focus(); } else { PrivateDataMultiView.SetActiveView(AuthorizeTwitter); } twitterCtx = auth.CachedCredentialsAvailable ? new TwitterContext(auth) : new TwitterContext(); var tweets = from tweet in twitterCtx.Status where tweet.Type == (auth.CachedCredentialsAvailable ? StatusType.Friends : StatusType.Public) select tweet; TwitterListView.DataSource = tweets; TwitterListView.DataBind(); // demonstrate serialization var serializableUser = (from user in twitterCtx.User where user.Type == UserType.Show && user.ScreenName == "JoeMayo" select user) .FirstOrDefault(); // if you have ASP.NET state server turned on // this will still work because User is serializable Session["SerializableUser"] = serializableUser; }
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(); }
async Task<TwitterContext> InitializeTwitterContext() { await Task.Delay(1); var authMock = new Mock<IAuthorizer>(); var execMock = new Mock<ITwitterExecute>(); var tcsAuth = new TaskCompletionSource<IAuthorizer>(); tcsAuth.SetResult(authMock.Object); var tcsResponse = new TaskCompletionSource<string>(); tcsResponse.SetResult(SingleStatusResponse); var tcsMedia = new TaskCompletionSource<string>(); tcsMedia.SetResult(MediaResponse); execMock.SetupGet(exec => exec.Authorizer).Returns(authMock.Object); execMock.Setup(exec => exec.PostToTwitterAsync<Status>( It.IsAny<string>(), It.IsAny<IDictionary<string, string>>(), It.IsAny<CancellationToken>())) .Returns(tcsResponse.Task); execMock.Setup(exec => exec.PostMediaAsync( It.IsAny<string>(), It.IsAny<IDictionary<string, string>>(), It.IsAny<byte[]>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(tcsMedia.Task); var ctx = new TwitterContext(execMock.Object); return ctx; }
/// <summary> /// Run all direct message related demos /// </summary> /// <param name="twitterCtx">TwitterContext</param> public static void Run(TwitterContext twitterCtx) { DirectMessageSentByQueryDemo(twitterCtx); //DirectMessageSentToQueryDemo(twitterCtx); //NewDirectMessageDemo(twitterCtx); //DestroyDirectMessageDemo(twitterCtx); }
internal static async Task RunAsync(TwitterContext twitterCtx) { char key; do { ShowMenu(); key = Console.ReadKey(true).KeyChar; switch (key) { case '0': Console.WriteLine("\n\tSearching...\n"); await DoSearchAsync(twitterCtx); break; case 'q': case 'Q': Console.WriteLine("\nReturning...\n"); break; default: Console.WriteLine(key + " is unknown"); break; } } while (char.ToUpper(key) != 'Q'); }
static void AsyncSearchSample(TwitterContext twitterCtx) { (from search in twitterCtx.Search where search.Type == SearchType.Search && search.Query == "LINQ To Twitter" select search) .MaterializedAsyncCallback(resp => { if (resp.Status != TwitterErrorStatus.Success) { Exception ex = resp.Exception; // handle error throw ex; } Search srch = resp.State.First(); 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)); Console.WriteLine("\n More Search demos can be downloaded from LINQ to Twitter's on-line samples at http://linqtotwitter.codeplex.com/wikipage?title=LINQ%20to%20Twitter%20Samples&referringTitle=Home"); }); }
protected void Application_Start( object sender, EventArgs e ) { ThreadPool.QueueUserWorkItem( _ => { var connectionContext = GlobalHost.ConnectionManager.GetConnectionContext<TweetsConnection>( ); var auth = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = "", ConsumerSecret = "", AccessToken = "", AccessTokenSecret = "" } }; while ( true ) { using ( TwitterContext context = new TwitterContext( auth ) ) { var tweets = ( from search in context.Search where search.Type == SearchType.Search && search.Query == "#fnord" select search ).SingleOrDefault( ); if ( tweets != null && tweets.Statuses != null ) connectionContext.Connection.Broadcast( tweets.Statuses.Select( t => t.Text ).ToList( ) ); } Thread.Sleep( 5000 ); } } ); }
/// <summary> /// Gets all the tweets since the last tweet that entered the system /// This method is used to put tweets in the system that were send when the service wasn't running /// </summary> /// <param name="postId">Id of the last tweet from the stream</param> public void GetTweetSinceId(string postId) { serviceLog.WriteEntry("GetTweetSinceId SinceID: " + postId); ulong sinceId; if (ulong.TryParse(postId, out sinceId)) { using (TwitterContext twitterCtx = new TwitterContext(PinAutharizedUser)) { var userStatusResponse = (from tweet in twitterCtx.Status where tweet.Type == StatusType.Mentions && tweet.ScreenName == myScreenName && tweet.SinceID == sinceId select tweet) .ToList(); foreach (var tweet in userStatusResponse) { if (!string.IsNullOrWhiteSpace(tweet.Text)) { CreateQuestion(tweet.User.Identifier.ScreenName, tweet.Text, tweet.ID); } } } } else { serviceLog.WriteEntry("Not a valid postId" + sinceId); } }
static async Task DoFilterStreamAsync(TwitterContext twitterCtx) { Console.WriteLine("\nStreamed Content: \n"); int count = 0; var cancelTokenSrc = new CancellationTokenSource(); try { await (from strm in twitterCtx.Streaming .WithCancellation(cancelTokenSrc.Token) where strm.Type == StreamingType.Filter && strm.Track == "twitter" select strm) .StartAsync(async strm => { HandleStreamResponse(strm); if (count++ >= 5) cancelTokenSrc.Cancel(); }); } catch (OperationCanceledException) { Console.WriteLine("Stream cancelled."); } }
/// <summary> /// Pages through a list of followers using cursors /// </summary> /// <param name="twitterCtx">TwitterContext</param> private static void ShowFollowersWithCursorDemo(TwitterContext twitterCtx) { int pageNumber = 1; // "-1" means to begin on the first page string nextCursor = "-1"; // cursor will be "0" when no more pages // notice that I'm checking for null/empty - don't trust data while (!string.IsNullOrEmpty(nextCursor) && nextCursor != "0") { var followers = (from follower in twitterCtx.SocialGraph where follower.Type == SocialGraphType.Followers && follower.ID == "15411837" && follower.Cursor == nextCursor // <-- set this to use cursors select follower) .FirstOrDefault(); Console.WriteLine( "Page #" + pageNumber + " has " + followers.IDs.Count + " IDs."); // use the cursor for the next page // this is not a page number, but a marker (cursor) // to tell Twitter which page to return nextCursor = followers.CursorMovement.Next; pageNumber++; } }
/// <summary> /// Run all social graph related demos /// </summary> /// <param name="twitterCtx">TwitterContext</param> public static void Run(TwitterContext twitterCtx) { ShowFriendsDemo(twitterCtx); //ShowFriendsWithCursorDemo(twitterCtx); //ShowFollowersDemo(twitterCtx); //ShowFollowersWithCursorDemo(twitterCtx); }
/// <summary> /// Shows how to update the background image in an account and tiles the image /// </summary> /// <param name="twitterCtx">TwitterContext</param> private static void UpdateAccountBackgroundImageAndTileDemo(TwitterContext twitterCtx) { byte[] fileBytes = Utilities.GetFileBytes(@"C:\Users\jmayo\Documents\linq2twitter\linq2twitter\linq2twitter_v3_300x90.png"); var user = twitterCtx.UpdateAccountBackgroundImage(fileBytes, "linq2twitter_v3_300x90.png", "png", true); Console.WriteLine("User Image: " + user.ProfileBackgroundImageUrl); }
/// <summary> /// Shows how to update the background image in an account /// </summary> /// <param name="twitterCtx">TwitterContext</param> private static void UpdateAccountBackgroundImageBytes(TwitterContext twitterCtx) { byte[] fileBytes = Utilities.GetFileBytes(@"C:\Users\jmayo\Documents\linq2twitter\linq2twitter\200xColor_2.png"); var user = twitterCtx.UpdateAccountBackgroundImage(fileBytes, "200xColor_2.png", "png", false); Console.WriteLine("User Image: " + user.ProfileBackgroundImageUrl); }
internal static async Task RunAsync(TwitterContext twitterCtx) { char key; do { ShowMenu(); key = Console.ReadKey(true).KeyChar; switch (key) { case '0': Console.WriteLine("\n\tGetting trends...\n"); await GetTrendsForPlaceAsync(twitterCtx); break; case '1': Console.WriteLine("\n\tGetting available trend locations...\n"); await GetAvailableTrendLocationsAsync(twitterCtx); break; case '2': Console.WriteLine("\n\tGetting trends...\n"); await GetClosestTrendsAsync(twitterCtx); break; case 'q': case 'Q': Console.WriteLine("\nReturning...\n"); break; default: Console.WriteLine(key + " is unknown"); break; } } while (char.ToUpper(key) != 'Q'); }
public async Task<Account> GetTwitterAccount(string userId, string screenName) { var authTwitter = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = twitterAuthenticationSettings.Value.ConsumerKey, ConsumerSecret = twitterAuthenticationSettings.Value.ConsumerSecret, OAuthToken = twitterAuthenticationSettings.Value.OAuthToken, OAuthTokenSecret = twitterAuthenticationSettings.Value.OAuthSecret, UserID = ulong.Parse(userId), ScreenName = screenName } }; await authTwitter.AuthorizeAsync(); var twitterCtx = new TwitterContext(authTwitter); //VERY important you explicitly keep the "== true" part of comparison. ReSharper will prompt you to remove this, and if it does, the query will not work var account = await (from acct in twitterCtx.Account where (acct.Type == AccountType.VerifyCredentials) && (acct.IncludeEmail == true) select acct).SingleOrDefaultAsync(); return account; }
/// <summary> /// logon /// </summary> /// <returns></returns> public bool Logon() { try { _authorizer = PerformAuthorization(); _twitterContext = new Twitter.TwitterContext(_authorizer); try { var accounts = from acct in _twitterContext.Account where acct.Type == AccountType.VerifyCredentials select acct; Account account = accounts.SingleOrDefault(); User user = account.User; Status tweet = user.Status ?? new Status(); } catch (Exception exception) { throw new Exception("Authentication failed.", exception); } return(true); } catch (Exception exception) { RaiseOperationError(exception); return(false); } }
/// <summary> /// shows how to handle a TwitterQueryException with a query /// </summary> /// <param name="twitterCtx">TwitterContext</param> private static void HandleQueryExceptionDemo(TwitterContext twitterCtx) { // force the error by supplying bad credentials twitterCtx.AuthorizedClient = new UsernamePasswordAuthorization { UserName = "******", Password = "******", }; try { var statuses = from status in twitterCtx.Status where status.Type == StatusType.Mentions select status; var statusList = statuses.ToList(); } catch (TwitterQueryException tqe) { // log it to the console Console.WriteLine( "\nHTTP Error Code: {0}\nError: {1}\nRequest: {2}\n", tqe.HttpError, tqe.Response.Error, tqe.Response.Request); } }
public static void UpdateStatus(string tweet, IOAuthCredentials credentials) { var singleUserAuthorizer = new SingleUserAuthorizer { Credentials = credentials }; var twitterCtx = new TwitterContext(singleUserAuthorizer); twitterCtx.UpdateStatus(tweet); }
/// <summary> /// Shows how to update the background image in an account and tiles the image /// </summary> /// <param name="twitterCtx">TwitterContext</param> static void UpdateAccountBackgroundImageAndTileDemo(TwitterContext twitterCtx) { byte[] fileBytes = Utilities.GetFileBytes(@"..\..\images\200xColor_2.png"); var user = twitterCtx.UpdateAccountBackgroundImage(fileBytes, "200xColor_2.png", "png", true, true, true, true); Console.WriteLine("User Image: " + user.ProfileBackgroundImageUrl); }
/// <summary> /// 実行 /// </summary> public void Execute() { // // get user credentials and instantiate TwitterContext // ITwitterAuthorization auth; if (String.IsNullOrEmpty(Properties.Settings.Default.UserID)) { m_logger.Info("Skipping OAuth authorization demo because twitterConsumerKey and/or twitterConsumerSecret are not set in your .config file."); m_logger.Info("Using username/password authorization instead."); // For username/password authorization demo... auth = new UsernamePasswordAuthorization(Utilities.GetConsoleHWnd()); } else { //Console.WriteLine("Discovered Twitter OAuth consumer key in .config file. Using OAuth authorization."); m_logger.InfoFormat("Using '{0}'/**** authorization instead.", Properties.Settings.Default.UserID); auth = new UsernamePasswordAuthorization(); var desktopAuth = (UsernamePasswordAuthorization)auth; desktopAuth.AllowUIPrompt = false; desktopAuth.UserName = Properties.Settings.Default.UserID; desktopAuth.Password = Properties.Settings.Default.Password; } // TwitterContext is similar to DataContext (LINQ to SQL) or ObjectContext (LINQ to Entities) // For Twitter using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/", "http://search.twitter.com/")) { // If we're using OAuth, we need to configure it with the ConsumerKey etc. from the user. if (twitterCtx.AuthorizedClient is OAuthAuthorization) { InitializeOAuthConsumerStrings(twitterCtx); } // Whatever authorization module we selected... sign on now. // See the bottom of the method for sign-off procedures. try { auth.SignOn(); } catch (OperationCanceledException) { Console.WriteLine("Login canceled. Demo exiting."); return; } // Search & Retweet SearchAndRetweet(twitterCtx); // // Sign-off, including optional clearing of cached credentials. // auth.SignOff(); } }
private void DoPinAuth() { m_pinAuth = new PinAuthorizer { Credentials = new InMemoryCredentials { ConsumerKey = "", ConsumerSecret = "" }, UseCompression = true, GoToTwitterAuthorization = pageLink => Dispatcher.BeginInvoke(() => WebBrowser.Navigate(new Uri(pageLink))) }; m_pinAuth.BeginAuthorize(resp => Dispatcher.BeginInvoke(() => { switch (resp.Status) { case TwitterErrorStatus.Success: break; case TwitterErrorStatus.TwitterApiError: case TwitterErrorStatus.RequestProcessingException: MessageBox.Show( resp.Error.ToString(), resp.Message, MessageBoxButton.OK); break; } })); m_twitterCtx = new TwitterContext(m_pinAuth, "https://api.twitter.com/1/", "https://search.twitter.com/"); }
protected string GetImageInfo(string twitterName, string defaultURL) { if (twitterName == null) return defaultURL; var twitterUrl = defaultURL; var auth = new MvcAuthorizer { CredentialStore = new SessionStateCredentialStore { ConsumerKey = "fUpi8KuU3hMWsCHueZIww", ConsumerSecret = "4gCFXwi5zW5CYIoGSNgydL9dmqVM9T9BUS9ElrMI" } }; var twitterCtx = new TwitterContext(auth) {ReadWriteTimeout = 300}; try { var userResponse = (from user in twitterCtx.User where user.Type == UserType.Show && user.ScreenName == twitterName.Replace("@", "") select user).ToArray(); var firstOrDefault = userResponse.FirstOrDefault(); if (firstOrDefault != null) twitterUrl = firstOrDefault.ProfileImageUrl; } catch(Exception) { return defaultURL; } return twitterUrl; }
protected string GetImageInfo(string twitterName, string defaultURL) { if (twitterName == null) return defaultURL; string twitterURL = defaultURL; var auth = new MvcAuthorizer(); SessionStateCredentials s = new SessionStateCredentials(); s.ConsumerKey = "fUpi8KuU3hMWsCHueZIww"; s.ConsumerSecret = "4gCFXwi5zW5CYIoGSNgydL9dmqVM9T9BUS9ElrMI"; auth.Credentials = s; var twitterCtx = new TwitterContext(auth); try { var userResponse = (from user in twitterCtx.User where user.Type == UserType.Lookup && user.ScreenName == twitterName.Replace("@", "") select user).ToList(); if (userResponse == null) { return defaultURL; } twitterURL = userResponse.FirstOrDefault().ProfileImageUrl; } catch { return defaultURL; } return twitterURL; }
async protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); if (MainActivity.Activities.ContainsKey("SearchTwitter")) { MainActivity.Activities["SearchTwitter"].Finish(); MainActivity.Activities.Remove("SearchTwitter"); MainActivity.Activities.Add("SearchTwitter", this); } else { MainActivity.Activities.Add("SearchTwitter", this); } //has the user already authenticated from a previous session? see AccountStore.Create().Save() later IEnumerable <Xamarin.Auth.Account> accounts = Xamarin.Auth.AccountStore.Create(this).FindAccountsForService("UndertheShopTwitApp"); SearchTerm = Intent.GetStringExtra("keyword"); shopID = Intent.GetStringExtra("SHOP_ID_NUMBER"); local = Intent.GetStringExtra("Local"); //check the account store for a valid account marked as "Twitter" and then hold on to it for future requests foreach (Xamarin.Auth.Account account in accounts) { loggedInAccount = account; break; } if (loggedInAccount == null) { Toast.MakeText(this, GetString(Resource.String.authfail), ToastLength.Short).Show(); var next = new Intent(this.ApplicationContext, typeof(ShopInfoActivity)); next.PutExtra("SHOP_ID_NUMBER", shopID); next.PutExtra("Local", local); StartActivity(next); Finish(); } else { var cred = new LinqToTwitter.InMemoryCredentialStore(); cred.ConsumerKey = loggedInAccount.Properties["oauth_consumer_key"]; cred.ConsumerSecret = loggedInAccount.Properties["oauth_consumer_secret"]; cred.OAuthToken = loggedInAccount.Properties["oauth_token"]; cred.OAuthTokenSecret = loggedInAccount.Properties["oauth_token_secret"]; var auth0 = new LinqToTwitter.PinAuthorizer() { CredentialStore = cred, }; var TwitterCtx = new LinqToTwitter.TwitterContext(auth0); Console.WriteLine(TwitterCtx.User); _searches = await(from tweet in TwitterCtx.Search where (tweet.Type == SearchType.Search) && (tweet.Query == SearchTerm) select tweet).ToListAsync(); this.ListAdapter = new SearchAdapter(this, _searches[0].Statuses); } }
private async Task <SocialModel> GetTwitterData() { SocialModel model = new SocialModel(); var account = AccountStore.Create().FindAccountsForService(AccountServiceTwitter).FirstOrDefault(); var auth = new LinqToTwitter.SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = "FWinTbxeDRfqL6pd6TyvBWqvY", ConsumerSecret = "vqHOpCafR8eNNy140xfNRy80W2zyN0A4whM9lcVWj9oSPalDAz", AccessToken = account.Properties["oauth_token"], AccessTokenSecret = account.Properties["oauth_token_secret"], } }; var twitterCtx = new LinqToTwitter.TwitterContext(auth); try { var verifyResponse = await (from acct in twitterCtx.Account where acct.Type == LinqToTwitter.AccountType.VerifyCredentials && (acct.IncludeEmail == true) select acct) .SingleOrDefaultAsync(); if (verifyResponse != null && verifyResponse.User != null) { LinqToTwitter.User user = verifyResponse.User; model.Email = user.Email; model.Id = user.UserIDResponse; model.AvatarUrl = user.ProfileImageUrl.Replace("normal", "bigger"); model.AuthType = AuthType.Twitter; if (!String.IsNullOrEmpty(user.Name)) { model.Name = user.Name; } else if (!String.IsNullOrEmpty(user.ScreenNameResponse)) { model.Name = user.ScreenNameResponse; } return(model); } } catch (LinqToTwitter.TwitterQueryException) { } return(model); }
private void getUserDetails() { if (auth.CompleteAuthorization(Request.Url) == true) { var twitterCtx = new LinqToTwitter.TwitterContext(auth); var user = (from tweet in twitterCtx.User where tweet.Type == UserType.Show && tweet.ScreenName == auth.Credentials.ScreenName select tweet).SingleOrDefault(); username.InnerText = auth.Credentials.ScreenName; profilepic.Src = user.ProfileImageUrl; } }
public static List <Tweet> SearchTwitter(string SearchString, DateTime?date = null) { if (date == null) { date = DateTime.Today; } var singleUserAuth = new SingleUserAuthorizer { Credentials = new SingleUserInMemoryCredentials { ConsumerKey = _consumerKey, ConsumerSecret = _consumerSecret, TwitterAccessToken = _accessToken, TwitterAccessTokenSecret = _accessTokenSecret } }; var twitterCtx = new LinqToTwitter.TwitterContext(singleUserAuth); var results = from search in twitterCtx.Search where search.Query == SearchString && search.Type == SearchType.Search && search.ResultType == ResultType.Recent && search.SearchLanguage == "en" && search.Until == date.GetValueOrDefault().AddDays(1) && search.Count == 100 select search; Search srch = results.Single(); var result = new List <Tweet>(); //Console.WriteLine(srch.Statuses.Count); srch.Statuses .ForEach(entry => result.Add(new Tweet { Text = entry.Text, FollowersCount = entry.User.FollowersCount, CreatedAt = entry.CreatedAt, FavoriteCount = entry.Favorited ? (int)entry.FavoriteCount : 0, RetweetCount = entry.Retweeted ? (int)entry.RetweetCount : 0, Positive = GetPositiveSentiment(entry.Text) }) ); return(result); }
/// <summary> /// logon with specific credentials /// </summary> /// <returns></returns> public bool Logon(string accessToken, string accessSecret, string authenticationKey, string autenthicationSecret) { try { _authorizer = PerformAuthorization(accessToken, accessSecret, authenticationKey, autenthicationSecret); _twitterContext = new Twitter.TwitterContext(_authorizer); var accounts = from acct in _twitterContext.Account where acct.Type == AccountType.VerifyCredentials select acct; Account account = accounts.SingleOrDefault(); User user = account.User; Status tweet = user.Status ?? new Status(); return(true); } catch { return(false); } }
private static void ShowTweets(string i_sUser, int i_iCount) { var authTwitter = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = "4Kl5yOtTAl1tg6ItCtDFfhaxy", ConsumerSecret = "pUQgM6XnP2GjDIgNIH5LavVeCJEZ6CltnuSNQxvZE62z8J1j4V", OAuthToken = "120139909-ZdyoSXu8wsw1plYhVgQWB58ieCdv9p5tGoCxSw0t", OAuthTokenSecret = "wd0jneYWx4uOnLPfxJKEHZkz9fbqyGXYKTyAdUZKxLF20" } }; var Twitter = new LinqToTwitter.TwitterContext(authTwitter); var untildate = new DateTime(2017, 7, 13); var srch = (from search in Twitter.Search where search.Type == SearchType.Search && search.Query == "Twitter" && search.GeoCode == "36.9710,-55.447967,500mi" && search.Until == untildate select search) .SingleOrDefault(); Console.WriteLine("\nQuery: {0}\n", srch.SearchMetaData.Query); var count = 0; srch.Statuses.ForEach(entry => Console.WriteLine( "ID: {0, -200}, Source: {1}\nContent: {2}\n", entry.StatusID, entry.Source, entry.Text)); srch.Statuses.ForEach(entry => count++); Console.WriteLine("count: " + count); Console.ReadKey(); }
/// <summary> /// Modifies an existing list /// </summary> /// <param name="listID">ID or slug of list</param> /// <param name="slug">name of list</param> /// <param name="ownerID">ID of user who owns the list.</param> /// <param name="ownerScreenName">Screen name of user who owns the list.</param> /// <param name="mode">public or private</param> /// <param name="description">list description</param> /// <returns>List info for modified list</returns> public static List UpdateList(this TwitterContext ctx, string listID, string slug, string name, string ownerID, string ownerScreenName, string mode, string description) { return(UpdateList(ctx, listID, slug, name, ownerID, ownerScreenName, mode, description, null)); }
public void getSource() { List <ListItems> columnList = new List <ListItems>(); if (auth.CompleteAuthorization(Request.Url) == true) { dict = new DictionaryDB(); var twitterCtx = new LinqToTwitter.TwitterContext(auth); var tweets = from t in twitterCtx.Status where t.Type == StatusType.User && t.ScreenName == DropDownList1.SelectedValue && t.Count == Int32.Parse(tweetnum.SelectedValue) select t; foreach (var tweetStatus in tweets) { var listItem = new ListItems(); List <UrlEntity> Urle = tweetStatus.Entities.UrlEntities; foreach (var url in Urle) { if (!string.IsNullOrWhiteSpace(url.ExpandedUrl)) { listItem.url = url.ExpandedUrl; } } listItem.tweet = tweetStatus.Text; listItem.date = tweetStatus.CreatedAt; if (!string.IsNullOrEmpty(dict.getTweetCategory(tweetStatus.Text))) { listItem.category = dict.getTweetCategory(tweetStatus.Text); } else { listItem.category = "Others"; } columnList.Add(listItem); } ListView1.DataSource = columnList.AsQueryable().ToArray(); ListView1.DataBind(); if (tweets != null) { var dictionaryword = dict.getDictionaryWords(); foreach (var tweetStatus in tweets) { foreach (string word in dictionaryword) { if (tweetStatus.Text.Contains(word) == true) { string category = dict.getWordCategory(word); break; } } } #region Pie Charts (Home, Network, Desktop, Mobile, Others) foreach (var tweetStatus in tweets) { if (!string.IsNullOrEmpty(dict.getTweetCategory(tweetStatus.Text))) { if (dict.getTweetCategory(tweetStatus.Text) == "Network") { NetworkList.Add(tweetStatus); networkCategory++; #region Network Pie Chart if (dict.getSecTweetCategory(tweetStatus.Text) == "Emails") { emailCategory++; } else if (dict.getSecTweetCategory(tweetStatus.Text) == "Online Game") { OnlineCategory++; } else if (dict.getSecTweetCategory(tweetStatus.Text) == "Social Media") { SocialCategory++; } else if (dict.getSecTweetCategory(tweetStatus.Text) == "Server") { ServerCategory++; } else if (dict.getSecTweetCategory(tweetStatus.Text) == "Website") { WebsiteCategory++; } else { netotherCategory++; } #endregion } else if (dict.getTweetCategory(tweetStatus.Text) == "Desktop") { desktopCategory++; DesktopList.Add(tweetStatus); #region Desktop Pie Chart if (dict.getSecTweetCategory(tweetStatus.Text) == "Com Hardware") { DHCategory++; } else if (dict.getSecTweetCategory(tweetStatus.Text) == "Com Software") { DSCategory++; } else if (dict.getSecTweetCategory(tweetStatus.Text) == "Operating System") { OperatingCategory++; } else { DeskOtherCategory++; } #endregion } else if (dict.getTweetCategory(tweetStatus.Text) == "Mobile") { mobileCategory++; MobileList.Add(tweetStatus); #region Mobile Pie Chart if (dict.getSecTweetCategory(tweetStatus.Text) == "Telecommunication") { telecomCategory++; } else if (dict.getSecTweetCategory(tweetStatus.Text) == "Hardware") { MHCategory++; } else if (dict.getSecTweetCategory(tweetStatus.Text) == "Software") { MSCategory++; } else if (dict.getSecTweetCategory(tweetStatus.Text) == "Platform") { PlatformCategory++; } else { MobOtherCategory++; } #endregion } } else { otherCategory++; OthersList.Add(tweetStatus); } } #endregion #region Home Categories (Segment) if (networkCategory != 0) { DataPoint network = new DataPoint(); network.SetValueXY("Network", networkCategory); Chart1.Series[0].Points.Add(network); Chart1.Series["Series1"]["PieLabelStyle"] = "outside"; columnList.Clear(); foreach (var tweetStatus in NetworkList) { var listItem = new ListItems(); List <UrlEntity> Urle = tweetStatus.Entities.UrlEntities; foreach (var url in Urle) { if (!string.IsNullOrWhiteSpace(url.ExpandedUrl)) { listItem.url = url.ExpandedUrl; } } listItem.tweet = tweetStatus.Text; listItem.date = tweetStatus.CreatedAt; if (!string.IsNullOrEmpty(dict.getSecTweetCategory(tweetStatus.Text))) { listItem.category = dict.getSecTweetCategory(tweetStatus.Text); } else { listItem.category = "Others"; } columnList.Add(listItem); } ListView2.DataSource = columnList.AsQueryable().ToArray(); ListView2.DataBind(); } if (desktopCategory != 0) { DataPoint desktop = new DataPoint(); desktop.SetValueXY("Desktop", desktopCategory); Chart1.Series[0].Points.Add(desktop); Chart1.Series["Series1"]["PieLabelStyle"] = "outside"; columnList.Clear(); foreach (var tweetStatus in DesktopList) { var listItem = new ListItems(); List <UrlEntity> Urle = tweetStatus.Entities.UrlEntities; foreach (var url in Urle) { if (!string.IsNullOrWhiteSpace(url.ExpandedUrl)) { listItem.url = url.ExpandedUrl; } } listItem.tweet = tweetStatus.Text; listItem.date = tweetStatus.CreatedAt; if (!string.IsNullOrEmpty(dict.getSecTweetCategory(tweetStatus.Text))) { listItem.category = dict.getSecTweetCategory(tweetStatus.Text); } else { listItem.category = "Others"; } columnList.Add(listItem); } ListView4.DataSource = columnList.AsQueryable().ToArray(); ListView4.DataBind(); } if (mobileCategory != 0) { DataPoint mobile = new DataPoint(); mobile.SetValueXY("Mobile", mobileCategory); Chart1.Series[0].Points.Add(mobile); Chart1.Series["Series1"]["PieLabelStyle"] = "outside"; columnList.Clear(); foreach (var tweetStatus in MobileList) { var listItem = new ListItems(); List <UrlEntity> Urle = tweetStatus.Entities.UrlEntities; foreach (var url in Urle) { if (!string.IsNullOrWhiteSpace(url.ExpandedUrl)) { listItem.url = url.ExpandedUrl; } } listItem.tweet = tweetStatus.Text; listItem.date = tweetStatus.CreatedAt; if (!string.IsNullOrEmpty(dict.getSecTweetCategory(tweetStatus.Text))) { listItem.category = dict.getSecTweetCategory(tweetStatus.Text); } else { listItem.category = "Others"; } columnList.Add(listItem); } ListView3.DataSource = columnList.AsQueryable().ToArray(); ListView3.DataBind(); } if (otherCategory != 0) { DataPoint others = new DataPoint(); others.SetValueXY("Others", otherCategory); Chart1.Series["Series1"]["PieLabelStyle"] = "outside"; Chart1.Series[0].Points.Add(others); columnList.Clear(); foreach (var tweetStatus in OthersList) { var listItem = new ListItems(); List <UrlEntity> Urle = tweetStatus.Entities.UrlEntities; foreach (var url in Urle) { if (!string.IsNullOrWhiteSpace(url.ExpandedUrl)) { listItem.url = url.ExpandedUrl; } } listItem.tweet = tweetStatus.Text; listItem.date = tweetStatus.CreatedAt; if (!string.IsNullOrEmpty(dict.getSecTweetCategory(tweetStatus.Text))) { listItem.category = dict.getSecTweetCategory(tweetStatus.Text); } else { listItem.category = "Others"; } columnList.Add(listItem); } ListView5.DataSource = columnList.AsQueryable().ToArray(); ListView5.DataBind(); } #endregion #region Network Categories (Segment) if (emailCategory != 0) { DataPoint email = new DataPoint(); email.SetValueXY("Email", emailCategory); Chart2.Series[0].Points.Add(email); Chart2.Series["Series1"]["PieLabelStyle"] = "outside"; } if (OnlineCategory != 0) { DataPoint onlinegame = new DataPoint(); onlinegame.SetValueXY("Online Game", OnlineCategory); Chart2.Series[0].Points.Add(onlinegame); Chart2.Series["Series1"]["PieLabelStyle"] = "outside"; } if (SocialCategory != 0) { DataPoint social = new DataPoint(); social.SetValueXY("Social Media", SocialCategory); Chart2.Series[0].Points.Add(social); Chart2.Series["Series1"]["PieLabelStyle"] = "outside"; } if (WebsiteCategory != 0) { DataPoint website = new DataPoint(); website.SetValueXY("Website", WebsiteCategory); Chart2.Series[0].Points.Add(website); Chart2.Series["Series1"]["PieLabelStyle"] = "outside"; } if (ServerCategory != 0) { DataPoint server = new DataPoint(); server.SetValueXY("Server", ServerCategory); Chart2.Series[0].Points.Add(server); Chart2.Series["Series1"]["PieLabelStyle"] = "outside"; } if (netotherCategory != 0) { DataPoint netother = new DataPoint(); netother.SetValueXY("Others", netotherCategory); Chart2.Series[0].Points.Add(netother); Chart2.Series["Series1"]["PieLabelStyle"] = "outside"; } if (emailCategory == 0 && OnlineCategory == 0 && SocialCategory == 0 && WebsiteCategory == 0 && ServerCategory == 0 && netotherCategory == 0) { Chart2.Visible = false; } #endregion #region Mobile Category (Segment) if (telecomCategory != 0) { DataPoint telecom = new DataPoint(); telecom.SetValueXY("Telecom", telecomCategory); Chart3.Series[0].Points.Add(telecom); Chart3.Series["Series1"]["PieLabelStyle"] = "outside"; } if (MHCategory != 0) { DataPoint mobhardware = new DataPoint(); mobhardware.SetValueXY("Hardware", MHCategory); Chart3.Series[0].Points.Add(mobhardware); Chart3.Series["Series1"]["PieLabelStyle"] = "outside"; } if (MSCategory != 0) { DataPoint mobsoftware = new DataPoint(); mobsoftware.SetValueXY("Software", MSCategory); Chart3.Series[0].Points.Add(mobsoftware); Chart3.Series["Series1"]["PieLabelStyle"] = "outside"; } if (PlatformCategory != 0) { DataPoint platform = new DataPoint(); platform.SetValueXY("Platform", PlatformCategory); Chart3.Series[0].Points.Add(platform); Chart3.Series["Series1"]["PieLabelStyle"] = "outside"; } if (MobOtherCategory != 0) { DataPoint mobothers = new DataPoint(); mobothers.SetValueXY("Others", MobOtherCategory); Chart3.Series[0].Points.Add(mobothers); Chart3.Series["Series1"]["PieLabelStyle"] = "outside"; } if (telecomCategory == 0 && MHCategory == 0 && MSCategory == 0 && PlatformCategory == 0 && MobOtherCategory == 0) { Chart3.Visible = false; } #endregion #region Desktop Categories (Segment) if (DHCategory != 0) { DataPoint DeskHardware = new DataPoint(); DeskHardware.SetValueXY("Hardware", DHCategory); Chart4.Series[0].Points.Add(DeskHardware); Chart4.Series["Series1"]["PieLabelStyle"] = "outside"; } if (DSCategory != 0) { DataPoint DeskSoftware = new DataPoint(); DeskSoftware.SetValueXY("Software", DSCategory); Chart4.Series[0].Points.Add(DeskSoftware); Chart4.Series["Series1"]["PieLabelStyle"] = "outside"; } if (OperatingCategory != 0) { DataPoint OS = new DataPoint(); OS.SetValueXY("Operating System", OperatingCategory); Chart4.Series[0].Points.Add(OS); Chart4.Series["Series1"]["PieLabelStyle"] = "outside"; } if (DeskOtherCategory != 0) { DataPoint DeskOther = new DataPoint(); DeskOther.SetValueXY("Others", DeskOtherCategory); Chart4.Series[0].Points.Add(DeskOther); Chart4.Series["Series1"]["PieLabelStyle"] = "outside"; } if (DHCategory == 0 && DSCategory == 0 && OperatingCategory == 0 && DeskOtherCategory == 0) { Chart4.Visible = false; } #endregion } } activate = "activated"; }
/// <summary> /// Removes a user as a list subscriber /// </summary> /// <param name="listID">ID of list.</param> /// <param name="slug">Name of list to remove from.</param> /// <param name="ownerID">ID of user who owns the list.</param> /// <param name="ownerScreenName">Screen name of user who owns the list.</param> /// <returns>List info for list subscription removed from</returns> public static List UnsubscribeFromList(this TwitterContext ctx, string listID, string slug, string ownerID, string ownerScreenName) { return(UnsubscribeFromList(ctx, listID, slug, ownerID, ownerScreenName, null)); }
/// <summary> /// Deletes membership for a comma-separated list of users /// </summary> /// <param name="listID">ID of list.</param> /// <param name="slug">Name of list to remove from.</param> /// <param name="userIds">Comma-separated list of user IDs of users to remove from list membership.</param> /// <param name="screenNames">Comma-separated list of screen names of users to remove from list membership.</param> /// <param name="ownerID">ID of users who owns the list.</param> /// <param name="ownerScreenName">Screen name of user who owns the list.</param> /// <returns>List info for list subscription removed from</returns> public static List DestroyAllFromList(this TwitterContext ctx, string listID, string slug, string userIds, string screenNames, string ownerID, string ownerScreenName) { return(DestroyAllFromList(ctx, listID, slug, userIds, screenNames, ownerID, ownerScreenName, null)); }
/// <summary> /// Adds a list of users to a list. /// </summary> /// <param name="listID">ID of List.</param> /// <param name="slug">List name.</param> /// <param name="ownerID">ID of user who owns the list.</param> /// <param name="ownerScreenName">Screen name of user who owns the list.</param> /// <param name="userIDs">List of user IDs to be list members. (max 100)</param> /// <returns>List info for list members added to.</returns> public static List AddMemberRangeToList(this TwitterContext ctx, string listID, string slug, string ownerID, string ownerScreenName, List <ulong> userIDs) { return(AddMemberRangeToList(ctx, listID, slug, ownerID, ownerScreenName, userIDs, null)); }
/// <summary> /// Removes a user as a list member /// </summary> /// <param name="userID">ID of user to add to list.</param> /// <param name="screenName">ScreenName of user to add to list.</param> /// <param name="listID">ID of list.</param> /// <param name="slug">Name of list to remove from.</param> /// <param name="ownerID">ID of user who owns the list.</param> /// <param name="ownerScreenName">Screen name of user who owns the list.</param> /// <returns>List info for list member removed from</returns> public static List DeleteMemberFromList(this TwitterContext ctx, string userID, string screenName, string listID, string slug, string ownerID, string ownerScreenName) { return(DeleteMemberFromList(ctx, userID, screenName, listID, slug, ownerID, ownerScreenName, null)); }
/// <summary> /// Deletes a favorite from the logged-in user's profile /// </summary> /// <param name="id">id of status to add to favorites</param> /// <returns>status of favorite</returns> public static Status DestroyFavorite(this TwitterContext ctx, string id) { return(DestroyFavorite(ctx, id, true, null)); }
/// <summary> /// Creates a new list /// </summary> /// <param name="listName">name of list</param> /// <param name="mode">public or private</param> /// <param name="description">list description</param> /// <returns>List info for new list</returns> public static List CreateList(this TwitterContext ctx, string listName, string mode, string description) { return(CreateList(ctx, listName, mode, description, null)); }
/// <summary> /// Adds a favorite to the logged-in user's profile /// </summary> /// <param name="id">id of status to add to favorites</param> /// <returns>status of favorite</returns> public static Status CreateFavorite(this TwitterContext ctx, string id) { return(CreateFavorite(ctx, id, true, null)); }
/// <summary> /// Deletes a favorite from the logged-in user's profile /// </summary> /// <param name="id">id of status to add to favorites</param> /// <param name="includeEntities">Response doesn't include entities when false. (default: true)</param> /// <returns>status of favorite</returns> public static Status DestroyFavorite(this TwitterContext ctx, string id, bool includeEntities) { return(DestroyFavorite(ctx, id, includeEntities, null)); }
/// <summary> /// lets logged-in user report spam /// </summary> /// <param name="userID">user id of alleged spammer</param> /// <param name="screenName">screen name of alleged spammer</param> /// <returns>Alleged spammer user info</returns> public static User ReportSpam(this TwitterContext ctx, string userID, string screenName) { return(ReportSpam(ctx, userID, screenName, null)); }
/// <summary> /// Adds a favorite to the logged-in user's profile /// </summary> /// <param name="id">id of status to add to favorites</param> /// <param name="includeEntities">Response doesn't include entities when false. (default: true)</param> /// <returns>status of favorite</returns> public static Status CreateFavorite(this TwitterContext ctx, string id, bool includeEntities) { return(CreateFavorite(ctx, id, true, null)); }