Exemplo n.º 1
0
        public virtual OAuthAccessToken GetAccessToken(OAuthRequestToken requestToken, string?verifier)
        {
            if (_consumerKey == null || _consumerSecret == null)
            {
                throw new InvalidOperationException("_consumerKey == null || _consumerSecret == null");
            }
            var args = new FunctionArguments
                       (
                _consumerKey,
                _consumerSecret,
                requestToken.Token,
                requestToken.TokenSecret,
                verifier
                       );

            var request  = _accessTokenQuery.Invoke(args);
            var response = _oauth.Request(request);

            SetResponse(response);

            var query       = OAuthWorkflow.ParseQuery(response.Content);
            var accessToken = new OAuthAccessToken
                              (
                query["oauth_token"] ?? "?",
                query["oauth_token_secret"] ?? "?",
                Convert.ToInt64(query["user_id"] ?? "0"),
                query["screen_name"] ?? "?"
                              );

            return(accessToken);
        }
Exemplo n.º 2
0
        public RedirectToRouteResult TwitterCallback(string oauth_token, string oauth_verifier)
        {
            var requestToken = new TweetSharp.OAuthRequestToken {
                Token = oauth_token
            };
            string Key    = "";
            string Secret = "";

            TwitterService service = new TwitterService(Key, Secret);

            TweetSharp.OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);
            service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
            VerifyCredentialsOptions option = new VerifyCredentialsOptions();
            TwitterUser _user = service.VerifyCredentials(option);
            User        user  = new User();

            user.picture = _user.ProfileImageUrl;


            String[] name = _user.Name.ToString().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            user.login = name[0] + name[1];

            user.email           = "pass";
            user.validationEmail = true;
            user.password        = _user.Id.ToString();
            UserService.InserNew(user);

            return(RedirectToAction("Index", "Account"));
        }
