Esempio n. 1
0
        public static PNStatusCategory GetPNStatusCategory(WebExceptionStatus webExceptionStatus, string webExceptionMessage)
        {
            PNStatusCategory ret = PNStatusCategory.PNUnknownCategory;

            switch (webExceptionStatus)
            {
            case WebExceptionStatus.RequestCanceled:
                ret = PNStatusCategory.PNCancelledCategory;
                break;

            case WebExceptionStatus.ConnectFailure:
            case WebExceptionStatus.SendFailure:
            case WebExceptionStatus.Pending:
            case WebExceptionStatus.Success:
                ret = PNStatusCategory.PNNetworkIssuesCategory;
                break;

            default:
                if (string.Compare(webExceptionStatus.ToString(), "SecureChannelFailure", StringComparison.CurrentCultureIgnoreCase) == 0 ||
                    string.Compare(webExceptionStatus.ToString(), "NameResolutionFailure", StringComparison.CurrentCultureIgnoreCase) == 0)
                {
                    ret = PNStatusCategory.PNNetworkIssuesCategory;
                }
                else
                {
                    Debug.WriteLine("ATTENTION: webExceptionStatus = " + webExceptionStatus.ToString());
                }
                break;
            }
            return(ret);
        }
Esempio n. 2
0
        public static PubnubErrorCode GetErrorType(WebExceptionStatus webExceptionStatus, string webExceptionMessage)
        {
            PubnubErrorCode ret = PubnubErrorCode.None;

            switch (webExceptionStatus)
            {
                #if ((!__MonoCS__) && (!SILVERLIGHT) && !WINDOWS_PHONE && !NETFX_CORE)
            case WebExceptionStatus.NameResolutionFailure:
                ret = PubnubErrorCode.NameResolutionFailure;
                break;

            case WebExceptionStatus.ProtocolError:
                ret = PubnubErrorCode.ProtocolError;
                break;

            case WebExceptionStatus.ServerProtocolViolation:
                ret = PubnubErrorCode.ServerProtocolViolation;
                break;

            case WebExceptionStatus.ReceiveFailure:
                ret = PubnubErrorCode.ReceiveFailure;
                break;
                #endif
            case WebExceptionStatus.RequestCanceled:
                ret = PubnubErrorCode.WebRequestCanceled;
                break;

            case WebExceptionStatus.ConnectFailure:
                ret = PubnubErrorCode.ConnectFailure;
                break;

            case WebExceptionStatus.Pending:
                if (webExceptionMessage == "Machine suspend mode enabled. No request will be processed.")
                {
                    ret = PubnubErrorCode.PubnubClientMachineSleep;
                }
                break;

            default:
#if NETFX_CORE
                if (webExceptionStatus.ToString() == "NameResolutionFailure")
                {
                    ret = PubnubErrorCode.NameResolutionFailure;
                }
                else
                {
                    Debug.WriteLine("ATTENTION: webExceptionStatus = " + webExceptionStatus.ToString());
                    ret = PubnubErrorCode.None;
                }
#else
                Debug.WriteLine("ATTENTION: webExceptionStatus = " + webExceptionStatus.ToString());
                ret = PubnubErrorCode.None;
#endif
                break;
            }
            return(ret);
        }
Esempio n. 3
0
        public void Send_TransientExceptionEncountered_ShouldBeRetried(WebExceptionStatus webExceptionStatus)
        {
            const int numberTimesToRetry = 5;
            var       retryCount         = 0;

            var retryHandler = new RetryHandler(numberTimesToRetry, 2, 10, RetryHandler.BackOffStrategy.Exponential)
            {
                BackOffFunc = seconds =>
                {
                    retryCount++;
                    return(Task.FromResult(0));
                }
            };

            dynamic restClient = new RestClient("http://test.test", new Config(retryHandler)
                                                .UseUnitTestHandler(request =>
            {
                throw new HttpRequestException(webExceptionStatus.ToString(), new WebException(webExceptionStatus.ToString(), webExceptionStatus));
            }));

            var exception    = Assert.ThrowsAsync <HttpRequestException>(async() => await restClient.Get());
            var webException = exception.InnerException as WebException;

            Assert.That(exception.Data["IsTransient"], Is.EqualTo(true));
            Assert.That(webException?.Status, Is.EqualTo(webExceptionStatus));
            Assert.That(retryCount, Is.EqualTo(numberTimesToRetry));
        }
