Exemplo n.º 1
0
        private HttpWebResponse SendRequestImpl(MethodType type, string url, IEnumerable <KeyValuePair <string, object> > parameters, ConnectionOptions options)
        {
            try
            {
                var prmArray = InternalUtils.FormatParameters(parameters);
                var uri      = CreateUri(type, url, prmArray);

                if (type == MethodType.Post && ContainsBinaryData(prmArray))
                {
                    return(Request.HttpPostWithMultipartFormData(uri, prmArray,
                                                                 CreateAuthorizationHeader(type, uri, null), options));
                }

                return(type == MethodType.Post
                    ? Request.HttpPost(uri, prmArray, CreateAuthorizationHeader(type, uri, prmArray), options)
                    : Request.HttpNoBody(type, uri, CreateAuthorizationHeader(type, uri, null), options));
            }
            catch (WebException ex)
            {
                var tex = TwitterException.Create(ex);
                if (tex != null)
                {
                    throw tex;
                }
                throw;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Sends a request to the specified url with the specified content.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="contentType">The Content-Type header.</param>
        /// <param name="content">The content.</param>
        /// <returns>A <see cref="HttpWebResponse"/>.</returns>
        public HttpWebResponse PostContent(string url, string contentType, byte[] content)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(nameof(url));
            }
            if (string.IsNullOrEmpty(contentType) != (content == null))
            {
                throw new ArgumentException("Both contentType and content must be null or not null.");
            }
            if (contentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException("Use SendRequest method to send the content in application/x-www-form-urlencoded.");
            }

            try
            {
                var uri = new Uri(url);
                return(Request.HttpPost(uri, contentType, content, CreateAuthorizationHeader(MethodType.Post, uri, null), this.ConnectionOptions));
            }
            catch (WebException ex)
            {
                var tex = TwitterException.Create(ex);
                if (tex != null)
                {
                    throw tex;
                }
                throw;
            }
        }
Exemplo n.º 3
0
        private void HandleQueryException(TwitterException ex)
        {
            if (_exceptionHandler.SwallowWebExceptions)
            {
                return;
            }

            throw ex;
        }
Exemplo n.º 4
0
        private void LogExceptionOrThrow(TwitterException ex)
        {
            if (_exceptionHandler.LogExceptions)
            {
                _exceptionHandler.AddTwitterException(ex);
            }

            if (!_exceptionHandler.SwallowWebExceptions)
            {
                throw ex;
            }
        }
