private async Task<AsyncOperationResult<T>> TryClusterOperationAsync<T>(OperationMetadata node, Func<OperationMetadata, Task<T>> operation, bool avoidThrowing, CancellationToken token)
        {
            Debug.Assert(node != null);

            token.ThrowIfCancellationRequested();
            var shouldRetry = false;

            var operationResult = new AsyncOperationResult<T>();
            try
            {
                operationResult.Result = await operation(node).ConfigureAwait(false);
                operationResult.Success = true;
            }
            catch (Exception e)
            {
                bool wasTimeout;
                if (HttpConnectionHelper.IsServerDown(e, out wasTimeout))
                {
                    shouldRetry = true;
                    operationResult.WasTimeout = wasTimeout;
                }
                else
                {
                    var ae = e as AggregateException;
                    ErrorResponseException errorResponseException;
                    if (ae != null)
                        errorResponseException = ae.ExtractSingleInnerException() as ErrorResponseException;
                    else
                        errorResponseException = e as ErrorResponseException;

                    if (errorResponseException != null && (errorResponseException.StatusCode == HttpStatusCode.Redirect || errorResponseException.StatusCode == HttpStatusCode.ExpectationFailed))
                        shouldRetry = true;
                }

                if (shouldRetry == false && avoidThrowing == false)
                    throw;
            }

            if (operationResult.Success)
                FailureCounters.ResetFailureCount(node.Url);

            return operationResult;
        }
        private async Task <AsyncOperationResult <T> > TryExecuteOperationAsync <T>(string url, string counterStoreName, Func <string, string, Task <T> > operation, bool avoidThrowing, OperationCredentials credentials, CancellationToken cancellationToken)
        {
            var  tryWithPrimaryCredentials = failureCounters.IsFirstFailure(url);
            bool shouldTryAgain            = false;

            try
            {
                cancellationToken.ThrowCancellationIfNotDefault(); //canceling the task here potentially will stop the recursion
                var result = await operation(url, counterStoreName).ConfigureAwait(false);

                failureCounters.ResetFailureCount(url);
                return(new AsyncOperationResult <T>
                {
                    Result = result,
                    Success = true
                });
            }
            catch (Exception e)
            {
                var ae = e as AggregateException;
                ErrorResponseException errorResponseException;
                if (ae != null)
                {
                    errorResponseException = ae.ExtractSingleInnerException() as ErrorResponseException;
                }
                else
                {
                    errorResponseException = e as ErrorResponseException;
                }
                if (tryWithPrimaryCredentials && credentials.HasCredentials() && errorResponseException != null)
                {
                    failureCounters.IncrementFailureCount(url);

                    if (errorResponseException.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        shouldTryAgain = true;
                    }
                }

                if (shouldTryAgain == false)
                {
                    if (avoidThrowing == false)
                    {
                        throw;
                    }

                    bool wasTimeout;
                    var  isServerDown = HttpConnectionHelper.IsServerDown(e, out wasTimeout);

                    if (e.Data.Contains(Constants.RequestFailedExceptionMarker) && isServerDown)
                    {
                        return(new AsyncOperationResult <T>
                        {
                            Success = false,
                            WasTimeout = wasTimeout,
                            Error = e
                        });
                    }

                    if (isServerDown)
                    {
                        return(new AsyncOperationResult <T>
                        {
                            Success = false,
                            WasTimeout = wasTimeout,
                            Error = e
                        });
                    }
                    throw;
                }
            }
            return(await TryExecuteOperationAsync(url, counterStoreName, operation, avoidThrowing, credentials, cancellationToken).ConfigureAwait(false));
        }
        private async Task <AsyncOperationResult <T> > TryClusterOperationAsync <T>(OperationMetadata node, Func <OperationMetadata, IRequestTimeMetric, Task <T> > operation, bool avoidThrowing, CancellationToken token)
        {
            Debug.Assert(node != null);

            token.ThrowIfCancellationRequested();
            var shouldRetry = false;

            var operationResult = new AsyncOperationResult <T>();

            try
            {
                operationResult.Result = await operation(node, null).ConfigureAwait(false);

                operationResult.Success = true;
            }
            catch (Exception e)
            {
                bool wasTimeout;
                if (HttpConnectionHelper.IsServerDown(e, out wasTimeout))
                {
                    shouldRetry = true;
                    operationResult.WasTimeout = wasTimeout;
                    if (Log.IsDebugEnabled)
                    {
                        Log.Debug($"Operation failed because server {node.Url} is down.");
                    }
                }
                else
                {
                    var ae = e as AggregateException;
                    ErrorResponseException errorResponseException;
                    if (ae != null)
                    {
                        errorResponseException = ae.ExtractSingleInnerException() as ErrorResponseException;
                    }
                    else
                    {
                        errorResponseException = e as ErrorResponseException;
                    }

                    if (errorResponseException != null)
                    {
                        if (errorResponseException.StatusCode == HttpStatusCode.Redirect)
                        {
                            IEnumerable <string> values;
                            if (errorResponseException.Response.Headers.TryGetValues("Raven-Leader-Redirect", out values) == false &&
                                values.Contains("true") == false)
                            {
                                throw new InvalidOperationException("Got 302 Redirect, but without Raven-Leader-Redirect: true header, maybe there is a proxy in the middle", e);
                            }
                            var redirectUrl   = errorResponseException.Response.Headers.Location.ToString();
                            var newLeaderNode = Nodes.FirstOrDefault(n => n.Url.Equals(redirectUrl)) ?? new OperationMetadata(redirectUrl, node.Credentials, node.ClusterInformation);
                            SetLeaderNodeToKnownLeader(newLeaderNode);
                            if (Log.IsDebugEnabled)
                            {
                                Log.Debug($"Redirecting to {redirectUrl} because {node.Url} responded with 302-redirect.");
                            }
                            return(await TryClusterOperationAsync(newLeaderNode, operation, avoidThrowing, token).ConfigureAwait(false));
                        }

                        if (errorResponseException.StatusCode == HttpStatusCode.ExpectationFailed)
                        {
                            if (Log.IsDebugEnabled)
                            {
                                Log.Debug($"Operation failed with status code {HttpStatusCode.ExpectationFailed}, will retry.");
                            }
                            shouldRetry = true;
                        }
                    }
                }

                if (shouldRetry == false && avoidThrowing == false)
                {
                    throw;
                }

                operationResult.Error = e;
            }

            if (operationResult.Success)
            {
                FailureCounters.ResetFailureCount(node.Url);
            }

            return(operationResult);
        }
