protected void CheckIfTokenExpired(HttpRequestException e)
        {
            const string unauthorizedMessage = "401 (Unauthorized)";

            if (e.Message == unauthorizedMessage)
            {
                ShowViewModel<LoginViewModel>();
            }
        }
Пример #2
0
 protected override async Task<Exception> HandleHttpRequestExceptionAsync(HttpRequestException exception) {
     // Broker is not responding. Try regular ping.
     string status = await Uri.GetMachineOnlineStatusAsync();
     return string.IsNullOrEmpty(status)
         ? new RHostDisconnectedException(Resources.Error_BrokerNotRunning.FormatInvariant(Name), exception)
         : await base.HandleHttpRequestExceptionAsync(exception);
 }
 public MediaFireApiException(
     HttpRequestException requestException,
     HttpRequestConfiguration requestConfiguration,
     MediaFireResponseBase errorDetails)
     : base(errorDetails.Message)
 {
     RequestException = requestException;
     RequestConfiguration = requestConfiguration;
     Response = errorDetails;
 }
Пример #4
0
        public static NFXException Throw(HttpStatusCode code, Exception originalException, DropBoxRequest request)
        {
            StringBuilder additionallyMessage = new StringBuilder();
            additionallyMessage.Append(GetDescriptionByCode(code));
            additionallyMessage.AppendFormat(" Url: {0}; MethodName: {1}."
                                             , request.CreateHttpRequestMessage().RequestUri
                                             , request.MethodName);
            if (originalException is HttpRequestException)
                originalException = new HttpRequestException(originalException.Message, originalException);

            return new NFXException(additionallyMessage.ToString(), originalException);
        }
Пример #5
0
 public static HttpResponseMessage ProcessGetResponseWebException(HttpRequestException requestException, HttpRequestMessage request, HttpAbortReason abortReason)
 {
     var inner = requestException.InnerException;
     if (inner != null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertHttpRequestException(requestException, request, abortReason));
     }
     else
     {
         // There is no inner exception so there's not enough information to be able to convert to the correct WCF exception.
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(requestException.Message, requestException));
     }
 }
 public static WebDavClientException Create (HttpRequestException x)
 {
   var match = Regex.Match (x.Message, @"'(?<code>\d{3})'\s+\('(?<description>.*?)'\)");
   if (match.Success)
   {
     return new WebDavClientException (
         x,
         (HttpStatusCode) int.Parse (match.Groups["code"].Value),
         match.Groups["description"].Value);
   }
   else
   {
     return new WebDavClientException (x, null, null);
   }
 }
Пример #7
0
        public static RestServiceException Parse(HttpRequestException ex, RestSharpClientShim client, RequestShim req)
        {
            var err = ParseByMessage(ex, client, req);
            if (err == null)
                err = ParseByMessage(ex.InnerException, client, req);
            if (err != null) return err;


            var inr = ex.InnerException;

            if (inr == null)
                return Unknown("No inner exception", ex, client, req);

            if (inr is WebException)
                return CastWebException((WebException)inr, client, req);

            return Unknown("None of the Parse-ables", ex, client, req);
        }
Пример #8
0
        public static Exception ConvertHttpRequestException(HttpRequestException exception, HttpRequestMessage request, HttpAbortReason abortReason)
        {
            Contract.Assert(exception.InnerException != null, "InnerException must be set to be able to convert");

            uint hresult = (uint)exception.InnerException.HResult;
            switch (hresult)
            {
                // .Net Native HttpClientHandler sometimes reports an incorrect handle state when a connection is aborted, so we treat it as a connection reset error
                case WININET_E_INCORRECT_HANDLE_STATE:
                    goto case WININET_E_CONNECTION_RESET;
                case WININET_E_CONNECTION_RESET:
                    return new CommunicationException(SR.Format(SR.HttpReceiveFailure, request.RequestUri), exception);
                case WININET_E_NAME_NOT_RESOLVED:
                    return new EndpointNotFoundException(SR.Format(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), exception);
                default:
                    return new CommunicationException(exception.Message, exception);
            }
        }
 public async Task publishContainerRoot(ContainerRoot containerRoot)
 {
     var saver = new org.kevoree.pmodeling.api.json.JSONModelSerializer();
     string json = saver.serialize(containerRoot);
     using (var client = new HttpClient())
     {
         client.BaseAddress = new Uri(baseUrl);
         client.DefaultRequestHeaders.Accept.Clear();
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         var httpcontent = new StringContent(json, Encoding.UTF8, "application/json");
         var res = await client.PostAsync("/deploy", httpcontent);
         if (!res.IsSuccessStatusCode)
         {
             var e = new HttpRequestException();
             throw e;
         }
     }
 }