Exemplo n.º 5
0
        private void HandleException(
            string queryURL,
            RateLimitTrackerMode rateLimitTrackerMode,
            TwitterException exception,
            ITwitterQuery queryParameter)
        {
            var statusCode = exception.StatusCode;

            if (rateLimitTrackerMode != RateLimitTrackerMode.None && statusCode == TweetinviConsts.STATUS_CODE_TOO_MANY_REQUEST)
            {
                _rateLimitUpdater.ClearRateLimitsForQuery(queryURL);
            }

            _tweetinviEvents.RaiseAfterQueryExecuted(new QueryAfterExecuteExceptionEventArgs(queryParameter, exception));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Verify and get information about the user (requires an access token).
        /// </summary>
        public TwitterUser VerifyCredentials()
        {
            // Make a call to the API
            HttpStatusCode status;
            string         response = Raw.VerifyCredentials(out status);

            // Check for errors
            if (status != HttpStatusCode.OK)
            {
                throw TwitterException.Parse(response);
            }

            // Parse the response
            return(TwitterUser.ParseJson(response));
        }
Exemplo n.º 7
0
        private async Task HandleException(
            ITwitterRequest request,
            TwitterException exception,
            IRateLimitUpdater rateLimitUpdater)
        {
            var       statusCode = exception.StatusCode;
            const int tooManyRequestStatusCode = 429;

            if (request.ExecutionContext.RateLimitTrackerMode != RateLimitTrackerMode.None && statusCode == tooManyRequestStatusCode)
            {
                await rateLimitUpdater.ClearRateLimitsForQueryAsync(request.Query.Url, request.Query.TwitterCredentials).ConfigureAwait(false);
            }

            request.ExecutionContext.Events.RaiseAfterExecutingQuery(new AfterExecutingQueryExceptionEventArgs(request.Query, exception));
        }
 public static void TwitterException(TwitterException ex)
 {
     Console.WriteLine("Something Went wrong");
     Console.WriteLine("Message: " + ex.Message);
     Console.WriteLine("Source: " + ex.Source);
     Console.WriteLine("Stack Trace: " + ex.StackTrace);
     Console.WriteLine("TargetSite: " + ex.TargetSite);
     Console.WriteLine("Inner Exception: " + ex.InnerException);
     Console.WriteLine("HResult: " + ex.HResult);
     Console.WriteLine("HelpLink: " + ex.HelpLink);
     Console.WriteLine("Status: " + ex.Status);
     Console.WriteLine("Twitter Description: " + ex.TwitterDescription);
     Console.WriteLine("WebException: " + ex.WebException);
     Console.WriteLine("Status Code: " + ex.StatusCode);
 }
Exemplo n.º 9
0
        internal static Task <AsyncResponse> ResponseCallback(this Task <AsyncResponse> task, CancellationToken cancellationToken)
        {
            return(task.Done(async res =>
            {
                if (!res.Source.IsSuccessStatusCode)
                {
                    var tex = await TwitterException.Create(res).ConfigureAwait(false);
                    if (tex != null)
                    {
                        throw tex;
                    }
                    res.Source.EnsureSuccessStatusCode();
                }

                return res;
            }, cancellationToken).Unwrap());
        }
Exemplo n.º 10
0
 /// <summary>
 /// Sends a request to the specified url with the specified parameters.
 /// </summary>
 /// <returns>
 /// The stream.
 /// </returns>
 /// <param name='type'>
 /// Type of HTTP request.
 /// </param>
 /// <param name='url'>
 /// URL.
 /// </param>
 /// <param name='parameters'>
 /// Parameters.
 /// </param>
 public Stream SendRequest(MethodType type, string url, IDictionary <string, object> parameters)
 {
     try
     {
         foreach (var kvp in parameters.ToArray())
         {
             if (kvp.Value is IEnumerable <string> ||
                 kvp.Value is IEnumerable <int> ||
                 kvp.Value is IEnumerable <uint> ||
                 kvp.Value is IEnumerable <long> ||
                 kvp.Value is IEnumerable <ulong> ||
                 kvp.Value is IEnumerable <decimal> ||
                 kvp.Value is IEnumerable <float> ||
                 kvp.Value is IEnumerable <double> )
             {
                 parameters[kvp.Key] = ((System.Collections.IEnumerable)kvp.Value)
                                       .Cast <object>().Select(x => x.ToString())
                                       .JoinToString(",");
             }
         }
         if (type != MethodType.Get && parameters.Values.Any(x => x is Stream || x is IEnumerable <byte> || x is FileInfo))
         {
             return(Request.HttpPostWithMultipartFormData(url, parameters,
                                                          CreateAuthorizationHeader(type, url, null), UserAgent, Proxy, type == MethodType.Post));
         }
         else
         {
             var header = CreateAuthorizationHeader(type, url, parameters);
             return(type == MethodType.Get ? Request.HttpGet(url, parameters, header, UserAgent, Proxy) :
                    type == MethodType.Post ? Request.HttpPost(url, parameters, header, UserAgent, Proxy, true) :
                    Request.HttpPost(url, parameters, header, UserAgent, Proxy, false));
         }
     }
     catch (WebException ex)
     {
         var tex = TwitterException.Create(this, ex);
         if (tex != null)
         {
             throw tex;
         }
         else
         {
             throw;
         }
     }
 }
Exemplo n.º 11
0
        internal static Task <AsyncResponse> ResponseCallback(this Task <AsyncResponse> task, CancellationToken cancellationToken)
        {
#if WIN_RT
            return(task.ContinueWith(async t =>
            {
                if (t.IsFaulted)
                {
                    t.Exception.InnerException.Rethrow();
                }

                if (!t.Result.Source.IsSuccessStatusCode)
                {
                    var tex = await TwitterException.Create(t.Result).ConfigureAwait(false);
                    if (tex != null)
                    {
                        throw tex;
                    }
                    t.Result.Source.EnsureSuccessStatusCode();
                }

                return t.Result;
            }, cancellationToken).Unwrap());
#else
            return(task.ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    var wex = t.Exception.InnerException as WebException;
                    if (wex != null)
                    {
                        var tex = TwitterException.Create(wex);
                        if (tex != null)
                        {
                            throw tex;
                        }
                    }
                    t.Exception.InnerException.Rethrow();
                }

                return t.Result;
            }, cancellationToken));