Beispiel #4
0
        async private void buttonLoginOnClick(object sender, RoutedEventArgs e)
        {
            #region STARE POBIERANIE PAKIETU
            //HttpClient client = new HttpClient();
            //client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0");
            //var response = await client.GetAsync("https://ts2.travian.pl/login.php");

            //response.EnsureSuccessStatusCode();
            //string content = await response.Content.ReadAsStringAsync();
            #endregion

            string recivedLoginPackage = await HttpConnectionHelper.GetPackage("https://ts2.travian.pl/login.php");

            SerialKey = HttpConnectionHelper.GetLoginSecretCode(recivedLoginPackage);

            nazwaLogin = textBoxLogin.Text;
            nazwaHaslo = textPasswordBox.Password.ToString();

            trescRzadania = HttpConnectionHelper.setLoginPostData(nazwaLogin, nazwaHaslo, SerialKey);


            #region STARE WYSYŁANIE PAKIETU
            //HttpWebRequest requestt = (HttpWebRequest)WebRequest.Create("https://ts2.travian.pl/login.php");
            //requestt.Method = "POST";
            //string postData = trescRzadania;
            //byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            //requestt.ContentType = "application/x-www-form-urlencoded";
            ////requestt.Referer = "http://webpage.com/";
            //requestt.ContentLength = byteArray.Length;
            //requestt.CookieContainer = new CookieContainer();
            //requestt.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";

            //Stream dataStream = requestt.GetRequestStream();
            //dataStream.Write(byteArray, 0, byteArray.Length);
            //dataStream.Close(); // *** [1] ***

            ////client.Dispose();

            //HttpWebResponse response10 = (HttpWebResponse)requestt.GetResponse();


            //using (dataStream = dataStream = response10.GetResponseStream())
            //{
            //    // Open the stream using a StreamReader for easy access.
            //    StreamReader reader = new StreamReader(dataStream);
            //    // Read the content.
            //    string responseFromServer = reader.ReadToEnd();
            //    // Display the content.
            //    //scroolViewer.Content = responseFromServer;
            //    odpowiedzLogowania = responseFromServer.Trim();
            //}

            #endregion

            odpowiedzLogowania = HttpConnectionHelper.SendPackage("https://ts2.travian.pl/login.php", trescRzadania);


            if (HttpConnectionHelper.IsLoginOkey(odpowiedzLogowania))
            {
                MessageBox.Show("Logowanie udane!", "Stan logowania", MessageBoxButton.OK, MessageBoxImage.Information);
                Okno2 nextForm = new Okno2();
                //nextForm.pierwszaOdpowiedz = odpowiedzLogowania;
                this.Hide();
                nextForm.ShowDialog();
                this.Close();
            }

            else
            {
                MessageBox.Show("Błąd logowania!", "Stan logowania", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Beispiel #5
0
        private async Task EstablishConnection()
        {
            if (disposed)
            {
                return;
            }

            DisposeHeartbeatTimer();

            var requestParams = new CreateHttpJsonRequestParams(null, url + "/changes/events?id=" + id, HttpMethods.Get, credentials, Conventions)
            {
                AvoidCachingRequest       = true,
                DisableRequestCompression = true
            };

            logger.Info("Trying to connect to {0} with id {1}", requestParams.Url, id);
            bool retry = false;
            IObservable <string> serverEvents = null;

            try
            {
                serverEvents = await jsonRequestFactory.CreateHttpJsonRequest(requestParams)
                               .ServerPullAsync().ConfigureAwait(false);
            }
            catch (Exception e)
            {
                logger.WarnException("Could not connect to server: " + url + " and id " + id, e);

                Connected = false;
                ConnectionStatusChanged(this, EventArgs.Empty);

                if (disposed)
                {
                    logger.Warn("Failed to connect to {0} with id {1}, probably shutting down...", url, id);
                    throw;
                }
                HttpStatusCode code;
                if (HttpConnectionHelper.IsHttpStatus(e, out code, HttpStatusCode.NotFound, HttpStatusCode.Forbidden, HttpStatusCode.Unauthorized, HttpStatusCode.ServiceUnavailable))
                {
                    logger.Error("Failed to connect to {0} with id {1}, server returned with an error code:{2}", url, id, code);
                    throw;
                }

                logger.Warn("Failed to connect to {0} with id {1}, will try again in 15 seconds", url, id);
                retry = true;
            }

            if (retry)
            {
                await Time.Delay(TimeSpan.FromSeconds(15)).ConfigureAwait(false);
                await EstablishConnection().ConfigureAwait(false);

                return;
            }
            if (disposed)
            {
                Connected = false;
                ConnectionStatusChanged(this, EventArgs.Empty);
                throw new ObjectDisposedException(this.GetType().Name);
            }

            Connected = true;
            ConnectionStatusChanged(this, EventArgs.Empty);
            connection = (IDisposable)serverEvents;
            serverEvents.Subscribe(this);

            clientSideHeartbeatTimer = new Timer(ClientSideHeartbeat, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));

            await SubscribeOnServer().ConfigureAwait(false);
        }