public void InitializeRequest_Sets_Request_Headers()
        {
            var req = new Request("https://api.twitter.com/statuses/public.json");
            const string UserAgent = "LINQ to Twitter v2.0";
            var pinAuth = new PinAuthorizer();
            var oAuthMock = new Mock<IOAuthTwitter>();
            string outUrl;
            string queryString = "oauth_token=token";
            oAuthMock.Setup(oAuth => oAuth.GetOAuthQueryString(HttpMethod.GET, req, string.Empty, out outUrl, out queryString));
            pinAuth.OAuthTwitter = oAuthMock.Object;

            pinAuth.UserAgent = UserAgent;
            pinAuth.ReadWriteTimeout = new TimeSpan(0, 0, 1);
            pinAuth.Timeout = new TimeSpan(0, 0, 2);
            pinAuth.UseCompression = true;

            var httpReq = pinAuth.Get(req) as HttpWebRequest;

            Assert.NotNull(httpReq);
            Assert.Equal(UserAgent, httpReq.UserAgent);
            Assert.Equal(1000, httpReq.ReadWriteTimeout);
            Assert.Equal(2000, httpReq.Timeout);
            Assert.Equal("gzip, deflate", httpReq.Headers[HttpRequestHeader.AcceptEncoding]);
            Assert.Equal(DecompressionMethods.Deflate | DecompressionMethods.GZip, httpReq.AutomaticDecompression);
        }
        private void DoPinAuth()
        {
            m_pinAuth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "",
                    ConsumerSecret = ""
                },
                UseCompression = true,
                GoToTwitterAuthorization = pageLink =>
                    Dispatcher.BeginInvoke(() => WebBrowser.Navigate(new Uri(pageLink)))
            };

            m_pinAuth.BeginAuthorize(resp =>
                Dispatcher.BeginInvoke(() =>
                {
                    switch (resp.Status)
                    {
                        case TwitterErrorStatus.Success:
                            break;
                        case TwitterErrorStatus.TwitterApiError:
                        case TwitterErrorStatus.RequestProcessingException:
                            MessageBox.Show(
                                resp.Error.ToString(),
                                resp.Message,
                                MessageBoxButton.OK);
                            break;
                    }
                }));

            m_twitterCtx = new TwitterContext(m_pinAuth, "https://api.twitter.com/1/", "https://search.twitter.com/");
        }
Example #3
0
        static void authorize()
        {
            auth = new PinAuthorizer()
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "FiLff3SigcHPhHQxsSmpVQ", //ConfigurationManager.AppSettings["consumerKey"],
                    ConsumerSecret = "xzmPCd8drcHurgaDG3SRdRooZCBzf1ZvgmekadUYZcQ" //ConfigurationManager.AppSettings["consumerSecret"]
                },
                GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
                GetPin = () =>
                {
                    Console.Write("Enter Twitter PIN: ");
                    var input = Console.ReadLine().Trim();
                    return input;
                },
                AuthAccessType = AuthAccessType.Write
            };

            auth.Authorize();

            if (!auth.IsAuthorized)
            {
                Console.WriteLine("Not authorized");
                Environment.Exit(0);
            }
        }
Example #4
0
        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            this.pinAuth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "",
                    ConsumerSecret = ""
                },
                UseCompression = true,
                GoToTwitterAuthorization = pageLink =>
                    Dispatcher.BeginInvoke(() => OAuthWebBrowser.Navigate(new Uri(pageLink, UriKind.Absolute)))
            };

            this.pinAuth.BeginAuthorize(resp =>
                Dispatcher.BeginInvoke(() =>
                {
                    switch (resp.Status)
                    {
                        case TwitterErrorStatus.Success:
                            break;
                        case TwitterErrorStatus.TwitterApiError:
                        case TwitterErrorStatus.RequestProcessingException:
                            MessageBox.Show(
                                resp.Exception.ToString(),
                                resp.Message,
                                MessageBoxButton.OK);
                            break;
                    }
                }));
        }
Example #5
0
    public ITwitterAuthorizer Auth()
    {
      var credentials = new InMemoryCredentials
      {
        ConsumerKey = this.consumerKey,
        ConsumerSecret = this.consumerSecret
      };

      if (!string.IsNullOrEmpty(accessToken) && !string.IsNullOrEmpty(oAuthToken))
      {
        credentials.AccessToken = this.accessToken;
        credentials.OAuthToken = this.oAuthToken;
      }

      var auth = new PinAuthorizer
      {
        Credentials = credentials,
        UseCompression = true,
        GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
        GetPin = () =>
        {
          Console.WriteLine("\nAfter you authorize this application, Twitter will give you a 7-digit PIN Number.\n");
          Console.Write("Enter the PIN number here: ");
          return Console.ReadLine();
        }
      };

      auth.Authorize();

      return auth;
    }