#endif
        }
Exemplo n.º 12
0
        Task <AsyncResponse> ResponseCallback(Task <AsyncResponse> t)
        {
#if WIN_RT
            if (t.IsFaulted)
            {
                throw t.Exception.InnerException;
            }

            if (!t.Result.Source.IsSuccessStatusCode)
            {
                var tex = await TwitterException.Create(t.Result).ConfigureAwait(false);

                if (tex != null)
                {
                    throw tex;
                }
                t.Result.Source.EnsureSuccessStatusCode();
            }

            return(t.Result);
#else
            return(Task.Factory.StartNew(() =>
            {
                if (t.IsFaulted)
                {
                    var wex = t.Exception.InnerException as WebException;
                    if (wex != null)
                    {
                        var tex = TwitterException.Create(wex);
                        if (tex != null)
                        {
                            throw tex;
                        }
                    }
                    throw t.Exception.InnerException;
                }

                return t.Result;
            }));
#endif
        }
Exemplo n.º 13
0
        public void TestInitialize()
        {
            _fakeBuilder             = new FakeClassBuilder <TweetQueryExecutor>();
            _fakeTweetQueryGenerator = _fakeBuilder.GetFake <ITweetQueryGenerator>();
            _fakeTwitterAccessor     = _fakeBuilder.GetFake <ITwitterAccessor>();

            var fakeWebExceptionInfoExtractor = A.Fake <IWebExceptionInfoExtractor>();

            var twitter139ExceptionInfos = new TwitterExceptionInfo {
                Code = 139
            };

            fakeWebExceptionInfoExtractor.CallsTo(x => x.GetTwitterExceptionInfo(It.IsAny <WebException>())).Returns(new [] { twitter139ExceptionInfos });
            _fake139TwitterException = new TwitterException(fakeWebExceptionInfoExtractor, new WebException(), TestHelper.GenerateString());

            var twitterOtherExceptionInfos = new TwitterExceptionInfo {
                Code = 1
            };

            fakeWebExceptionInfoExtractor.CallsTo(x => x.GetTwitterExceptionInfo(It.IsAny <WebException>())).Returns(new[] { twitterOtherExceptionInfos });
            _fakeOtherTwitterException = new TwitterException(fakeWebExceptionInfoExtractor, new WebException(), TestHelper.GenerateString());
        }
Exemplo n.º 14
0
        private void LogExceptionOrThrow(TwitterException ex)
        {
            if (_exceptionHandler.LogExceptions)
            {
                _exceptionHandler.AddTwitterException(ex);
            }

            if (!_exceptionHandler.SwallowWebExceptions)
            {
                throw ex;
            }
        }
		public override abstract void Failure (TwitterException p0);