Esempio n. 4
0
        /// <summary>
        /// Converts the status of a connection to a string.
        /// </summary>
        /// <returns> The readable connection status. </returns>
        /// <param name="status"> The current web exception status. </param>
        public static string HumanReadableConnectionStatus(WebExceptionStatus status)
        {
            switch (status)
            {
            case WebExceptionStatus.NameResolutionFailure:
                return("Server Not Found");

            default:
                return(status.ToString());
            }
        }
Esempio n. 5
0
        private static void RunTestHtml()
        {
            string g   = Guid.NewGuid().ToString();
            string url = @"http://noithatnewlife.com/sofa-g-cp82.html";

            for (int i = 0; i < 1000; i++)
            {
                WebExceptionStatus webExp = new WebExceptionStatus();
                string             html   = GABIZ.Base.HtmlUrl.HTMLTransmitter.getHTML(url, 45, 2, out webExp);
                log.Info(g + ":" + i.ToString() + webExp.ToString());
            }
        }
 internal static string GetWebStatusString(WebExceptionStatus status)
 {
     int index = (int) status;
     if ((index >= s_Mapping.Length) || (index < 0))
     {
         throw new InternalException();
     }
     string str = s_Mapping[index];
     if (str == null)
     {
         str = "net_webstatus_" + status.ToString();
         s_Mapping[index] = str;
     }
     return str;
 }
 protected internal virtual void FailRequest(WebExceptionStatus webStatus)
 {
     if (Logging.On)
     {
         Logging.PrintError(Logging.RequestCache, SR.GetString("net_log_cache_failing_request_with_exception", new object[] { webStatus.ToString() }));
     }
     if (webStatus == WebExceptionStatus.CacheEntryNotFound)
     {
         throw ExceptionHelper.CacheEntryNotFoundException;
     }
     if (webStatus == WebExceptionStatus.RequestProhibitedByCachePolicy)
     {
         throw ExceptionHelper.RequestProhibitedByCachePolicyException;
     }
     throw new WebException(NetRes.GetWebStatusString("net_requestaborted", webStatus), webStatus);
 }
        internal static string GetWebStatusString(WebExceptionStatus status)
        {
            int index = (int)status;

            if ((index >= s_Mapping.Length) || (index < 0))
            {
                throw new InternalException();
            }
            string str = s_Mapping[index];

            if (str == null)
            {
                str = "net_webstatus_" + status.ToString();
                s_Mapping[index] = str;
            }
            return(str);
        }
Esempio n. 9
0
        internal static string GetWebStatusString(WebExceptionStatus status)
        {
            int statusInt = (int)status;

            if (statusInt >= s_Mapping.Length || statusInt < 0)
            {
                throw new InternalException();
            }

            string message = Volatile.Read(ref s_Mapping[statusInt]);

            if (message == null)
            {
                message = "net_webstatus_" + status.ToString();
                Volatile.Write(ref s_Mapping[statusInt], message);
            }
            return(message);
        }
        internal static string GetWebStatusString(WebExceptionStatus status)
        {
            int statusInt = (int)status;

            if (statusInt >= s_Mapping.Length || statusInt < 0)
            {
                throw new InternalException();
            }

            string message = s_Mapping[statusInt];

            if (message == null)
            {
                message = "net_webstatus_" + status.ToString();
                s_Mapping[statusInt] = message;
            }
            return(message);
        }
        internal static string GetWebStatusString(WebExceptionStatus status)
        {
            int statusInt = (int) status;
            if (statusInt >= s_Mapping.Length || statusInt < 0)
            {
                throw new InternalException();
            }

            string message = s_Mapping[statusInt];
            if (message == null)
            {
                message = "net_webstatus_" + status.ToString();
                s_Mapping[statusInt] = message;
            }
            return message;
        }
