Example #1
0
 public Dictionary <string, object>[] ExecutePOSTQueryReturningCollectionOfObjects(
     string url,
     ObjectResponseDelegate objectHandler          = null,
     WebExceptionHandlingDelegate exceptionHandler = null)
 {
     return(ExecuteQuery(url, HttpMethod.POST, objectHandler, exceptionHandler));
 }
Example #2
0
        /// <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);
        }
Example #3
0
        /// <summary>
        /// Retrieve the timeline of the current user from the Twitter API.
        /// Update the corresponding attribute if required by the parameter createTimeline.
        /// Return the timeline of the current user
        /// </summary>
        /// <param name="token">Token of the current user</param>
        /// <param name="wexDelegate">Handler of WebException thrown by the Twitter API</param>
        /// <param name="createTimeline">False by default. If true, the attribute _timeline is updated with the result</param>
        /// <returns>Null if the user token is null, the timeline of the user represented by the token otherwise</returns>
        private List <ITweet> GetUserTimeline(IToken token,
                                              WebExceptionHandlingDelegate wexDelegate = null,
                                              bool createTimeline = false)
        {
            token = GetQueryToken(token);

            if (token == null)
            {
                Console.WriteLine("Token must be specified");
                return(null);
            }

            List <ITweet> timeline = new List <ITweet>();

            ObjectResponseDelegate tweetDelegate = delegate(Dictionary <string, object> tweetContent)
            {
                Tweet t = new Tweet(tweetContent, _shareTokenWithChild ? _token : null);
                timeline.Add(t);
            };

            token.ExecuteSinceMaxQuery(String.Format(Resources.User_GetUserTimeline, Id), tweetDelegate, wexDelegate);

            if (createTimeline)
            {
                _timeline = timeline;
            }

            return(timeline);
        }
        /// <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);
        }
Example #5
0
        /// <summary>
        /// Method allowing to request data from an URL targeting a specific timeframe (using since_id and max_id parameters).
        /// Since_id must be included in the method_url parameter.
        /// Iterate over the different pages of results for this time frame.
        /// For each iteration, memorize the maximum of all the object ids and reuse it in the URL to request objects for the
        /// next iteration. Also, handle each object retrieved with the ObjectResponseDelegate given in parameter.
        /// </summary>
        /// <param name="url">Url from Twitter Api to query. Can include a since_id parameter</param>
        /// <param name="sinceMaxDelegate">delegate handling the objects retrieved from the Twitter API</param>
        /// <param name="webExceptionHandlerDelegate">Handle exceptions occuring upon request to the Twitter API</param>
        public void ExecuteSinceMaxQuery(
            string url,
            ObjectResponseDelegate sinceMaxDelegate,
            WebExceptionHandlingDelegate webExceptionHandlerDelegate = null)
        {
            string updated_method_url = url;
            long   maxId           = Int64.MaxValue;
            int    startLoop       = 1;
            int    nbItemsReceived = 0;

            ObjectResponseDelegate objectDelegate = delegate(Dictionary <string, object> o)
            {
                ++nbItemsReceived;
                long itemId = (long)o["id"];

                if (maxId > itemId)
                {
                    maxId = itemId;
                }

                if (sinceMaxDelegate != null)
                {
                    sinceMaxDelegate(o);
                }
            };

            while (startLoop != nbItemsReceived)
            {
                try
                {
                    dynamic responseObject = ExecuteGETQuery(updated_method_url, objectDelegate, webExceptionHandlerDelegate);

                    if (responseObject == null)
                    {
                        break;
                    }

                    if (startLoop == nbItemsReceived)
                    {
                        break;
                    }

                    // Request the following items starting from the oldest item handled
                    updated_method_url = String.Format(url + "&max_id={0}", maxId);
                    // Avoid to start from the last tweet already handled when we will go over the next loop
                    startLoop = 1;
                }
                catch (WebException wex)
                {
                    if (ExceptionHandler != null)
                    {
                        ExceptionHandler(wex);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Example #6
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 <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);
        }
Example #7
0
        /// <summary>
        /// Retrieve the lists of suggested users associated to the current user from the Twitter API.
        /// Update the corresponding attribute according to the value of the parameter.
        /// Return the lists of suggested users.
        /// </summary>
        /// <param name="createSuggestedUserList">update the _suggestedUserList if true</param>
        /// <returns>null if the token parameter is null, the lists of suggested users otherwise</returns>
        public List <ISuggestedUserList> GetSuggestedUserList(bool createSuggestedUserList = true)
        {
            if (_token == null)
            {
                return(null);
            }

            List <ISuggestedUserList> suggUserList = new List <ISuggestedUserList>();

            ObjectResponseDelegate objectDelegate = delegate(Dictionary <string, object> responseObject)
            {
                suggUserList.Add(new SuggestedUserList(
                                     (string)responseObject["name"],
                                     (string)responseObject["slug"],
                                     (int)responseObject["size"]));
            };

            // Retrieve the lists of suggested users from the Twitter API
            _token.ExecuteGETQuery(Resources.TokenUser_GetUserSuggestions, objectDelegate);

            // Update the attribute if requested
            if (createSuggestedUserList)
            {
                _suggested_user_list = suggUserList;
            }

            return(suggUserList);
        }
Example #8
0
 public Dictionary <string, object> ExecutePOSTQuery(
     string url,
     ObjectResponseDelegate objectHandler          = null,
     WebExceptionHandlingDelegate exceptionHandler = null)
 {
     return(ExecuteQueryWithSingleResponse(url, HttpMethod.POST, objectHandler, exceptionHandler));
 }
Example #9
0
        public ITweet PublishRetweet()
        {
            if (_id == null || !IsTweetPublished || IsTweetDestroyed)
            {
                return(null);
            }

            Tweet result = null;

            string query = String.Format(Resources.Tweet_PublishRetweet, _id);

            WebExceptionHandlingDelegate wex = delegate(WebException exception)
            {
                if (exception.GetWebExceptionStatusNumber() == 403)
                {
                    result = null;
                }
            };

            ObjectResponseDelegate objectDelegate = delegate(Dictionary <string, object> responseObject)
            {
                result = new Tweet(responseObject, _shareTokenWithChild ? _token : null);
            };

            _token.ExecutePOSTQuery(query, objectDelegate, wex);

            return(result);
        }
Example #10
0
        /// <summary>
        /// Retrieve the settings of the Token's owner
        /// </summary>
        private void GetSettings()
        {
            ObjectResponseDelegate objectDelegate = delegate(Dictionary <string, object> responseObject)
            {
                Settings = new TokenUserSettings(responseObject);
            };

            _token.ExecuteGETQuery(Resources.TokenUser_GetAccountSettings, objectDelegate);
        }
Example #11
0
        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);
        }