Exemplo n.º 3
0
        private void PINLogin_Click(object sender, EventArgs e)
        {
            try
            {
                // PIN入力
                string verifier = PINTextBox.Text;
                access = service.GetAccessToken(requestToken, verifier);
                service.AuthenticateWith(access.Token, access.TokenSecret);

                // xmlにToken保存
                Settings.Instance.token_s = access.Token;
                Settings.Instance.select_s = access.TokenSecret;
                Settings.SaveToXmlFile();

                // 完了メッセージ
                MessageBox.Show("アカウントが設定されました。", "情報", MessageBoxButtons.OK, MessageBoxIcon.Information);

                // 閉じる
                Close();
            }
            catch (Exception ex)
            {
                // 例外発生時のメッセージ
                MessageBox.Show("例外が発生しました。\n" + ex, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public virtual OAuthAccessToken GetAccessToken(OAuthRequestToken requestToken, string verifier)
        {
            var args = new FunctionArguments
            {
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret,
                Token          = requestToken.Token,
                TokenSecret    = requestToken.TokenSecret,
                Verifier       = verifier
            };

            var request  = _accessTokenQuery.Invoke(args);
            var response = _oauth.Request(request);

            SetResponse(response);

            var query       = HttpUtility.ParseQueryString(response.Content);
            var accessToken = new OAuthAccessToken
            {
                Token       = query["oauth_token"] ?? "?",
                TokenSecret = query["oauth_token_secret"] ?? "?",
                UserId      = Convert.ToInt64(query["user_id"] ?? "0"),
                ScreenName  = query["screen_name"] ?? "?"
            };

            return(accessToken);
        }
        public virtual OAuthAccessToken GetAccessTokenWithXAuth(string username, string password)
        {
            var args = new FunctionArguments
            {
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret,
                Username       = username,
                Password       = password
            };

            var request  = _xAuthQuery.Invoke(args);
            var response = _oauth.Request(request);

            SetResponse(response);

            var query       = HttpUtility.ParseQueryString(response.Content);
            var accessToken = new OAuthAccessToken
            {
                Token       = query["oauth_token"] ?? "?",
                TokenSecret = query["oauth_token_secret"] ?? "?",
                UserId      = Convert.ToInt64(query["user_id"] ?? "0"),
                ScreenName  = query["screen_name"] ?? "?"
            };

            return(accessToken);
        }
Exemplo n.º 6
0
        public Tweeter()
        {
            var _consumerKey = "J9iaXHK7R0bpKiRabxQ";
            var _consumerSecret = "Xs6XJggEvXtMVDvaYAvTLnIm13G70ymcdhwQ3J1M";

            // this authentication snippet borrowed from https://github.com/danielcrenna/tweetsharp

            service = new TwitterService(_consumerKey, _consumerSecret);

            // Step 1 - Retrieve an OAuth Request Token
            OAuthRequestToken requestToken = service.GetRequestToken();

            // Step 2 - Redirect to the OAuth Authorization URL
            // Uri uri = service.GetAuthorizationUri(requestToken);
            // Process.Start(uri.ToString());

            // Step 3 - Exchange the Request Token for an Access Token

            // OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);
            // OAuthAccessToken generated manually through dev.twitter.com so no need for this bit since it's just me tweetin ma shit

            var access = new OAuthAccessToken();
            access.Token = "1196853272-YbSEB0Mnaj6lK3tOKGQ8nwOVLnfhXldwqjlzNmk";
            access.TokenSecret = "4BHhe3iUdlh6o2Re0OmMq3v6e8OwH9vw149MEPR3I";

            // Step 4 - User authenticates using the Access Token
            service.AuthenticateWith(access.Token, access.TokenSecret);
            // service.SendTweet(new SendTweetOptions { Status = "Hello World" });
        }
Exemplo n.º 7
0
 /// <summary>
 /// 認証情報を保存する
 /// </summary>
 /// <param name="token"></param>
 public static void AuthInfoSet(OAuthAccessToken token)
 {
     using (System.IO.StreamWriter sw = new System.IO.StreamWriter("Auth.txt", false))
     {
         sw.WriteLine(token.Token);
         sw.WriteLine(token.TokenSecret);
     }
 }
Exemplo n.º 8
0
        public static OAuthAccessToken getOAuthTokens(AccountTwitter account)
        {
            OAuthAccessToken tokens = new TweetSharp.OAuthAccessToken();

            tokens.Token       = account.Token;
            tokens.TokenSecret = account.TokenSecret;

            return(tokens);
        }
Exemplo n.º 9
0
 /// <summary>
 /// OAuthで認証します。
 /// トークンを取得していない場合、
 /// GetRequestURLなどを用いて取得できます。
 /// </summary>
 /// <param name="at">OAuthAccessToken</param>
 public Task AuthenticateAsync(OAuthAccessToken at)
 {
     return Task.Run(() =>
     {
         UserToken = at.Token;
         UserTokenSecret = at.TokenSecret;
         Service.AuthenticateWith(at.Token, at.TokenSecret);
     });
 }
        public GetTweetResponse GetTweetsMentioningMe(OAuthAccessToken access)
        {
            _twitterService.AuthenticateWith(access.Token, access.TokenSecret);

            IEnumerable<TwitterStatus> tweets = _twitterService.ListTweetsMentioningMe();

            TweeterStatusAdapter adapter = new TweeterStatusAdapter();

            return new GetTweetResponse { TweeterStatuses = adapter.Convert(tweets) };
        }
        public GetTweetResponse GetTweets(OAuthAccessToken access)
        {
            _twitterService.AuthenticateWith(access.Token, access.TokenSecret);

            IEnumerable<TwitterStatus> tweets = _twitterService.ListTweetsOnHomeTimeline(INITIAL_TWEETS_COUNT);

            TweeterStatusAdapter adapter = new TweeterStatusAdapter();

            return new GetTweetResponse { TweeterStatuses = adapter.Convert(tweets) };
        }
Exemplo n.º 12
0
        public void AuthTwitter2(string strPin)
        {
            // Step 3 - Exchange the Request Token for an Access Token
            string verifier = strPin; // <-- This is input into your application by your user
            _accessToken = service.GetAccessToken(requestToken, verifier);

            // Step 4 - User authenticates using the Access Token
            service.AuthenticateWith(_accessToken.Token, _accessToken.TokenSecret);
            IEnumerable<TwitterStatus> mentions = service.ListTweetsMentioningMe();
        }
Exemplo n.º 13
0
 private void authTwitter(TwitterService twitterService)
 {
     string authUri = twitterService.GetAuthenticationUrl(requestToken).ToString();
     System.Diagnostics.Process.Start(authUri.ToString());
     SettingsManager SM = new SettingsManager();
     SM.ShowDialog();
     pin = SM.twitterPIN;
     oAccessToken = twitterService.GetAccessToken(requestToken, pin);
     AdvancedSoftwareProject.Properties.Settings.Default.AccessToken = oAccessToken.Token;
     AdvancedSoftwareProject.Properties.Settings.Default.AccessTokenSecret = oAccessToken.TokenSecret;
     AdvancedSoftwareProject.Properties.Settings.Default.Save();
     twitterService.AuthenticateWith(AdvancedSoftwareProject.Properties.Settings.Default.AccessToken, AdvancedSoftwareProject.Properties.Settings.Default.AccessTokenSecret);
 }
Exemplo n.º 14
0
 private void HandleAuthenticationAccessToken(OAuthAccessToken token, TwitterResponse response)
 {
     _accessToken = token;
     settings["twitter_screenname"] = _accessToken.ScreenName;
     settings["twitter_token"] = _accessToken.Token;
     settings["twitter_tokensecret"] = _accessToken.TokenSecret;
     settings["twitter_chk"] = "1";
     settings.Save();
     Dispatcher.BeginInvoke(delegate()
     {
         success();
     });
 }
        public virtual void GetAccessToken(OAuthRequestToken requestToken, string verifier, Action <OAuthAccessToken, TwitterResponse> action)
        {
            var args = new FunctionArguments
            {
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret,
                Token          = requestToken.Token,
                TokenSecret    = requestToken.TokenSecret,
                Verifier       = verifier
            };

            var request = _accessTokenQuery.Invoke(args);

            _oauth.BeginRequest(request, (req, resp, state) =>
            {
                Exception exception;
                var entity = TryAsyncResponse(() =>
                {
                    if (resp == null || resp.StatusCode != HttpStatusCode.OK)
                    {
                        return(null);
                    }

#if WINRT
                    var query       = new Windows.Foundation.WwwFormUrlDecoder(resp.Content);
                    var accessToken = new OAuthAccessToken
                    {
                        Token       = query.GetFirstValueByName("oauth_token") ?? "?",
                        TokenSecret = query.GetFirstValueByName("oauth_token_secret") ?? "?",
                        UserId      = Convert.ToInt64(query.GetFirstValueByName("user_id") ?? "0"),
                        ScreenName  = query.GetFirstValueByName("screen_name") ?? "?"
                    };
#else
                    var query       = HttpUtility.ParseQueryString(resp.Content);
                    var accessToken = new OAuthAccessToken
                    {
                        Token       = query["oauth_token"] ?? "?",
                        TokenSecret = query["oauth_token_secret"] ?? "?",
                        UserId      = Convert.ToInt64(query["user_id"] ?? "0"),
                        ScreenName  = query["screen_name"] ?? "?"
                    };
#endif
                    return(accessToken);
                },
                                              out exception);

                action(entity, new TwitterResponse(resp, exception));
            }
                                );
        }
Exemplo n.º 16
0
        public virtual void GetAccessToken(OAuthRequestToken requestToken, string?verifier, Action <OAuthAccessToken?, TwitterResponse> action)
        {
            if (_consumerKey == null || _consumerSecret == null || requestToken.TokenSecret == null)
            {
                throw new InvalidOperationException("_consumerKey == null || _consumerSecret == null || requestToken.TokenSecret == null");
            }
            var args = new FunctionArguments
                       (
                _consumerKey,
                _consumerSecret,
                requestToken.Token,
                requestToken.TokenSecret,
                verifier
                       );

            var request = _accessTokenQuery.Invoke(args);

            _oauth.BeginRequest(request, (req, resp, state) =>
            {
                Exception?exception;
                var entity = TryAsyncResponse(() =>
                {
                    if (resp == null || resp.StatusCode != HttpStatusCode.OK)
                    {
                        return(null);
                    }

                    var query       = OAuthWorkflow.ParseQuery(resp.Content);
                    var accessToken = new OAuthAccessToken
                                      (
                        query["oauth_token"] ?? "?",
                        query["oauth_token_secret"] ?? "?",
                        Convert.ToInt64(query["user_id"] ?? "0"),
                        query["screen_name"] ?? "?"
                                      );
                    return(accessToken);
                },
                                              out exception);

                action(entity, new TwitterResponse(resp, exception));
            }
                                );
        }
Exemplo n.º 17
0
		private void workerAddAccount_DoWork(Object sender, DoWorkEventArgs e)
		{
			accessToken = e.Argument as OAuthAccessToken;

			if (accessToken == null)
			{
				e.Result = null;
				return;
			}

			try
			{
				TwitterManager.Service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
				e.Result = TwitterManager.Service.GetUserProfile(new GetUserProfileOptions { });
			}
			catch
			{
				e.Result = null;
			}
		}
Exemplo n.º 18
0
        public TwitterViewModel()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                try
                {
                    AccessToken = IsolatedStorageSettings.ApplicationSettings["AccessToken"] as OAuthAccessToken;
                    TwitterUsername = IsolatedStorageSettings.ApplicationSettings["TwitterUsername"] as string;
                    TwitterPassword = IsolatedStorageSettings.ApplicationSettings["TwitterPassword"] as string;

                    SelectedPushpin = IsolatedStorageSettings.ApplicationSettings["SelectedPushpin"] as PushpinModel;
                    //We create the summary if it doesn't exist only when when authentication against ODAF website has been established
                    CommentService.Authenticated += (sender, e) =>
                        {
                            CommentService.CreateSummaryAsync(SelectedPushpin);
                        };
                    CommentService.SummaryCreated += (sender, e) =>
                        {
                            SummaryHasBeenCreated = true;
                        };
                    CommentService.AuthenticateAsync(AccessToken.Token, AccessToken.TokenSecret);

                    if (AccessToken == null || TwitterUsername == null || TwitterPassword == null)
                    {
                        throw new KeyNotFoundException();
                    }
                    Twitter.AuthenticateWith(AccessToken.Token, AccessToken.TokenSecret);
                    HasUserAlreadyAuthorizedApp = true;
                }
                catch (KeyNotFoundException)
                {
                    HasUserAlreadyAuthorizedApp = false;
                    GetRequestToken();
                }
            }

            _AuthenticateUserCommand = new DelegateCommand(AuthenticateUser, (obj) => true);
            _SendTweetCommand = new DelegateCommand(SendTweet, CanSendTweet);
            _ResetTwitterCredentialsCommand = new DelegateCommand(ResetTwitterCredentials, (obj) => true);
            _TakePhotoCommand = new DelegateCommand(TakePhoto, (obj) => HasUserAlreadyAuthorizedApp);
        }
Exemplo n.º 19
0
 private void button2_Click(object sender, EventArgs e)
 {
     try
     {
         // Step 3 - Exchange the Request Token for an Access Token
         string verifier = textBox2.Text; // <-- This is input into your application by your user
         access = service.GetAccessToken(requestToken, verifier);
         if (access.Token == "?")
         {
             MessageBox.Show("入力された暗証番号は正しくありません", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
             this.DialogResult = DialogResult.Abort;
             this.Close();
             return;
         }
         this.DialogResult = DialogResult.OK;
         this.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString(), "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 20
0
        public virtual void GetAccessToken(OAuthRequestToken requestToken, string verifier, Action <OAuthAccessToken, TwitterResponse> action)
        {
            var args = new FunctionArguments
            {
                ConsumerKey    = _consumerKey,
                ConsumerSecret = _consumerSecret,
                Token          = requestToken.Token,
                TokenSecret    = requestToken.TokenSecret,
                Verifier       = verifier
            };

            var request = _accessTokenQuery.Invoke(args);

            _oauth.BeginRequest(request, (req, resp, state) =>
            {
                Exception exception;
                var entity = TryAsyncResponse(() =>
                {
                    if (resp == null || resp.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        return(null);
                    }

                    var query       = HttpUtility.ParseQueryString(resp.Content);
                    var accessToken = new OAuthAccessToken
                    {
                        Token       = query["oauth_token"] ?? "?",
                        TokenSecret = query["oauth_token_secret"] ?? "?",
                        UserId      = Convert.ToInt32(query["user_id"] ?? "0"),
                        ScreenName  = query["screen_name"] ?? "?"
                    };
                    return(accessToken);
                },
                                              out exception);

                action(entity, new TwitterResponse(resp, exception));
            }
                                );
        }
        public void GetTweetsMentioningMe_ShouldReturnTweetsWithMentions()
        {
            List<TwitterStatus> twitterStatuses = Builder<TwitterStatus>
                .CreateListOfSize(2)
                .WhereAll()
                .Have(ts => ts.User = Builder<TwitterUser>.CreateNew().Build())
                .Build()
                .ToList();

            OAuthAccessToken accessToken = new OAuthAccessToken { Token = "abcd", TokenSecret = "A@c#" };

            Mock.Get(_mockTwitterService).Setup(mockService => mockService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret));

            Mock.Get(_mockTwitterService).Setup(mockService => mockService.ListTweetsMentioningMe()).Returns(
                twitterStatuses);

            GetTweetResponse response = _authenticationService.GetTweetsMentioningMe(accessToken);

            Mock.Get(_mockTwitterService).VerifyAll();

            Assert.IsNotNull(response);
            Assert.AreEqual(2, response.TweeterStatuses.Count());
        }
Exemplo n.º 22
0
        /// <summary>
        /// Twitterクライアント部分
        /// </summary>
        /// <param name="inputer">
        /// pinコード認証を行う場合にurlを引数にpinコードを返すProc.
        /// tokenが保存されている場合は使わない.
        /// 大抵はユーザに入力してもらう.
        /// Process.Startで表示してコンソールかダイアログで入力がベター.
        /// </param>
        public Twitter(Func<string, string> inputer)
        {
            this.inputer = inputer;

            // load consumer key
            var cf = Config.instance;
            service = new TwitterService(cf.c_key, cf.c_secret);

            // serviceのinstanceにProxyを設定しても適用されないため,強引に(App内部の)標準設定を書き換える.
            System.Net.WebRequest.DefaultWebProxy = cf.proxy;

            // load access token
            if (File.Exists(tokenFile))
            {
                var token = YamlNode.FromYamlFile(tokenFile).topSeq();
                access = new OAuthAccessToken
                {
                    Token = token[0].getString(),
                    TokenSecret = token[1].getString()
                };
                auth();
            }
            else Authorize();
        }
Exemplo n.º 23
0
        public OAuthAccessToken GetUser()
        {
            if (DefaultExists())
            {
                foreach (Profile user in profiles)
                {
                    if (user.Active)
                    {
                        OAuthAccessToken token = new OAuthAccessToken();
                        token.Token = user.UserKey;
                        token.TokenSecret = user.UserSecret;
                        token.ScreenName = user.Name;
                        WriteFile();

                        return token;
                    }
                }
                return null;
            }
            else
            {
                profiles[0].Default = true;
                profiles[0].Active = true;
                OAuthAccessToken token = new OAuthAccessToken();
                token.Token = profiles[0].UserKey;
                token.TokenSecret = profiles[0].UserSecret;
                token.ScreenName = profiles[0].Name;

                return token;
            }
        }
        void CallBackVerifiedResponse(OAuthAccessToken at, TwitterResponse response)
        {
            if (at != null)
            {



                IsolatedSettingsHelper.SetValue<string>("ttoken", at.Token);
                IsolatedSettingsHelper.SetValue<string>("ttokensec", at.TokenSecret);

                try
                {

                    Dispatcher.BeginInvoke(() =>
                    {
                        //////////////////////////
                        OAuthCredentials credentials = new OAuthCredentials();

                        credentials.Type = OAuthType.ProtectedResource;
                        credentials.SignatureMethod = OAuthSignatureMethod.HmacSha1;
                        credentials.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader;
                        credentials.ConsumerKey = TwitterSettings.ConsumerKey;
                        credentials.ConsumerSecret = TwitterSettings.ConsumerKeySecret;

                        credentials.Token = at.Token;
                        credentials.TokenSecret = at.TokenSecret;
                        credentials.Version = "1.1";
                        //credentials.ClientUsername = "";
                        credentials.CallbackUrl = "none";

                        var service = new TwitterService(TwitterSettings.ConsumerKey, TwitterSettings.ConsumerKeySecret);

                        service.AuthenticateWith(at.Token, at.TokenSecret);

                        SendTweetOptions st = new SendTweetOptions();
                        st.Status = "post";
                        service.SendTweet(new SendTweetOptions { Status = post }, CallBackVerifiedResponse1);

                        ///////////////////////////////
                    });
                }
                catch
                {
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("An error occurred,please try again.");
                        return;
                    });

                }



            }
            else
            {
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Wrong pin please try again", "Error", MessageBoxButton.OK);
                    GetTwitterToken();
                });
            }
        }
        private void saveAccessToken(OAuthAccessToken token)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("accessToken"))
                IsolatedStorageSettings.ApplicationSettings["accessToken"] = token;
            else
                IsolatedStorageSettings.ApplicationSettings.Add("accessToken", token);

            IsolatedStorageSettings.ApplicationSettings.Save();
        }
