<commit_before>using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using ServiceStack.Logging;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
using ServiceStack.Common.Web;
#if NETFX_CORE
using Windows.System.Threading;
using System.Threading.Tasks;
#endif

namespace ServiceStack.ServiceClient.Web
{
    /**
     * Need to provide async request options
     * http://msdn.microsoft.com/en-us/library/86wf6409(VS.71).aspx
     */

    public class AsyncServiceClient
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(AsyncServiceClient));
        private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(60);
        private HttpWebRequest _webRequest = null;

        /// <summary>
        /// The request filter is called before any request.
        /// This request filter is executed globally.
        /// </summary>
        public static Action<HttpWebRequest> HttpWebRequestFilter { get; set; }

        /// <summary>
        /// The response action is called once the server response is available.
        /// It will allow you to access raw response information. 
        /// This response action is executed globally.
        /// Note that you should NOT consume the response stream as this is handled by ServiceStack
        /// </summary>
        public static Action<HttpWebResponse> HttpWebResponseFilter { get; set; }

        /// <summary>
        /// Called before request resend, when the initial request required authentication
        /// </summary>
        public Action<WebRequest> OnAuthenticationRequired { get; set; }

        public static int BufferSize = 8192;

        public ICredentials Credentials { get; set; }

        public bool AlwaysSendBasicAuthHeader { get; set; }

        public bool StoreCookies { get; set; }

        public CookieContainer CookieContainer { get; set; }

        /// <summary>
        /// The request filter is called before any request.
        /// This request filter only works with the instance where it was set (not global).
        /// </summary>
        public Action<HttpWebRequest> LocalHttpWebRequestFilter { get; set; }

        /// <summary>
        /// The response action is called once the server response is available.
        /// It will allow you to access raw response information. 
        /// Note that you should NOT consume the response stream as this is handled by ServiceStack
        /// </summary>
        public Action<HttpWebResponse> LocalHttpWebResponseFilter { get; set; }

        public string BaseUri { get; set; }

        internal class RequestState<TResponse> : IDisposable
        {
            private bool _timedOut; // Pass the correct error back even on Async Calls

            public RequestState()
            {
                BufferRead = new byte[BufferSize];
                TextData = new StringBuilder();
                BytesData = new MemoryStream(BufferSize);
                WebRequest = null;
                ResponseStream = null;
            }

            public string HttpMethod;

            public string Url;

            public StringBuilder TextData;

            public MemoryStream BytesData;

            public byte[] BufferRead;

            public object Request;

            public HttpWebRequest WebRequest;

            public HttpWebResponse WebResponse;

            public Stream ResponseStream;

            public int Completed;

            public int RequestCount;

#if NETFX_CORE// && !WINDOWS_PHONE
            public ThreadPoolTimer Timer;
#else
            public Timer Timer;
#endif

            public Action<TResponse> OnSuccess;

            public Action<TResponse, Exception> OnError;

#if SILVERLIGHT
            public bool HandleCallbackOnUIThread { get; set; }
#endif

            public void HandleSuccess(TResponse response)
            {
                if (this.OnSuccess == null)
                    return;

#if SILVERLIGHT && !NETFX_CORE
                if (this.HandleCallbackOnUIThread)
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => this.OnSuccess(response));
                else
                    this.OnSuccess(response);
#else
                this.OnSuccess(response);
#endif
            }

            public void HandleError(TResponse response, Exception ex)
            {
                if (this.OnError == null)
                    return;

                Exception toReturn = ex;
                if (_timedOut)
                {
#if SILVERLIGHT
                    WebException we = new WebException("The request timed out", ex, WebExceptionStatus.RequestCanceled, null);
#else
                    var we = new WebException("The request timed out", ex, WebExceptionStatus.Timeout, null);
#endif
                    toReturn = we;
                }

#if SILVERLIGHT && !NETFX_CORE
                if (this.HandleCallbackOnUIThread)
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => this.OnError(response, toReturn));
                else
                    this.OnError(response, toReturn);
#else
                OnError(response, toReturn);
