Example #1
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 #2
0
 public Dictionary <string, object>[] ExecutePOSTQueryReturningCollectionOfObjects(
     string url,
     ObjectResponseDelegate objectHandler          = null,
     WebExceptionHandlingDelegate exceptionHandler = null)
 {
     return(ExecuteQuery(url, HttpMethod.POST, objectHandler, exceptionHandler));
 }
Example #3
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 #4
0
        public bool Destroy(IToken token = null, bool getUserInfo = false)
        {
            token = GetQueryToken(token);

            // We cannot destroy a tweet that has not been published
            // We cannot destroy a tweet that has already been destroyed
            if (!_isTweetPublished || _isTweetDestroyed || _id == null || token == null)
            {
                return(false);
            }

            bool result = true;

            // If a WebException occurs, the deletion has not been performed
            WebExceptionHandlingDelegate wex = delegate
            {
                result = false;
            };

            string destroyQuery = String.Format(Resources.Tweet_Destroy, _id);

            token.ExecutePOSTQuery(destroyQuery, null, wex);

            _isTweetDestroyed = result;
            return(result);
        }
Example #5
0
        /// <summary>
        /// Get the Home timeline of the current user
        /// </summary>
        /// <param name="queryToken">Token to be used to perform the query</param>
        /// <param name="count">Maximum number of Tweet received</param>
        /// <param name="trim_user">User information sent with the Tweet</param>
        /// <param name="exclude_replies">When true the replies to tweet are not retrieved</param>
        /// <param name="since_id">Minimum Id of tweet to receive</param>
        /// <param name="max_id">Maximum Id of twee to receive</param>
        /// <param name="wex">Exception handler</param>
        /// <returns>Tweets from the Home timeline</returns>
        private List <ITweet> GetHomeTimeLine(
            IToken queryToken,
            int count,
            bool trim_user,
            bool exclude_replies,
            int?since_id,
            int?max_id,
            WebExceptionHandlingDelegate wex)
        {
            if (queryToken == null)
            {
                Console.WriteLine("Token must be specified");
                return(null);
            }

            string query;

            if (since_id == null && max_id == null)
            {
                query = String.Format(Resources.TokenUser_GetLatestHomeTimeline, count, trim_user, exclude_replies);
            }
            else
            {
                query = String.Format(Resources.TokenUser_GetHomeTimeline,
                                      count, trim_user, exclude_replies, since_id, max_id);
            }

            return(ResultGenerator.GetTweets(queryToken, query, null, wex));
        }
Example #6
0
        /// <summary>
        /// Request the list of direct message from Twitter using the token and the URL given in parameter
        /// Handle the exception when the token represents a user who did not authorize the application to get the direct messages
        /// </summary>
        /// <param name="token"></param>
        /// <param name="url"></param>
        /// <param name="directMessageDelegate"></param>
        /// <returns>The list of messages retrieved from the Twitter API</returns>
        private List <IMessage> GetDirectMessages(IToken token,
                                                  string url,
                                                  ObjectCreatedDelegate <IMessage> directMessageDelegate = null)
        {
            token = GetQueryToken(token);

            if (token == null || url == null)
            {
                throw new ArgumentException("token or request url is null");
            }

            WebExceptionHandlingDelegate webExceptionDelegate = delegate(WebException wex)
            {
                int?wexStatusNumber = ExceptionUtils.GetWebExceptionStatusNumber(wex);
                if (wexStatusNumber == null)
                {
                    throw wex;
                }

                switch (wexStatusNumber)
                {
                case 403:
                    Exception e = new Exception("Not enough permission to access direct messages. " +
                                                "Update the application access level and ask the user to reauthorize it.");
                    throw e;

                default:
                    throw wex;
                }
            };

            return(ResultGenerator.GetMessages(token, url, directMessageDelegate, webExceptionDelegate));
        }
Example #7
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 #8
0
 // Execute a generic simple query
 public virtual string ExecuteQuery(
     string url,
     HttpMethod httpMethod,
     WebExceptionHandlingDelegate exceptionHandler)
 {
     return(ExecuteQueryWithSpecificParameters(url, httpMethod, exceptionHandler, GenerateParameters()));
 }