Esempio n. 12
0
		public static PubnubErrorCode GetErrorType(WebExceptionStatus webExceptionStatus, string webExceptionMessage)
		{
			PubnubErrorCode ret = PubnubErrorCode.None;
			switch (webExceptionStatus)
            {
                #if ((!__MonoCS__) && (!SILVERLIGHT) && !WINDOWS_PHONE && !NETFX_CORE)
				case WebExceptionStatus.NameResolutionFailure:
				ret = PubnubErrorCode.NameResolutionFailure;
				break;
				case WebExceptionStatus.ProtocolError:
				ret = PubnubErrorCode.ProtocolError;
				break;
				case WebExceptionStatus.ServerProtocolViolation:
				ret = PubnubErrorCode.ServerProtocolViolation;
				break;
                #endif
                case WebExceptionStatus.RequestCanceled:
				ret = PubnubErrorCode.WebRequestCanceled;
				break;
				case WebExceptionStatus.ConnectFailure:
                    ret = PubnubErrorCode.ConnectFailure;
				break;
				case WebExceptionStatus.Pending:
				if (webExceptionMessage == "Machine suspend mode enabled. No request will be processed.")
				{
					ret = PubnubErrorCode.PubnubClientMachineSleep;
				}
				break;
				default:
#if NETFX_CORE
                if (webExceptionStatus.ToString() == "NameResolutionFailure")
                {
                    ret = PubnubErrorCode.NameResolutionFailure;
                }
                else
                {
                    Debug.WriteLine("ATTENTION: webExceptionStatus = " + webExceptionStatus.ToString());
                    ret = PubnubErrorCode.None;
                }
#else             
				Debug.WriteLine("ATTENTION: webExceptionStatus = " + webExceptionStatus.ToString());
                ret = PubnubErrorCode.None;
#endif
				break;
			}
			return ret;
		}
Esempio n. 13
0
        internal void WriteHeadersCallback(WebExceptionStatus errorStatus, ConnectStream stream, bool async)
        {
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::WriteHeadersCallback", ValidationHelper.HashString(stream));
            if(errorStatus == WebExceptionStatus.Success)
            {
                bool completed = EndWriteHeaders(async);
                if (!completed) {
                    errorStatus = WebExceptionStatus.Pending;
                }
                else {
                    GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(stream) + "::WriteHeaders completed:true BytesLeftToWrite:" + stream.BytesLeftToWrite.ToString());
                    if (stream.BytesLeftToWrite == 0) {
                        //
                        // didn't go pending, no data to write. we're done.
                        //
                        stream.CallDone();
                    }
                }
            }

            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::WriteHeadersCallback", errorStatus.ToString());
        }
        internal static string GetWebStatusString(WebExceptionStatus status)
        {
            int statusInt = (int) status;
            if (statusInt >= s_Mapping.Length || statusInt < 0)
            {
                throw new InternalException();
            }

            string message = Volatile.Read(ref s_Mapping[statusInt]);
            if (message == null)
            {
                message = "net_webstatus_" + status.ToString();
                Volatile.Write(ref s_Mapping[statusInt], message);
            }
            return message;
        }
Esempio n. 15
0
        /// <summary>
        /// Trata o erro da resposta.
        /// </summary>
        /// <param name="response"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private static Exception HandleErrorResponse(WebResponse response, WebExceptionStatus status)
        {
            Exception exception    = null;
            var       httpResponse = (HttpWebResponse)response;

            try
            {
                if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                {
                    return(new Exception("Unauthorized : " + httpResponse.Server));
                }
                string message = ResourceMessageFormatter.Create(() => Properties.Resources.InvalidServerResponse, httpResponse != null ? FormatHttpStatus(httpResponse) : status.ToString()).Format();
                string name    = null;
                for (int i = 0; i < response.Headers.Count; i++)
                {
                    if (response.Headers.Keys[i] == "X-Exception")
                    {
                        name = response.Headers.GetValues(i)[0];
                        using (var reader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
                        {
                            message = reader.ReadToEnd();
                            break;
                        }
                    }
                }
                exception = new Exception(message);
            }
            catch (Exception exception2)
            {
                return(exception2);
            }
            return(exception);
        }
Esempio n. 16
0
        //
        protected internal virtual void FailRequest(WebExceptionStatus webStatus)
        {
            if (Logging.On)
            {
                Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_failing_request_with_exception, webStatus.ToString()));
            }
            if (webStatus == WebExceptionStatus.CacheEntryNotFound)
            {
                throw ExceptionHelper.CacheEntryNotFoundException;
            }
            else if (webStatus == WebExceptionStatus.RequestProhibitedByCachePolicy)
            {
                throw ExceptionHelper.RequestProhibitedByCachePolicyException;
            }

            throw new WebException(NetRes.GetWebStatusString("net_requestaborted", webStatus), webStatus);
        }