Example #6
0
        public void Authorize()
        {
            var auth = new PinAuthorizer()
            {
                UserAgent = "AAafeen v" + Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                Credentials = new InMemoryCredentials()
                {
                    ConsumerKey = "BFtEaHnLWCMp9UjJEjBg",
                    ConsumerSecret = "VYwKqXpJsLPwYhdSzmQD0ri3K2Fh4n4MQyFIxZ6ME"
                },
                GoToTwitterAuthorization = uri => Process.Start(uri),
                GetPin = () =>
                {
                    var f = new InputPinCodeWindow();
                    f.ShowDialog();
                    return f.PinCode;
                }
            };

            try
            {
                auth.Authorize();
            }
            catch (Exception ex)
            {
                throw new Exception("認証に失敗しました。", ex);
            }

            Methods.twCtx.AuthorizedClient = auth;
        }
        /**
         * In this function we firstly load the auth pin authorizer with the application credentials.
         * We also load the login twitter page in order to obtain the pin.
         */
        void OAuthPage_Loaded(object sender, RoutedEventArgs e)
        {
            //Auth definition with our application credentials
            auth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = Constants.getConsumerKey(),
                    ConsumerSecret = Constants.getConsumerSecret()
                },
                UseCompression = true,
                //Browser authentication webpage
                GoToTwitterAuthorization = pageLink =>
                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                        () => OAuthWebBrowser.Navigate(new Uri(pageLink, UriKind.Absolute)))
            };

            auth.BeginAuthorize(resp =>
                Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    switch (resp.Status)
                    {
                        case TwitterErrorStatus.Success:
                            break;
                        case TwitterErrorStatus.RequestProcessingException:
                        case TwitterErrorStatus.TwitterApiError:
                            //new MessageDialog(resp.Error.ToString(), resp.Message).ShowAsync();
                            break;
                    }
                }));
        }
Example #8
0
		public  List<LinqToTwitter.Status> GetTwitterData()
		{
			BTProgressHUD.Show();
			//has the user already authenticated from a previous session? see AccountStore.Create().Save() later
			IEnumerable<Xamarin.Auth.Account> accounts = AccountStore.Create().FindAccountsForService("Twitter");

			//check the account store for a valid account marked as "Twitter" and then hold on to it for future requests

			var cred = new LinqToTwitter.InMemoryCredentialStore();
			cred.ConsumerKey = loggedInAccount.Properties["oauth_consumer_key"];
			cred.ConsumerSecret = loggedInAccount.Properties["oauth_consumer_secret"];
			cred.OAuthToken = loggedInAccount.Properties["oauth_token"];
			cred.OAuthTokenSecret = loggedInAccount.Properties["oauth_token_secret"];
			var auth = new LinqToTwitter.PinAuthorizer()
			{
				CredentialStore = cred,
			};
			var TwitterCtx = new LinqToTwitter.TwitterContext(auth);
			Console.WriteLine(TwitterCtx.User);
			List<LinqToTwitter.Status> tl = 
				(from tweet in TwitterCtx.Status
					where tweet.Type == LinqToTwitter.StatusType.Home
					select tweet).ToList();
			BTProgressHUD.Dismiss();
			return tl;
			//Console.WriteLine("Tweets Returned: " + tl.Count.ToString());
		}