Example #9
0
        /// <summary>
        /// Reinitialize the list of ids of the users blocked by the current user if required by the boolean parameter.
        /// Retrieve information about the users blocked by the current user from the Twitter API.
        /// </summary>
        /// <param name="blockedUsersQuery">Request to send to the Twitter API</param>
        /// <param name="del">delegate that will handle the data sent in the Twitter API's response</param>
        /// <param name="createBlockedUsersIds">True by default. Update the attribute _blocked_users_ids if this parameter is true</param>
        /// <returns>Null if there is no valid token for the current user. Otherwise, The list of ids of the users blocked by the current user.</returns>
        private void executeBlockedUsersQuery(string blockedUsersQuery,
                                              DynamicResponseDelegate del,
                                              bool createBlockedUsersIds = true)
        {
            // Reset the list of blocked users' ids if required
            if (createBlockedUsersIds)
            {
                _blocked_users_ids = null;
                _blocked_users_ids = new List <long>();
            }

            WebExceptionHandlingDelegate wexDel = delegate(WebException wex)
            {
                int?wexStatusNumber = ExceptionUtils.GetWebExceptionStatusNumber(wex);
                switch (wexStatusNumber)
                {
                // Handle the Exception when the user's token is not valid
                case 401:
                    throw new WebException("Blocked users can only be accessed using the user's token. Any other token is rejected.", wex);

                default:
                    throw wex;
                }
            };

            _token.ExecuteCursorQuery(blockedUsersQuery, 0, Int32.MaxValue, del, wexDel);
        }
Example #10
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>
        /// <returns>Null if there is no user token, the timeline of the current user otherwise</returns>
        public List <ITweet> GetUserTimeline(bool createUserTimeline = false, IToken token = null)
        {
            // Handle the possible exceptions thrown by the Twitter API
            WebExceptionHandlingDelegate wexDel = delegate(WebException wex)
            {
                // Get the exception status number
                int?wexStatusNumber = ExceptionUtils.GetWebExceptionStatusNumber(wex);
                if (wexStatusNumber == null)
                {
                    throw wex;
                }

                switch (wexStatusNumber)
                {
                case 400:
                    //Rate limit reached. Throw a new Exception with a specific message
                    throw new WebException("Rate limit is reached", wex);

                default:
                    //Throw the exception "as-is"
                    throw wex;
                }
            };

            return(GetUserTimeline(_token, wexDel, createUserTimeline));
        }
Example #11
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);
        }
Example #12
0
 public Dictionary <string, object> ExecutePOSTQuery(
     string url,
     ObjectResponseDelegate objectHandler          = null,
     WebExceptionHandlingDelegate exceptionHandler = null)
 {
     return(ExecuteQueryWithSingleResponse(url, HttpMethod.POST, objectHandler, exceptionHandler));
 }
        /// <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 #14
0
        public virtual string ExecuteQueryWithSpecificParameters(
            string url,
            HttpMethod httpMethod,
            WebExceptionHandlingDelegate exceptionHandler,
            IEnumerable <IOAuthQueryParameter> headers)
        {
            string result = null;

            HttpWebRequest httpWebRequest = null;
            WebResponse    response       = null;

            try
            {
                httpWebRequest             = GetQueryWebRequest(url, httpMethod, headers);
                httpWebRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

                // Opening the connection
                response = httpWebRequest.GetResponse();
                Stream stream = response.GetResponseStream();

                _lastHeadersResult = response.Headers;

                if (stream != null)
                {
                    // Getting the result
                    StreamReader responseReader = new StreamReader(stream);
                    result = responseReader.ReadLine();
                }

                // Closing the connection
                response.Close();
                httpWebRequest.Abort();
            }
            catch (WebException wex)
            {
                if (exceptionHandler != null)
                {
                    exceptionHandler(wex);
                }
                else
                {
                    throw;
                }

                if (response != null)
                {
                    response.Close();
                }

                if (httpWebRequest != null)
                {
                    httpWebRequest.Abort();
                }
            }

            return(result);
        }
Example #15
0
 public Dictionary <string, object> ExecuteCursorQuery(
     string url,
     long cursor = 0,
     int max     = Int32.MaxValue,
     DynamicResponseDelegate responseHandler       = null,
     WebExceptionHandlingDelegate exceptionHandler = null)
 {
     return(ExecuteCursorQuery(url, ref cursor, max, responseHandler, exceptionHandler));
 }
