public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary<string, string> @params)
        {
            var twitterService = new TwitterService(KeyStorage.Get("twitterKey"), KeyStorage.Get("twitterSecret"));

            if (String.IsNullOrEmpty(context.Request["oauth_token"]) ||
                String.IsNullOrEmpty(context.Request["oauth_verifier"]))
            {
                var requestToken = twitterService.GetRequestToken(context.Request.Url.AbsoluteUri);

                var uri = twitterService.GetAuthorizationUri(requestToken);

                context.Response.Redirect(uri.ToString(), true);
            }
            else
            {
                var requestToken = new OAuthRequestToken { Token = context.Request["oauth_token"] };
                var accessToken = twitterService.GetAccessToken(requestToken, context.Request["oauth_verifier"]);
                twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);

                var user = twitterService.VerifyCredentials(new VerifyCredentialsOptions());

                return ProfileFromTwitter(user);
            }

            return new LoginProfile();

        }
Esempio n. 2
0
 public TwitterUser GetUser(LoginModel model)
 {
     var twitterService = new TweetSharp.TwitterService(ConsumerKey, ConsumerSecret);
     twitterService.AuthenticateWith(model.Token, model.Secret);
     TwitterUser user = twitterService.VerifyCredentials(new VerifyCredentialsOptions() { IncludeEntities = false, SkipStatus = false });
     return user;
 }
Esempio n. 3
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" });
        }
Esempio n. 4
0
        public IQueryable<DisplayItem> GetSocialInfomation(string name)
        {
            IQueryable<DisplayItem> items = null;

            try
            {
                var twitterClientInfo = new TwitterClientInfo();
                twitterClientInfo.ConsumerKey = SettingsHelper.ConsumerKey;
                twitterClientInfo.ConsumerSecret = SettingsHelper.ConsumerSecret;

                var twitterService = new TwitterService(twitterClientInfo);
                twitterService.AuthenticateWith(SettingsHelper.AccessToken, SettingsHelper.AccessSecret);
                var searchOptions = new SearchOptions
                {
                    Q = name,
                };

                var searchResults = twitterService.Search(searchOptions);
                items = searchResults.Statuses.Select(x => ConvertToDataItem(x)).AsQueryable();
            }
            catch(Exception ex)
            {
                Logger.Error(ex);
            }

            return items;
        }
Esempio n. 5
0
        public static void SendTweet()
        {
            GetPixelImageFile();

            string key         = ConfigurationSettings.AppSettings.Get("twitterConsumerKey");
            string secret      = ConfigurationSettings.AppSettings.Get("twitterConsumerSecret");
            string token       = ConfigurationSettings.AppSettings.Get("twitterAccessToken");
            string tokenSecret = ConfigurationSettings.AppSettings.Get("twitterAccessTokenSecret");

            string message = "";


            var service = new TweetSharp.TwitterService(key, secret);

            service.AuthenticateWith(token, tokenSecret);
            using (var stream = new FileStream(@"C:\Images\Pixel.png", FileMode.Open))
            {
                var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions
                {
                    Status = message,
                    Images = new Dictionary <string, Stream> {
                        { "john", stream }
                    }
                });
            }
        }
        public TweetViewModel(ITweetTimer tweetTimer, TwitterService service)
        {
            this.tweetTimer = tweetTimer;
            this.service = service;

            Tweets = new BindableCollection<Tweet>();
        }
Esempio n. 7
0
        public BritBoxingTwitterInfo(Cache cache, TwitterService service)
        {
            _cache = cache;
            _service = service;

            UpdateContent();
        }
Esempio n. 8
0
        public static void GetUserToken(TwitterService service)
        {
            // Step 1 - Retrieve an OAuth Request Token
            OAuthRequestToken requestToken = service.GetRequestToken();

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

            Console.WriteLine("Enter this uri into a browser:\n{0}", uri.ToString());

            Console.WriteLine("Enter the pin given by twitter");

            // Step 3 - Exchange the Request Token for an Access Token
            string verifier = Console.ReadLine(); // <-- This is input into your application by your user
            OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);

            if(access == null)
            {
                Console.WriteLine("no tokens returned");
                return;
            }

            Console.WriteLine("Access Token:\n{0}", access.Token);
            Console.WriteLine("Access Secret:\n{0}", access.TokenSecret);

            // Step 4 - User authenticates using the Access Token
            service.AuthenticateWith(access.Token, access.TokenSecret);
        }
        // This URL is registered as the application's callback at http://dev.twitter.com
        public ActionResult ReturnFromTwitter(string oauth_token, string oauth_verifier)
        {
            var requestToken = new OAuthRequestToken { Token = oauth_token };

            // Step 3 - Exchange the Request Token for an Access Token
            string _consumerKey = System.Configuration.ConfigurationManager.AppSettings["consumerKeyLogin"];
            string _consumerSecret = System.Configuration.ConfigurationManager.AppSettings["consumerSecretLogin"];
            TwitterService service = new TwitterService(_consumerKey, _consumerSecret);
            OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier);

            string TwitterToken = accessToken.Token;
            string TwitterToeknSecret = accessToken.TokenSecret;
            Session[Sessionvars.TwitterRequestToken] = TwitterToken;  //You can save this token in your database for pulling user's data in future. this will be save every time while getting permission
            Session[Sessionvars.TwitterRequestTokenSecert] = TwitterToeknSecret; //You can save this token in your database for pulling user's data in future. this will be save every time while getting permission
            ViewBag.TwitterToken = accessToken.Token;

            // Step 4 - User authenticates using the Access Token

            //service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
            //TwitterUser user = service.VerifyCredentials();
            //var status = user.Status;
            //ViewBag.status = status;
            //ViewBag.UserName = user.Name;
            //ViewBag.location = user.Location;
            //ViewBag.count = user.FollowersCount;

            //TwitterDirectMessage Ds = service.SendDirectMessage(user.Id, "hi this test messages");
            //service.SendTweet("hi this is test from me at live");
            //service.SendTweet("msg", user.Id);
            //ViewBag.Userid = service.BeginFollowUserNotifications(user.Id);

            return RedirectToAction("Invite");
        }