#endif
            }

            public void StartTimer(TimeSpan timeOut)
            {
#if NETFX_CORE
                this.Timer = ThreadPoolTimer.CreateTimer(this.TimedOut, timeOut); //Timer(this.TimedOut, this, (int)timeOut.TotalMilliseconds, System.Threading.Timeout.Infinite);
#else
                this.Timer = new Timer(this.TimedOut, this, (int)timeOut.TotalMilliseconds, System.Threading.Timeout.Infinite);
#endif
            }

#if NETFX_CORE
            public void TimedOut(ThreadPoolTimer timer)
            {
                if (Interlocked.Increment(ref Completed) == 1)
                {
                    if (this.WebRequest != null)
                    {
                        _timedOut = true;
                        this.WebRequest.Abort();
                    }
                }
                timer.Cancel();
                timer = null;
                this.Dispose();
            }
#else
            public void TimedOut(object state)
            {
                if (Interlocked.Increment(ref Completed) == 1)
                {
                    if (this.WebRequest != null)
                    {
                        _timedOut = true;
                        this.WebRequest.Abort();
                    }
                }
                this.Timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                this.Timer.Dispose();
                this.Timer = null;
                this.Dispose();
            }
#endif

            public void Dispose()
            {
                if (this.BytesData != null)
                {
                    this.BytesData.Dispose();
                    this.BytesData = null;
                }
                if (this.Timer != null)
                {
                    this.Timer.Dispose();
                    this.Timer = null;
                }
            }
        }

        public bool DisableAutoCompression { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }

        public void SetCredentials(string userName, string password)
        {
            this.UserName = userName;
            this.Password = password;<commit_msg>Stop/cancel timer when request completes in AsyncServiceClient<commit_after>using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using ServiceStack.Logging;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
using ServiceStack.Common.Web;
#if NETFX_CORE
using Windows.System.Threading;
using System.Threading.Tasks;
#endif

namespace ServiceStack.ServiceClient.Web
{
    /**
     * Need to provide async request options
     * http://msdn.microsoft.com/en-us/library/86wf6409(VS.71).aspx
     */

    public class AsyncServiceClient
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(AsyncServiceClient));
        private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(60);
        private HttpWebRequest _webRequest = null;

        /// <summary>
        /// The request filter is called before any request.
        /// This request filter is executed globally.
        /// </summary>
        public static Action<HttpWebRequest> HttpWebRequestFilter { get; set; }

        /// <summary>
        /// The response action is called once the server response is available.
        /// It will allow you to access raw response information. 
        /// This response action is executed globally.
        /// Note that you should NOT consume the response stream as this is handled by ServiceStack
        /// </summary>
        public static Action<HttpWebResponse> HttpWebResponseFilter { get; set; }

        /// <summary>
        /// Called before request resend, when the initial request required authentication
        /// </summary>
        public Action<WebRequest> OnAuthenticationRequired { get; set; }

        public static int BufferSize = 8192;

        public ICredentials Credentials { get; set; }

        public bool AlwaysSendBasicAuthHeader { get; set; }

        public bool StoreCookies { get; set; }

        public CookieContainer CookieContainer { get; set; }

        /// <summary>
        /// The request filter is called before any request.
        /// This request filter only works with the instance where it was set (not global).
        /// </summary>
        public Action<HttpWebRequest> LocalHttpWebRequestFilter { get; set; }

        /// <summary>
        /// The response action is called once the server response is available.
        /// It will allow you to access raw response information. 
        /// Note that you should NOT consume the response stream as this is handled by ServiceStack
        /// </summary>
        public Action<HttpWebResponse> LocalHttpWebResponseFilter { get; set; }

        public string BaseUri { get; set; }

        internal class RequestState<TResponse> : IDisposable
        {
            private bool _timedOut; // Pass the correct error back even on Async Calls

            public RequestState()
            {
                BufferRead = new byte[BufferSize];
                TextData = new StringBuilder();
                BytesData = new MemoryStream(BufferSize);
                WebRequest = null;
                ResponseStream = null;
            }

            public string HttpMethod;

            public string Url;

            public StringBuilder TextData;

            public MemoryStream BytesData;

            public byte[] BufferRead;

            public object Request;

            public HttpWebRequest WebRequest;

            public HttpWebResponse WebResponse;

            public Stream ResponseStream;

            public int Completed;

            public int RequestCount;

#if NETFX_CORE// && !WINDOWS_PHONE
            public ThreadPoolTimer Timer;
#else
            public Timer Timer;
#endif

            public Action<TResponse> OnSuccess;

            public Action<TResponse, Exception> OnError;

#if SILVERLIGHT
            public bool HandleCallbackOnUIThread { get; set; }
#endif

            public void HandleSuccess(TResponse response)
            {
                StopTimer();

                if (this.OnSuccess == null)
                    return;

#if SILVERLIGHT && !NETFX_CORE
                if (this.HandleCallbackOnUIThread)
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => this.OnSuccess(response));
                else
                    this.OnSuccess(response);
#else
                this.OnSuccess(response);
#endif
            }

            public void HandleError(TResponse response, Exception ex)
            {
                StopTimer();

                if (this.OnError == null)
                    return;

                Exception toReturn = ex;
                if (_timedOut)
                {
#if SILVERLIGHT
                    WebException we = new WebException("The request timed out", ex, WebExceptionStatus.RequestCanceled, null);
#else
                    var we = new WebException("The request timed out", ex, WebExceptionStatus.Timeout, null);
#endif
                    toReturn = we;
                }

#if SILVERLIGHT && !NETFX_CORE
                if (this.HandleCallbackOnUIThread)
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => this.OnError(response, toReturn));
                else
                    this.OnError(response, toReturn);
#else
                OnError(response, toReturn);
#endif                
            }

            public void StartTimer(TimeSpan timeOut)
            {
#if NETFX_CORE
                this.Timer = ThreadPoolTimer.CreateTimer(this.TimedOut, timeOut); //Timer(this.TimedOut, this, (int)timeOut.TotalMilliseconds, System.Threading.Timeout.Infinite);
#else
                this.Timer = new Timer(this.TimedOut, this, (int)timeOut.TotalMilliseconds, System.Threading.Timeout.Infinite);
#endif
            }

            public void StopTimer()
            {
                if (this.Timer != null)
                {
#if NETFX_CORE
                    this.timer.Cancel();                   
#else
                    this.Timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                    this.Timer.Dispose();
#endif
                    this.Timer = null;
                }
            }