Example #16
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(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);
        }
        public IToken GenerateToken(
            string twitterConfirmationCode,
            string authorizationKey,
            string authorizationSecret,
            string consumerKey,
            string consumerSecret)
        {
            IOAuthCredentials credentials = new OAuthCredentials(authorizationKey,
                                                                 authorizationSecret,
                                                                 consumerKey,
                                                                 consumerSecret);

            IOAuthToken token = new OAuthToken(credentials);

            List <IOAuthQueryParameter> headers = token.GenerateParameters().ToList();

            headers.Add(new OAuthQueryParameter("oauth_verifier", twitterConfirmationCode, true, true, false));

            string response = "";

            WebExceptionHandlingDelegate wex = delegate(WebException exception)
            {
                if (ExceptionUtils.GetWebExceptionStatusNumber(exception) == 401)
                {
                    response = null;
                }
            };

            response = token.ExecuteQueryWithSpecificParameters(Resources.OAuthRequestAccessToken,
                                                                HttpMethod.POST,
                                                                wex,
                                                                headers);

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

            Match responseInformation = Regex.Match(response, Resources.OAuthTokenAccessRegex);

            IToken result = null;

            if (responseInformation.Groups["oauth_token"] != null &&
                responseInformation.Groups["oauth_token_secret"] != null)
            {
                result = new Token(responseInformation.Groups["oauth_token"].Value,
                                   responseInformation.Groups["oauth_token_secret"].Value,
                                   consumerKey,
                                   consumerSecret);
            }

            return(result);
        }
        /// <summary>
        /// Provide simplified ways to query a list of Messages
        /// </summary>
        /// <param name="token">Token to be used</param>
        /// <param name="queryUrl">URL from which we expect results</param>
        /// <param name="objectCreatedDelegate">Delegate to happen after a Message being created</param>
        /// <param name="wex">WebException to manage errors</param>
        /// <returns>Collection of messages retrieved from the query</returns>
        public static List <IMessage> GetMessages(IToken token,
                                                  string queryUrl,
                                                  ObjectCreatedDelegate <IMessage> objectCreatedDelegate = null,
                                                  WebExceptionHandlingDelegate wex = null)
        {
            ObjectCreatorDelegate <IMessage> userCreator = delegate(Dictionary <string, object> data)
            {
                return(new Message(data));
            };

            return(GetListOfTwitterObject(token, queryUrl, userCreator, objectCreatedDelegate, wex));
        }
        /// <summary>
        /// Provide simplified ways to query a list of Tweets
        /// </summary>
        /// <param name="token">Token to be used</param>
        /// <param name="queryUrl">URL from which we expect results</param>
        /// <param name="objectCreatedDelegate">Delegate to happen after a Tweet being created</param>
        /// <param name="wex">WebException to manage errors</param>
        /// <returns>Collection of tweets retrieved from the query</returns>
        public static List <ITweet> GetTweets(IToken token,
                                              string queryUrl,
                                              ObjectCreatedDelegate <ITweet> objectCreatedDelegate = null,
                                              WebExceptionHandlingDelegate wex = null)
        {
            ObjectCreatorDelegate <ITweet> tweetCreator = delegate(Dictionary <string, object> data)
            {
                return(new Tweet(data));
            };

            return(GetListOfTwitterObject(token, queryUrl, tweetCreator, objectCreatedDelegate, wex));
        }
Example #20
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);
            }

            return(ResultGenerator.GetUsers(token, url, null, exceptionHandlerDelegate));
        }