Esempio n. 10
0
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            if (img_bool == true && twit_pic == "")
            {
                MessageBox.Show("Image upload in progress. please wait.", "Sorry", MessageBoxButton.OK);
                return;
            }

            if (WatermarkTB.Text == emptystr)
            {
                MessageBox.Show("Please input your mind :)", "Sorry", MessageBoxButton.OK);
                return;
            }

            TwitterService service = new TwitterService("g8F2KdKH40gGp9BXemw13Q", "OyFRFsI05agcJtURtLv8lpYbYRwZAIL5gr5xQNPW0Q");
            service.AuthenticateWith((string)settings["twitter_token"], (string)settings["twitter_tokensecret"]);
            string tweet = WatermarkTB.Text;
            if (img_bool == true)
                tweet += " " + twit_pic;

            service.SendTweet(tweet,
                (tweets, response) =>
                {

                });
            MessageBox.Show("Share successfully.", "Thanks", MessageBoxButton.OK);
            this.NavigationService.GoBack();
        }
Esempio n. 11
0
 public void SetupTwitterClient()
 {
     TwitterClientInfo twitterClient = new TwitterClientInfo();
     twitterClient.ConsumerKey = "4FTAZV9NXphr04Stq9yIpQ";
     twitterClient.ConsumerSecret = "ZJ5yGtPrOcxsZQzsajnf8G8hDaP8QAwlRfEM0HUqHcc";
     twitterService = new TwitterService(twitterClient);
 }
Esempio n. 12
0
        static void Main(string[] args)
        {
            var _consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"].ToString();
            var _consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"].ToString();

            // configure access token
            //var _accessToken = ConfigurationManager.AppSettings["twitterAccess"].ToString();
            //var _accessTokenSecret = ConfigurationManager.AppSettings["twitterAccessSecret"].ToString();

            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
            string verifier = "123456"; // <-- This is input into your application by your user
            OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);

            // Step 4 - User authenticates using the Access Token
            service.AuthenticateWith(access.Token, access.TokenSecret);

            //service.AuthenticateWith(_accessToken, _accessTokenSecret);

            //SendATweet();
            //GeoLocationLookup();
            ListFollowers();

            Console.ReadKey();
        }
Esempio n. 13
0
        public static void Main(string[] args)
        {
            var service = new TwitterService(consumerKey, consumerSecret);

            //			GetUserToken(service);
            ListenOnUserStream(service);
        }
Esempio n. 14
0
        public static IReadOnlyCollection<PoliticalTweet> LoadTweets( IEnumerable<string> handles )
        {
            var service = new TwitterService( ConsumerKey, ConsumerSecret );
            service.AuthenticateWith( AccessToken, AccessTokenSecret );
            var results = new List<PoliticalTweet>();

            foreach ( var handle in handles.Distinct() )
            {
                try
                {
                    var response = service.ListTweetsOnUserTimeline( new ListTweetsOnUserTimelineOptions
                    {
                        ScreenName = handle,
                        Count = 200,
                        IncludeRts = false,
                        ExcludeReplies = true
                    } );
                    results.AddRange( response.Select( t => new PoliticalTweet( handle, t.Text, t.CreatedDate, t.IdStr ) ) );

                    Debug.WriteLine( $"{service.Response.RateLimitStatus.RemainingHits} remaining hits." );
                    if ( service.Response.RateLimitStatus.RemainingHits <= 0 )
                    {
                        var wait = service.Response.RateLimitStatus.ResetTime.ToUniversalTime() - DateTime.UtcNow;
                        Debug.WriteLine( $"Rate limit reached. Sleeping for {wait}." );
                        Thread.Sleep( wait );
                    }
                }
                catch
                {
                    Debug.WriteLine( $"Skipping {handle}" );
                }
            }

            return results;
        }
        public List<TwitterFollower> getTwitterFollowerList()
        {
            List<TwitterFollower> twitterFollowerList = new List<TwitterFollower>();

            string _consumerKey = System.Configuration.ConfigurationManager.AppSettings["consumerKeyLogin"];
            string _consumerSecret = System.Configuration.ConfigurationManager.AppSettings["consumerSecretLogin"];
            TwitterService service = new TwitterService(_consumerKey, _consumerSecret);

            if (!string.IsNullOrEmpty(Session[Sessionvars.TwitterRequestToken].ToString()))
            {

                service.AuthenticateWith(Session[Sessionvars.TwitterRequestToken].ToString(), Session[Sessionvars.TwitterRequestTokenSecert].ToString());

                TwitterUser user = service.VerifyCredentials();
                var followers = service.ListFollowers();

                foreach (var follower in followers)
                {
                    twitterFollowerList.Add(
                   new TwitterFollower
                   {
                       Id = follower.Id,
                       ScreenName = follower.ScreenName
                   });
                }

            }

            return twitterFollowerList;
        }