Esempio n. 17
0
		public static PubnubErrorCode GetErrorType(WebExceptionStatus webExceptionStatus, string webExceptionMessage)
		{
			PubnubErrorCode ret = PubnubErrorCode.None;
			switch (webExceptionStatus)
            {
				case WebExceptionStatus.NameResolutionFailure:
				    ret = PubnubErrorCode.NameResolutionFailure;
				    break;
				case WebExceptionStatus.ProtocolError:
				    ret = PubnubErrorCode.ProtocolError;
				    break;
				case WebExceptionStatus.ServerProtocolViolation:
				    ret = PubnubErrorCode.ServerProtocolViolation;
				    break;
                case WebExceptionStatus.ReceiveFailure:
                    ret = PubnubErrorCode.ReceiveFailure;
                    break;
                case WebExceptionStatus.SecureChannelFailure:
                    ret = PubnubErrorCode.ReceiveFailure;
                    break;
                case WebExceptionStatus.RequestCanceled:
				    ret = PubnubErrorCode.WebRequestCanceled;
				    break;
				case WebExceptionStatus.ConnectFailure:
                    ret = PubnubErrorCode.ConnectFailure;
				    break;
                case WebExceptionStatus.TrustFailure:
                    ret = PubnubErrorCode.TrustFailure;
                break;
                case WebExceptionStatus.Timeout:
                    ret = PubnubErrorCode.RequestTimeout;
                    break;
				case WebExceptionStatus.Pending:
				    if (webExceptionMessage == "Machine suspend mode enabled. No request will be processed.")
				    {
					    ret = PubnubErrorCode.PubnubClientMachineSleep;
				    }
				    break;
				default:
#if NETFX_CORE
                if (webExceptionStatus.ToString() == "NameResolutionFailure")
                {
                    ret = PubnubErrorCode.NameResolutionFailure;
                }
                else
                {
                    Debug.WriteLine("ATTENTION: webExceptionStatus = " + webExceptionStatus.ToString());
                    ret = PubnubErrorCode.None;
                }
#else             
				Debug.WriteLine("ATTENTION: webExceptionStatus = " + webExceptionStatus.ToString());
                ret = PubnubErrorCode.None;
#endif
				break;
			}
			return ret;
		}