Exemplo n.º 26
0
 public bool AuthenticateWith(string verifier)
 {
     try
     {
         _accessToken = _service.GetAccessToken(_requestToken, verifier);
         _service.AuthenticateWith(_accessToken.Token, _accessToken.TokenSecret);
         return true;
     }
     catch
     {
         IsInitialized = false;
         return false;
     }
 }
        public void GetTweetsSince_ShouldReturnTweetsSinceTweetId()
        {
            List<TwitterStatus> twitterStatuses = Builder<TwitterStatus>
                .CreateListOfSize(2)
                .WhereAll()
                .Have(ts => ts.User = Builder<TwitterUser>.CreateNew().Build())
                .Build()
                .ToList();

            OAuthAccessToken accessToken = new OAuthAccessToken { Token = "abcd", TokenSecret = "A@c#" };

            Mock.Get(_mockTwitterService).Setup(mockService => mockService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret));

            Mock.Get(_mockTwitterService).Setup(mockService => mockService.ListTweetsOnHomeTimelineSince(100)).Returns(
                twitterStatuses);

            GetTweetsRequest getTweetsRequest = new GetTweetsRequest { AccessToken = accessToken, LastTweetId = 100 };
            GetTweetResponse response = _authenticationService.GetTweetsSince(getTweetsRequest);

            Mock.Get(_mockTwitterService).VerifyAll();

            Assert.IsNotNull(response);
            Assert.AreEqual(2, response.TweeterStatuses.Count());
        }