Example #9
0
        async protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            if (MainActivity.Activities.ContainsKey("SearchTwitter"))
            {
                MainActivity.Activities["SearchTwitter"].Finish();
                MainActivity.Activities.Remove("SearchTwitter");
                MainActivity.Activities.Add("SearchTwitter", this);
            }
            else
            {
                MainActivity.Activities.Add("SearchTwitter", this);
            }
            //has the user already authenticated from a previous session? see AccountStore.Create().Save() later
            IEnumerable <Xamarin.Auth.Account> accounts = Xamarin.Auth.AccountStore.Create(this).FindAccountsForService("UndertheShopTwitApp");

            SearchTerm = Intent.GetStringExtra("keyword");
            shopID     = Intent.GetStringExtra("SHOP_ID_NUMBER");
            local      = Intent.GetStringExtra("Local");

            //check the account store for a valid account marked as "Twitter" and then hold on to it for future requests
            foreach (Xamarin.Auth.Account account in accounts)
            {
                loggedInAccount = account;
                break;
            }
            if (loggedInAccount == null)
            {
                Toast.MakeText(this, GetString(Resource.String.authfail), ToastLength.Short).Show();
                var next = new Intent(this.ApplicationContext, typeof(ShopInfoActivity));
                next.PutExtra("SHOP_ID_NUMBER", shopID);
                next.PutExtra("Local", local);
                StartActivity(next);
                Finish();
            }

            else
            {
                var cred = new LinqToTwitter.InMemoryCredentialStore();
                cred.ConsumerKey      = loggedInAccount.Properties["oauth_consumer_key"];
                cred.ConsumerSecret   = loggedInAccount.Properties["oauth_consumer_secret"];
                cred.OAuthToken       = loggedInAccount.Properties["oauth_token"];
                cred.OAuthTokenSecret = loggedInAccount.Properties["oauth_token_secret"];
                var auth0 = new LinqToTwitter.PinAuthorizer()
                {
                    CredentialStore = cred,
                };
                var TwitterCtx = new LinqToTwitter.TwitterContext(auth0);
                Console.WriteLine(TwitterCtx.User);
                _searches = await(from tweet in TwitterCtx.Search
                                  where (tweet.Type == SearchType.Search) &&
                                  (tweet.Query == SearchTerm)
                                  select tweet).ToListAsync();
                this.ListAdapter = new SearchAdapter(this, _searches[0].Statuses);
            }
        }
        public void TwitterContext_Single_Param_Constructor_Sets_Defaults()
        {
            const string BaseUrl = "https://api.twitter.com/1.1/";
            const string SearchUrl = "https://api.twitter.com/1.1/search/";
            ITwitterAuthorizer authorizedClient = new PinAuthorizer();
            var ctx = new TwitterContext(authorizedClient);

            Assert.Same(authorizedClient, ctx.AuthorizedClient);
            Assert.Equal(BaseUrl, ctx.BaseUrl);
            Assert.Equal(SearchUrl, ctx.SearchUrl);
        }
        public void Get_Calls_GetOAuthQueryString()
        {
            var req = new Request("https://api.twitter.com/statuses/public.json");
            var pinAuth = new PinAuthorizer();
            var oAuthMock = new Mock<IOAuthTwitter>();
            string outUrl;
            string queryString = "oauth_token=token";
            oAuthMock.Setup(oAuth => oAuth.GetOAuthQueryString(HttpMethod.GET, req, string.Empty, out outUrl, out queryString));
            pinAuth.OAuthTwitter = oAuthMock.Object;

            pinAuth.Get(req);

            oAuthMock.Verify(oAuth => oAuth.GetOAuthQueryString(HttpMethod.GET, req, string.Empty, out outUrl, out queryString), Times.Once());
        }
Example #12
0
        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            pinAuth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials 
                { 
                    ConsumerKey = "", 
                    ConsumerSecret = "" 
                },
                UseCompression = true,
                GoToTwitterAuthorization = pageLink => Dispatcher.BeginInvoke(() => OAuthWebBrowser.Navigate(new Uri(pageLink, UriKind.Absolute)))
            };

            this.pinAuth.BeginAuthorize(resp =>
                Dispatcher.BeginInvoke(() =>
                {
                    switch (resp.Status)
                    {
                        case TwitterErrorStatus.Success:
                            break;
                        case TwitterErrorStatus.TwitterApiError:
                        case TwitterErrorStatus.RequestProcessingException:
                            MessageBox.Show(
                                resp.Exception.ToString(),
                                resp.Message,
                                MessageBoxButton.OK);
                            break;
                    }
                }));

            //
            // comment out the code above and uncomment this code to use SingleUserAuthorizer
            //

            //var auth = new SingleUserAuthorizer
            //{
            //    Credentials = new SingleUserInMemoryCredentials
            //    {
            //        ConsumerKey = "", // twitter Consumer key
            //        ConsumerSecret = "", // twitter Consumer secret
            //        TwitterAccessToken = "", // twitter Access token
            //        TwitterAccessTokenSecret = "" // twitter Access token secret
            //    }
            //};

            //SharedState.Authorizer = auth;

            //NavigationService.GoBack();
        }
        public void Authorize_Requires_GetPin_Handler()
        {
            const string AuthLink = "https://authorizationlink";
            var pinAuth = new PinAuthorizer {Credentials = new InMemoryCredentials()};
            var oAuthMock = new Mock<IOAuthTwitter>();
            oAuthMock.Setup(oAuth => oAuth.AuthorizationLinkGet(It.IsAny<string>(), It.IsAny<string>(), "oob", false, AuthAccessType.NoChange))
                     .Returns(AuthLink);
            pinAuth.OAuthTwitter = oAuthMock.Object;
            string destinationUrl = string.Empty;
            pinAuth.GoToTwitterAuthorization = link => destinationUrl = link;

            var ex = Assert.Throws<InvalidOperationException>(() => pinAuth.Authorize());

            Assert.True(ex.Message.Contains("GetPin"));
        }
        public void Authorize_Launches_Browser()
        {
            const string AuthLink = "https://authorizationlink";
            var pinAuth = new PinAuthorizer {Credentials = new InMemoryCredentials()};
            var oAuthMock = new Mock<IOAuthTwitter>();
            oAuthMock.Setup(oAuth => oAuth.AuthorizationLinkGet(It.IsAny<string>(), It.IsAny<string>(), "oob", false, AuthAccessType.NoChange))
                     .Returns(AuthLink);
            pinAuth.OAuthTwitter = oAuthMock.Object;
            pinAuth.GetPin = () => "1234567";
            string destinationUrl = string.Empty;
            pinAuth.GoToTwitterAuthorization = link => destinationUrl = link;

            pinAuth.Authorize();

            Assert.Equal(AuthLink, destinationUrl);
        }
        public void IsAuthorized_Returns_False_When_1_Credential_Is_Empty()
        {
            var pinAuth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    AccessToken = "A",
                    ConsumerKey = "C",
                    ConsumerSecret = "S",
                    OAuthToken = ""
                }
            };

            bool isAuth = pinAuth.IsAuthorized;

            Assert.False(isAuth);
        }
        public void IsAuthorized_Returns_True_When_Credentials_Are_Present()
        {
            var pinAuth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    AccessToken = "A",
                    ConsumerKey = "C",
                    ConsumerSecret = "S",
                    OAuthToken = "O"
                }
            };

            bool isAuth = pinAuth.IsAuthorized;

            Assert.True(isAuth);
        }