Пример #10
0
        protected HttpInput(IHttpTransportFactorySettings settings, bool isRequest, bool enableChannelBinding)
        {
            _settings = settings;
            _bufferManager = settings.BufferManager;
            _messageEncoder = settings.MessageEncoderFactory.Encoder;
            _httpRequestException = null;
            _isRequest = isRequest;
            _inputStream = null;
            _enableChannelBinding = enableChannelBinding;

            if (isRequest)
            {
                _streamed = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
            }
            else
            {
                _streamed = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
            }
        }
        /// <summary>
        /// Send (or 'ping') the URL of this sites sitemap.xml file to search engines like Google, Bing and Yahoo, 
        /// This method should be called each time the sitemap changes. Google says that 'We recommend that you 
        /// resubmit a Sitemap no more than once per hour.' The way we 'ping' our sitemap to search engines is 
        /// actually an open standard See 
        /// http://www.sitemaps.org/protocol.html#submit_ping
        /// You can read the sitemap ping documentation for the top search engines below:
        /// Google - http://googlewebmastercentral.blogspot.co.uk/2014/10/best-practices-for-xml-sitemaps-rssatom.html
        /// Bing - http://www.bing.com/webmaster/help/how-to-submit-sitemaps-82a15bd4.
        /// Yahoo - https://developer.yahoo.com/search/siteexplorer/V1/ping.html
        /// </summary>