Example #12
0
        // Execute a query that should return a single object
        private Dictionary <string, object> ExecuteQueryWithSingleResponse(
            string url,
            HttpMethod httpMethod,
            ObjectResponseDelegate objectDeletage,
            WebExceptionHandlingDelegate exceptionHandler)
        {
            Dictionary <string, object>[] results = ExecuteQuery(url, httpMethod, objectDeletage, exceptionHandler);

            if (results != null && results.Count() == 1)
            {
                return(results[0]);
            }

            return(null);
        }
Example #13
0
        protected bool Publish(IToken token, string query)
        {
            token = GetQueryToken(token);

            // If id exists it means that the tweet already exist on twitter
            // We cannot republish this tweet
            if (_id != null || _isTweetPublished || _isTweetDestroyed ||
                String.IsNullOrEmpty(_text) || token == null)
            {
                return(false);
            }

            bool result = true;

            WebExceptionHandlingDelegate wexHandler = delegate(WebException wex)
            {
                int indexOfStatus = wex.Response.Headers.AllKeys.ToList().IndexOf("status");

                if (indexOfStatus >= 0)
                {
                    string statusValue = wex.Response.Headers.Get(indexOfStatus);

                    switch (statusValue)
                    {
                    case "403 Forbidden":
                        // You are trying to post the same Tweet another time!
                        result = false;
                        break;

                    default:
                        throw wex;
                    }
                }
                else
                {
                    throw wex;
                }
            };

            ObjectResponseDelegate objectDelegate = Populate;

            token.ExecutePOSTQuery(query, objectDelegate, wexHandler);

            return(result);
        }
Example #14
0
        public void SetFavourite(bool?isFavourite, IToken token = null)
        {
            token = GetQueryToken(token);

            if (token == null || isFavourite == _favourited || isFavourite == null ||
                !_isTweetPublished || _isTweetDestroyed || _id == null)
            {
                return;
            }

            string query = (bool)isFavourite ?
                           String.Format(Resources.Tweet_CreateFavourite, _id)
                : String.Format(Resources.Tweet_DestroyFavourite, _id);

            ObjectResponseDelegate responseDelegate = delegate(Dictionary <string, object> responseObject)
            {
                _favourited = responseObject.GetProp("favorited") as bool?;
            };

            token.ExecutePOSTQuery(query, responseDelegate, null);
        }
Example #15
0
        /// <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);
        }
Example #16
0
        // Execute a basic query
        private Dictionary <string, object>[] ExecuteQuery(
            string url,
            HttpMethod httpMethod,
            ObjectResponseDelegate objectDeletage,
            WebExceptionHandlingDelegate exceptionHandler)
        {
            dynamic result = null;

            try
            {
                // Exception Handler is being called by the OAuthToken
                string response = ExecuteQuery(url, httpMethod, exceptionHandler);

                if (_lastHeadersResult["X-RateLimit-Remaining"] != null)
                {
                    XRateLimitRemaining = Int32.Parse(_lastHeadersResult["X-RateLimit-Remaining"]);
                }

                // Getting the result back from Twitter

                if (response == null)
                {
                    return(null);
                }

                dynamic jsonResponse = _jsSerializer.Deserialize <dynamic>(response);

                if (jsonResponse is object[])
                {
                    object[] temp = (_jsSerializer.Deserialize <dynamic>(response) as object[]);

                    if (temp != null)
                    {
                        result = temp.OfType <Dictionary <string, object> >().ToArray();

                        if (objectDeletage != null)
                        {
                            foreach (Dictionary <string, object> o in result)
                            {
                                objectDeletage(o);
                            }
                        }
                    }
                }
                else
                {
                    result    = new Dictionary <string, object> [1];
                    result[0] = jsonResponse;

                    if (objectDeletage != null)
                    {
                        objectDeletage(jsonResponse);
                    }
                }
            }
            catch (WebException wex)
            {
                #region Exception Management
                // This Exception management should only be called when there is no specific exception handler
                // Or when the Exception Handler gets an error it was not expecting

                if (ExceptionHandler != null)
                {
                    // Use the inner ExceptionHandler
                    ExceptionHandler(wex);
                }
                else
                {
                    throw;
                }

                #endregion
            }

            return(result);
        }
Example #17
0
        /// <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);
        }