Exemplo n.º 16
0
        /// <summary>
        /// Gets a user from the specified <var>JsonObject</var>.
        /// </summary>
        /// <param name="obj">The instance of <var>JsonObject</var> to parse.</param>
        public static TwitterUser Parse(JsonObject obj)
        {
            // Error checking
            if (obj == null)
            {
                return(null);
            }
            if (obj.HasValue("error"))
            {
                throw TwitterException.Parse(obj.GetArray("error"));
            }

            TwitterUser user = new TwitterUser(obj);

            #region Basic properties

            user.Id              = obj.GetInt64("id");
            user.IdStr           = obj.GetString("id_str");
            user.Name            = obj.GetString("name");
            user.ScreenName      = obj.GetString("screen_name");
            user.Location        = obj.GetString("location");
            user.Url             = obj.GetString("url");
            user.Description     = obj.GetString("description");
            user.IsProtected     = obj.GetBoolean("protected");
            user.FollowersCount  = obj.GetInt32("followers_count");
            user.FriendsCount    = obj.GetInt32("friends_count");
            user.ListedCount     = obj.GetInt32("listed_count");
            user.CreatedAt       = TwitterUtils.ParseDateTime(obj.GetString("created_at"));
            user.FavouritesCount = obj.GetInt32("favourites_count");
            if (obj.HasValue("utc_offset"))
            {
                user.UtcOffset = obj.GetInt32("utc_offset");
            }
            user.TimeZone            = obj.GetString("time_zone");
            user.IsGeoEnabled        = obj.GetBoolean("geo_enabled");
            user.IsVerified          = obj.GetBoolean("verified");
            user.StatusesCount       = obj.GetInt32("statuses_count");
            user.Language            = obj.GetString("lang");
            user.ContributorsEnabled = obj.GetBoolean("contributors_enabled");
            user.IsTranslator        = obj.GetBoolean("is_translator");
            user.FollowRequestSent   = obj.HasValue("follow_request_sent") && obj.GetBoolean("follow_request_sent");
            user.Status   = obj.GetObject("status", TwitterStatusMessage.Parse);
            user.Entities = obj.GetObject("entities", TwitterUserEntities.Parse);

            #endregion

            #region Profile properties

            user.HasDefaultProfile              = obj.GetBoolean("default_profile");
            user.HasDefaultProfileImage         = obj.GetBoolean("default_profile_image");
            user.ProfileBackgroundColor         = obj.GetString("profile_background_color");
            user.ProfileBackgroundImageUrl      = obj.GetString("profile_background_image_url");
            user.ProfileBackgroundImageUrlHttps = obj.GetString("profile_background_image_url_https");
            user.ProfileBackgroundTile          = obj.GetBoolean("profile_background_tile");
            user.ProfileBannerUrl          = obj.GetString("profile_banner_url");
            user.ProfileImageUrl           = obj.GetString("profile_image_url");
            user.ProfileImageUrlHttps      = obj.GetString("profile_image_url_https");
            user.ProfileLinkColor          = obj.GetString("profile_link_color");
            user.ProfileSidebarBorderColor = obj.GetString("profile_sidebar_border_color");
            user.ProfileSidebarFillColor   = obj.GetString("profile_sidebar_fill_color");
            user.ProfileTextColor          = obj.GetString("profile_text_color");
            user.ProfileUseBackgroundImage = obj.GetBoolean("profile_use_background_image");

            #endregion

            return(user);
        }
Exemplo n.º 17
0
		private Task<string> CallAsyncBase(string method, Uri uri, IDictionary<string, object> dic, string str, byte[] arr, Stream stm, string contentType = ContentType, string callback = null)
		{
			method = method.ToUpper();

			return Task.Factory.StartNew<string>(() =>
				{
					Exception ex;

					try
					{
						HttpWebRequest req = this.MakeRequestBase(method, uri, dic, str, arr, stm, callback) as HttpWebRequest;
						req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

						if (!string.IsNullOrEmpty(contentType))
							req.ContentType = contentType;

						if (this.Proxy != null)
							req.Proxy = this.Proxy;

						if (method == "POST" && (stm != null || arr != null || dic != null || str != null))
						{
							if (stm != null)
							{
								if (stm.CanSeek) stm.Seek(0, SeekOrigin.Begin);

								req.ContentLength = stm.Length;
								WriteTo(stm, req.GetRequestStream());
							}
							else
							{
								Stream streamReq;
								if (arr != null)
									streamReq = new MemoryStream(arr);
								else if (dic != null)
									streamReq = new MemoryStream(Encoding.UTF8.GetBytes(TOAuth.ToString(dic, true)));
								else
									streamReq = new MemoryStream(Encoding.UTF8.GetBytes(str));

								using (streamReq)
								{
									req.ContentLength = streamReq.Length;
									WriteTo(streamReq, req.GetRequestStream());
								}
							}
						}

						using (WebResponse wres = req.GetResponse())
							using (Stream stream = wres.GetResponseStream())
								using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
									return reader.ReadToEnd();
					}
					catch (WebException e)
					{
						TwitterException te;

						if (e.Response != null)
						{
							using (e.Response)
							{
								using (Stream stream = e.Response.GetResponseStream())
								{
									using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
									{
										te = new TwitterException(e, e.Status, reader.ReadToEnd());
										reader.Close();
									}
								}
							}
							
							ex = te;
						}
						else
							ex = e;
					}
					catch (Exception e)
					{
						ex = e;
					}

					if (ex != null)
						throw ex;

					return null;
				});
		}