Esempio n. 18
0
        /*++

            CloseConnectionSocket - close the socket.

            This method is called when we want to close the conection.
            It must be called with the critical section held.

            The key thing about this method is that it's only called
            when we know that we don't have an async read pending with
            the socket, either because we're being called from the read
            callback or we're called after an error from a user read (the
            user read couldn't have happened if we have a read down).
            Because of this it's OK for us to null out the socket and
            let the next caller try to autoreconnect. This makes life
            simpler, all connection closes (either ours or server
            initiated) eventually go through here. This is also the
            only place that can null out the socket - if that happens somewhere
            else, we get into a race condition where an autoreconnect can happen
            while we still have a receive buffer down, which could result in
            two buffers at once.

            As to what we do: we loop through our write list and pull requests
            off it, and give each request an error failure. Then we close the
            socket and null out our reference, and go ahead and let the next
            request go.

            Input:

                status      - WebExceptionStatus indicating the reason that this method
                                was called. This may be WebExceptionStatus.Success,
                                indicating a normal shutdown.

            Returns:

                Nothing.

        --*/
        private void CloseConnectionSocket(WebExceptionStatus status, ref ConnectionReturnResult returnResult) {

            HttpWebRequest[] ReqArray = null;
            HttpWebRequest NextRequest;
            Exception innerException = null;
            bool Retry = true;

            GlobalLog.Enter("Connection#" + ValidationHelper.HashString(this) + "::CloseConnectionSocket", status.ToString());
            GlobalLog.Print("_WriteList Clear() + (size) " + m_WriteList.Count.ToString() + " - cnt#" + ValidationHelper.HashString(this));

            // gets set to null below
            NetworkStream chkTransport = Transport;

                innerException = UnderlyingException;
                UnderlyingException = null;
            // in the case of abort, disable retry
            if (m_Abort) {
                Retry = false;
                status = WebExceptionStatus.RequestCanceled;
                // remove abort
                m_Abort = false; // reset
            }

            DebugDumpArrayListEntries(m_WriteList);

            if ( m_WriteList.Count == 0 ) {
                Retry = false;
                m_Transport = null;
            }
            else {
                ReqArray = new HttpWebRequest[m_WriteList.Count];
                m_WriteList.CopyTo(ReqArray, 0);
                m_WriteList.Clear();
                m_Transport = null;
            }

            CheckIdle();

            //
            // (assumes under crit sec)
            // Copy WriteList off
            // Clear WriteList
            // Search CopiedWriteList for any bad entries and leaves
            //  (this list will get walked through and scanvanged with SetResponse(error))
            // If all are Good Entries to allow for retry and then adds them to beginning of WaitList
            // then clears any error code in m_Error
            //

            if (Retry) {
                foreach (HttpWebRequest Request in ReqArray) {
                    if (!Request.OnceFailed && !(Request.RequireBody && Request.HaveWritten)) {
                        // disable pipeline/mark failure for next time
                        Request.InternalPipelined = false;
                        Request.OnceFailed = true;
                    }
                    else {
                        Retry = false;
                    }
                }

                // if there is something to retry, then readd it to get sent
                //  again on the wait list
                if (Retry && ReqArray.Length > 0) {
                    m_Error = WebExceptionStatus.Success;
                    m_ReadState = ReadState.Start; // FIXFIX
                    m_WaitList.InsertRange(0, ReqArray);

                    CheckNonIdle();

                    ReqArray = null;
                }
                else {
                    Retry = false;
                }
            }

            if (Retry) {
                GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::CloseConnectionSocket() retrying requests");
            }

            NextRequest = CheckNextRequest();

            if (NextRequest == null) {
                // If we don't have another request, then mark the connection
                // as free now. In general, the connection gets marked as
                // busy once we stop doing keep alive on it.

                m_Free = true;
            }

            if (NextRequest != null) {
                m_Free = false;
                StartRequest(NextRequest, false);
            }
            else {
                Monitor.Exit(this);
            }

            if (chkTransport != null) {
                GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::CloseConnectionSocket() closing transport:" + ValidationHelper.HashString(chkTransport));
                chkTransport.Close();
            }

            //
            // On Error from connection,
            //  walk through failed entries and set failure
            //

            if (ReqArray != null) {
                if (status == WebExceptionStatus.Success) {
                    status = WebExceptionStatus.ConnectionClosed;
                }

                ConnectionReturnResult.AddExceptionRange(
                    ref returnResult,
                    ReqArray,
                    new WebException(
                            NetRes.GetWebStatusString("net_connclosed", status),
                            innerException,
                            status,
                            null /* no response */ ));
            }

            GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::CloseConnectionSocket");
        }
Esempio n. 19
0
    /// <summary>
    /// Logs the URL in the TreeView.
    /// </summary>
    /// <param name='url'>
    /// URL to log.
    /// </param>
    /// <param name='status'>
    /// Status/Description to log against the URL.
    /// </param>
    private void AddURL(Uri url, HttpStatusCode status, WebExceptionStatus exceptionStatus, string statusDescription)
    {
        var      resultListStore = (TreeStore)this.tvResults.Model;
        TreeIter iter;

        // try to get the index of the URL in the TreeView
        var index = this.FindIterIndexByURL(url.AbsoluteUri);

        // decide whether to append the status to an existing URL or to create a new line for the URL
        if (-1 != index)
        {
            resultListStore.GetIterFromString(out iter, index.ToString());
        }
        else
        {
            iter = resultListStore.AppendValues(url.AbsoluteUri);
        }

        if (status.ToString() == statusDescription.Replace(" ", ""))
        {
            statusDescription = string.Empty;
        }

        resultListStore.AppendValues(iter, string.Format("{0} {1} {2}", status.ToString(), exceptionStatus.ToString(), statusDescription).Trim(), DateTime.Now.ToString());
        this.tvResults.Model = resultListStore;
    }
        public void Status_IsNotTransient(WebExceptionStatus status)
        {
            var ex = new WebException(status.ToString(), status);

            Assert.IsFalse(_retryStrategy.IsTransient(ex));
        }