public OAuthDialog() { InitializeComponent(); pinTextBox.Visibility = Visibility.Hidden; pinLbl.Visibility = Visibility.Hidden; pinInstruction.Visibility = Visibility.Hidden; _consumerKey = Settings.Default.ConsumerKey; _consumerSecret = Settings.Default.ConsumerSecret; //get a request token. this is only used during //this process. var getRequestTokenRequest = FluentTwitter.CreateRequest() .Authentication.GetRequestToken(_consumerKey, _consumerSecret); var response = getRequestTokenRequest.Request(); _requestToken = response.AsToken(); //TODO: handle the case where the token is NULL because //twitter is down or broken in a manner suitable to your app //wait for the user to click the "Authorize button" }
public string CreateAndSignAccessToken(string oauth_token) { var accessToken = FluentTwitter.CreateRequest() .Authentication.GetAccessToken(OAuth.GetOAuthSecrets().Key, OAuth.GetOAuthSecrets().Secret, oauth_token); var response = accessToken.Request(); var result = response.AsToken(); if (result == null) { var error = response.AsError(); if (error != null) { throw new Exception(error.ErrorMessage); } throw new Exception(); } if (result.Token != null && result.TokenSecret != null && result.ScreenName != null) { return(SignedString.CreateSignedString(Encryptor.EncryptString(SerializeToken(result), EncryptingKey), SigningKey)); } else { return(null); } }
void IStyleInstance.UpdateContent(ref notification_info NotificationInfo) { string myUpdate = NotificationInfo.Title + " - " + NotificationInfo.Text; if (myUpdate.Length > 140) { myUpdate = myUpdate.Substring(0, 137) + "..."; } try { var twitter = FluentTwitter.CreateRequest() .AuthenticateWith(Settings.Default.ConsumerKey, Settings.Default.ConsumerSecret, Settings.Default.AccessToken, Settings.Default.AccessTokenSecret) .Account().VerifyCredentials(); var response = twitter.Request(); var profile = response.AsUser(); if (profile != null) { var twitterPost = FluentTwitter.CreateRequest() .AuthenticateWith(Settings.Default.ConsumerKey, Settings.Default.ConsumerSecret, Settings.Default.AccessToken, Settings.Default.AccessTokenSecret) .Statuses().Update(myUpdate); var postresponse = twitterPost.Request(); } } catch { MessageBox.Show("Error in sending notification to Twitter", "Error sending to Twitter", MessageBoxButton.OK); } }
private static bool VerifyOAuthCredentials() { bool authorized = false; try { var twitter = FluentTwitter.CreateRequest() .AuthenticateWith(Settings.Default.ConsumerKey, Settings.Default.ConsumerSecret, Settings.Default.AccessToken, Settings.Default.AccessTokenSecret) .Account().VerifyCredentials(); var response = twitter.Request(); var profile = response.AsUser(); if (profile != null) { authorized = true; } } catch (Exception exp) { MessageBox.Show(exp.Message + "\n\n" + exp.StackTrace, "Error in communication with Twitter", MessageBoxButton.OK, MessageBoxImage.Error); } return(authorized); }
public IList <Tweet> GetTweets() { var twitter = FluentTwitter.CreateRequest() .AuthenticateAs(this._credentials.UserName, this._credentials.Password) .Statuses().OnFriendsTimeline().AsXml(); var response = twitter.Request(); this.CheckXmlResponseForErrors(response); XDocument doc = XDocument.Parse(response); List <Tweet> tweets = (from x in doc.Descendants("status") let u = x.Element("user") select new Tweet() { Id = int.Parse(x.Element("id").Value), CreatedOn = x.Element("created_at").Value.ParseDateTime(), Message = x.Element("text").Value, User = new User() { Name = u.Element("name").Value, PictureUrl = u.Element("profile_image_url").Value } }).ToList(); return(tweets); }
public string GetAuthenticationUrl() { var twitter = FluentTwitter.CreateRequest().Authentication.GetRequestToken(OAuth.GetOAuthSecrets().Key, OAuth.GetOAuthSecrets().Secret); var response = twitter.Request(); var token = response.AsToken(); var error = response.AsError(); if (error != null) { throw new Exception(error.ErrorMessage); } if (token == null) { if (response.Exception != null) { throw new Exception("Error getting authentication request token", response.Exception); } throw new Exception("error getting authentication request token error code " + response.ResponseHttpStatusCode); } return(FluentTwitter.CreateRequest().Authentication.GetAuthorizationUrl(token.Token).Replace("/authorize", "/authenticate")); }
private void okBtn_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(pinTextBox.Text)) { MessageBox.Show("Enter the PIN provided by twitter.com", "Can't complete Authorization", MessageBoxButton.OK, MessageBoxImage.Error); return; } string pin = pinTextBox.Text; var twitter = FluentTwitter.CreateRequest().Authentication.GetAccessToken(_consumerKey, _consumerSecret, _requestToken.Token, pin); var response = twitter.Request(); var result = response.AsToken(); if (result == null || string.IsNullOrEmpty(result.Token)) { MessageBox.Show(response.AsError().ErrorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation); //TODO: handle this error condition. //the user may have incorrectly entered the PIN or twitter //may be down. Handle this in a way that makes sense for your //application. DialogResult = false; return; } Settings.Default.AccessToken = result.Token; Settings.Default.AccessTokenSecret = result.TokenSecret; Settings.Default.Save(); this.DialogResult = true; Close(); }
public string GetPublicStatuses() { var twitter = FluentTwitter.CreateRequest(info) .Statuses() .OnPublicTimeline().AsJson(); return(twitter.Request()); }
public string VerifyCredentials(string username, string password) { var userCredentials = FluentTwitter.CreateRequest(info) .AuthenticateAs(username, password) .Accounts().VerifyCredentials().AsJson(); return(userCredentials.Request()); }
public ITwitterStatuses authenticatedStatuses() { this.Twitter = FluentTwitter.CreateRequest().AuthenticateWith(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAuthToken.Token, OAuthToken.TokenSecret); this.Statuses = this.Twitter.Statuses(); return(this.Statuses); }
private void SearchForHashTags(string tag, IList <NewsItem> results) { var search = FluentTwitter.CreateRequest() .Search() .Query() .ContainingHashTag(tag); MapResults(search, results); }
public string UpdateStaus(string username, string password, string updateText) { var update = FluentTwitter.CreateRequest(info) .AuthenticateAs(username, password) .Statuses() .Update(updateText).AsJson(); return(update.Request()); }
private void SearchForUser(string tag, IList <NewsItem> results) { var search = FluentTwitter.CreateRequest() .Search() .Query() .FromUser(tag); MapResults(search, results); }
public string GetFriendStatuses(string username, string password) { var friendStatus = FluentTwitter.CreateRequest(info) .AuthenticateAs(username, password) .Statuses() .OnFriendsTimeline().AsJson(); return(friendStatus.Request()); }
public void SendTweet(string message) { var twitter = FluentTwitter.CreateRequest(this._info) .AuthenticateAs(this._credentials.UserName, this._credentials.Password) .Statuses().Update(message) .AsXml(); var response = twitter.Request(); this.CheckXmlResponseForErrors(response); }
public void SendTweet(string message, string picture) { var twitter = FluentTwitter.CreateRequest(this._info) .AuthenticateAs(this._credentials.UserName, this._credentials.Password) .Photos().PostPhoto(picture, SendPhotoServiceProvider.TwitPic) .Statuses().Update(message) .AsXml(); var response = twitter.Request(); this.CheckXmlResponseForErrors(response); }
public bool SendReply(string twitterUserName, string twitterPassword, string twitterUserNameReceiver, string message) { var update = FluentTwitter.CreateRequest() .AuthenticateAs(twitterUserName, twitterPassword) .Statuses() .Update("@{0} {1}".ToFormat(twitterUserNameReceiver, message)) .AsJson(); update.Request(); return(true); }
private void AuthorizeDesktopBtn_Click(object sender, RoutedEventArgs e) { AuthorizeDesktopBtn.IsEnabled = false; pinTextBox.Visibility = System.Windows.Visibility.Visible; pinLbl.Visibility = Visibility.Visible; pinInstruction.Visibility = Visibility.Visible; var twitter = FluentTwitter.CreateRequest() .Authentication .AuthorizeDesktop(_consumerKey, _consumerSecret, _requestToken.Token); twitter.Request(); //wait again until the user has authorized the desktop app //entered the PIN, and clicked "OK" }
public void LogIn(string username, string password) { // Log in to Twitter service using xAuth authentication. var request = FluentTwitter.CreateRequest().Configuration.UseHttps().Authentication .GetClientAuthAccessToken(username, password); var response = request.Request(); if (response.IsTwitterError) { throw new InvalidOperationException(response.Response); } var token = response.AsToken(); this.service.AuthenticateWith(token.Token, token.TokenSecret); this.TwitterUser = this.service.GetUserProfile(); this.IsAuthenticated = true; }
public TwitterService(NetworkCredential credential) { this._info = new TwitterClientInfo(); this._info.ClientName = "SurfaceTwitterApp"; this._info.ClientVersion = "0.1"; this._info.ClientUrl = "http://www.t-systems-mms.com/surface"; this._credentials = credential; var twitter = FluentTwitter.CreateRequest() .AuthenticateAs(this._credentials.UserName, this._credentials.Password) .Statuses().Replies().AsXml(); var response = twitter.Request(); CheckXmlResponseForErrors(response); this.IsAuthenticated = true; }
public void Execute(JobExecutionContext context) { var reminderService = context.Get("ReminderService") as ReminderService; var account = context.Get("Account") as Account; DateTime zmanSunset = SchedulerHelper.GetZman(DateTime.UtcNow, reminderService.Location, reminderService.ZmanName) .ToLocalTime(); TwitterResult twitter = FluentTwitter.CreateRequest() .AuthenticateAs(account.UserName, account.Password) .Statuses().Update( string.Format( reminderService.JobOptions["Message"], zmanSunset.ToShortTimeString()) ) .AsJson().Request(); }
private void kickOffBackgroundRequestIfNecessary(NodeDevice device) { if (device == null) { throw new ArgumentNullException("device"); } if (deviceShouldBeRunning(device) && !deviceState.IsRunning(device)) { // start it deviceState.SetIsRunning(device, true); string[] addressParts = device.Address.ToString().Split(new string[] { AbstractTwitterDevice.ADDRESS_SEPARATOR }, StringSplitOptions.None); string token = new FieldBase64(addressParts[0]).Decode(); string tokenSecret = new FieldBase64(addressParts[1]).Decode(); var twitter = FluentTwitter.CreateRequest() .AuthenticateWith(TwitterConsumer.ConsumerKey, TwitterConsumer.ConsumerSecret, token, tokenSecret) .Statuses().OnUserTimeline(); twitter.CallbackTo((sender, result, userstate) => { deviceState.SetUserStatusMonitor(device, result.AsStatuses()); // Implement some rate limiting long waitSeconds100Percent = 20; if (result.RateLimitStatus.RemainingHits > 0) { long secondsBeforeReset = (long)result.RateLimitStatus.ResetTime.Subtract(DateTime.Now).TotalSeconds; waitSeconds100Percent = secondsBeforeReset / result.RateLimitStatus.RemainingHits; } long waitSecondsMinimum = 20; if (result.RateLimitStatus.HourlyLimit > 0) { waitSecondsMinimum = 3600 / result.RateLimitStatus.HourlyLimit; } long waitSeconds = Math.Max((long)((1 / 50.Percent()) * waitSeconds100Percent), waitSecondsMinimum); // limits to a certain percentage, with a floor System.Threading.Thread.Sleep((int)(waitSeconds * 1000)); deviceState.SetIsRunning(device, false); }); twitter.BeginRequest(); } }
/// <summary> /// Returns the new Address field for the NodeDevice /// </summary> public FieldString ShowDialog() { Window dlg = new AuthenticateDialogView(); dlg.Owner = mainWindowExport.Value; dlg.DataContext = this; dlg.ShowDialog(); FieldString retVal = null; if (Username != string.Empty) { var twitter = FluentTwitter.CreateRequest() .Configuration.UseHttps() .Authentication.GetClientAuthAccessToken(TwitterConsumer.ConsumerKey, TwitterConsumer.ConsumerSecret, Username, Password.ConvertToUnsecureString()); var response = twitter.Request(); try { var token = response.AsToken(); // the token and token secret seem to be base-64 encoded already, but there's no guarantee, so let's encode them again var item1 = FieldBase64.Encode(token.Token).ToString(); var item2 = FieldBase64.Encode(token.TokenSecret).ToString(); retVal = new FieldString(item1 + AbstractTwitterDevice.ADDRESS_SEPARATOR + item2); messagingService.ShowMessage(Resources.Strings.ContextMenu_Authenticate_Success, Resources.Strings.ContextMenu_Authenticate_Success_Title); } catch (Exception ex) { logger.Error("Error authenticating Twitter", ex); messagingService.ShowMessage(Resources.Strings.ContextMenu_Authenticate_Fail, Resources.Strings.ContextMenu_Authenticate_Fail_Title); } } return(retVal); }
public string getAuthorizationUrl() { "[O2TwitterAPI] retriving Authorization Url".info(); var twitter = FluentTwitter.CreateRequest() .Configuration.UseHttps() .Authentication.GetRequestToken(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET); var response = twitter.Request(); if (response.ResponseHttpStatusCode.neq(200)) { "error in first twitter response".error(); return(null); } var unauthorizedToken = response.AsToken(); var url = FluentTwitter.CreateRequest().Authentication.GetAuthorizationUrl(unauthorizedToken.Token); "[O2TwitterAPI] Authorization Url retrived: {0}".info(url); return(url); }
private void FluentExample(Dispatcher dispatcher) { FluentTwitter.CreateRequest() .Statuses().OnPublicTimeline().AsJson() .BeginRequest((statuses, response) => { if (response.StatusCode == HttpStatusCode.OK) { ProcessIncomingTweets(response, statuses, dispatcher); } }); FluentTwitter.CreateRequest() .Statuses().Update(DateTime.Now.Ticks.ToString()) .BeginRequest((status, response) => { if (response.StatusCode != HttpStatusCode.OK) { return; } var tweet = new Tweet(status); dispatcher.BeginInvoke(() => _tweets.Items.Add(tweet)); }); }
public bool login(OAuthToken oAuthToken) { if (oAuthToken.isNull()) { "[O2TwitterApi] in login, provided OAuthToken parameter was null".error(); return(false); } try { OAuthToken = oAuthToken; "login to Twitter via OAuth under user:{0}".info(oAuthToken.ScreenName); this.Twitter = FluentTwitter.CreateRequest() .AuthenticateWith(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, oAuthToken.Token, oAuthToken.TokenSecret); var response = this.Twitter.Account().VerifyCredentials().AsJson().Request(); IsLoggedIn = response.ok(); if (IsLoggedIn) { this.Statuses = this.Twitter.Statuses(); this.UserLoggedIn = response.AsUser(); "Sucessfully connected to twitter user: '******' (id:{1})".info(this.UserLoggedIn.Name, this.UserLoggedIn.Id); } else { "Failed to connect to twitter user {0}".error(Username); } return(IsLoggedIn); } catch (Exception ex) { ex.log("[in O2TwitterAPI.login"); } return(false); }
public OAuthToken getAuthToken(string autorizationUrl, string username, string password) { var sync = new AutoResetEvent(false); OAuthToken oauthToken = null; var tokenFile = getTokenFileForUser(username); if (tokenFile.valid() && tokenFile.fileExists()) { "[O2TwitterAPI] found cached token for user: {0}".info(username); return(tokenFile.load <OAuthToken>()); } var ie = autorizationUrl.ie(); // will open a new instance of IE //var ie = panel.add_IE(); // will use an Embeded version of IE // configure IE to handle twitter redirect ie.beforeNavigate( (url) => { "[O2TwitterAPI] in BeforeNavigate for: {0}".debug(url); if (url.starts("http://o2platform.com/?oauth_token=")) { O2Thread.mtaThread( () => { var splitted = url.uri().Query.split("="); if (splitted.size() == 2 && splitted[0] == "?oauth_token") { var token = splitted[1]; "[O2TwitterAPI] Found Token: {0}".info(token); var twitter = FluentTwitter.CreateRequest() .Authentication.GetAccessToken(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, token); oauthToken = twitter.Request().AsToken(); if (oauthToken.notNull()) { oauthToken.saveAs(tokenFile); "[O2TwitterAPI] OAuthToken saved to: {0}".info(tokenFile); } } sync.Set(); // continue }); "[O2TwitterAPI] Found O2Platform.com Twitter redirect, stoping IE request".debug(); return(true); } return(false); }); //perform login section ie.open(autorizationUrl); if (ie.hasLink("Sign out")) { ie.link("Sign out").click(); } if (ie.hasField("session[password]") && ie.hasField("session[username_or_email]")) { ie.field("session[username_or_email]").value(username); ie.field("session[password]").value(password); ie.button("Allow").click(); } if (sync.WaitOne(10000).isFalse()) // wait until the redirect has been processed { "[O2TwitterAPI] OAuthToken request timeout".error(); } ie.close(); return(oauthToken); }