Esempio n. 16
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            TwitterService service = new TwitterService(consumerKeyTextBox.Text, consumerSecretTextBox.Text, accessTokenTextBox.Text, accessTokenSecretTextBox.Text);

            TwitterUser user = service.VerifyCredentials();

            if (service.Response.InnerException != null)
            {
                TwitterError error = service.Deserialize<TwitterError>(service.Response.Response);
                if (!string.IsNullOrEmpty(error.ErrorMessage))
                {
                    e.Result = error; // return the error object on failure
                }
                else
                {
                    e.Result = null; // err, dunno. return null
                }
            }
            else if (user != null)
            {
                e.Result = user; // return user object on success
            }
            else
            {
                e.Result = null; // unknown error
            }
        }
Esempio n. 17
0
 public ExListWindow(MainWindow mw)
 {
     InitializeComponent();
     main = mw;
     svc = main.Service;
     me = main.CurrentUser;
 }
Esempio n. 18
0
 public Twitter(String consumerKey, String consumerSecret)
 {
     this.isAuthed = false;
     _TwitterService = new TwitterService(consumerKey, consumerSecret);
     this.ConsumerKey = consumerKey;
     this.ConsumerSecret = consumerSecret;
 }
Esempio n. 19
0
 public TwitterService GetAuthenticatedService()
 {
     var twitterClientInfo = new TwitterClientInfo {ConsumerKey = ConsumerKey, ConsumerSecret = ConsumerSecret};
     twitterService = new TwitterService(twitterClientInfo);
     twitterService.AuthenticateWith(AccessToken, AccessTokenSecret);
     return twitterService;
 }
        public ActionResult Index()
        {
            if (Request.IsAuthenticated)
            {
                var claimsIdentity = HttpContext.User.Identity as ClaimsIdentity;
                var claims = claimsIdentity.Claims;

                var accessTokenClaim = claims.FirstOrDefault(x => x.Type == Startup.TwitterAccessTokenClaimType);
                var accessTokenSecretClaim =
                    claims.FirstOrDefault(x => x.Type == Startup.TwitterAccessTokenSecretClaimType);

                if (accessTokenClaim != null && accessTokenSecretClaim != null)
                {
                    var service = new TwitterService(
                        Startup.TwitterConsumerKey,
                        Startup.TwitterConsumerSecret,
                        accessTokenClaim.Value,
                        accessTokenSecretClaim.Value
                        );

                    ViewBag.Tweets = service.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions());
                }
            }
            return View();
        }
Esempio n. 21
0
        static void Main(string[] args)
        {
            TwangManSays("********************************************");
            TwangManSays("*             HANG THE TWANG               *");
            TwangManSays("********************************************");
            CurrentGames = new Dictionary<long, TwitterThread>();
            tweetsToSend = new ConcurrentQueue<SendArgs>();

           
            TwitterSender = new Task(DoWork);
            TwitterSender.Start();

            _sendService = new TwitterService(Authentication.ConsumerKey, Authentication.ConsumerSecret);
            _sendService.AuthenticateWith(Authentication.AccessToken, Authentication.AccessTokenSecret);

            _service = new TwitterService(Authentication.ConsumerKey, Authentication.ConsumerSecret);
            _service.AuthenticateWith(Authentication.AccessToken, Authentication.AccessTokenSecret);

            TwitterListener = new Task(Listen);
            TwitterListener.Start();


            Console.ReadLine();
            _service.CancelStreaming();
        }
 private static TwitterService GetAuthenticatedService()
 {
     var service = new TwitterService(_consumerKey, _consumerSecret);
     service.TraceEnabled = true;
     service.AuthenticateWith(_accessToken, _accessTokenSecret);
     return service;
 }
Esempio n. 23
0
        public void SendTweet(IEnumerable <SpotifyTrack> tracks)
        {
            var service = new TweetSharp.TwitterService(ConsumerKey, ConsumerSecretKey);

            service.AuthenticateWith(TwitterToken, TwitterTokenSecret);

            var listOfTracks = new StringBuilder();

            foreach (var track in tracks)
            {
                track.Artist = track.Artist.Replace(",", "");
                track.Name   = track.Name.Replace(",", "");

                if (listOfTracks.Length > 140)
                {
                    service.SendTweet(new SendTweetOptions {
                        Status = $"@BBCR1 ,{listOfTracks}"
                    });
                    listOfTracks.Clear();
                    continue;
                }

                listOfTracks.Append(track.Artist);
                listOfTracks.Append("- ");
                listOfTracks.Append(track.Name);
                listOfTracks.Append(", ");
            }
        }
Esempio n. 24
0
 public TwitterWrapper()
 {
     Service = new TwitterService(ConfigurationManager.AppSettings["consumerAccessorA"], ConfigurationManager.AppSettings["consumerAccessorB"]);
     Service.AuthenticateWith(ConfigurationManager.AppSettings["authTokenA"], ConfigurationManager.AppSettings["authTokenB"]);
     // Ha. I hope you don't use your Twitter account for anything else, Ryan...
     Service.IncludeRetweets = true;
 }
Esempio n. 25
0
 public ActionResult Login(string returnUrl)
 {
     var service = new TwitterService(ConsumerKey, ConsumerSecret);
     var requestToken = service.GetRequestToken(Url.Action("LoginCallback", "Auth", new {returnUrl}, Request.Url.Scheme));
     var uri = service.GetAuthorizationUri(requestToken);
     return Redirect(uri.ToString());
 }