Example #17
0
        async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            pinAuth = new PinAuthorizer
            {
                // Get the ConsumerKey and ConsumerSecret for your app and load them here.
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
                },
                // Note: GetPin isn't used here because we've broken the authorization
                // process into two parts: begin and complete
                GoToTwitterAuthorization = pageLink => Dispatcher.BeginInvoke((Action)
                    (() => OAuthWebBrowser.Navigate(new Uri(pageLink, UriKind.Absolute))))
            };

            await pinAuth.BeginAuthorizeAsync();
        }
Example #18
0
 public static IOAuthCredentials Authenticate() {
     var auth = new PinAuthorizer {
         Credentials = new InMemoryCredentials {
             ConsumerKey = "????????????????",
             ConsumerSecret = "????????????????"
         },
         AuthAccessType = AuthAccessType.Write,
         UseCompression = true,
         GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
         GetPin = () => {
             // this executes after user authorizes, which begins with the call to auth.Authorize() below.
             Console.WriteLine("\nAfter you authorize this application, Twitter will give you a 7-digit PIN Number.\n");
             Console.Write("Enter the PIN number here: ");
             return Console.ReadLine();
         }
     };
     auth.Authorize();
     return auth.Credentials;
 }
 private void Authenticate()
 {
     if (SuspensionManager.SessionState.ContainsKey("Authorizer"))
     {
         auth = SuspensionManager.SessionState["Authorizer"] as PinAuthorizer;
     }
     else if (SuspensionManager.SessionState.ContainsKey("SavedAuthorizer") &&
         SuspensionManager.SessionState["SavedAuthorizer"] != null)
     {
         LocalDataCredentials cred = (LocalDataCredentials)SuspensionManager.SessionState["SavedAuthorizer"];
         auth = new PinAuthorizer
         {
             Credentials = cred,
             UseCompression = true
         };
         SuspensionManager.SessionState["Authorizer"] = auth;
         auth.ScreenName = cred.ScreenName;
         auth.UserId = cred.UserId;
     }
 }
Example #20
0
        static ITwitterAuthorizer DoPinOAuth()
        {
            var auth = new PinAuthorizer()
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = ConsumerKey,
                    ConsumerSecret = ConsumerSecret
                },
                GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
                GetPin = () =>
                {
                    string result = null;
                    InputBox.Show("Twitter Authentication", 
                        "Enter the PIN number Twitter will give you here: ", ref result);
                    return result;
                }
            };

            return auth;
        }
        public void StreamUsersTweets(IList<RetreaveIndex> indexesToStream)
        {
            Running = true;
            DoUserStreams(indexesToStream);

            return;
            StringBuilder usersToFollow = new StringBuilder();
            bool first = true;
            //foreach uesr get the associated users
            //should only be one anyway.
            foreach (RetreaveIndex index in indexesToStream)
            {
                foreach (RegisteredUser user in index.AssociatedUsers)
                {
                    if (!first)
                        usersToFollow.Append(",");

                    usersToFollow.Append(user.TwitterId);
                    first = false;
                }
            }

            Console.WriteLine("Starting stream for " + usersToFollow.ToString());
            InMemoryCredentials credentials = new InMemoryCredentials();
            //user credentials
            credentials.AccessToken = AuthenticationTokens.AppOwnerAccessTokenSecret;
            credentials.OAuthToken = AuthenticationTokens.AppOwnerAccessToken;

            //app specific credentials
            credentials.ConsumerKey = AuthenticationTokens.TwitterConsumerKey;
            credentials.ConsumerSecret = AuthenticationTokens.TwitterConsumerSecret;

            //save to pin authorizer
            PinAuthorizer authorizer = new PinAuthorizer();
            authorizer.Credentials = credentials;

            TwitterContext twitterCtx = new TwitterContext(authorizer);

            //DoSiteStream(twitterCtx, usersToFollow.ToString());
        }