Exemplo n.º 28
0
        public virtual OAuthAccessToken GetAccessTokenWithXAuth(string username, string password)
        {
            var args = new FunctionArguments
            {
                ConsumerKey = _consumerKey,
                ConsumerSecret = _consumerSecret,
                Username = username,
                Password = password
            };

            var request = _xAuthQuery.Invoke(args);
            var response = _oauth.Request(request);

            SetResponse(response);

            var query = HttpUtility.ParseQueryString(response.Content);
            var accessToken = new OAuthAccessToken
            {
                Token = query["oauth_token"] ?? "?",
                TokenSecret = query["oauth_token_secret"] ?? "?",
                UserId = Convert.ToInt32(query["user_id"] ?? "0"),
                ScreenName = query["screen_name"] ?? "?"
            };

            return accessToken;
        }
Exemplo n.º 29
0
        public virtual void GetAccessToken(OAuthRequestToken requestToken, string verifier, Action<OAuthAccessToken, TwitterResponse> action)
        {
            var args = new FunctionArguments
            {
                ConsumerKey = _consumerKey,
                ConsumerSecret = _consumerSecret,
                Token = requestToken.Token,
                TokenSecret = requestToken.TokenSecret,
                Verifier = verifier
            };

            var request = _accessTokenQuery.Invoke(args);

           _oauth.BeginRequest(request, (req, resp, state) =>
                               {
                                   Exception exception;
                                   var entity = TryAsyncResponse(() =>
                                   {
                                        if (resp == null || resp.StatusCode != HttpStatusCode.OK)
                                        {
                                            return null;
                                        }

                                       var query = HttpUtility.ParseQueryString(resp.Content);
                                       var accessToken = new OAuthAccessToken
                                       {
                                           Token = query["oauth_token"] ?? "?",
                                           TokenSecret = query["oauth_token_secret"] ?? "?",
                                           UserId = Convert.ToInt32(query["user_id"] ?? "0"),
                                           ScreenName = query["screen_name"] ?? "?"
                                       };
                                       return accessToken;
                                   },
                                   out exception);

                                   action(entity, new TwitterResponse(resp, exception));
                               }
               );
        }
