Exemplo n.º 1
0
 public static void createUserV2(Token token, long id = 700562792)
 {
     User user = new User(id);
     // Here we need to specify the token to retrieve the information
     // otherwise the information won't be filled
     user.FillUser(token);
 }
Exemplo n.º 2
0
        public void Constructor1()
        {
            Token token = new Token();

            Assert.AreEqual(token.AccessToken, "");
            Assert.AreEqual(token.AccessTokenSecret, "");
            Assert.AreEqual(token.ConsumerKey, "");
            Assert.AreEqual(token.ConsumerSecret, "");
        }
Exemplo n.º 3
0
        /// <summary>
        /// Function that execute cursor query and send information for each query executed
        /// </summary>
        /// <param name="token"></param>
        static void ExecuteCursorQuery(Token token)
        {
            // The delegate is a function that will be called for each cursor
            Token.DynamicResponseDelegate del = delegate(dynamic jsonResponse, long previous_cursor, long next_cursor)
            {
                Console.WriteLine(previous_cursor + " -> " + next_cursor + " : " + jsonResponse.Count);
            };

            token.ExecuteCursorQuery("https://api.twitter.com/1/friends/ids.json?user_id=700562792", del);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Simple function that uses ExecuteQuery to retrieve information from the Twitter API
        /// </summary>
        /// <param name="token"></param>
        static void ExecuteQuery(Token token)
        {
            // Retrieving information from Twitter API through Token method ExecuteRequest
            dynamic timeline = token.ExecuteQuery("https://api.twitter.com/1/statuses/home_timeline.json");

            // Working on each different object sent as a response to the Twitter API query
            for (int i = 0; i < timeline.Length; ++i)
            {
                Dictionary<String, object> post = timeline[i];
                Console.WriteLine(String.Format("{0} : {1}\n", i, post["text"]));
            }
        }
Exemplo n.º 5
0
        public Tweet(long? id, Token token = null, bool cleanString = true)
        {
            if (id == null)
                throw new Exception("id cannot be null!");
            _id = id;
            _id_str = id.ToString();

            if (token != null)
            {
                this.token = token;
                this.FillTweet(token, cleanString);
            }
        }
Exemplo n.º 6
0
        private static void create_tweet_with_entities(Token token)
        {
            // This tweet has classic entities
            Tweet tweet1 = new Tweet(127512260116623360, token);

            // This tweet has media entity
            try
            {
                Tweet tweet2 = new Tweet(112652479837110270, token);
            }
            catch (WebException wex)
            {
                Console.WriteLine("Tweet has not been created!");
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Fill User basic information retrieving the information thanks to a Token
        /// <param name="token">Token to use to get infos</param>
        public void FillUser(Token token)
        {
            if (token != null)
            {
                var query = "";
                if (_id != null)
                    query = String.Format(this.query_user_from_id, id);
                else
                    if (_screen_name != null)
                        query = String.Format(this.query_user_from_name, screen_name);
                    else
                        return;

                var jsonResponse = token.ExecuteQuery(query);
                dynamic dynamicUser = jsonResponse[0];
                if (dynamicUser is Dictionary<String, object>)
                {
                    Dictionary<String, object> dUser = dynamicUser as Dictionary<String, object>;
                    fillUser(dUser);
                }
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// Create a Tweet and retrieve the propreties through given token
 /// </summary>
 /// <param name="username">Username</param>
 /// <param name="token">Token saved in class propreties</param>
 public User(string username, Token token = null)
     : this()
 {
     _screen_name = username;
     if (token != null)
     {
         this.token = token;
         this.FillUser(token);
     }
 }
Exemplo n.º 9
0
 public User(long id, Token token = null)
     : this((long?)id, token)
 {
 }
Exemplo n.º 10
0
        /// <summary>
        /// Method to start a stream from a Token
        /// </summary>
        /// <param name="token">Token to get the credentials to query the stream</param>
        public void StartStream(Token token)
        {
            if (_isRunning)
                throw new OperationCanceledException("You cannot run the stream multiple times");

            #region Variables
            long todayTicks = DateTime.Now.Ticks;
            DateTime init = new DateTime(todayTicks - todayTicks % TimeSpan.TicksPerDay + 1);

            state = StreamState.Resume;
            HttpWebRequest webRequest = token.GenerateRequest(new Uri(StreamUrl));
            StreamReader reader = init_webRequest(webRequest);

            string jsonTweet;
            int error_occured = 0;
            #endregion

            while (state != StreamState.Stop)
            {
                try
                {
                    jsonTweet = null;
                    jsonTweet = reader.ReadLine();

                    #region Error Checking
                    if (jsonTweet == null || jsonTweet == "")
                    {
                        if (error_occured == 0)
                        {
                            ++error_occured;
                        }
                        else if (error_occured == 1)
                        {
                            ++error_occured;
                            webRequest.Abort();
                            reader = init_webRequest(webRequest);
                        }
                        else if (error_occured == 2)
                        {
                            ++error_occured;
                            webRequest.Abort();
                            webRequest = token.GenerateRequest(new Uri(StreamUrl));
                            reader = init_webRequest(webRequest);
                        }
                        else
                        {
                            Console.WriteLine("Twitter API is not accessible");
                            Trace.WriteLine("Twitter API is not accessible");
                            break;
                        }
                    }
                    else if (error_occured != 0)
                        error_occured = 0;
                    #endregion
                    Tweet tweet = Tweet.Create(jsonTweet);

                    if (processTweetDelegate != null)
                    {
                        processTweetDelegate(tweet, false);
                    }

                }
                catch (IOException ex)
                {
                    // Verify the implementation of the Exception handler
                    #region IOException Handler
                    if (ex.Message == "Unable to read data from the transport connection: The connection was closed.")
                        reader = init_webRequest(webRequest);

                    try
                    {
                        jsonTweet = reader.ReadLine();
                    }
                    catch (IOException ex2)
                    {
                        if (ex2.Message == "Unable to read data from the transport connection: The connection was closed.")
                        {
                            Trace.WriteLine("Streamreader was unable to read from the stream!");
                            if (processTweetDelegate != null)
                                processTweetDelegate(null, true);
                            break;
                        }
                    }
                    #endregion
                }
            }

            #region Clean
            webRequest.Abort();
            reader.Dispose();
            state = StreamState.Stop;
            #endregion
        }
Exemplo n.º 11
0
        /// <summary>
        /// Initiating auto error handler
        /// You will not receive error information if handled by default error handler
        /// </summary>
        /// <param name="token"></param>
        static void integrated_error_handler(Token token)
        {
            token.Integrated_Exception_Handler = true;

            // Error is not automatically handled

            try
            {
                // Calling a method that does not exist
                dynamic timeline = token.ExecuteQuery("https://api.twitter.com/1/users/contributors.json?user_id=700562792");
            }
            catch (WebException wex)
            {
                Console.WriteLine("An error occured!");
                Console.WriteLine(wex);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Show a the list of Friends from a userId
        /// </summary>
        /// <param name="token">Credentials</param>
        /// <param name="id">UserId to be analyzed</param>
        private static void getFriends(Token token, long id = 700562792)
        {
            User user = new User(id);
            var res = user.getFriends(token);
            Console.WriteLine("List of friends from " + id);

            foreach (long friend_id in res)
                Console.WriteLine(friend_id);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Update the exception handler attribute with the 3rd parameter
        /// Get the list of users matching the Twitter request url (contributors or contributees)
        /// </summary>
        /// <param name="token"> Current user token to access the Twitter API</param>
        /// <param name="url">Twitter requets URL</param>
        /// <param name="exceptionHandlerDelegate">Delegate method to handle Twitter request exceptions</param>
        /// <returns>Null if the token parameter is null or if the Twitter request fails. A list of users otherwise (contributors or contributees).</returns>
        private List<User> getContributionObjects(Token token, String url, Token.WebExceptionHandlingDelegate exceptionHandlerDelegate = null)
        {
            //
            if (token == null)
            {
                Console.WriteLine("User's token is needed");
                return null;
            }

            // Update the exception handler
            //token.Integrated_Exception_Handler = false;
            token.ExceptionHandler = exceptionHandlerDelegate;

            dynamic webRequestResult = token.ExecuteQuery(url);

            List<User> result = null;
            if (webRequestResult != null)
            {
                // Create and fill a user list with the data retrieved from Twitter (Dictionary<String, object>[])
                result = new User[] { }.ToList();
                if (webRequestResult is object[])
                {
                    object[] retrievedContributors = webRequestResult as object[];
                    foreach (object rc in retrievedContributors)
                    {
                        if (rc is Dictionary<String, object>)
                        {
                            Dictionary<String, object> userInfo = rc as Dictionary<String, object>;
                            User u = new User();
                            u.fillUser(userInfo);
                            result.Add(u);
                        }
                    }
                }
            }

            return result;
        }
Exemplo n.º 14
0
 static void getProfileImage(Token token)
 {
     User ladygaga = new User("ladygaga", token);
     Console.WriteLine(ladygaga.GetProfileImage(ImageSize.bigger, true));
 }
Exemplo n.º 15
0
        /// <summary>
        /// When assigning an error_handler to a Token think that it will be kept alive 
        /// until you specify it does not exist anymore by specifying :
        /// 
        /// token.Integrated_Exception_Handler = false;
        /// 
        /// You can assign null value if you do not want anything to be performed for you
        /// </summary>
        /// <param name="token"></param>
        static void token_integrated_error_handler(Token token)
        {
            token.ExceptionHandler = delegate(WebException wex)
            {
                Console.WriteLine("You received a Token generated error!");
                Console.WriteLine(wex.Message);
            };

            // Calling a method that does not exist
            dynamic timeline = token.ExecuteQuery("https://api.twitter.com/1/users/contributors.json?user_id=700562792");

            // Reset to basic Handler
            token.Integrated_Exception_Handler = false;
        }
Exemplo n.º 16
0
 /// <summary>
 /// Testing the 3 ways to handle errors
 /// </summary>
 /// <param name="token"></param>
 static void test_error_functions(Token token)
 {
     integrated_error_handler(token);
     token_integrated_error_handler(token);
     execute_query_error_handler(token);
 }
Exemplo n.º 17
0
 private static void streaming_example(Token token)
 {
     // Creating a Delegate to use processTweet function to analyze each Tweet coming from the stream
     Stream.ProcessTweetDelegate produceTweetDelegate = new Stream.ProcessTweetDelegate(processTweet);
     // Creating the stream and specifying the delegate
     Stream myStream = new Stream(produceTweetDelegate);
     // Starting the stream by specifying credentials thanks to the Token
     myStream.StartStream(token);
 }
Exemplo n.º 18
0
 public static void createUser(Token token, long id = 700562792)
 {
     User user = new User(id, token);
 }
Exemplo n.º 19
0
        /// <summary>
        /// Run a basic application to provide a code example
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            // Initializing a Token with Twitter Credentials
            Token token = new Token()
            {
                AccessToken = ConfigurationManager.AppSettings["token_AccessToken"],
                AccessTokenSecret = ConfigurationManager.AppSettings["token_AccessTokenSecret"],
                ConsumerKey = ConfigurationManager.AppSettings["token_ConsumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["token_ConsumerSecret"]
            };

            Console.WriteLine("Creating Tweet from id");
            get_rate_limit(token);
            test_error_functions(token);

            Console.WriteLine("End");
            Console.ReadKey();
        }
Exemplo n.º 20
0
        public List<long> getFriends(Token token, bool createUserList = false, long cursor = 0)
        {
            if (token == null)
                return null;

            if (cursor == 0)
            {
                Friend_ids = new List<long>();
                Friends = new List<User>();
            }

            Token.DynamicResponseDelegate del = delegate(dynamic responseObject, long previous_cursor, long next_cursor)
            {
                foreach (var friend_id in responseObject["ids"])
                {
                    Friend_ids.Add((long)friend_id);
                    if (createUserList)
                        Friends.Add(new User((long)friend_id));
                }
            };

            if (id != null)
                token.ExecuteCursorQuery(String.Format(query_user_friends, id), del);
            else
                if (_screen_name != null)
                    token.ExecuteCursorQuery(String.Format(query_user_friends_from_name, screen_name), del);

            return Friend_ids;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Get the Profile Image for a user / Possibility to download it
        /// </summary>
        /// <param name="token"></param>
        /// <param name="size">Size of the image</param>
        /// <param name="download">Define if you want to download the image</param>
        /// <param name="location">Define location to store it</param>
        /// <returns>Url to access the image from a browser</returns>
        public string GetProfileImage(Token token, ImageSize size = ImageSize.normal, bool download = false, string location = "")
        {
            if (token == null)
                return null;

            if (screen_name == null && id == null)
                return null;

            string url = null;
            string img_name = null;

            if (screen_name != null)
            {
                url = String.Format(query_user_profile_image_from_name, screen_name, size);
                img_name = screen_name;
            }
            else
                if (id != null)
                {
                    url = String.Format(query_user_profile_image, id, size);
                    img_name = id.ToString();
                }

            // Using WebClient
            if (download && url != null)
                using (WebClient client = new WebClient())
                {
                    client.DownloadFile(url, String.Format("{0}{1}_{2}.jpg", location, img_name, size));
                }

            #region Note
            // Using WebRequest
            // if you want to change from WebClient to WebRequest you can simply use the code behind by extending the class
            // WebRequest request = WebRequest.Create(String.Format(query_user_profile_image, screen_name, size));
            // WebResponse response = request.GetResponse();
            #endregion

            return url;
        }
Exemplo n.º 22
0
        private static void getFollowers(Token token, long? id = 700562792)
        {
            User user = new User((long)id);
            var res = user.getFollowers(token);

            Console.WriteLine(res.Count());
            foreach (long follower_id in res)
            {
                Console.WriteLine(follower_id);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Create a Tweet and retrieve the propreties through given token
        /// </summary>
        /// <param name="id">UserId</param>
        /// <param name="token">Token saved in class propreties</param>
        public User(long? id, Token token = null)
            : this()
        {
            if (id == null)
                throw new Exception("id cannot be null!");
            _id = id;
            _id_str = id.ToString();

            if (token != null)
            {
                this.token = token;
                this.FillUser(token);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Uses the handler for only one query / work also for cursor queries
        /// </summary>
        /// <param name="token"></param>
        static void execute_query_error_handler(Token token)
        {
            Token.WebExceptionHandlingDelegate del = delegate(WebException wex)
            {
                Console.WriteLine("You received an execute_query_error!");
                Console.WriteLine(wex.Message);
            };

            dynamic timeline = token.ExecuteQuery("https://api.twitter.com/1/users/contributors.json?user_id=700562792", del);
        }
Exemplo n.º 25
0
        public void FillTweet(Token token, bool cleanString = true)
        {
            if (token != null)
            {
                var query = "";
                if (_id != null)
                    query = String.Format(this.query_tweet_from_id_with_entities, id);
                else
                    return;

                // If 404 error throw Exception that Tweet has not been created
                var jsonResponse = token.ExecuteQuery(query);
                dynamic dynamicTweet = jsonResponse;
                if (dynamicTweet is Dictionary<String, object>)
                {
                    Dictionary<String, object> dTweet = dynamicTweet as Dictionary<String, object>;
                    fillTweet(dTweet, cleanString);
                }
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Enable you to get all information from Token and how many query you can execute
 /// Each time a query is executed the XRateLimitRemaining is updated.
 /// To improve efficiency, the other values are NOT.
 /// If you need these please call the function GetRateLimit()
 /// </summary>
 /// <param name="token"></param>
 static void get_rate_limit(Token token)
 {
     int remaining = token.GetRateLimit();
     Console.WriteLine("Used : " + remaining);
     Console.WriteLine("Used : " + token.XRateLimitRemaining);
     Console.WriteLine("Total per hour : " + token.XRateLimit);
     Console.WriteLine("Time before reset : " + token.ResetTimeInSeconds);
 }
Exemplo n.º 27
0
 public Tweet(long id, Token token = null, bool cleanString = true)
     : this((long?)id, token, cleanString)
 {
 }
Exemplo n.º 28
0
 static void getContributors(Token token, long id = 700562792, bool createContributorList = false)
 {
     User user = new User(id, token);
     List<User> contributors = user.GetContributors(createContributorList);
     List<User> contributorsAttribute = user.contributors;
     if (createContributorList && contributors != null)
     {
         if ((contributors == null && contributorsAttribute != null) || (contributors != null && contributorsAttribute == null)
             || (!contributors.Equals(contributorsAttribute)))
         {
             Console.WriteLine("The object attribute should be identical to the method result");
         }
     }
     if (contributors != null)
     {
         foreach (User c in contributors)
         {
             Console.WriteLine("contributor id = " + c.id + " - screen_name = " + c.screen_name);
         }
     }
 }