Example #22
0
        private void parametresFenetre_Load(object sender, EventArgs e)
        {
            var auth = new PinAuthorizer()
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
                },
                GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
                GetPin = () =>
                {
                    Console.WriteLine(
                        "\nAfter authorizing this application, Twitter " +
                        "will give you a 7-digit PIN Number.\n");
                    Console.Write("Enter the PIN number here: ");
                    return Console.ReadLine();
                }
            };

            auth.AuthorizeAsync();
        }
        public void Authorize_Gets_Access_Token()
        {
            string screenName = "JoeMayo";
            string userID = "123";
            const string PinCode = "1234567";
            const string AuthToken = "token";
            const string AuthLink = "https://authorizationlink?oauth_token=" + AuthToken;
            var pinAuth = new PinAuthorizer {Credentials = new InMemoryCredentials()};
            var oAuthMock = new Mock<IOAuthTwitter>();
            oAuthMock.Setup(oAuth => oAuth.AuthorizationLinkGet(It.IsAny<string>(), It.IsAny<string>(), "oob", false, AuthAccessType.NoChange))
                     .Returns(AuthLink);
            oAuthMock.Setup(oAuth => oAuth.AccessTokenGet(AuthToken, PinCode, It.IsAny<string>(), string.Empty, out screenName, out userID));
            pinAuth.OAuthTwitter = oAuthMock.Object;
            pinAuth.GetPin = () => PinCode;
            string destinationUrl = string.Empty;
            pinAuth.GoToTwitterAuthorization = link => destinationUrl = link;

            pinAuth.Authorize();

            oAuthMock.Verify(oauth => oauth.AccessTokenGet(AuthToken, PinCode, It.IsAny<string>(), string.Empty, out screenName, out userID), Times.Once());
            Assert.Equal(screenName, pinAuth.ScreenName);
            Assert.Equal(userID, pinAuth.UserId);
            Assert.Equal(AuthLink, destinationUrl);
        }
Example #24
0
        private static void locate(PinAuthorizer tw)
        {
            System.Console.WriteLine("Please Type in how many DataLines should be taken (0 for all): ");
            int takeUserInput = Convert.ToInt32(Console.ReadLine());
            System.Console.WriteLine("Please Type in how many Datalines should be skipped (0 for none): ");
            int skipUserInput = Convert.ToInt32(Console.ReadLine());
            System.Console.WriteLine("Please type in the Information intervall: ");
            int informationIntervall = Convert.ToInt32(Console.ReadLine());
            System.Console.WriteLine("Do you want to retrieve Tweets about the progress? (0 no 1 yes)");
            int tweetInformation = Convert.ToInt32(Console.ReadLine());

            using (knowledgeObjects DB = new knowledgeObjects())
            {
                DB.Configuration.AutoDetectChangesEnabled = false;
                DB.Configuration.ValidateOnSaveEnabled = false;

                List<tweetRandomSample2> tweetsCollection = new List<tweetRandomSample2>();

                if (takeUserInput == 0)
                {

                    tweetsCollection = (List<tweetRandomSample2>)(from tweets in DB.tweetRandomSample2
                                                            orderby tweets.id
                                                            select tweets).Skip(skipUserInput).ToList();
                }
                else
                {
                    tweetsCollection = (List<tweetRandomSample2>)(from tweets in DB.tweetRandomSample2
                                                            orderby tweets.id
                                                            select tweets).Take(takeUserInput).Skip(skipUserInput).ToList();
                }

                Stopwatch stopwatch = new Stopwatch();
                TweetInformation ti = new TweetInformation();

                TimeSpan timespan = new TimeSpan();
                TimeSpan actualTime = new TimeSpan();

                TweetLoc tl = new TweetLoc(0);

                int i = 0;
                GeoNames knowledgeResult = new GeoNames();
                GeoNames tweetCountry = new GeoNames();
                foreach (var item in tweetsCollection)
                {
                    using (GeonamesDataEntities geonamesDB = new GeonamesDataEntities()) {
                        tweetCountry = (from geonames in geonamesDB.GeoNames
                                        where geonames.geonameid == item.geoNames_geoNamesId
                                        select geonames).ToList().First();
                    }

                    i++;
                    stopwatch.Start();
                    ti = new TweetInformation();
                    ti.userlocation = item.userlocation;
                    ti.timezone = item.timezone;
                    ti.longitude = item.lon;
                    ti.latitude = item.lat;
                    ti.baseDataId = item.id;
                    ti.coord = item.coord;
                    ti.randomSampleId = item.id;
                    tl.saveLocateResults(ti);
                    stopwatch.Stop();
                    actualTime += stopwatch.Elapsed;
                    timespan += stopwatch.Elapsed;
                    stopwatch.Reset();
                    if (i % informationIntervall == 0)
                    {
                        string tweetTXT = i + " T " + new RoundedTimeSpan(timespan.Ticks, 2) + " avg " + new RoundedTimeSpan(timespan.Ticks / i, 2) + " avg5k " + new RoundedTimeSpan(actualTime.Ticks / informationIntervall, 2);
                        System.Console.WriteLine(tweetTXT);
                        if (tweetInformation == 1)
                        {
                            statusUpdate("@pide2001 " + tweetTXT, tw);
                            }
                        actualTime = TimeSpan.Zero;
                    }
                }

                System.Console.WriteLine("Press any key to quit !");
                System.Console.ReadLine();

            }
        }
        private static TwitterContext CreateContext(string accessToken, string oAuthToken)
        {
            var auth = new PinAuthorizer()
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "rgRMroMnWQ8IoUNYcNIX0BsLV",
                    ConsumerSecret = "vfX2T7V9kwmwDzCyBW8ZP91jElRhGnCNnG6fbfcvz1ysOrt8Bz",
                    AccessToken = accessToken,
                    OAuthToken = oAuthToken
                },
                GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
                GetPin = () =>
                {
                    Console.WriteLine(
                        "\nAfter authorizing this application, Twitter " +
                        "will give you a 7-digit PIN Number.\n");
                    Console.Write("Enter the PIN number here: ");

                    var pin =  Console.ReadLine();

                    return pin;
                }
            };

            auth.AuthAccessType = AuthAccessType.Write;
            auth.Authorize();

            return new TwitterContext(auth);

        }