Exemplo n.º 30
0
        public void AddProfile()
        {
            ScreenDraw.Tweets.Clear();
            ScreenDraw.Tweets.Refresh();

            OAuthAccessToken userKey = new OAuthAccessToken();
            OAuthRequestToken requestToken = User.Account.GetRequestToken();
            Window auth = new Window(1, ScreenInfo.WindowWidth, 3, 0);
            Uri uri = User.Account.GetAuthorizationUri(requestToken);
            Process.Start(uri.ToString());

            Curses.Echo = true;

            auth.Add("Please input the authentication number: ");
            auth.Refresh();
            string verifier = auth.GetString(7);

            userKey = User.Account.GetAccessToken(requestToken, verifier);
            Profile newProfile = new Profile();

            newProfile.Name = userKey.ScreenName;
            newProfile.UserKey = userKey.Token;
            newProfile.UserSecret = userKey.TokenSecret;

            if (ProfileExists(newProfile))
            {
                ScreenDraw.ShowMessage("User already exists in the list");
            }
            else
            {
                profiles.Add(newProfile);
                WriteFile();
                ScreenDraw.ShowMessage("User added");
            }
            Curses.Echo = false;
            auth.Dispose();

            ScreenDraw draw = new ScreenDraw();
            draw.ShowTimeline();
        }
 private void saveAccessToken(OAuthAccessToken token)
 {
 }