Exemplo n.º 18
0
		private void ErrorSet(Exception e, Async async)
		{
			try
			{
				if (e is WebException)
				{
					WebException we = e as WebException;
		
					TwitterException te;

					using (we.Response)
					{
						using (StreamReader reader = new StreamReader(we.Response.GetResponseStream(), Encoding.UTF8))
						{
							te = new TwitterException(e, we.Status, reader.ReadToEnd());
							reader.Close();
						}
						we.Response.Close();
					}
				
					async.Exception = te;
				}
				else
				{
					async.Exception = e;
				}

				try
				{
					async.Request.Abort();
				}
				catch { }
			}
			catch { }

			async.IsCompleted = true;

			async.AsyncWaitHandle.Set();
			if (async.CallBack != null)
				async.CallBack.Invoke(async);
		}
Exemplo n.º 19
0
 public override void Failure(TwitterException failureException)
 {
     Toast.MakeText(context, context.GetString(Resource.String.uploadContactsError), ToastLength.Short).Show();
 }
Exemplo n.º 20
0
        /// <summary>
        /// Gets a status message (tweet) from the specified <var>JsonObject</var>.
        /// </summary>
        /// <param name="obj">The instance of <var>JsonObject</var> to parse.</param>
        public static TwitterStatusMessage Parse(JsonObject obj)
        {
            // Error checking
            if (obj == null)
            {
                return(null);
            }
            if (obj.HasValue("error"))
            {
                throw TwitterException.Parse(obj.GetArray("error"));
            }
            if (obj.HasValue("errors"))
            {
                throw TwitterException.Parse(obj.GetArray("errors"));
            }

            TwitterStatusMessage msg = new TwitterStatusMessage(obj)
            {
                Id          = obj.GetInt64("id"),
                Text        = obj.GetString("text"),
                Source      = obj.GetString("source"),
                IsTruncated = obj.GetBoolean("truncated")
            };

            // Twitter has some strange date formats
            msg.CreatedAt = TwitterUtils.ParseDateTimeUtc(obj.GetString("created_at"));

            // Parse the reply information
            if (obj.HasValue("in_reply_to_status_id"))
            {
                msg.InReplyTo = new TwitterReplyTo {
                    StatusId    = obj.GetInt64("in_reply_to_status_id"),
                    StatusIdStr = obj.GetString("in_reply_to_status_id_str"),
                    UserId      = obj.GetInt64("in_reply_to_user_id"),
                    UserIdStr   = obj.GetString("in_reply_to_user_id_str"),
                    ScreenName  = obj.GetString("in_reply_to_screen_name")
                };
            }

            msg.RetweetCount  = obj.GetInt32("retweet_count");
            msg.FavoriteCount = obj.GetInt32("favorite_count");

            // Related to the authenticating user
            msg.HasFavorited = obj.GetBoolean("favorited");
            msg.HasRetweeted = obj.GetBoolean("retweeted");

            // Parse the entities (if any)
            msg.Entities = obj.GetObject("entities", TwitterStatusMessageEntities.Parse);

            // For some weird reason Twitter flips the coordinates by writing longitude before latitude
            // See: https://dev.twitter.com/docs/platform-objects/tweets#obj-coordinates)
            msg.Coordinates = TwitterCoordinates.Parse(obj.GetObject("coordinates"));

            // See: https://dev.twitter.com/docs/platform-objects/tweets#obj-contributors

            /*if (tweet.contributors != null) {
             *  List<TwitterContributor> contributors = new List<TwitterContributor>();
             *  foreach (dynamic contributor in tweet.contributors) {
             *      contributors.Add(new TwitterContributor {
             *          UserId = contributor.id,
             *          ScreenName = contributor.screen_name
             *      });
             *  }
             *  msg.Contributors = contributors.ToArray();
             * }*/

            msg.User  = obj.GetObject("user", TwitterUser.Parse);
            msg.Place = obj.GetObject("place", TwitterPlace.Parse);

            msg.IsPossiblyOffensive = obj.GetBoolean("possibly_sensitive");
            msg.Language            = obj.GetString("lang");

            return(msg);
        }