Example #26
0
        static IAuthorizer DoPinOAuth()
        {
            var auth = new PinAuthorizer()
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
                },
                GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
                GetPin = () =>
                {
                    Console.WriteLine(
                        "\nAfter authorizing this application, Twitter " +
                        "will give you a 7-digit PIN Number.\n");
                    Console.Write("Enter the PIN number here: ");
                    return Console.ReadLine();
                }
            };

            return auth;
        }
        public void IsAuthorized_Returns_False_When_2_Credentials_Are_Null()
        {
            var pinAuth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    AccessToken = "A",
                    ConsumerKey = "C",
                    ConsumerSecret = null,
                    OAuthToken = null
                }
            };

            bool isAuth = pinAuth.IsAuthorized;

            Assert.False(isAuth);
        }
Example #28
0
        private static PinAuthorizer twitter()
        {
            var auth = new PinAuthorizer()
            {

                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = "Ssa9qRLFOUS8SdaD1TE0w",
                    ConsumerSecret = "sUcQ8oB7QJmXITjo8PGihGDxSbHrzCxmTs6BjVxlDo",
                    OAuthToken = "92306096-X3nzRe89yM1zvjX5nqsENEkmKViHqoxequa8ysRAw",
                    OAuthTokenSecret = "kYV8ZE3Px3PjeeOEjvo9VQZk37TktLXYM1UUJQCrta0yY"
                }
                //GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
                //GetPin = () =>
                //{
                //    Console.WriteLine(
                //        "\nAfter authorizing this application, Twitter " +
                //        "will give you a 7-digit PIN Number.\n");
                //    Console.Write("Enter the PIN number here: ");
                //    return Console.ReadLine();
                //}
            };

            auth.AuthorizeAsync();

            return auth;
        }
Example #29
0
 private static void statusUpdate(String tweetText, PinAuthorizer auth)
 {
     using (var twitter = new TwitterContext(auth))
     {
         var tweet = twitter.TweetAsync(tweetText);
     }
 }
Example #30
0
        private static void statistics(PinAuthorizer tw)
        {
            using (knowledgeObjects DB = new knowledgeObjects())
            {

                List<learningBase> tweetsCollection = new List<learningBase>();

                tweetsCollection = (List<learningBase>)(from tweets in DB.learningBase
                                                        orderby tweets.id
                                                        select tweets).ToList();

                Stopwatch stopwatch = new Stopwatch();
                TweetInformation ti = new TweetInformation();

                TimeSpan timespan = new TimeSpan();
                TimeSpan actualTime = new TimeSpan();

                TweetLoc tl = new TweetLoc(10);

                int i = 0;

                foreach (var item in tweetsCollection)
                {

                    i++;
                    stopwatch.Start();
                    ti = new TweetInformation();
                    ti.userlocation = item.userlocation;
                    ti.timezone = item.timezone;
                    ti.longitude = item.lon;
                    ti.latitude = item.lat;
                    ti.baseDataId = item.id;
                    tl.getGeographyStatistics(ti);
                    stopwatch.Stop();
                    actualTime += stopwatch.Elapsed;
                    timespan += stopwatch.Elapsed;
                    stopwatch.Reset();
                    if (i % 10 == 0)
                    {
                        string tweetTXT = i + " T " + new RoundedTimeSpan(timespan.Ticks, 2) + " avg " + new RoundedTimeSpan(timespan.Ticks / i, 2) + " avg5k " + new RoundedTimeSpan(actualTime.Ticks / 1000, 2);
                        System.Console.WriteLine(tweetTXT);
                        //statusUpdate("@pide2001 " + tweetTXT, tw);
                        actualTime = TimeSpan.Zero;
                    }
                }

                System.Console.WriteLine("Median " + tl.statistics.getMedianOfDistances());
                System.Console.WriteLine("Average " + tl.statistics.getAverageDistance());
                System.Console.WriteLine("Biggest " + tl.statistics.getBiggestDistance());
                System.Console.WriteLine("Smallest " + tl.statistics.getSmallestDistance());
                Tuple<GeographyData, TweetKnowledgeObj> know = tl.statistics.getBiggestDistanceAndInformation();
                System.Console.WriteLine("Biggest distance between " + know.Item1.geonamesId + " and " + know.Item2.baseDataId);

                System.Console.WriteLine("Press any key to quit !");
                System.Console.ReadLine();

            }
        }