#if Release
        public async Task PingSearchEngines()
        {
            foreach (string sitemapPingLocation in SitemapPingLocations)
            {
                string url = sitemapPingLocation + 
                    this.urlHelper.Encode(this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetSitemapXml));
                HttpResponseMessage response = await this.httpClient.GetAsync(url);
                if (!response.IsSuccessStatusCode)
                {
                    HttpRequestException exception = new HttpRequestException(string.Format(
                        CultureInfo.InvariantCulture,
                        "Pinging search engine {0}. Response status code does not indicate success: {1} ({2}).",
                        url,
                        (int)response.StatusCode,
                        response.ReasonPhrase));
                    this.logger.LogError("Error while pinging site-map to search engines.", exception)
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Iterates a request over a set of proxies until one works, or all proxies have failed.
        /// </summary>
        /// <param name="multiProxy">The set of proxies to use.</param>
        /// <param name="firstProxy">The first proxy try.</param>
        private async Task <HttpResponseMessage> SendAsyncMultiProxy(HttpRequestMessage request, bool doRequestAuth, MultiProxy multiProxy, Uri firstProxy, CancellationToken cancellationToken)
        {
            HttpRequestException rethrowException = null;

            do
            {
                try
                {
                    return(await SendAsyncCore(request, firstProxy, doRequestAuth, isProxyConnect : false, cancellationToken).ConfigureAwait(false));
                }
                catch (HttpRequestException ex) when(ex.AllowRetry != RequestRetryType.NoRetry)
                {
                    rethrowException = ex;
                }
            }while (multiProxy.ReadNext(out firstProxy, out _));

            ExceptionDispatchInfo.Throw(rethrowException);
            return(null); // should never be reached: VS doesn't realize Throw() never returns.
        }
Пример #13
0
        private static Exception GetStreamCopyException(Exception originalException)
        {
            // HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream
            // provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content
            // types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple
            // exceptions (depending on the underlying transport), but just HttpRequestExceptions
            // Custom stream should throw either IOException or HttpRequestException.
            // We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we
            // don't want to hide such "usage error" exceptions in HttpRequestException.
            // ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in
            // the response stream being closed.
            Exception result = originalException;

            if ((result is IOException) || (result is ObjectDisposedException))
            {
                result = new HttpRequestException(SR.net_http_content_stream_copy_error, result);
            }
            return(result);
        }
Пример #14
0
        /// <summary>
        /// Send (or 'ping') the URL of this sites sitemap.xml file to search engines like Google, Bing and Yahoo, 
        /// This method should be called each time the sitemap changes. Google says that 'We recommend that you 
        /// resubmit a Sitemap no more than once per hour.' The way we 'ping' our sitemap to search engines is 
        /// actually an open standard See 
        /// http://www.sitemaps.org/protocol.html#submit_ping
        /// You can read the sitemap ping documentation for the top search engines below:
        /// Google - http://googlewebmastercentral.blogspot.co.uk/2014/10/best-practices-for-xml-sitemaps-rssatom.html
        /// Bing - http://www.bing.com/webmaster/help/how-to-submit-sitemaps-82a15bd4.
        /// Yahoo - https://developer.yahoo.com/search/siteexplorer/V1/ping.html
        /// </summary>
        public async Task PingSearchEngines()
        {

            if (this.hostingEnvironment.IsProduction())
            {
                foreach (var sitemapPingLocation in this.sitemapSettings.Value.SitemapPingLocations)
                {
                    var sitemapUrl = this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetSitemapXml).TrimEnd('/');
                    var url = sitemapPingLocation + WebUtility.UrlEncode(sitemapUrl);
                    var response = await this.httpClient.GetAsync(url);
                    if (!response.IsSuccessStatusCode)
                    {
                        var exception = new HttpRequestException(string.Format(
                            CultureInfo.InvariantCulture,
                            "Pinging search engine {0}. Response status code does not indicate success: {1} ({2}).",
                            url,
                            (int)response.StatusCode,
                            response.ReasonPhrase));
                        this.logger.LogError("Error while pinging site-map to search engines.", exception);
                    }
                }
            }
        }
Пример #15
0
        internal static WebExceptionStatus GetStatusFromException(HttpRequestException ex)
        {
            WebExceptionStatus status;

            // Issue 2384: update WebException.GetStatusFromException after System.Net.Http API changes
            //
            // For now, we use the .HResult of the exception to help us map to a suitable
            // WebExceptionStatus enum value.  The .HResult is set into this exception by
            // the underlying .NET Core and .NET Native versions of the System.Net.Http stack.
            // In the future, the HttpRequestException will have its own .Status property that is
            // an enum type that is more compatible directly with the WebExceptionStatus enum.
            switch (ex.HResult)
            {
                case (int)Interop.Http.CURLcode.CURLE_COULDNT_RESOLVE_HOST:
                    status = WebExceptionStatus.NameResolutionFailure;
                    break;
                default:
                    status = WebExceptionStatus.UnknownError;
                    break;
            }

            return status;
        }
Пример #16
0
		public async Task GetVariableValueAsyncHttpRequestExceptionTest()
		{
			using (ParticleCloudMock cloud = new ParticleCloudMock())
			{
				var ex = new HttpRequestException("Unable to resolve");
				cloud.RequestCallBack = (a, b, c) =>
				{
					throw ex;
				};

				var p = new ParticleDeviceMock(cloud, JObject.Parse("{'id':'3', 'name': 'test', 'variables':{'temp':'int'}}"));
				Assert.IsNotNull(p);
				var vv = await p.GetVariableValueAsync("Test");
				Assert.IsNotNull(vv);
				Assert.IsFalse(vv.Success);
				Assert.AreEqual(ex.Message, vv.Error);
				Assert.AreEqual(ex, vv.Exception);
			}
		}
Пример #17
0
 private static Exception GetStreamCopyException(Exception originalException)
 {
     // HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream
     // provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content
     // types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple
     // exceptions (depending on the underlying transport), but just HttpRequestExceptions
     // Custom stream should throw either IOException or HttpRequestException.
     // We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we
     // don't want to hide such "usage error" exceptions in HttpRequestException.
     // ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in
     // the response stream being closed.
     Exception result = originalException;
     if ((result is IOException) || (result is ObjectDisposedException))
     {
         result = new HttpRequestException(SR.net_http_content_stream_copy_error, result);
     }
     return result;
 }
Пример #18
0
        private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error)
        {
            Contract.Ensures((Contract.Result<MemoryStream>() != null) ||
                (Contract.ValueAtReturn<Exception>(out error) != null));

            error = null;

            // If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the
            // content length exceeds the max. buffer size.
            long? contentLength = Headers.ContentLength;

            if (contentLength != null)
            {
                Debug.Assert(contentLength >= 0);

                if (contentLength > maxBufferSize)
                {
                    error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize));
                    return null;
                }

                // We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize.
                return new LimitMemoryStream((int)maxBufferSize, (int)contentLength);
            }

            // We couldn't determine the length of the buffer. Create a memory stream with an empty buffer.
            return new LimitMemoryStream((int)maxBufferSize, 0);
        }
        protected override internal Task ExecuteRequest(HttpClient httpClient, HttpRequestMessage request)
        {
            object fullBody = null;
            Exception error = null;
            HttpResponseMessage response = null;
            if (_tokenSource.IsCancellationRequested)
            {
                RespondWithResult(fullBody, new Exception(string.Format("{0}: Request {1} has been aborted", this, request)), response);
                var tcs = new TaskCompletionSource<bool>();
                tcs.SetCanceled();
                return tcs.Task;
            }

            Log.D(Tag + ".ExecuteRequest", "Sending request: {0}", request);
            var requestTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_tokenSource.Token);
            var retVal = httpClient.SendAsync(request, requestTokenSource.Token);
            retVal.ConfigureAwait(false).GetAwaiter().OnCompleted(() => {
                requestTokenSource.Dispose();
                try {
                    response = retVal.Result;
                } catch(Exception e) {
                    var err = (e is AggregateException) ? e.InnerException : e;
                    Log.E(Tag, "Unhandled Exception", err);
                    error = err;
                    RespondWithResult(fullBody, err, response);
                    return;
                }

                try
                {
                    if (response == null)
                    {
                        Log.E(Tag, "Didn't get response for {0}", request);

                        error = new HttpRequestException();
                        RespondWithResult(fullBody, error, response);
                    }
                    else if (!response.IsSuccessStatusCode)
                    {
                        HttpStatusCode status = response.StatusCode;

                        Log.E(Tag, "Got error status: {0} for {1}.  Reason: {2}", status.GetStatusCode(), request, response.ReasonPhrase);
                        error = new HttpResponseException(status);

                        RespondWithResult(fullBody, error, response);
                    }
                    else
                    {
                        Log.D(Tag, "Processing response: {0}", response);
                        var entity = response.Content;
                        var contentTypeHeader = entity.Headers.ContentType;
                        Stream inputStream = null;
                        if (contentTypeHeader != null && contentTypeHeader.ToString().Contains("multipart/"))
                        {
                            Log.V(Tag, "contentTypeHeader = {0}", contentTypeHeader.ToString());
                            try
                            {
                                _topReader = new MultipartReader(contentTypeHeader.ToString(), this);
                                inputStream = entity.ReadAsStreamAsync().Result;
                                const int bufLen = 1024;
                                var buffer = new byte[bufLen];
                                var numBytesRead = 0;
                                while ((numBytesRead = inputStream.Read(buffer, 0, bufLen)) > 0)
                                {
                                    if (numBytesRead != bufLen)
                                    {
                                        var bufferToAppend = new Couchbase.Lite.Util.ArraySegment<byte>(buffer, 0, numBytesRead).ToArray();
                                        _topReader.AppendData(bufferToAppend);
                                    }
                                    else
                                    {
                                        _topReader.AppendData(buffer);
                                    }
                                }
                                _topReader.Finished();
                                RespondWithResult(fullBody, error, response);
                            }
                            finally
                            {
                                try
                                {
                                    inputStream.Close();
                                }
                                catch (IOException)
                                {
                                }
                            }
                        }
                        else
                        {
                            Log.V(Tag, "contentTypeHeader is not multipart = {0}", contentTypeHeader.ToString());
                            if (entity != null)
                            {
                                try
                                {
                                    inputStream = entity.ReadAsStreamAsync().Result;
                                    fullBody = Manager.GetObjectMapper().ReadValue<object>(inputStream);
                                    RespondWithResult(fullBody, error, response);
                                }
                                finally
                                {
                                    try
                                    {
                                        inputStream.Close();
                                    }
                                    catch (IOException)
                                    {
                                    }
                                }
                            }
                        }
                    }
                }
                catch (AggregateException e)
                {
                    var err = e.InnerException;
                    Log.E(Tag, "Unhandled Exception", err);
                    error = err;
                    RespondWithResult(fullBody, err, response);
                }
                catch (IOException e)
                {
                    Log.E(Tag, "IO Exception", e);
                    error = e;
                    RespondWithResult(fullBody, e, response);
                }
                catch (Exception e)
                {
                    Log.E(Tag, "ExecuteRequest Exception: ", e);
                    error = e;
                    RespondWithResult(fullBody, e, response);
                }
                finally {
                    response.Dispose();
                }
            });

            return retVal;
        }
