/// <summary> /// Populate User basic information retrieving the information thanks to a Token /// </summary> /// <param name="token">Token to use to get infos</param> public void PopulateUser(IToken token) { if (token != null) { string query; // Depending of the whether we have the id or the username we use the appropriate query if (_id != null) { query = String.Format(Resources.User_GetUserFromId, Id); } else { if (_screen_name != null) { query = String.Format(Resources.User_GetUserFromScreenName, ScreenName); } else { return; } } dynamic dynamicUser = token.ExecuteGETQuery(query); Populate(dynamicUser); } }
/// <summary> /// Perform a basic search on Twitter API and returns the T type specified /// </summary> /// <param name="searchQuery">Search to be sent</param> /// <param name="resultPerPage">Number of result per page</param> /// <param name="pageNumber">Page expected</param> /// <param name="token">Token used to perform the search</param> /// <param name="includeEntities">Include entities to the results</param> /// <returns>Collection of results</returns> public List <IUser> Search(string searchQuery, int resultPerPage, int pageNumber, IToken token = null, bool includeEntities = false) { token = GetQueryToken(token); if (token == null) { throw new Exception("A token is required to perform an request on twitter API"); } List <IUser> result = new List <IUser>(); // Delegate that will create users from each of the objects retrieved from the search ObjectResponseDelegate objectResponseDelegate = delegate(Dictionary <string, object> responseObject) { IUser user = User.Create(responseObject); if (user != null) { result.Add(user); } }; string httpQuery = string.Format(Resources.UserSearchEngine_SimpleSearch, searchQuery, resultPerPage, pageNumber); token.ExecuteGETQuery(httpQuery, objectResponseDelegate, null); return(result); }
/// <summary> /// Provide simplified ways to query a list of TwitterObject /// </summary> /// <param name="token">Token to be used</param> /// <param name="queryUrl">URL from which we expect results</param> /// <param name="objectCreatorDelegate">Method to be used to create the expected object</param> /// <param name="objectCreatedDelegate">Delegate to happen after a TwitterObject being created</param> /// <param name="wex">WebException to manage errors</param> /// <returns>Collection of TwitterObject retrieved from the query</returns> public static List <T> GetListOfTwitterObject <T>(IToken token, string queryUrl, ObjectCreatorDelegate <T> objectCreatorDelegate, ObjectCreatedDelegate <T> objectCreatedDelegate = null, WebExceptionHandlingDelegate wex = null) { if (token == null || objectCreatorDelegate == null) { return(null); } List <T> result = new List <T>(); ObjectResponseDelegate objectDelegate = delegate(Dictionary <string, object> objectContent) { T newObject = objectCreatorDelegate(objectContent); if (objectCreatedDelegate != null) { objectCreatedDelegate(newObject); } result.Add(newObject); }; token.ExecuteGETQuery(queryUrl, objectDelegate, wex); return(result); }
/// <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 <IUser> GetContributionObjects(IToken token, String url, WebExceptionHandlingDelegate exceptionHandlerDelegate = null) { token = GetQueryToken(token); if (token == null) { Console.WriteLine("User's token is required"); return(null); } List <IUser> result = new List <IUser>(); ObjectResponseDelegate objectDelegate = delegate(Dictionary <string, object> responseObject) { if (responseObject != null) { result.Add(new User(responseObject)); } }; token.ExecuteGETQuery(url, objectDelegate, exceptionHandlerDelegate); return(result); }
/// <summary> /// Uses the handler for only one query / work also for cursor queries /// </summary> /// <param name="token"></param> static void execute_query_error_handler(IToken token) { WebExceptionHandlingDelegate del = delegate(WebException wex) { Console.WriteLine("You received an execute_query_error!"); Console.WriteLine(wex.Message); }; token.ExecuteGETQuery("https://api.twitter.com/1.1/users/contributors.json?user_id=700562792", null, del); }
// ReSharper disable UnusedMember.Local #region Token #region Execute Query /// <summary> /// Simple function that uses ExecuteQuery to retrieve information from the Twitter API /// </summary> /// <param name="token"></param> static void ExecuteQuery(IToken token) { // Retrieving information from Twitter API through Token method ExecuteRequest dynamic timeline = token.ExecuteGETQuery("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("{0} : {1}\n", i, post["text"]); } }
public void ExecuteQueryWithDelegate() { IToken token = TokenTestSingleton.Instance; // Retrieving information from Twitter API through Token method ExecuteRequest ObjectResponseDelegate objectResponseDelegate = delegate(Dictionary <string, object> responseObject) { Debug.WriteLine("{0}\n", responseObject["text"]); }; token.ExecuteGETQuery("https://api.twitter.com/1.1/statuses/home_timeline.json", objectResponseDelegate); }
/// <summary> /// Populate User basic information retrieving the information thanks to a Token /// </summary> /// <param name="token">Token to use to get infos</param> public void PopulateUser(IToken token) { token = GetQueryToken(token); if (token != null) { string query = Resources.User_GetUser; if (AddUserInformationInQuery(ref query)) { Dictionary <string, object> dynamicUser = token.ExecuteGETQuery(query); Populate(dynamicUser); } } }
/// <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(IToken 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 token.ExecuteGETQuery("https://api.twitter.com/1.1/users/contributors.json?user_id=700562792"); // Reset to basic Handler token.IntegratedExceptionHandler = false; // OR token.ResetExceptionHandler(); }
/// <summary> /// Create a Message from its id. Its content is retrieved from the Twitter API using the valid token given in parameter. /// Throw an argument exception if one of the parameters is null. /// </summary> /// <param name="id">id of the message</param> /// <param name="token">token used to request the message's data to the Twitter API</param> /// <exception cref="ArgumentException">One of the argument is null</exception> public Message(long id, IToken token) : this() { // id and token must be specified to be able to retrieve the message data from the Twitter API if (token == null) { throw new ArgumentException("Token must be defined to retrieve content."); } _token = token; // Retrieve the message data from the Twitter API object messageContent = token.ExecuteGETQuery(String.Format(Resources.Messages_GetDirectMessage, id)); // Populate the message with the data retrieved from the Twitter API Populate((Dictionary <String, object>)messageContent); }
/// <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(IToken token) { token.IntegratedExceptionHandler = true; // Error is not automatically handled try { // Calling a method that does not exist token.ExecuteGETQuery("https://api.twitter.com/1.1/users/contributors.json?user_id=700562792"); } catch (WebException wex) { Console.WriteLine("An error occured!"); Console.WriteLine(wex); } }
/// <summary> /// Populate the information of Tweet for which we set the ID /// </summary> /// <param name="token">Token to perform the query</param> /// <param name="cleanString">Clean the string so that it is readalble</param> public void PopulateTweet(IToken token, bool cleanString = true) { token = GetQueryToken(token); if (token != null) { string query; if (_id != null) { query = String.Format(Resources.Tweet_GetFromIdWithEntities, Id); } else { throw new Exception("Id needs to be set to retrieve it from Twitter."); } // If 404 error throw Exception that Tweet has not been created WebExceptionHandlingDelegate wex = delegate(WebException exception) { int indexOfStatus = exception.Response.Headers.AllKeys.ToList().IndexOf("status"); if (indexOfStatus != -1) { string statusValue = exception.Response.Headers.Get(indexOfStatus); // The tweet with the specific Id does not exist if (statusValue == "404 Not Found") { // Throwing an exception will stop the creation of the Tweet throw new Exception(String.Format("Tweet[{0}] does not exist!", Id)); } } }; Dictionary <String, object> dynamicTweet = token.ExecuteGETQuery(query, null, wex); Populate(dynamicTweet, cleanString); _token = token; } }
/// <summary> /// Retrieve the data from the Twitter API for the list of suggested users associated to the attribute _slug. /// Process this data and store it in the attributes name, size and members /// An Exception is thrown the parameter is null, if no data could be retrieved from Twitter, or if it is incomplete. /// </summary> /// <param name="token">Token used to request data from the Twitter API</param> public void RefreshAll(IToken token) { if (token == null) { throw new ArgumentException("Token must be specified in parameter"); } // Retrieve data from the Twitter API dynamic twitterSuggUserListDetails = token.ExecuteGETQuery(String.Format(Resources.SuggestedUserList_Get, this.Slug)); if (twitterSuggUserListDetails != null) { // Extract the name and the size attributes from Twitter's response Dictionary <string, object> suggUserListDetailsDico = twitterSuggUserListDetails; _name = (string)suggUserListDetailsDico["name"]; _size = (int)suggUserListDetailsDico["size"]; // Create a task to clean these attributes in 50 minutes from now AddScheduledTask(); if (suggUserListDetailsDico["users"] != null) { // Extract all the members of this list from Twitter's response and store them in the attribute members Dictionary <string, object>[] membersTable = (Dictionary <string, object>[])suggUserListDetailsDico["users"]; ExtractMembers(membersTable); } else { // throw an exception if the members of this list cannot be found in the response from Twitter HandleMembersErrorFromTwitter(); } } else { // Throw an exception and reset the values of the details fields if Twitter's response did not contain any data ResetAllDetailFields(); throw new Exception("no details returned by Twitter for this suggested list"); } }
/// <summary> /// Get all the retweets of the current tweet /// </summary> /// <returns> /// Null if the current tweet has a null if or a null token. /// The list of tweets representing the retweets of the current tweet otherwise. /// </returns> public List <ITweet> GetRetweets( bool getUserInfo = false, bool refreshRetweetList = false, IToken token = null) { token = GetQueryToken(token); if (Id == null || token == null) { return(null); } List <ITweet> retweets = new List <ITweet>(); ObjectResponseDelegate retweetDelegate = delegate(Dictionary <string, object> responseObject) { Tweet t = new Tweet(responseObject, _shareTokenWithChild ? this._token : null); retweets.Add(t); }; try { token.ExecuteGETQuery(String.Format(Resources.Tweet_GetRetweetOfTweet, Id), retweetDelegate, null); if (refreshRetweetList) { this._retweets = retweets; } } catch (WebException) { throw; } return(retweets); }
/// <summary> /// Return a list of users corresponding to the list of user ids and screen names given in parameter. /// Throw an exception if the token given in parameter is null or if both lists given in parameters are null. /// </summary> /// <param name="userIds"> /// List of user screen names. This parameter can be null /// List of user ids. This parameter can be null /// </param> /// <param name="screen_names"></param> /// <param name="token">Token used to request the users' information from the Twitter API</param> /// <returns>The list of users retrieved from the Twitter API</returns> public static List <IUser> Lookup(List <long> userIds, List <string> screen_names, IToken token) { if (token == null) { throw new ArgumentException("Token must not be null"); } if (userIds == null && screen_names == null) { throw new ArgumentException("User ids or screen names must be specified"); } List <IUser> users = new List <IUser>(); if (userIds == null) { userIds = new List <long>(); } if (screen_names == null) { screen_names = new List <string>(); } int userIndex = 0; int screenNameIndex = 0; while ((userIndex < userIds.Count) || (screenNameIndex < screen_names.Count)) { // Keep track of the number of users that we are going to request from the Twitter API int indicesSumBeforeLoop = userIndex + screenNameIndex; string userIdsStrList = "user_id="; string screen_namesStrList = "screen_name="; // Maximum number of users that can be requested from the Twitter API (in 1 single request) int listMaxSize = 100; // Take request parameters from both names list and id list // userIndex + screenNameIndex - indicesSumBeforeLoop) < listMaxSize ==> Check that the number of parameters given to the Twitter API request does not exceed the limit while (((userIndex + screenNameIndex - indicesSumBeforeLoop) < listMaxSize) && (userIndex < userIds.Count) && (screenNameIndex < screen_names.Count)) { screen_namesStrList += screen_names.ElementAt(screenNameIndex++) + "%2C"; userIdsStrList += userIds.ElementAt(userIndex++) + "%2C"; } // Take request from id list while (((userIndex + screenNameIndex - indicesSumBeforeLoop) < listMaxSize) && (userIndex < userIds.Count)) { userIdsStrList += userIds.ElementAt(userIndex++) + "%2C"; } // Take name from id list while (((userIndex + screenNameIndex - indicesSumBeforeLoop) < listMaxSize) && (screenNameIndex < screen_names.Count)) { screen_namesStrList += screen_names.ElementAt(screenNameIndex++) + "%2C"; } String query = Resources.UserUtils_Lookup; // Add new parameters to the query and format it query = enrichLookupQuery(query, screen_namesStrList); query = enrichLookupQuery(query, userIdsStrList); ObjectResponseDelegate objectDelegate = delegate(Dictionary <string, object> responseObject) { User u = User.Create(responseObject); users.Add(u); }; token.ExecuteGETQuery(query, objectDelegate); } return(users); }