Exemplo n.º 32
0
        /// <summary>
        /// This method permits to store the OAuthRequestToken
        /// </summary>
        private void GetRequestToken()
        {
            RequestToken = new OAuthRequestToken();
            AccessToken = new OAuthAccessToken();

            Twitter.GetRequestToken((request, Response) =>
            {
                if (Response.StatusCode == HttpStatusCode.OK)
                {
                    RequestToken = request;
                    Uri uri = Twitter.GetAuthorizationUri(RequestToken);
                    TwitterAuthorizationUri = uri;
                }
            });
        }
Exemplo n.º 33
0
 /// <summary>
 /// This method permits to store the user OAuthAccessToken, and also his username and password to access Twitpic API.
 /// </summary>
 private void AuthenticateUser(object obj)
 {
     Twitter.GetAccessToken(RequestToken, TwitterCodePin, (access, Response) =>
     {
         if (Response.StatusCode == HttpStatusCode.OK)
         {
             AccessToken = access; // Store it for reuse
             Twitter.AuthenticateWith(access.Token, access.TokenSecret);
             IsolatedStorageSettings.ApplicationSettings["AccessToken"] = AccessToken;
             IsolatedStorageSettings.ApplicationSettings["TwitterUsername"] = TwitterUsername;
             IsolatedStorageSettings.ApplicationSettings["TwitterPassword"] = TwitterPassword;
             Deployment.Current.Dispatcher.BeginInvoke(() =>
             {
                 HasUserAlreadyAuthorizedApp = true;
             });
         }
     });
 }