Пример #20
0
        protected virtual void OnUserStreamHttpError(HttpRequestException e)
        {

        }
Пример #21
0
        // only valid response codes are 500 (if it's a fault) or 200 (iff it's a response message)
        public static HttpInput ValidateRequestReplyResponse(HttpRequestMessage request, HttpResponseMessage response,
          HttpChannelFactory<IRequestChannel> factory, HttpRequestException responseException)
        {
            ValidateAuthentication(request, response, responseException, factory);

            HttpInput httpInput = null;

            // We will close the HttpResponseMessage if we got an error code betwen 200 and 300 and 
            // 1) an exception was thrown out or 
            // 2) it's an empty message and we are using SOAP.
            // For responses with status code above 300, System.Net will close the underlying connection so we don't need to worry about that.
            if ((200 <= (int)response.StatusCode && (int)response.StatusCode < 300) || response.StatusCode == HttpStatusCode.InternalServerError)
            {
                if (response.StatusCode == HttpStatusCode.InternalServerError
                    && string.Compare(response.ReasonPhrase, HttpChannelUtilities.StatusDescriptionStrings.HttpStatusServiceActivationException, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ServiceActivationException(SR.Format(SR.Hosting_ServiceActivationFailed, request.RequestUri)));
                }
                else
                {
                    bool throwing = true;
                    try
                    {
                        string contentType = GetContentTypeString(response);
                        long contentLength = GetContentLength(response);
                        if (string.IsNullOrEmpty(contentType))
                        {
                            if (!ValidateEmptyContent(response))
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(
                                    new ProtocolException(
                                        SR.HttpContentTypeHeaderRequired,
                                        responseException)));
                            }
                        }
                        else if (contentLength != 0)
                        {
                            MessageEncoder encoder = factory.MessageEncoderFactory.Encoder;
                            if (!encoder.IsContentTypeSupported(contentType))
                            {
                                int bytesRead;
                                String responseExcerpt = GetResponseStreamString(response, out bytesRead);

                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(
                                    new ProtocolException(
                                        SR.Format(
                                            SR.ResponseContentTypeMismatch,
                                            contentType,
                                            encoder.ContentType,
                                            bytesRead,
                                            responseExcerpt), responseException)));
                            }

                            httpInput = HttpInput.CreateHttpInput(response, factory);
                            httpInput.HttpRequestException = responseException;
                        }

                        throwing = false;
                    }
                    finally
                    {
                        if (throwing)
                        {
                            response.Dispose();
                        }
                    }
                }

                if (httpInput == null)
                {
                    if (factory.MessageEncoderFactory.MessageVersion == MessageVersion.None)
                    {
                        httpInput = HttpInput.CreateHttpInput(response, factory);
                        httpInput.HttpRequestException = responseException;
                    }
                    else
                    {
                        // In this case, we got a response with
                        // 1) status code between 200 and 300
                        // 2) Non-empty Content Type string
                        // 3) Zero content length
                        // Since we are trying to use SOAP here, the message seems to be malicious and we should
                        // just close the response directly.
                        response.Dispose();
                    }
                }
            }
            else
            {
                if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new EndpointNotFoundException(SR.Format(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), responseException));
                }

                if (response.StatusCode == HttpStatusCode.ServiceUnavailable)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ServerTooBusyException(SR.Format(SR.HttpServerTooBusy, request.RequestUri.AbsoluteUri), responseException));
                }

                if (response.StatusCode == HttpStatusCode.UnsupportedMediaType)
                {
                    string statusDescription = response.ReasonPhrase;
                    if (!string.IsNullOrEmpty(statusDescription))
                    {
                        if (string.Compare(statusDescription, HttpChannelUtilities.StatusDescriptionStrings.HttpContentTypeMissing, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.Format(SR.MissingContentType, request.RequestUri), responseException));
                        }
                    }
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.Format(SR.FramingContentTypeMismatch, request.Content.Headers.ContentType.ToString(), request.RequestUri), responseException));
                }

                if (response.StatusCode == HttpStatusCode.GatewayTimeout)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(response.StatusCode + " " + response.ReasonPhrase, responseException));
                }

                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedResponseException(responseException, response));
            }

            return httpInput;
        }