Esempio n. 26
0
 public TwitterApi()
 {
     _service = new TwitterServiceEntity(ConfigurationManager.AppSettings.Get("consumerKey"),
                                         ConfigurationManager.AppSettings.Get("consumerSecret"));
     _service.AuthenticateWith(ConfigurationManager.AppSettings.Get("token"),
                               ConfigurationManager.AppSettings.Get("tokenSecret"));
 }
Esempio n. 27
0
        public async Task <IActionResult> Create([Bind("ID,GameID,Path,Content,Likes")] Article article)
        {
            if (ModelState.IsValid)
            {
                string key         = "QNm1VD6rhVk5uQO1lFE4xj3TK";
                string secret      = "wyrMxltWxebxRh0CpWpetfstsZvKCvtleQbM0ybuLkJ9pmIKlS";
                string token       = "392392197-2Tche78I2E0ambYnzoNTHlC58ohagMciJQ31uf33";
                string tokenSecret = "ODMVW5HsJho3te2XcSHdINGL3q0zPHR70PllOoOWUxq6O";

                var service = new TweetSharp.TwitterService(key, secret);
                service.AuthenticateWith(token, tokenSecret);

                var result = service.SendTweet(new SendTweetOptions
                {
                    Status = "Hey! Game Sense got a new Article for you gamers!\n come check it out!!"
                });


                _context.Add(article);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["GameID"] = new SelectList(_context.Gamedb, "ID", "Name", article.GameID);
            return(View(article));
        }
Esempio n. 28
0
        private void Connect(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret)
        {
            // In v1.1, all API calls require authentication
            var service = new TwitterService(consumerKey, consumerSecret);
            service.AuthenticateWith(accessToken, accessTokenSecret);

            Log("Connected");

            TwitterRateLimitStatusSummary rate = service.GetRateLimitStatus(new GetRateLimitStatusOptions());

            Log("Limimte rate: " + rate.RawSource);

            var tweets = service.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions());
            foreach (var tweet in tweets)
            {
                Console.WriteLine("{0} says '{1}'", tweet.User.ScreenName, tweet.Text);
            }

            TwitterCursorList<TwitterUser> friends = service.ListFollowers(new ListFollowersOptions());

            Log("Friends: " + friends.Count);

            foreach (var friend in friends)
            {
                Log(String.Format("Friend: {0}", friend.Name));
            }
        }
Esempio n. 29
0
        private static List<TwitterStatus> SendTextMessage(TwitterService service, MessageEntity message)
        {
            List<TwitterStatus> statuses = new List<TwitterStatus>();

            String hashTag = String.Format("{0}{1}", "#LiveSkypeChat", Environment.NewLine); //TODO: module - defining current top hashtag

            List<string> splittedTwitterMessage = SplitMessage(message.TwitterMessage, hashTag);

            int messgaeIndex = 0;

            foreach (string messagePart in splittedTwitterMessage)
            {
                String twitterMessage = String.Empty;
                messgaeIndex++;

                if (splittedTwitterMessage.Count > 1)
                {
                    String counter = String.Format("{0}/{1}{2}", messgaeIndex, splittedTwitterMessage.Count, Environment.NewLine);
                    twitterMessage = String.Format("{0}{1}{2}: {3}", hashTag, counter, message.TwitterNick, messagePart);
                }
                else
                {
                    twitterMessage = String.Format("{0}{1}: {2}", hashTag, message.TwitterNick, messagePart);
                }

                TwitterStatus status = service.SendTweet(new SendTweetOptions { Status = twitterMessage });
                statuses.Add(status);
            }

            return statuses;
        }
Esempio n. 30
0
        /// 
        /// Uploads the photo and sends a new Tweet
        /// 
        /// <param name="binaryImageData">The binary image data.
        /// <param name="tweetMessage">The tweet message.
        /// <param name="filename">The filename.
        /// Return true, if the operation was succeded.
        public string UploadPhoto(string imageFile, string tpkey, string usrtoken, string usrsecret, string contoken, string consecret)
        {
            TwitterService service = new TwitterService(contoken, consecret);
            service.AuthenticateWith(usrtoken, usrsecret);

            Hammock.RestRequest request = service.PrepareEchoRequest();
            request.Path = "upload.xml";
            request.AddFile("media", "uploadfile", imageFile, "image/jpeg");
            request.AddField("key", tpkey);

            Hammock.RestClient client = new Hammock.RestClient() { Authority = "http://api.twitpic.com", VersionPath = "2" };
            Hammock.RestResponse response = client.Request(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                XDocument doc = XDocument.Parse(response.Content);

                XElement image = doc.Element("image");

                return image.Element("url").Value;
            }
            else
                throw new Exception("Error occured while uploading image to TwitPic servers. Please try again later");

            return "";
        }
Esempio n. 31
0
        public List<Models.User> Get(bool invite = false)
        {
            List<Models.User> output = new List<Models.User>();
            Models.Service service = _db.User.FirstOrDefault(c => c.UserId == WebSecurity.CurrentUserId).Services.FirstOrDefault(c => c.Provider == "twitter");
            if (service != null)
            {
                TwitterService twitter = new TwitterService(Settings.Settings.TwitterConsumerKey, Settings.Settings.TwitterConsumerSecret, service.Token, service.TokenSecret);

                var friends = twitter.ListFriends().ToList();

                foreach (var friend in friends)
                {

                    var username = OAuthWebSecurity.GetUserName("twitter", friend.Id.ToString());
                    if (username != null && invite == false)
                    {
                        int Id = WebSecurity.GetUserId(username);
                        Models.User user = _db.User.FirstOrDefault(c => c.UserId == Id);
                        output.Add(user);

                    }
                    else if(username == null && invite == true)
                    {
                        output.Add(new Models.User { Id = friend.Id, Image=friend.ProfileImageUrl, Name=friend.ScreenName});

                    }

                }

            }
            return output;
        }