Example #31
0
        private static void analysis(PinAuthorizer tw)
        {
            using (knowledgeObjects DB = new knowledgeObjects())
            {
                //DB.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
                DB.Configuration.AutoDetectChangesEnabled = false;
                DB.Configuration.ValidateOnSaveEnabled = false;

                //get tweetRandomSample to iterate over tweets and analyse the results
                var tweetRandomSample = (from trs
                            in DB.tweetRandomSample2
                                         select trs).ToList();

                Stopwatch stopwatch = new Stopwatch();
                int counter = 0;
                //iterate over tweets
                foreach (var tweet in tweetRandomSample)
                {
                    counter++;
                    //new List to hold Lists sorted by NGramOrder
                    List<List<knowledgeBaseGeocoding>> ListsByOrder = new List<List<knowledgeBaseGeocoding>>();

                    //getting knowledgeBaseGeocoding entries per tweet
                    List<knowledgeBaseGeocoding> knowledgeBaseGeocodingList = tweet.knowledgeBaseGeocoding.ToList();

                    if (knowledgeBaseGeocodingList.Select(g => g.knowledgeBaseId).FirstOrDefault()!= null)
                    {
                        //get maximumNGram
                        var max = knowledgeBaseGeocodingList.Max(g => g.NGramOrder);
                        List<knowledgeBaseGeocoding> temporaryList = new List<knowledgeBaseGeocoding>();
                        //Add lists from max NGramOrder down to 1
                        var knowledgeBaseGeocoding = (from kbg
                            in DB.knowledgeBaseGeocoding where kbg.tweetRandomSampleId == tweet.id
                                                 select kbg).Include("knowledgeBase").ToList();

                        for (int i = 1; i <= max; i++)
                        {

                            if (knowledgeBaseGeocoding.Where(g => g.NGramOrder.Value == i).ToList().Count > 0)
                            {
                                ListsByOrder.Add(knowledgeBaseGeocoding.Where(g => g.NGramOrder.Value == i).ToList());                            }

                        }

                        //iterate over lists
                        foreach (var liste in ListsByOrder)
                        {
                                var order = liste.First().NGramOrder;
                                var tweetId = liste.First().tweetRandomSampleId;

                                //sql function to make it even faster
                                int sum = (int)DB.getSumOfNGramCounts(tweetId, order).FirstOrDefault();

                                //cityLevel
                                Tuple<int, float> idMaxPercentageCity = Tuple.Create(0, (float)0.0);
                                float currentPercentage = 0;
                                int ngramcoCity = 0;
                                foreach (var knowledgeBaseGeocodingEntry in liste)
                                {
                                    int ngramco = (int)knowledgeBaseGeocodingEntry.NgramCount;
                                    currentPercentage = ((float)ngramco / (float)sum);
                                    if (idMaxPercentageCity.Item2 < currentPercentage)
                                    {
                                        idMaxPercentageCity = Tuple.Create(knowledgeBaseGeocodingEntry.id, currentPercentage);
                                        ngramcoCity = ngramco;
                                    }
                                }

                                int geonamesidCity = liste.Where(g => g.id == idMaxPercentageCity.Item1).Select(g => g.KnowledgeBase.GeoNamesId).FirstOrDefault();
                                int knowledgeBaseIdCity = liste.Where(g => g.id == idMaxPercentageCity.Item1).Select(g => g.KnowledgeBase.Id).FirstOrDefault(); ;
                                double? percentageMaxCity = idMaxPercentageCity.Item2;
                                int countCity = (int)liste.Where(g => g.id == idMaxPercentageCity.Item1).Select(g => g.KnowledgeBase.NGramCount).FirstOrDefault();
                                //System.Console.WriteLine("geonId {0} knowledgeBaseid {1} percentageMax {2} count {3}" ,geonamesid,knowledgeBaseId,percentageMax,count);

                                //admin2
                                var result = liste.GroupBy(o => o.KnowledgeBase.Admin2Id)
                                            .Select(g => new { admin2Id = g.Key, total = g.Sum(i => i.NgramCount) });

                                Tuple<int, float> idMaxPercentageAdmin2 = Tuple.Create(0, (float)0.0);
                                int lossAdmin2 = 0;
                                int ngramcoAdmin2 = 0;
                                foreach (var entryadmin2 in result)
                                {
                                    int ngramco = (int)entryadmin2.total;
                                    currentPercentage = ((float)ngramco / (float)sum);
                                    //System.Console.WriteLine(currentPercentage + " " + entryadmin2.admin2Id);
                                    if (idMaxPercentageAdmin2.Item2 < currentPercentage)
                                    {
                                        if (entryadmin2.admin2Id != null)
                                        {
                                            idMaxPercentageAdmin2 = Tuple.Create((int)entryadmin2.admin2Id, currentPercentage);
                                            ngramcoAdmin2 = ngramco;
                                        }
                                        else
                                        {
                                            lossAdmin2 = (int)entryadmin2.total;

                                        }
                                    }
                                }
                                //System.Console.WriteLine(idMaxPercentageAdmin2);
                                //System.Console.WriteLine("loss adm2 " + lossAdmin2);

                                //admin1
                                var resultAdmin1 = liste.GroupBy(o => o.KnowledgeBase.Admin1Id)
                                            .Select(g => new { admin1Id = g.Key, total = g.Sum(i => i.NgramCount) });

                                Tuple<int, float> idMaxPercentageAdmin1 = Tuple.Create(0, (float)0.0);
                                int lossAdmin1 = 0;
                                int ngramcoAdmin1 = 0;
                                foreach (var entryadmin1 in resultAdmin1)
                                {
                                    int ngramco = (int)entryadmin1.total;
                                    currentPercentage = ((float)ngramco / (float)sum);
                                    //.Console.WriteLine(currentPercentage + " " + entryadmin1.admin1Id);
                                    if (idMaxPercentageAdmin1.Item2 < currentPercentage)
                                    {
                                        if (entryadmin1.admin1Id != null)
                                        {
                                            idMaxPercentageAdmin1 = Tuple.Create((int)entryadmin1.admin1Id, currentPercentage);
                                            ngramcoAdmin1 = ngramco;
                                        }
                                        else
                                        {
                                            lossAdmin1 = (int)entryadmin1.total;

                                        }
                                    }
                                }
                                //.Console.WriteLine(idMaxPercentageAdmin1);

                                //System.Console.WriteLine("loss adm1 " + lossAdmin1);

                                //country
                                var resultCountry = liste.GroupBy(o => o.KnowledgeBase.CountryId)
                                            .Select(g => new { countryId = g.Key, total = g.Sum(i => i.NgramCount) });

                                Tuple<int, float> idMaxPercentageCountry = Tuple.Create(0, (float)0.0);
                                int ngramcoCountry = 0;
                                foreach (var entryCountry in resultCountry)
                                {
                                    int ngramco = (int)entryCountry.total;
                                    currentPercentage = ((float)ngramco / (float)sum);
                                    //System.Console.WriteLine(currentPercentage + " " + entryCountry.countryId);
                                    if (idMaxPercentageCountry.Item2 < currentPercentage)
                                    {

                                        idMaxPercentageCountry = Tuple.Create((int)entryCountry.countryId, currentPercentage);
                                        ngramcoCountry = ngramco;
                                    }
                                }
                                //System.Console.WriteLine(idMaxPercentageCountry);

                                DB.resultsKnowledgeBaseGeocoding.Add(new resultsKnowledgeBaseGeocoding
                                {
                                    nGramOrder = order,
                                    overallCount = sum,
                                    tweetRandomSampleId = tweetId,
                                    city_geonamesId = geonamesidCity,
                                    city_knowledgeBaseId = knowledgeBaseIdCity,
                                    city_percentage = percentageMaxCity,
                                    city_count = ngramcoCity,
                                    adm2_geonamesId = idMaxPercentageAdmin2.Item1,
                                    adm2_percentage = idMaxPercentageAdmin2.Item2,
                                    adm2_loss = lossAdmin2,
                                    adm2_count = ngramcoAdmin2,
                                    adm1_geonamesId = idMaxPercentageAdmin1.Item1,
                                    adm1_percentage = idMaxPercentageAdmin1.Item2,
                                    adm1_loss = lossAdmin1,
                                    adm1_count = ngramcoAdmin1,
                                    country_geonamesId = idMaxPercentageCountry.Item1,
                                    country_percentage = idMaxPercentageCountry.Item2,
                                    country_count = ngramcoCountry
                                });
                                DB.SaveChanges();

                        }
                    }
                    if (counter % 500 == 0) {
                        System.Console.WriteLine("tweets so far: " + counter);
                        statusUpdate("@pide2001 " + counter, tw);
                    }

                   }

            }

            System.Console.WriteLine("Press any key to quit !");
            System.Console.ReadLine();
        }