Пример #22
0
 private static bool ShouldRetry(HttpRequestException httpRequestException)
 {
     var shouldRetry = false;
     if (httpRequestException.Message.IndexOf(((int)HttpStatusCode.NotFound).ToString(), StringComparison.Ordinal) != -1 ||
         httpRequestException.Message.IndexOf(((int)HttpStatusCode.BadGateway).ToString(), StringComparison.Ordinal) != -1)
     {
         shouldRetry = true;
     }
     else
     {
         var webException = httpRequestException.InnerException as System.Net.WebException;
         if (webException != null)
         {
             if (webException.Status == System.Net.WebExceptionStatus.ConnectFailure)
             {
                 shouldRetry = true;
             }
         }
     }
     return shouldRetry;
 }
        private static string GetFriendlyMessage(HttpRequestException rex)
        {
            if (rex.Message.Contains("404"))
                return "Could not find specified URL. Server responded with Not Found (404) status code";

            return rex.Message;
        }
Пример #24
0
        private static void ValidateAuthentication(HttpRequestMessage request, HttpResponseMessage response,
    HttpRequestException responseException, HttpChannelFactory<IRequestChannel> factory)
        {
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                string message = SR.Format(SR.HttpAuthorizationFailed, factory.AuthenticationScheme,
                    response.Headers.WwwAuthenticate.ToString());
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    TraceResponseException(new MessageSecurityException(message, responseException)));
            }

            if (response.StatusCode == HttpStatusCode.Forbidden)
            {
                string message = SR.Format(SR.HttpAuthorizationForbidden, factory.AuthenticationScheme);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    TraceResponseException(new MessageSecurityException(message, responseException)));
            }
        }
 public HttpRequestExtendedException(HttpResponseMessage response, HttpRequestException excep, string responseContent)
     : base(string.Empty, excep)
 {
     Response = response;
     ResponseContent = responseContent;
 }
            public void CompleteDeserialization(object deserialized)
            {
                HttpRequestException ex = (HttpRequestException)deserialized;

                ex.SerializeObjectState += handleSerialization;
            }