Esempio n. 32
0
        public Account ProcessAuthentication(string pin)
        {
            TwitterService service = new TwitterService(_consumerKey, _consumerSecret);

            OAuthAccessToken access = service.GetAccessToken(_requestToken, pin);

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

            var profile = service.GetUserProfile();

            Account account = AccountManager.Instance.GetCurrentAccounts().Where(acc => acc.Username == profile.ScreenName).FirstOrDefault();
            if (account != null)
            {
                throw new AuthFailureException("User " +account.Username +  " already has an account with TweetOBox.");
            }
            if (profile != null && account == null)
            {
                account = new Account();
                account.Username = profile.ScreenName;
               // account.Password = profile.p
                account.AccountType = (int)AccountTypeEnum.Twitter;
                account.AccessToken = access.Token;
                account.AccessTokenSecret = access.TokenSecret;
                account.IsOAuth = true;
                AccountManager.Instance.AddAccount(account,false);
            }
            else
            {
                throw new AuthFailureException(service.Response.StatusDescription);
            }

            return account;
        }
Esempio n. 33
0
        protected void Load(TwitterResource resource)
        {
            var service = new TwitterService(SensitiveData.ConsumerToken, SensitiveData.ConsumerSecret, resource.User.Key, resource.User.Secret);

            switch (resource.Type)
            {
                case ResourceType.Home:
                    service.ListTweetsOnHomeTimeline(new ListTweetsOnHomeTimelineOptions { Count = 1, IncludeEntities = true }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.Mentions:
                    service.ListTweetsMentioningMe(new ListTweetsMentioningMeOptions { Count = 1, IncludeEntities = true }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.Messages:
                    service.ListDirectMessagesReceived(new ListDirectMessagesReceivedOptions { Count = 1 }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.Favorites:
                    service.ListFavoriteTweets(new ListFavoriteTweetsOptions { Count = 1 }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.List:
                    service.ListTweetsOnList(new ListTweetsOnListOptions
                    {
                        IncludeRts = false,
                        Count = 1,
                        OwnerScreenName = resource.Data.Substring(1, resource.Data.IndexOf('/') - 1),
                        Slug = resource.Data.Substring(resource.Data.IndexOf('/') + 1)
                    }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.Search:
                    service.Search(new SearchOptions { Count = 1, IncludeEntities = true, Q = resource.Data }, (status, response) => ReceiveTweetable(status.Statuses.Cast<ITweetable>(), response, resource));
                    break;
                case ResourceType.Tweets:
                    service.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { Count = 1, ScreenName = resource.Data, IncludeRts = true }, (status, response) => ReceiveTweetable(status.Cast<ITweetable>(), response, resource));
                    break;
            }
        }
Esempio n. 34
0
        public override void Post()
        {
            if ((String.IsNullOrEmpty(token = Config.TwitterAccessToken)
                || String.IsNullOrEmpty(tokenSecret = Config.TwitterTokenSecret))
                && !this.Auth())
            {
                App.Instance.AddError(Config.AUTHORIZATION_ERROR_EN, Config.TWITTER_TITLE);
                return;
            }
            else
            {
                //Authorize with the saved access token and secret
                TwitterClientInfo twitterClientInfo = new TwitterClientInfo();
                twitterClientInfo.ConsumerKey = ConsumerKey;
                twitterClientInfo.ConsumerSecret = ConsumerSecret;
                TwitterService twitterService = new TwitterService(twitterClientInfo);
                //twitterService.AuthenticateWith(token, tokenSecret);
            }

            try
            {
                this.PostTweet();
            }
            catch (Exception)
            {
                App.Instance.AddError(Config.TWITTER_ERROR, Config.TWITTER_TITLE);
            }
        }
Esempio n. 35
0
        /// <summary>
        /// Get Authenticated Service
        /// </summary>
        /// <returns>TwitterService</returns>
        private tweet.TwitterService GetAuthenticatedService()
        {
            var service = new tweet.TwitterService(_consumerKey, _consumerSecret);

            service.AuthenticateWith(_accessToken, _accessTokenSecret);

            return(service);
        }
        public TwitterService()
        {
            string comsumerKey       = ConfigurationManager.AppSettings["TwitterComsumerKey"];
            string comsumerSecret    = ConfigurationManager.AppSettings["TwitterComsumerSecret"];
            string accessToken       = ConfigurationManager.AppSettings["TwitterAccessToken"];
            string accessTokenSecret = ConfigurationManager.AppSettings["TwitterAccessTokenSecret"];

            _service = new TweetSharp.TwitterService(comsumerKey, comsumerSecret);
            _service.AuthenticateWith(accessToken, accessTokenSecret);
        }
Esempio n. 37
0
        public string Retweet(string userName, string Nick, long id)
        {
            var twitterSecret = new Social_media_access.Models.TwitterSecretData(userName, Nick);
            var service       = new TweetSharp.TwitterService(twitterSecret._OAuthConsumerKey, twitterSecret._OAuthConsumerSecret);

            service.AuthenticateWith(twitterSecret._OAuthAccessToken, twitterSecret._OAuthAccessTokenSecret);
            var TwitterStatus = service.Retweet(new RetweetOptions {
                Id = id
            });

            return("Retweeted successfully");
        }
Esempio n. 38
0
        public JsonResult GetHomeTweetsSince(string userName, string Nick, long id)
        {
            var twitterSecret = new Social_media_access.Models.TwitterSecretData(userName, Nick);
            var service       = new TweetSharp.TwitterService(twitterSecret._OAuthConsumerKey, twitterSecret._OAuthConsumerSecret);

            service.AuthenticateWith(twitterSecret._OAuthAccessToken, twitterSecret._OAuthAccessTokenSecret);
            var _ListTweetsOnHomeTimelineOptions = new TweetSharp.ListTweetsOnHomeTimelineOptions();

            _ListTweetsOnHomeTimelineOptions.Count   = 11;
            _ListTweetsOnHomeTimelineOptions.SinceId = id;
            var tweets = service.ListTweetsOnHomeTimeline(_ListTweetsOnHomeTimelineOptions);

            return(Json(tweets, JsonRequestBehavior.AllowGet));
        }
Esempio n. 39
0
        protected void TwLogin(object sender, EventArgs e)
        {
            string ConsumerKey = "yy4aasn9I4eLf1V8nwi7774sY";
            string ConsumerSecret = "1XvBnRBUVkovOewd2YiX44C7CgVIopUycRBXQg3WQfeQ4YrkeC";
            string TokenKey = "130485515-rTi0o1wolaWdTZQT8WQxZrQMiIgmvJVXz50oHNWH";
            string TokenSecretKey = "oSjy2f59Y6J5UnTuhVYIwAEPrMzQAeGkTMGrqlEbQL2MG";

            var service = new TweetSharp.TwitterService(ConsumerKey, ConsumerSecret, TokenKey, TokenSecretKey); //Replace keys with values from step #5
            var twitterStatus = service.SendTweet(new SendTweetOptions() { Status = FBpostbox.Text });
            if (twitterStatus != null)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Tweet was Successful');", true);
                Response.Redirect("https://twitter.com");
            }
        }
Esempio n. 40
0
        public TwitterTokenResponse GetRequestToken()
        {
            TweetSharp.TwitterService service = new TweetSharp.TwitterService(_twitterSettings.AppId, _twitterSettings.AppSecret);

            OAuthRequestToken requestToken = service.GetRequestToken(_twitterSettings.CallbackUrl);

            var twitterResponse = new TwitterTokenResponse
            {
                OAuthToken             = requestToken.Token,
                OAuthTokenSecret       = requestToken.TokenSecret,
                OAuthCallbackConfirmed = requestToken.OAuthCallbackConfirmed
            };

            return(twitterResponse);
        }
Esempio n. 41
0
        /// <summary>
        /// Authenticates credentials
        /// </summary>
        protected async Task AuthenticateAsync()
        {
            TweetSharp.TwitterService service = new TweetSharp.TwitterService(
                ConfigurationManager.AppSettings["TwitterConsumerKey"],
                ConfigurationManager.AppSettings["TwitterConsumerSecret"],
                ConfigurationManager.AppSettings["TwitterAccessToken"],
                ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
                );

            await Task.Run(() =>
            {
                service.AuthenticateWith(ConfigurationManager.AppSettings["TwitterAccessToken"],
                                         ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]);
            }
                           );
        }
Esempio n. 42
0
        protected void Button1_Click1(object sender, EventArgs e)
        {
            var service       = new TweetSharp.TwitterService("92Zy5mZCGwyPbYjDV6du68y96", "Ze60Gt9EaIPi2kSPulBSa3XpdRSHKTt6RMw7vd0Py20fuHbjYd", "4763102124-bB0DUXSGMrinnb2OzkxUHTkFtqZI49nOm8akcSp", "ozKSMMnA5luoJ4UUWwXyh7DnXmqJ6mg0RHIbMPvnaWPpw"); //Replace keys with values from step #5
            var twitterStatus = service.SendTweet(new SendTweetOptions()
            {
                Status = TextBox1.Text.Trim()
            });

            if (twitterStatus != null)
            {
                Label9.Text = "Weather Updated at " + DateTime.Now.ToString();
            }
            else
            {
                Label9.Text = "Error in Updating Tweet. Please Try again Later.";
            }
        }
Esempio n. 43
0
        public async Task <IActionResult> Create([Bind("MeetID,TrainingTypeID,TrainerID,MeetDate,Price")] Meeting meeting, string oauth_token, string oauth_verifier)
        {
            if (ModelState.IsValid)
            {
                var trainer = await _context.AspNetUsers.FindAsync(meeting.TrainerID);

                if (trainer == null)
                {
                    ViewData["NotFound"] = "The requested trainer is no longer available";
                    return(View("~/Views/Home/Index.cshtml"));
                }
                var trainingType = await _context.TrainingTypes.FindAsync(meeting.TrainingTypeID);

                if (trainingType == null)
                {
                    ViewData["NotFound"] = "The requested trainning method is no longer available";
                    return(View("~/Views/Home/Index.cshtml"));
                }

                _context.Add(meeting);
                await _context.SaveChangesAsync();

                string key         = "r6tXd2oaTFEqADpqI7GwsiR5o";
                string secret      = "6vqMDzhw0KmSiHXa7VXGARMc8FyEBIxK6EK52XyA6EopEIos4H";
                string token       = "1288845984898994179-vGxfZsfSKO2RpkQpdD3KcCTzoze9C1";
                string tokenSecret = "9xRofqqaVXfTaF8lChqBFlWbHwnnsdy9wN3xCPyr7BPRQ";
                var    service     = new TweetSharp.TwitterService(key, secret);
                service.AuthenticateWith(token, tokenSecret);
                TwitterUser user      = service.VerifyCredentials(new VerifyCredentialsOptions());
                var         traintype = await _context.TrainingTypes
                                        .FirstOrDefaultAsync(m => m.TrainingTypeId == meeting.TrainingTypeID);

                string message = string.Format("New {0} meeting is available at {1} {2}", traintype.Name, meeting.MeetDate.ToShortDateString(), meeting.MeetDate.ToShortTimeString());
                var    result  = service.SendTweet(new SendTweetOptions
                {
                    Status = message
                });


                return(RedirectToAction(nameof(Index)));
            }
            ViewData["TrainingTypeID"] = new SelectList(_context.TrainingTypes, "TrainingTypeId", "Name");
            ViewData["TrainerID"]      = this.GetRelevantTrainersToSelect();
            return(View(meeting));
        }
Esempio n. 44
0
        private void perfchart_fill1(data accelReport, string queue)
        {
            double resultx;
            double resulty;
            double resultz;
            string key         = "agOz9gCZATM58FI3ubCubyuot";
            string secret      = "57m1Xh5SGyuogn4zttjFpz6SHwRYBA9mpJdPNJHbXPoisf9KGn";
            string token       = "860367448268087296-yahVsCIdXOyDQzs7R9to8ITUurBaHHA";
            string tokenSecret = " wrGpbaIF98cGPXYuXZxMm0BYDLoyb7w4hq3GA2q5JzGhT";
            var    service     = new TweetSharp.TwitterService(key, secret);

            service.AuthenticateWith(token, tokenSecret);
            string message = "Peringatan telah terjadi gempa susulan dengan skala 6,3 dengan pusat gempa di lokasi Bandung";

            for (int i = 0; i < 40; i++)
            {
                resultx = ((double.Parse(accelReport.accelerations[i].x)));
                resulty = ((double.Parse(accelReport.accelerations[i].y)));
                resultz = ((double.Parse(accelReport.accelerations[i].z)));

                perfChart.AddValue((decimal)resultx);
                perfChart1.AddValue((decimal)resulty);
                perfChart2.AddValue((decimal)resultz);
                if (resultx > 9 || resulty > 9 || resultz > 9)
                {
                    //MessageBox.Show("TERJADI GEMPA");

                    textBox4.BeginInvoke(new Action(() => { textBox4.Text = "GEMPA"; }));
                    var result = service.SendTweet(new SendTweetOptions
                    {
                        Status = message
                    }
                                                   );
                    //lblResult.Text = result.Text.ToString();
                }
                Thread.Sleep(25);



                //defx = double.Parse(accelReport.accelerations[i].x);
                //defy = double.Parse(accelReport.accelerations[i].y);
                //defz = double.Parse(accelReport.accelerations[i].z);
            }
        }
Esempio n. 45
0
        public static List <User> fetchTwitterDetails(string myHashTag)
        {
            txtHashTag = myHashTag;

            //List<IList<Object>> twitterResult = new List<IList<object>>();
            //List<Object> twitterObject = new List<object>();
            var userResult = new List <User>();

            TweetSharp.TwitterService twService = new TweetSharp.TwitterService(_ConsumerKey, _ConsumerSecret);
            twService.AuthenticateWith(_AccessToken, _AccessTokenSecret);

            var twSearch = twService.Search(new TweetSharp.SearchOptions
            {
                Q          = txtHashTag.Trim(),
                Resulttype = TweetSharp.TwitterSearchResultType.Recent,
                Count      = 1
            });

            if (twSearch == null)
            {
                Console.WriteLine("Something is wrong...could not fetch details!");
            }

            else
            {
                List <TwitterStatus> tweetList = new List <TwitterStatus>(twSearch.Statuses);
                var user = new User();

                //twitterStats = new TwitterStatus();
                //var list = twSearch.Statuses.ToList();

                foreach (TwitterStatus t in tweetList)
                {
                    Console.WriteLine("Profile name: " + t.Author.ScreenName + ", Number of followers: " + t.User.FollowersCount);
                    //add details to object

                    user.screenName     = t.Author.ScreenName;
                    user.followersCount = t.User.FollowersCount;
                }

                userResult.Add(user);
            }
            return(userResult);
        }
Esempio n. 46
0
        public Application.Models.TwitterUser GetUserInfo(TwitterLoginDto twitterLogin)
        {
            TweetSharp.TwitterService service = new TweetSharp.TwitterService(_twitterSettings.AppId, _twitterSettings.AppSecret);

            // this is only temporary for testing purposes
            service.AuthenticateWith(_twitterSettings.AccessToken, _twitterSettings.AccessTokenSecret);

            // TODO: when we go in to production
            //var requestToken = new OAuthRequestToken
            //{
            //    Token = twitterLogin.OAuthToken
            //};
            //OAuthAccessToken accessToken = service.GetAccessToken(requestToken, twitterLogin.OAuthVerifier);
            //service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);

            var user = service.VerifyCredentials(new VerifyCredentialsOptions());

            return(new Application.Models.TwitterUser
            {
                Name = user.Name,
                ScreenName = user.ScreenName
            });
        }
        /// <summary>
        /// Send one tweet using TweetSharp
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task SendTweetWithTweetSharp(string status)
        {
            TweetSharp.TwitterService service = new TweetSharp.TwitterService(
                ConfigurationManager.AppSettings["TwitterConsumerKey"],
                ConfigurationManager.AppSettings["TwitterConsumerSecret"],
                ConfigurationManager.AppSettings["TwitterAccessToken"],
                ConfigurationManager.AppSettings["TwitterAccessTokenSecret"]
                );

            await this.AuthenticateAsync();

            /*
             * service.SendTweet(new SendTweetOptions { Status = status }, (tweet, response) =>
             * {
             *  if (response.StatusCode == HttpStatusCode.OK)
             *  {
             *      Console.ForegroundColor = ConsoleColor.Green;
             *      Console.WriteLine(DateTime.Now.ToString() + " Tweet Sent!");
             *      Console.ResetColor();
             *  }
             *  else
             *  {
             *      Console.ForegroundColor = ConsoleColor.Red;
             *      Console.WriteLine("ERROR " + response.Error.Message);
             *      Console.ResetColor();
             *  }
             *
             * });
             */

            await Task.Run(() =>
            {
                service.SendTweet(new SendTweetOptions {
                    Status = status
                });
            });
        }
Esempio n. 48
0
        private void btnClear_Click(object sender, EventArgs e)
        {
            perfChart.Clear();
            perfChart1.Clear();
            perfChart2.Clear();
            string a;

            string key         = "agOz9gCZATM58FI3ubCubyuot";
            string secret      = "57m1Xh5SGyuogn4zttjFpz6SHwRYBA9mpJdPNJHbXPoisf9KGn";
            string token       = "860367448268087296-yahVsCIdXOyDQzs7R9to8ITUurBaHHA";
            string tokenSecret = "wrGpbaIF98cGPXYuXZxMm0BYDLoyb7w4hq3GA2q5JzGhT";
            var    service     = new TweetSharp.TwitterService(key, secret);

            service.AuthenticateWith(token, tokenSecret);
            Console.WriteLine("Tweet Sent");
            string message = "Peringatan telah terjadi gempa susulan dengan skala 6,3 dengan pusat gempa di lokasi Bandung";

            {
                var result = service.SendTweet(new SendTweetOptions
                {
                    Status = message
                }

                                               );

                try
                {
                    a = result.Text.ToString();
                    Console.WriteLine(a);
                }
                catch (System.NullReferenceException z)
                {
                    Console.WriteLine("Tweet Failed");
                }
            }
        }
 public TwitterService()
 {
     _service = new TweetSharp.TwitterService(APP_KEY, APP_SECRET);
 }
Esempio n. 50
0
        public TweetsModel GetTweets(int numberOfResults, bool adminOverview)
        {
            var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            var tweetsModel   = new TweetsModel {
                ShowAdminOverView = adminOverview
            };
            var member = umbracoHelper.MembershipHelper.GetCurrentMember();

            if (member == null || member.IsHq() == false)
            {
                tweetsModel.ShowAdminOverView = false;
            }

            List <TwitterStatus> filteredTweets = new List <TwitterStatus>();

            try
            {
                var tweets =
                    UmbracoContext.Current.Application.ApplicationCache.RuntimeCache.GetCacheItem <IEnumerable <TwitterStatus> >("UmbracoSearchedTweets",
                                                                                                                                 () =>
                {
                    var service = new TweetSharp.TwitterService(
                        ConfigurationManager.AppSettings["twitterConsumerKey"],
                        ConfigurationManager.AppSettings["twitterConsumerSecret"]);
                    service.AuthenticateWith(
                        ConfigurationManager.AppSettings["twitterUserAccessToken"],
                        ConfigurationManager.AppSettings["twitterUserAccessSecret"]);

                    var options = new SearchOptions
                    {
                        Count      = 100,
                        Resulttype = TwitterSearchResultType.Recent,
                        Q          = "umbraco"
                    };

                    var results = service.Search(options);
                    return(results.Statuses);
                }, TimeSpan.FromMinutes(2));

                var settingsNode = umbracoHelper.TypedContentAtRoot().FirstOrDefault();
                if (settingsNode != null)
                {
                    var usernameFilter = settingsNode.GetPropertyValue <string>("twitterFilterAccounts")
                                         .ToLowerInvariant().Split(',').Where(x => x != string.Empty).ToArray();
                    var wordFilter = settingsNode.GetPropertyValue <string>("twitterFilterWords")
                                     .ToLowerInvariant().Split(',').Where(x => x != string.Empty);

                    filteredTweets = tweets.Where(x =>
                                                  x.Author.ScreenName.ToLowerInvariant().ContainsAny(usernameFilter) == false &&
                                                  x.Text.ToLowerInvariant().ContainsAny(wordFilter) == false &&
                                                  x.Text.StartsWith("RT ") == false)
                                     .Take(numberOfResults)
                                     .ToList();
                }

                tweetsModel.Tweets = filteredTweets;
            }
            catch (Exception ex)
            {
                LogHelper.Error <TwitterService>("Could not get tweets", ex);
            }

            return(tweetsModel);
        }
 public dskfj3k4adsfDF23cnv34fOAdmin2mcbue767bnmn326568Controller(IDataSource data)
 {
     service = new TweetSharp.TwitterService(key, secret);
     service.AuthenticateWith(token, tokenSecret);
     db = data;
 }
Esempio n. 52
0
 public Tweet()
 {
     _twitterService = GetAuthenticatedService();
     _twitterData    = GetTwitterData();
 }