#if NETFX_CORE
            public void TimedOut(ThreadPoolTimer timer)
            {
                if (Interlocked.Increment(ref Completed) == 1)
                {
                    if (this.WebRequest != null)
                    {
                        _timedOut = true;
                        this.WebRequest.Abort();
                    }
                }
                timer.Cancel();
                timer = null;
                this.Dispose();
            }
#else
            public void TimedOut(object state)
            {
                if (Interlocked.Increment(ref Completed) == 1)
                {
                    if (this.WebRequest != null)
                    {
                        _timedOut = true;
                        this.WebRequest.Abort();
                    }
                }
                if (this.Timer != null)
                {
                    this.Timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                    this.Timer.Dispose();
                    this.Timer = null;
                }
                this.Dispose();
            }
#endif

            public void Dispose()
            {
                if (this.BytesData != null)
                {
                    this.BytesData.Dispose();
                    this.BytesData = null;
                }
                if (this.Timer != null)
                {
                    this.Timer.Dispose();
                    this.Timer = null;
                }
            }
        }

        public bool DisableAutoCompression { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }

        public void SetCredentials(string userName, string password)
        {
            this.UserName = userName;
            this.Password = password;
{'fraction_non_alphanumeric': 0.08073406393878478, 'fraction_numerical': 0.002075092406458725, 'mean_word_length': 1.5901914679207256, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 43, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6271483', 'n_tokens_mistral': 3854, 'n_tokens_neox': 3585, 'n_words': 1048}