Пример #27
0
		public async Task CallFunctionAsyncHttpRequestExceptionTest()
		{
			using (ParticleCloudMock cloud = new ParticleCloudMock())
			{
				var ex = new HttpRequestException("Unable to Resolve");
				cloud.RequestCallBack = (a, b, c) =>
				{
					throw ex;
				};
				var p = new ParticleDeviceMock(cloud, JObject.Parse("{'id':'3', 'name': 'test', 'functions':['led']}"));
				Assert.IsNotNull(p);
				var cf = await p.CallFunctionAsync("LED", "cheese");
				Assert.IsNotNull(cf);
				Assert.AreEqual(ex.Message, cf.Error);
				Assert.AreEqual(ex, cf.Exception);
			}
		}
 protected abstract void AssertHttpRequestException(System.Net.Http.HttpRequestException e);
Пример #29
0
		public async Task FlashKnownAppAsyncHttpRequestExceptionTest()
		{
			using (ParticleCloudMock cloud = new ParticleCloudMock())
			{
				var ex = new HttpRequestException("Unable to resolve");
				cloud.RequestCallBack = (a, b, c) =>
				{
					throw ex;
				};

				var p = new ParticleDeviceMock(cloud, JObject.Parse("{'id':'3', 'name': 'test'}"));
				var result = await p.FlashKnownAppAsync("tinker");
				Assert.IsNotNull(result);
				Assert.IsFalse(result.Success);
				Assert.AreEqual(ex.Message, result.Error);
				Assert.AreEqual(ex, result.Exception);
			}
		}
        public void Respond_Throwing_Exception()
        {
            var exceptionToThrow = new HttpRequestException("Mocking an HTTP Request Exception.");

            Assert.Throws<HttpRequestException>(() => Test(r => r.Throw(exceptionToThrow)));
        }