Example #21
0
        public Dictionary <string, object> ExecuteCursorQuery(
            string url,
            ref long cursor,
            int max = Int32.MaxValue,
            DynamicResponseDelegate responseHandler       = null,
            WebExceptionHandlingDelegate exceptionHandler = null)
        {
            long previousCursor       = cursor;
            long nextCursor           = -1;
            int  nbOfObjectsProcessed = 0;

            while (previousCursor != nextCursor && nbOfObjectsProcessed < max)
            {
                try
                {
                    string queryDelimiter = "&";
                    if (url.EndsWith(".json") || url.EndsWith(".xml") || url.EndsWith("."))
                    {
                        queryDelimiter = "?";
                    }

                    Dictionary <string, object> responseObject = ExecuteGETQuery(String.Format("{0}" + queryDelimiter + "cursor={1}", url, nextCursor), null, exceptionHandler);

                    // Go to the next object
                    if (responseObject != null)
                    {
                        previousCursor = Int64.Parse(responseObject["previous_cursor"].ToString());
                        nextCursor     = Int64.Parse(responseObject["next_cursor"].ToString());
                    }

                    if (responseHandler != null)
                    {
                        // Manual response management
                        nbOfObjectsProcessed += responseHandler(responseObject, previousCursor, nextCursor);
                    }
                }
                catch (WebException wex)
                {
                    if (ExceptionHandler != null)
                    {
                        ExceptionHandler(wex);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            return(null);
        }
Example #22
0
        /// <summary>
        /// Get the Home timeline of the current user
        /// </summary>
        /// <param name="count">Maximum number of Tweet received</param>
        /// <param name="get_user_info">User information sent with the Tweet</param>
        /// <param name="exclude_replies">When true the replies to tweet are not retrieved</param>
        /// <param name="token">Token to be used to perform the query</param>
        /// <param name="since_id">Minimum Id of tweet to receive</param>
        /// <param name="max_id">Maximum Id of twee to receive</param>
        /// <param name="wex">Exception handler</param>
        /// <returns>Tweets from the Home timeline</returns>
        public List <ITweet> GetHomeTimeline(
            int count                        = 20,
            bool get_user_info               = true,
            bool exclude_replies             = true,
            IToken token                     = null,
            int?since_id                     = null,
            int?max_id                       = null,
            WebExceptionHandlingDelegate wex = null)
        {
            IToken queryToken = token ?? _token;

            return(GetHomeTimeLine(queryToken, count, get_user_info, exclude_replies,
                                   since_id, max_id, wex));
        }
Example #23
0
        public Dictionary <string, object> ExecuteCursorQuery(
            string url,
            long cursor = 0,
            DynamicResponseDelegate responseHandler       = null,
            WebExceptionHandlingDelegate exceptionHandler = null)
        {
            long previousCursor = cursor;
            long nextCursor     = -1;

            while (previousCursor != nextCursor)
            {
                try
                {
                    string queryDelimiter = "&";
                    if (url.EndsWith(".json") || url.EndsWith(".xml") || url.EndsWith("."))
                    {
                        queryDelimiter = "?";
                    }

                    dynamic responseObject = ExecuteGETQuery(String.Format("{0}" + queryDelimiter + "cursor={1}", url, nextCursor), null, exceptionHandler);

                    // Go to the next object
                    if (responseObject != null)
                    {
                        previousCursor = (long)responseObject["previous_cursor"];
                        nextCursor     = (long)responseObject["next_cursor"];
                    }

                    if (responseHandler != null)
                    {
                        // Manual response management
                        responseHandler(responseObject, previousCursor, nextCursor);
                    }
                }
                catch (WebException wex)
                {
                    if (ExceptionHandler != null)
                    {
                        ExceptionHandler(wex);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            return(null);
        }
Example #24
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 #25
0
        /// <summary>
        /// Get the list of contributors to the account of the current user
        /// Update the matching attribute of the current user if the parameter is true
        /// Return the list of contributors
        /// </summary>
        /// <param name="createContributorList">False by default. Indicates if the _contributors attribute needs to be updated with the result</param>
        /// <returns>The list of contributors to the account of the current user</returns>
        public List <IUser> GetContributors(bool createContributorList = false)
        {
            // Specific error handler
            // Manage the error 400 thrown when contributors are not enabled by the current user
            WebExceptionHandlingDelegate del = delegate(WebException wex)
            {
                int?wexStatusNumber = ExceptionUtils.GetWebExceptionStatusNumber(wex);
                if (wexStatusNumber != null)
                {
                    switch (wexStatusNumber)
                    {
                    case 400:
                        // Don't need to do anything, the method will return null
                        Console.WriteLine("Contributors are not enabled for this user");
                        break;

                    default:
                        // Other errors are not managed
                        throw wex;
                    }
                }
                else
                {
                    throw wex;
                }
            };

            List <IUser> result = null;

            // Contributors can be researched according to the user's id or screen_name
            if (this.Id != null)
            {
                result = GetContributionObjects(_token, String.Format(Resources.User_GetContributorsFromId, this.Id), del);
            }
            else if (this.ScreenName != null)
            {
                result = GetContributionObjects(_token, String.Format(Resources.User_GetContributorsFromScreenName, this.ScreenName), del);
            }

            // Update the attribute _contributors if required
            if (createContributorList)
            {
                _contributors = result;
            }

            return(result);
        }
Example #26
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 #27
0
        /// <summary>
        /// Get the list of contributors to the account of the current user
        /// Update the matching attribute of the current user if the parameter is true
        /// Return the list of contributors
        /// </summary>
        /// <param name="createContributorList">False by default. Indicates if the _contributors attribute needs to be updated with the result</param>
        /// <returns>The list of contributors to the account of the current user</returns>
        public List <IUser> GetContributors(bool createContributorList = false)
        {
            // Specific error handler
            // Manage the error 400 thrown when contributors are not enabled by the current user
            WebExceptionHandlingDelegate del = delegate(WebException wex)
            {
                int?wexStatusNumber = ExceptionUtils.GetWebExceptionStatusNumber(wex);
                if (wexStatusNumber != null)
                {
                    switch (wexStatusNumber)
                    {
                    case 400:
                        // Don't need to do anything, the method will return null
                        Console.WriteLine("Contributors are not enabled for this user");
                        break;

                    default:
                        // Other errors are not managed
                        throw wex;
                    }
                }
                else
                {
                    throw wex;
                }
            };

            string query = Resources.User_GetContributors;

            if (!AddUserInformationInQuery(ref query))
            {
                return(null);
            }

            List <IUser> result = GetContributionObjects(_token, query, del);

            if (createContributorList)
            {
                _contributors = result;
            }

            return(result);
        }
Example #28
0
        /// <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;
            }
        }
Example #29
0
        public List <IMention> GetLatestMentionsTimeline(int count = 20)
        {
            string query = String.Format(Resources.TokenUser_GetLatestMentionTimeline, count);

            WebExceptionHandlingDelegate wexDelegate = delegate(WebException wex)
            {
                int?wexStatusNumber = ExceptionUtils.GetWebExceptionStatusNumber(wex);
                switch (wexStatusNumber)
                {
                case 400:
                    throw new WebException("Wrong token for user id = " + this.Id, wex);

                default:
                    throw wex;
                }
            };

            LatestMentionsTimeline = ResultGenerator.GetMentions(_token, query, null, wexDelegate);
            return(LatestMentionsTimeline);
        }
Example #30
0
        /// <summary>
        /// Method allowing to query and url
        /// </summary>
        /// <param name="method_url">Url from Twitter Api to query</param>
        /// <returns>
        /// Return a dynamic object containing the json information
        /// representing the value from a json response
        /// </returns>
        public dynamic ExecuteQuery(string method_url, WebExceptionHandlingDelegate exceptionHandlerDelegate = null)
        {
            dynamic result = null;

            try
            {
                HttpWebRequest web_request    = GenerateRequest(new Uri(method_url));
                WebResponse    response       = web_request.GetResponse();
                StreamReader   responseReader = new StreamReader(web_request.GetResponse().GetResponseStream());

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

                string jsonText = responseReader.ReadLine();
                result = jss.Deserialize <dynamic>(jsonText);

                response.Close();
                web_request.Abort();
            }
            catch (WebException wex)
            {
                if (exceptionHandlerDelegate != null)
                {
                    exceptionHandlerDelegate(wex);
                }
                else
                if (ExceptionHandler != null)
                {
                    ExceptionHandler(wex);
                }
                else
                {
                    throw wex;
                }
            }

            return(result);
        }
Example #31
0
        /// <summary>
        /// Method allowing to query and url
        /// </summary>
        /// <param name="method_url">Url from Twitter Api to query</param>
        /// <returns>
        /// Return a dynamic object containing the json information 
        /// representing the value from a json response
        /// </returns>
        public dynamic ExecuteQuery(string method_url, WebExceptionHandlingDelegate exceptionHandlerDelegate = null)
        {
            dynamic result = null;
            try
            {
                HttpWebRequest web_request = GenerateRequest(new Uri(method_url));
                WebResponse response = web_request.GetResponse();
                StreamReader responseReader = new StreamReader(web_request.GetResponse().GetResponseStream());

                if (response.Headers["X-RateLimit-Remaining"] != null)
                    XRateLimitRemaining = Int32.Parse(response.Headers["X-RateLimit-Remaining"]);

                string jsonText = responseReader.ReadLine();
                result = jss.Deserialize<dynamic>(jsonText);

                response.Close();
                web_request.Abort();

            }
            catch (WebException wex)
            {
                if (exceptionHandlerDelegate != null)
                    exceptionHandlerDelegate(wex);
                else
                    if (ExceptionHandler != null)
                        ExceptionHandler(wex);
                    else
                        throw wex;
            }

            return result;
        }
Example #32
0
        public dynamic ExecuteCursorQuery(string method_url, long cursor = 0,
            DynamicResponseDelegate cursor_delegate = null, WebExceptionHandlingDelegate exceptionHandlerDelegate = null)
        {
            long previous_cursor = cursor;
            long next_cursor = -1;

            while (previous_cursor != next_cursor)
            {
                dynamic responseObject = null;
                try
                {
                    responseObject = this.ExecuteQuery(String.Format("{0}&cursor={1}", method_url, next_cursor));

                    if (responseObject != null)
                    {
                        previous_cursor = (long)responseObject["previous_cursor"];
                        next_cursor = (long)responseObject["next_cursor"];
                    }

                    if (cursor_delegate != null)
                        cursor_delegate(responseObject, previous_cursor, next_cursor);
                }
                catch (WebException wex)
                {
                    if (exceptionHandlerDelegate != null)
                        exceptionHandlerDelegate(wex);
                    else
                        if (ExceptionHandler != null)
                            ExceptionHandler(wex);
                        else
                            throw wex;
                }
            }

            return null;
        }