Exemplo n.º 34
0
 private TwitterProxy(string accessToken, string secretToken)
     : this()
 {
     _accessToken = new OAuthAccessToken {Token = accessToken, TokenSecret = secretToken};
 }
Exemplo n.º 35
0
        public virtual OAuthAccessToken GetAccessToken(OAuthRequestToken requestToken, string verifier)
        {
            var args = new FunctionArguments
            {
                ConsumerKey = _consumerKey,
                ConsumerSecret = _consumerSecret,
                Token = requestToken.Token,
                TokenSecret = requestToken.TokenSecret,
                Verifier = verifier
            };

            var request = _accessTokenQuery.Invoke(args);
            var response = _oauth.Request(request);

            SetResponse(response);

            var query = HttpUtility.ParseQueryString(response.Content);
            var accessToken = new OAuthAccessToken
                        {
                            Token = query["oauth_token"] ?? "?",
                            TokenSecret = query["oauth_token_secret"] ?? "?",
                            UserId = Convert.ToInt32(query["user_id"] ?? "0"),
                            ScreenName = query["screen_name"] ?? "?"
                        };

            return accessToken;
        }
Exemplo n.º 36
0
        /// <summary>
        /// Creates a user using OAuth
        /// </summary>
        private void CreateUser()
        {
            OAuthAccessToken userKey = new OAuthAccessToken();
            Profile defaultProfile = new Profile();
            TwitterService service = new TwitterService(appKey.Token, appKey.TokenSecret);
            OAuthRequestToken requestToken = service.GetRequestToken();
            Uri uri = service.GetAuthorizationUri(requestToken);
            Process.Start(uri.ToString());
            service.AuthenticateWith(appKey.Token, appKey.TokenSecret);

            Window auth = new Window(1, ScreenInfo.WindowWidth, 0, 0);
            Curses.Echo = true;
            auth.Add("Please input the authentication number: ");
            auth.Refresh();
            string verifier = auth.GetString(7);
            userKey = service.GetAccessToken(requestToken, verifier);
            defaultProfile.Active = true;
            defaultProfile.Default = true;
            defaultProfile.UserKey = userKey.Token;
            defaultProfile.UserSecret = userKey.TokenSecret;
            defaultProfile.Name = userKey.ScreenName;

            profiles.Add(defaultProfile);
            Curses.Echo = false;
            auth.Dispose();
            WriteFile();
        }
 private void userLoggedIn()
 {
     Dispatcher.BeginInvoke(() =>
     {
         VisibileControl(true);
         OAuthAccessToken token = new OAuthAccessToken();
         token.Token = ObjCommon.Twittertoken;
     });
 }
        void CallBackVerifiedResponse(OAuthAccessToken atoken, TwitterResponse response)
        {
            if (atoken != null)
            {

                //authorization complete - access tokens are now available
                dispatchme.BeginInvoke(() => MessageBox.Show("Authentication completed!"));
                //store the AccessToken and AccessTokenSecret in local static variables
                TwitterVariables.AccessToken = atoken.Token;
                TwitterVariables.AccessTokenSecret = atoken.TokenSecret;
                //to proceed, first we must authenticate with AccessToken and AccessTokenSecret
                service.AuthenticateWith(TwitterVariables.AccessToken, TwitterVariables.AccessTokenSecret);
                //Now we are ready to post a tweet

                //Important:
                //store the access token and Access Token Secret permanently in Isolated storage
                //so that user can avoid authenticating everytime he opens your application

            }
        }