Пример #31
0
        public static Exception ConvertHttpRequestException(HttpRequestException exception, HttpRequestMessage request, HttpAbortReason abortReason)
        {
            Contract.Assert(exception.InnerException != null, "InnerException must be set to be able to convert");

            uint hresult = (uint)exception.InnerException.HResult;
            switch (hresult)
            {
                // .Net Native HttpClientHandler sometimes reports an incorrect handle state when a connection is aborted, so we treat it as a connection reset error
                case WININET_E_INCORRECT_HANDLE_STATE:
                    goto case WININET_E_CONNECTION_RESET;
                case WININET_E_CONNECTION_RESET:
                    return new CommunicationException(SR.Format(SR.HttpReceiveFailure, request.RequestUri), exception);
                // Linux HttpClient returns ERROR_INVALID_HANDLE in the endpoint-not-found case, so map to EndpointNotFoundException
                case UnsafeNativeMethods.ERROR_INVALID_HANDLE:
                case WININET_E_NAME_NOT_RESOLVED:
                    return new EndpointNotFoundException(SR.Format(SR.EndpointNotFound, request.RequestUri.AbsoluteUri), exception);
                case CURLE_SSL_CACERT:
                case CURLE_SSL_CERTPROBLEM:
                case ERROR_WINHTTP_SECURE_FAILURE:
                    return new SecurityNegotiationException(SR.Format(SR.TrustFailure, request.RequestUri.Authority), exception);
                default:
                    return new CommunicationException(exception.Message, exception);
            }
        }
 protected static UserErrorModel Handle(HttpRequestException ex)
     =>
     new RecoverableUserError(ex, "Could not connect",
         "A http request has failed, is your internet connected? Are the DNS servers configured correctly?\n\nError info: " +
         ex.Message);
