private static void ConfigureEventHandlers() { jquery.jQuery.select("#okButton").on("click", (e, args) => { var cred = new TwitterCredentials { ApiKey = jquery.jQuery.select("#apiKeyInput").val() as string, ApiSecret = jquery.jQuery.select("#apiSecretInput").val() as string, AccessToken = jquery.jQuery.select("#accessTokenInput").val() as string, AccessTokenSecret = jquery.jQuery.select("#accessTokenSecretInput").val() as string, }; Electron.ipcRenderer.send(Constants.IPC.SetCredentials, cred); Electron.remote.getCurrentWindow().close(); return(null); }); jquery.jQuery.select("#cancelButton").on("click", (e, args) => { Electron.remote.getCurrentWindow().close(); return(null); }); }
private string GetTwitterURL() { credentials = new TwitterCredentials(tbTwitterKey.Text, tbTwitterSecret.Password); tokenizer = new TwitterTokenizer(); return(tokenizer.GetURL(credentials)); }
public IAuthenticationContext SetCredentials() { TwitterCredentials = new TwitterCredentials(TwitterConfig.ConsumerKey, TwitterConfig.ConsumerSecret); AuthenticationContext = AuthFlow.InitAuthentication(TwitterCredentials); return(AuthenticationContext); }
public ITwitterCredentials GenerateToken(IConsumerCredentials appCredentials) { var callbackParameter = _oAuthWebRequestGenerator.GenerateParameter("oauth_verifier", appCredentials.VerifierCode, true, true, false); try { var authHandler = new AuthHttpHandler(callbackParameter); var response = _twitterRequestHandler.ExecuteQuery(Resources.OAuthRequestAccessToken, HttpMethod.POST, authHandler, new TwitterCredentials(appCredentials)); if (response == null) { return(null); } Match responseInformation = Regex.Match(response, "oauth_token=(?<oauth_token>(?:\\w|\\-)*)&oauth_token_secret=(?<oauth_token_secret>(?:\\w)*)&user_id=(?<user_id>(?:\\d)*)&screen_name=(?<screen_name>(?:\\w)*)"); var credentials = new TwitterCredentials(); credentials.AccessToken = responseInformation.Groups["oauth_token"].Value; credentials.AccessTokenSecret = responseInformation.Groups["oauth_token_secret"].Value; credentials.ConsumerKey = appCredentials.ConsumerKey; credentials.ConsumerSecret = appCredentials.ConsumerSecret; return(credentials); } catch (TwitterException ex) { LogExceptionOrThrow(ex); } return(null); }
private static void InitTwitterCredentials() { var creds = new TwitterCredentials(AccessToken, AccessTokenSecret, ConsumerKey, ConsumerSecret); Auth.SetUserCredentials(ConsumerKey, ConsumerSecret, AccessToken, AccessTokenSecret); Auth.ApplicationCredentials = creds; }
private static IOAuthCredentials CredentialsCreator_CreateFromRedirectedCallbackURL_SingleStep(string consumerKey, string consumerSecret) { //if (string.IsNullOrEmpty(User.Default.TwitterAccessKey) || string.IsNullOrEmpty(User.Default.TwitterAccessToken)) // { Func <string, string> retrieveCallbackURL = url => { Console.WriteLine("Go on : {0}", url); Console.WriteLine("When redirected to your website copy and paste the URL: "); // Enter a value like: https://tweeetinvi.codeplex.com?oauth_token={tokenValue}&oauth_verifier={verifierValue} var callbackURL = Console.ReadLine(); return(callbackURL); }; // Here we provide the entire URL where the user has been redirected var newCredentials = CredentialsCreator.GetCredentialsFromCallbackURL_UsingRedirectedCallbackURL(retrieveCallbackURL, consumerKey, consumerSecret, "https://tweetinvi.codeplex.com"); Console.WriteLine("Access Token = {0}", newCredentials.AccessToken); Console.WriteLine("Access Token Secret = {0}", newCredentials.AccessTokenSecret); User.Default.TwitterAccessKey = newCredentials.AccessToken; User.Default.TwitterAccessToken = newCredentials.AccessTokenSecret; User.Default.Save(); return(newCredentials); //} return(TwitterCredentials.CreateCredentials(User.Default.TwitterAccessToken, User.Default.TwitterAccessKey, consumerKey, consumerSecret)); }
/*Constructor: takes the keys needed, last paramets are filters for the stream*/ public TwitterStreamProcessor(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, params string[] filters) { PictureDataQueue = new Queue <PictureData>(); PictureMetaDataList = new List <PictureMetaData>(); //The credentials for the twitter api var cred = new TwitterCredentials(consumerKey, consumerSecret, accessToken, accessTokenSecret); stream = Tweetinvi.Stream.CreateFilteredStream(cred); //insert the filters foreach (var filter in filters) { stream.AddTrack(filter); } //Delegate the method responsible for the handling of the matches stream.MatchingTweetReceived += handleMatchingTweet; //start the stream as a task: will run "forever" Task.Factory.StartNew(() => stream.StartStreamMatchingAllConditions()); StreamStart = DateTime.Now; }
public int GetTweetCount(string strTerm) { string oauth_consumer_key = System.Configuration.ConfigurationManager.AppSettings["oauth_consumer_key"]; string oauth_consumer_secret = System.Configuration.ConfigurationManager.AppSettings["oauth_consumer_secret"]; string oauth_access_token = System.Configuration.ConfigurationManager.AppSettings["oauth_access_token"]; string oauth_token_secret = System.Configuration.ConfigurationManager.AppSettings["oauth_token_secret"]; try { // Create a new set of credentials for the application. var appCredentials = new TwitterCredentials(oauth_consumer_key, oauth_consumer_secret, oauth_access_token, oauth_token_secret); // Use the user credentials in your application Auth.SetCredentials(appCredentials); // Simple Search var matchingTweets = Search.SearchTweets(strTerm); // Return the count of tweets return(matchingTweets.Count()); } catch (Exception ex) { string strError = ""; strError = ex.ToString(); return(0); } }
public void LoginAsDev() { if (!loggedIn) { if (!IsConnectedToInternet()) { FOutputStatus[0] = "Internet is f****d bro. Can't login as dev..."; FLogger.Log(LogType.Debug, "Internet is f****d bro. Can't login as dev..."); FOutputStatusBool[0] = false; loggedIn = false; ClearOutputPins(); } else { try { TwitterCredentials.SetCredentials(FDevCredentials[0], FDevCredentials[1], FCredentials[0], FCredentials[1]); //TwitterCredentials.SetCredentials("Access_Token", "Access_Token_Secret", "Consumer_Key", "Consumer_Secret"); GetRateLimits("Login failed! Bad credentials?"); } catch { FOutputStatus[0] = "Bad application or dev credentials, monsieur tete de bite."; FLogger.Log(LogType.Debug, "Bad application or dev credentials, monsieur tete de bite."); } } } else { FOutputStatus[0] = "You're already logged in, you douche, logout first."; FLogger.Log(LogType.Debug, "You'RE already logged in, you douche, logout first."); } }
public void SendToCloud(string data) { if (timeSync.Minute != DateTime.Now.Minute) { timeSync = DateTime.Now; var sensorData = JsonConvert.DeserializeObject <SensorSetStatusRequest>(data); if (sensorData != null) { if (!String.IsNullOrEmpty(sensorData?.Temperature.Celsius) && (sensorData?.Temperature.Celsius.Length >= 5)) { var credentials = new TwitterCredentials(this.ConfigurationUtility.TwitterConsumerAPIKey, this.ConfigurationUtility.TwitterConsumerSecretAPIKey, this.ConfigurationUtility.TwitterAccessToken, this.ConfigurationUtility.TwitterAccessTokenSecret); var tweet = Auth.ExecuteOperationWithCredentials(credentials, () => { return(Tweet.PublishTweet(String.Format(ConfigurationUtility.TwitterFormatMsg, sensorData?.Temperature.Celsius.Substring(0, 5).Replace(".", ","), sensorData?.LDR.Intensity))); }); } } } }
public void CreateStream() { TwitterCredentials.SetCredentials( RoleEnvironment.GetConfigurationSettingValue("UserAccessToken"), RoleEnvironment.GetConfigurationSettingValue("UserAccessSecret"), RoleEnvironment.GetConfigurationSettingValue("ConsumerKey"), RoleEnvironment.GetConfigurationSettingValue("ConsumerSecret")); //rateLimit = new ProtectedTimer(TimeSpan.FromSeconds(60), new Action(OnCheckRateRequestLimit)); //rateLimit.Start(); string words = RoleEnvironment.GetConfigurationSettingValue("TwitterSearchTerms"); string[] items = words.Split(';'); foreach (var item in items) { if (!string.IsNullOrEmpty(item)) { stream.AddTrack(item); Trace.Write(string.Concat("Track item -> ", item), typeof(TwitterStreamingEngine).FullName); } } stream.MatchingTweetReceived += OnMatchingTweetReceived; stream.DisconnectMessageReceived += OnStreamDisconnectMessageReveived; stream.WarningFallingBehindDetected += OnWarningFallingBehindDetected; stream.LimitReached += OnLimitReached; stream.StreamStarted += OnStreamStarted; stream.StreamStopped += OnStreamStopped; stream.StartStreamMatchingAllConditions(); }
public void AuthenticateAppViaBrowser() { var appCredentials = new TwitterCredentials(ConsumerKey, ConsumerSecret); authenticationContext = AuthFlow.InitAuthentication(appCredentials); Browser.Open(authenticationContext.AuthorizationURL); }
public ActionResult Index(string profileId) { var user = DbContext.AspNetUsers.FirstOrDefault(x => x.Id == profileId); var model = new ProfileViewModel { Name = user.Name, Description = user.Description, ImageUrl = user.ImageUrl, UserId = user.Id, UserName = user.UserName }; var skills = DbContext.skills_list.Where(x => x.UserId == profileId); skills.ForEach(x => model.Skills.Add(x.Skill)); var twitterCredentials = new TwitterCredentials("0N5Q3XLB9CyXBaskZGlurmjr4", "2wsz47zbOEQaj8hz2UCkozxFU8BwldpTPqb42I2grRYJWiYseF", "401598968-hM5pvUyjZPcH9J5B32l9u3SjuLoKuybwS2SNxdhA", "FN5HEHob09t75fJJB422KP4MmJMzg2DvKlMgCkhr9HjKV"); var profile = Auth.ExecuteOperationWithCredentials(twitterCredentials, () => { return(Tweetinvi.User.GetUserFromScreenName(user.UserName)); }); var tweets = Auth.ExecuteOperationWithCredentials(twitterCredentials, () => { return(profile.GetUserTimeline(10)); }); model.Tweets = tweets; return(View(model)); }
static IObservable <Fs.TweetEmotion> TweetEmotionObservable(TimeSpan throttle) { var consumerKey = "<your Key>"; var consumerSecretKey = "<your secret key>"; var accessToken = "<your access token>"; var accessTokenSecret = "<your secreat access token>"; // Implementation of the TweetSentiment Observable in C# return (Rx.Observable.Create <Fs.TweetEmotion>(observer => { var cred = new TwitterCredentials( consumerKey, consumerSecretKey, accessToken, accessTokenSecret); var stream = Stream.CreateSampleStream(cred); stream.FilterLevel = StreamFilterLevel.Low; stream.StartStreamAsync(); return Rx.Observable .FromEventPattern <TweetReceivedEventArgs>(stream, "TweetReceived") .Throttle(throttle) .Select(args => args.EventArgs) .Where(args => args.Tweet.Language == Language.English) .GroupBy(args => Fs.evaluateEmotion(args.Tweet.FullText)) .SelectMany(args => args.Select(tw => Fs.TweetEmotion.Create(tw.Tweet, args.Key))) .Subscribe(o => observer.OnNext(o)); })); }
public async Task <List <Root> > GetTweetSampleStreamAsync() { List <Root> elements = new List <Root>(); TwitterCredentials credentials = new TwitterCredentials { BearerToken = _config["BearerToken"] }; TwitterClient client = new TwitterClient(credentials); var sampleStreamV2 = client.StreamsV2.CreateSampleStream(); sampleStreamV2.TweetReceived += (sender, args) => { elements.Add(new Root { data = new Data { author_id = args.Tweet.AuthorId, created_at = args.Tweet.CreatedAt, id = args.Tweet.Id, text = args.Tweet.Text } }); // adding a cap for stream if (elements.Count == 1000) { sampleStreamV2.StopStream(); } }; await sampleStreamV2.StartAsync(); return(elements); }
public string Authorization() { string ConsumerKey = null; string ConsumerSecret = null; string AccessToken = null; string AccessSecret = null; try { string XML = Path.GetFullPath("Config.xml"); XmlDocument doc = new XmlDocument(); doc.Load(XML); ConsumerKey = doc.ChildNodes.Item(1).ChildNodes.Item(9).InnerText.ToString(); ConsumerSecret = doc.ChildNodes.Item(1).ChildNodes.Item(11).InnerText.ToString(); AccessToken = doc.ChildNodes.Item(1).ChildNodes.Item(13).InnerText.ToString(); AccessSecret = doc.ChildNodes.Item(1).ChildNodes.Item(15).InnerText.ToString(); } catch (FileNotFoundException) { if (GenXml == false) { GenerateXML(); } } ITwitterCredentials AppCredentials = new TwitterCredentials(ConsumerKey, ConsumerSecret, AccessToken, AccessSecret); var authenticationContext = AuthFlow.InitAuthentication(AppCredentials); string AuthUrl = authenticationContext.AuthorizationURL; AuthenticationContext = authenticationContext; return(AuthUrl); }
public ITwitterCredentials GetTwitterCredentials() { // Create a new set of credentials for the application. var appCredentials = new TwitterCredentials(_twitterDevApiSettings.ConsumerKey, _twitterDevApiSettings.ConsumerSecret); // Init the authentication process and store the related `AuthenticationContext`. var authenticationContext = AuthFlow.InitAuthentication(appCredentials); // Go to the URL so that Twitter authenticates the user and gives him a PIN code. var window = new TwitterOauth(authenticationContext.AuthorizationURL); window.ShowDialog(); if (string.IsNullOrWhiteSpace(window.Code)) { throw new Exception("User didn't succeed login"); } // With this pin code it is now possible to get the credentials back from Twitter var userCredentials = AuthFlow.CreateCredentialsFromVerifierCode(window.Code, authenticationContext); return(userCredentials); // Use the user credentials in your application //Auth.SetCredentials(userCredentials); }
public async Task <bool> AuthenticateUser() { const string consumerKey = Credentials.TwitterConsumerKey; const string consumerSecret = Credentials.TwitterConsumerSecret; var userCredentials = GetCredentials(); if (userCredentials != null) { Auth.SetUserCredentials(consumerKey, consumerSecret, userCredentials.AccessToken, userCredentials.AccessTokenSecret); return(true); } var appCredentials = new TwitterCredentials(consumerKey, consumerSecret); _authenticationContext = AuthFlow.InitAuthentication(appCredentials); if (_authenticationContext == null) { return(false); } Process.Start(_authenticationContext.AuthorizationURL); Pin = string.Empty; var dialog = new LoginDialog { DataContext = this }; await DialogHost.Show(dialog); if (string.IsNullOrWhiteSpace(Pin)) { return(false); } CreateAndSetCredentials(Pin); return(true); }
public static List <TweetDisplay> GetTweets(string searchCriteria) { // initialise a Credentials object with the keys supplied by the twitter api registration var credentials = CredentialsCreator.GenerateApplicationCredentials(consumerKey, consumerSecret); // tell twitter our credentials TwitterCredentials.SetCredentials(credentials.AuthorizationKey, credentials.AuthorizationSecret, credentials.ConsumerKey, credentials.ConsumerSecret); // Search the tweets containing the search criteria and create a list to display in the view, only use top 4 var items = Search.SearchTweets(searchCriteria).OrderByDescending(a => a.CreatedAt).ToList().Take(4); // create an empty list var results = new List <TweetDisplay>(); // Make a list of tweet items for using in the view foreach (var item in items) { var td = new TweetDisplay { CreatedAt = item.CreatedAt, Author = item.Creator.Name, Tweet = item.Text, ImageUrl = item.Creator.ProfileImageUrl }; results.Add(td); } return(results); }
public string startAuthFlow() { var appCredentials = new TwitterCredentials(ct, cs); authenticationContext = AuthFlow.InitAuthentication(appCredentials); return(authenticationContext.AuthorizationURL); }
public TwitterController(IConfiguration config, IOptionsSnapshot <TwitterCredentials> twitterCreds) { _lifxKey = config.GetValue <string>("lifxKey"); _twitterCreds = twitterCreds.Value; _utils = new Utils(config.GetValue <string>("cognitiveServices:apiUrl"), config.GetValue <string>("cognitiveServices:apiKey"), new HttpClient()); _twitterSearchTerm = config.GetValue <string>("twitterSearch"); }
private async static Task MainAsync(string[] args) { var twitterCredentials = new TwitterCredentials() { ConsumerKey = AppSettings.ApplicationConsumerKey, ConsumerSecret = AppSettings.ApplicationConsumerSecret, }; var twitter = new UserSession(twitterCredentials, new DesktopPlatformAdaptor()); var oathToken = await twitter.StartUserAuthentication(); Console.Write("Please enter the PIN as displayed in the new browser window: "); var pin = Console.ReadLine(); var credentials = await twitter.ConfirmPin(pin, oathToken); if (credentials.Valid) { string json = JsonConvert.SerializeObject(credentials); File.WriteAllText(@"credentials.json", json); Console.WriteLine("Credentials were successfully saved."); } else { Console.WriteLine("Credentials were invalid."); } Console.ReadLine(); }
public Twitter() { TwitterCredentials.SetCredentials(Properties.Settings.Default.access_token, Properties.Settings.Default.access_token_secret, Properties.Resources.api_key, Properties.Resources.api_key_secret); }
private static void SaveCredentialsToFile(string fileName, TwitterCredentials tc) { var json = JsonConvert.SerializeObject(tc, Formatting.Indented); var cypherText = json.ToSecureString().EncryptString(); File.WriteAllText(fileName, cypherText); }
public async Task GetRateLimits_FromTwitterApiOnly_GetsResultFromTwitterAccessor() { var expectedRateLimits = A.Fake <CredentialsRateLimitsDTO>(); var twitterAccessor = A.Fake <ITwitterAccessor>(); var container = new TweetinviContainer(); container.BeforeRegistrationCompletes += (sender, args) => { container.RegisterInstance(typeof(ITwitterAccessor), twitterAccessor); }; container.Initialize(); var fakeCredentials = new TwitterCredentials("consumerKey", "consumerSecret", "accessToken", "accessTokenSecret"); var client = new TwitterClient(fakeCredentials, new TwitterClientParameters { Container = container }); A.CallTo(() => twitterAccessor.ExecuteRequest <CredentialsRateLimitsDTO>(It.IsAny <ITwitterRequest>())) .Returns(new TwitterResult <CredentialsRateLimitsDTO> { DataTransferObject = expectedRateLimits }); // act var rateLimits = await client.RateLimits.GetRateLimits(RateLimitsSource.TwitterApiOnly); // arrange Assert.Same(rateLimits.CredentialsRateLimitsDTO, expectedRateLimits); }
/// <summary>Prompt the user to Authorize the MemeCannon to make tweets</summary> private static void UpdateUserSettings() { ITwitterCredentials appCreds = Auth.SetApplicationOnlyCredentials(twitterConsumerKey, twitterConsumerSecret); // This method execute the required webrequest to set the bearer Token Auth.InitializeApplicationOnlyCredentials(appCreds); // Create a new set of credentials for the application. TwitterCredentials appCredentials = new TwitterCredentials(twitterConsumerKey, twitterConsumerSecret); IAuthenticationContext authenticationContext = AuthFlow.InitAuthentication(appCredentials); ProcessStartInfo psi = new ProcessStartInfo(authenticationContext.AuthorizationURL) { UseShellExecute = true, Verb = "open" }; // Causes a WebBrowser to open and the user needs to OK app access Process.Start(psi); // Ask the user to enter the pin code given by Twitter Console.WriteLine("Enter PIN Code given by Twitter to continue:"); string pinCode = Console.ReadLine(); // With this pin code it is now possible to get the credentials back from Twitter ITwitterCredentials userCredentials = AuthFlow.CreateCredentialsFromVerifierCode(pinCode, authenticationContext); // Save off the accessToken and accessTokenSecret Program.CannonCfg.AccessToken = userCredentials.AccessToken; Program.CannonCfg.AccessTokenSecret = userCredentials.AccessTokenSecret; FileHelper.WriteJSONToFile("./CannonConfig.json", Program.CannonCfg.ToJson()); }
public static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("You didn't specified tracks to stream from Twitter!"); return; } var tracks = args[0].Split(',').ToArray(); var consumerKey = Environment.GetEnvironmentVariable("TWITTER_CONSUMER_KEY") ?? args.Skip(1).FirstOrDefault(); var consumerSecret = Environment.GetEnvironmentVariable("TWITTER_CONSUMER_SECRET") ?? args.Skip(2).FirstOrDefault(); var accessToken = Environment.GetEnvironmentVariable("TWITTER_ACCESS_TOKEN") ?? args.Skip(3).FirstOrDefault(); var accessTokenSecret = Environment.GetEnvironmentVariable("TWITTER_ACCESS_SECRET") ?? args.Skip(4).FirstOrDefault(); var credentials = new TwitterCredentials( consumerKey, consumerSecret, accessToken, accessTokenSecret ); using (CreateTweetStream(tracks, credentials).Subscribe( tweet => Console.WriteLine(tweet), error => Console.WriteLine($"Twitter stream failed with exception:{Environment.NewLine}{error}"), () => Console.WriteLine("Twitter stream completed.") )) { Console.WriteLine($"Service started streeming tweets for '{args[0]}'. Press any key to stop."); Console.ReadKey(); } }
public void LoadTwitterCredentials() { TwitterCredentials = new TwitterCredentials(TwitterConfig.ConsumerKey, TwitterConfig.ConsumerSecret, TwitterConfig.AccessToken, TwitterConfig.AccessTokenSecret); AuthenticationContext = AuthFlow.InitAuthentication(TwitterCredentials); Auth.SetCredentials(TwitterCredentials); }
public TwitterService(string consumerKey, string consumerSecret, string token, string tokenSecret, MentionsRepository repository) { _repository = repository; var userCredentials = new TwitterCredentials(consumerKey, consumerSecret, token, tokenSecret); _client = new TwitterClient(userCredentials); }
/// <summary> /// The method streams the real time tweets containing the given keyword /// The tweets should be in english language and contain geolocation /// </summary> /// <param name="keyword"></param> public static void tweetStreamer(string keyword) { _accessToken = ConfigurationManager.AppSettings["token_AccessToken"]; _accessTokenSecret = ConfigurationManager.AppSettings["token_AccessTokenSecret"]; _consumerKey = ConfigurationManager.AppSettings["token_ConsumerKey"]; _consumerSecret = ConfigurationManager.AppSettings["token_ConsumerSecret"]; var Credentials = TwitterCredentials.CreateCredentials(_accessToken, _accessTokenSecret, _consumerKey, _consumerSecret); TwitterCredentials.ExecuteOperationWithCredentials(Credentials, () => { var stream = Stream.CreateFilteredStream(); ICoordinates coordinates1 = new Coordinates(-180, -90); ICoordinates coordinates2 = new Coordinates(180, 90); ILocation location = new Location(coordinates1, coordinates2); stream.AddLocation(location); stream.AddTrack(keyword); stream.AddTweetLanguageFilter(Language.English); stream.MatchingTweetAndLocationReceived += (sender, args) => { var tweet = args.Tweet; Console.WriteLine("{0} {1} was detected ", tweet.Id, tweet.Text); //IEnumerable<ILocation> matchingLocations = args.MatchedLocations; processATweet(tweet, keyword); //Console.WriteLine("Text: "+ tweet.Text); }; stream.StartStreamMatchingAllConditions(); }); }
public new ITwitterCredentials Clone() { var clone = new TwitterCredentials(ConsumerKey, ConsumerSecret, AccessToken, AccessTokenSecret); CopyPropertiesToClone(clone); return clone; }
protected override async void OnNavigatedTo(NavigationEventArgs e) { await AuthTokens.KeyRetriever(); _appCredentials = new TwitterCredentials(AuthTokens.TwitterConsumerKey.Trim(), AuthTokens.TwitterConsumerSecret.Trim()); TwitterAuthenticatorMethod(); SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible; SystemNavigationManager.GetForCurrentView().BackRequested += (s, ex) => { var frame = Window.Current.Content as Frame; frame?.Navigate(typeof(MainPage)); }; }
public void AuthenticateAppViaBrowser() { var appCredentials = new TwitterCredentials(ConsumerKey, ConsumerSecret); authenticationContext = AuthFlow.InitAuthentication(appCredentials); Browser.Open(authenticationContext.AuthorizationURL); }
// Step 2 - Generate User Credentials public ITwitterCredentials GetCredentialsFromVerifierCode(string verifierCode, IAuthenticationToken authToken) { try { if (authToken == null) { throw new ArgumentNullException("Authentication Token cannot be null."); } if (verifierCode == null) { throw new ArgumentNullException("VerifierCode", "If you've received a verifier code that is null, " + "it means that authentication has failed!"); } var callbackParameter = _oAuthWebRequestGenerator.GenerateParameter("oauth_verifier", verifierCode, true, true, false); var authHandler = new AuthHttpHandler(callbackParameter, authToken); var response = _twitterRequestHandler.ExecuteQuery(Resources.OAuthRequestAccessToken, HttpMethod.POST, authHandler, new TwitterCredentials(authToken.ConsumerCredentials)); if (response == null) { return null; } var responseInformation = Regex.Match(response, Resources.OAuthTokenAccessRegex); if (responseInformation.Groups["oauth_token"] == null || responseInformation.Groups["oauth_token_secret"] == null) { return null; } var credentials = new TwitterCredentials( authToken.ConsumerKey, authToken.ConsumerSecret, responseInformation.Groups["oauth_token"].Value, responseInformation.Groups["oauth_token_secret"].Value); return credentials; } catch (TwitterException ex) { if (_exceptionHandler.LogExceptions) { _exceptionHandler.AddTwitterException(ex); } if (!_exceptionHandler.SwallowWebExceptions) { throw; } } return null; }