Пример #33
0
        protected override internal void ExecuteRequest(HttpClient httpClient, HttpRequestMessage request)
        {
            object fullBody = null;
            Exception error = null;
            HttpResponseMessage response = null;
            try
            {
                if (_tokenSource.IsCancellationRequested)
                {
                    RespondWithResult(fullBody, new Exception(string.Format("{0}: Request {1} has been aborted", this, request)), response);
                    return;
                }
            }
            catch (AggregateException e)
            {
                var err = e.InnerException;
                Log.E(Tag, "Unhandled Exception", err);
                error = err;
                RespondWithResult(fullBody, err, response);
                return;
            }
            catch (IOException e)
            {
                Log.E(Tag, "IO Exception", e);
                error = e;
                RespondWithResult(fullBody, e, response);
                return;
            }
            catch (Exception e)
            {
                Log.E(Tag, "ExecuteRequest Exception: ", e);
                error = e;
                RespondWithResult(fullBody, e, response);
                return;
            }

            try
            {
                Log.D(Tag + ".ExecuteRequest", "Sending request: {0}", request);
                var requestTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_tokenSource.Token);
                var responseTask = httpClient.SendAsync(request, requestTokenSource.Token);
                if (!responseTask.Wait((Int32)ManagerOptions.Default.RequestTimeout.TotalMilliseconds, requestTokenSource.Token))
                {
                    Log.E(Tag, "Response task timed out: {0}, {1}, {2}", responseTask, TaskScheduler.Current, Description());
                    throw new HttpResponseException(HttpStatusCode.RequestTimeout);
                }
                requestTokenSource.Dispose();
                response = responseTask.Result;
            }
            catch (AggregateException e)
            {
                var err = e.InnerException;
                Log.E(Tag, "Unhandled Exception: {0}, {1}", TaskScheduler.Current, Description());
                Log.E(Tag, "Unhandled Exception at Line 129 or 130", err);
                error = err;
                RespondWithResult(fullBody, err, response);
                return;
            }
            catch (IOException e)
            {
                Log.E(Tag, "IO Exception", e);
                error = e;
                RespondWithResult(fullBody, e, response);
                return;
            }
            catch (Exception e)
            {
                Log.E(Tag, "ExecuteRequest Exception: ", e);
                error = e;
                RespondWithResult(fullBody, e, response);
                return;
            }

            try
            {
                if (response == null)
                {
                    Log.E(Tag, "Didn't get response for {0}", request);

                    error = new HttpRequestException();
                    RespondWithResult(fullBody, error, response);
                }
                else if (!response.IsSuccessStatusCode)
                {
                    HttpStatusCode status = response.StatusCode;

                    Log.E(Tag, "Got error status: {0} for {1}.  Reason: {2}", status.GetStatusCode(), request, response.ReasonPhrase);
                    error = new HttpResponseException(status);

                    RespondWithResult(fullBody, error, response);
                }
                else
                {
                    Log.D(Tag, "Processing response: {0}", response);
                    var entity = response.Content;
                    var contentTypeHeader = entity.Headers.ContentType;
                    Stream inputStream = null;
                    if (contentTypeHeader != null && contentTypeHeader.ToString().Contains("multipart/"))
                    {
                        Log.V(Tag, "contentTypeHeader = {0}", contentTypeHeader.ToString());
                        try
                        {
                            _topReader = new MultipartReader(contentTypeHeader.ToString(), this);
                            inputStream = entity.ReadAsStreamAsync().Result;
                            const int bufLen = 1024;
                            var buffer = new byte[bufLen];
                            var numBytesRead = 0;
                            while ((numBytesRead = inputStream.Read(buffer, 0, bufLen)) > 0)
                            {
                                if (numBytesRead != bufLen)
                                {
                                    var bufferToAppend = new Couchbase.Lite.Util.ArraySegment<byte>(buffer, 0, numBytesRead).ToArray();
                                    _topReader.AppendData(bufferToAppend);
                                }
                                else
                                {
                                    _topReader.AppendData(buffer);
                                }
                            }
                            _topReader.Finished();
                            RespondWithResult(fullBody, error, response);
                        }
                        finally
                        {
                            try
                            {
                                inputStream.Close();
                            }
                            catch (IOException)
                            {
                            }
                        }
                    }
                    else
                    {
                        Log.V(Tag, "contentTypeHeader is not multipart = {0}", contentTypeHeader.ToString());
                        if (entity != null)
                        {
                            try
                            {
                                inputStream = entity.ReadAsStreamAsync().Result;
                                fullBody = Manager.GetObjectMapper().ReadValue<object>(inputStream);
                                RespondWithResult(fullBody, error, response);
                            }
                            finally
                            {
                                try
                                {
                                    inputStream.Close();
                                }
                                catch (IOException)
                                {
                                }
                            }
                        }
                    }
                }
            }
            catch (AggregateException e)
            {
                var err = e.InnerException;
                Log.E(Tag, "Unhandled Exception", err);
                error = err;
                RespondWithResult(fullBody, err, response);
            }
            catch (IOException e)
            {
                Log.E(Tag, "IO Exception", e);
                error = e;
                RespondWithResult(fullBody, e, response);
            }
            catch (Exception e)
            {
                Log.E(Tag, "ExecuteRequest Exception: ", e);
                error = e;
                RespondWithResult(fullBody, e, response);
            }
        }
        /// <summary>
        /// Send (or 'ping') the URL of this sites sitemap.xml file to search engines like Google, Bing and Yahoo, 
        /// This method should be called each time the sitemap changes. Google says that 'We recommend that you 
        /// resubmit a Sitemap no more than once per hour.' The way we 'ping' our sitemap to search engines is 
        /// actually an open standard See 
        /// http://www.sitemaps.org/protocol.html#submit_ping
        /// You can read the sitemap ping documentation for the top search engines below:
        /// Google - http://googlewebmastercentral.blogspot.co.uk/2014/10/best-practices-for-xml-sitemaps-rssatom.html
        /// Bing - http://www.bing.com/webmaster/help/how-to-submit-sitemaps-82a15bd4.
        /// Yahoo - https://developer.yahoo.com/search/siteexplorer/V1/ping.html
        /// </summary>
        public async Task PingSearchEngines()
        {
            // $Start-ApplicationInsights$
            this.telemetryClient.TrackEvent("PingSitemapToSearchEngines");
            // $End-ApplicationInsights$

            if (this.hostingEnvironment.IsProduction())
            {
                foreach (string sitemapPingLocation in this.sitemapSettings.Value.SitemapPingLocations)
                {
                    string sitemapUrl = this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetSitemapXml).TrimEnd('/');
                    string url = sitemapPingLocation + WebUtility.UrlEncode(sitemapUrl);
                    HttpResponseMessage response = await this.httpClient.GetAsync(url);
                    if (!response.IsSuccessStatusCode)
                    {
                        HttpRequestException exception = new HttpRequestException(string.Format(
                            CultureInfo.InvariantCulture,
                            "Pinging search engine {0}. Response status code does not indicate success: {1} ({2}).",
                            url,
                            (int)response.StatusCode,
                            response.ReasonPhrase));
                        // $Start-ApplicationInsights$
                        this.telemetryClient.TrackException(exception, new Dictionary<string, string>() { { "Url", url } });
                        // $End-ApplicationInsights$
                        this.logger.LogError("Error while pinging site-map to search engines.", exception);
                    }
                }
            }
        }