Esempio n. 1
0
        /// <summary>
        ///     Draws the content.
        /// </summary>
        private void DrawContent( )
        {
            RetryHandler.Retry(() =>
            {
                if (Clipboard.ContainsText( ))
                {
                    string text = Clipboard.GetText( );

                    if (!string.IsNullOrEmpty(text))
                    {
                        Guid guid;
                        if (Guid.TryParse(text, out guid) && !Misc.Settings.Default.MonitorGuid)
                        {
                            return;
                        }

                        long id;
                        if (long.TryParse(text, out id) && !Misc.Settings.Default.MonitorLong)
                        {
                            return;
                        }

                        if (!Misc.Settings.Default.MonitorAlias && !Misc.Settings.Default.MonitorPerfLog)
                        {
                            return;
                        }

                        var msg = IsPerfLog(text) ? new PerfGraphMessage(text).ToString() : new EntityBrowserMessage(text).ToString();

                        Settings.Channel.SendMessage(msg);
                    }
                }
            }, exceptionHandler: e => Settings.EventLog.WriteException(e));
        }
        public async Task RetryHandlerDoesNotRetryOnException()
        {
            CosmosClient client = MockDocumentClient.CreateMockCosmosClient();

            RetryHandler retryHandler         = new RetryHandler(client.DocumentClient.ResetSessionTokenRetryPolicy);
            int          handlerCalls         = 0;
            int          expectedHandlerCalls = 2;
            TestHandler  testHandler          = new TestHandler((request, cancellationToken) => {
                handlerCalls++;
                if (handlerCalls == expectedHandlerCalls)
                {
                    Assert.Fail("Should not retry on exception.");
                }

                throw new Exception("You shall not retry.");
            });

            retryHandler.InnerHandler = testHandler;
            RequestInvokerHandler invoker = new RequestInvokerHandler(client);

            invoker.InnerHandler = retryHandler;
            CosmosRequestMessage requestMessage = new CosmosRequestMessage(HttpMethod.Get, new System.Uri("https://dummy.documents.azure.com:443/dbs"));

            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType  = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            await invoker.SendAsync(requestMessage, new CancellationToken());
        }
Esempio n. 3
0
 public GraphClientFactoryTests()
 {
     this.testHttpMessageHandler = new MockRedirectHandler();
     handlers[0] = new RetryHandler();
     handlers[1] = new RedirectHandler();
     handlers[2] = new AuthenticationHandler();
 }
        public async Task IsRetriableResponse_UnparseableResponse()
        {
            var response = new HttpResponseMessage();

            response.Content = new StringContent("This isn't JSON");
            Assert.False(await RetryHandler.IsRetriableResponse(response));
        }
        /// <summary>
        /// Asynchronously sends a bulk email message and returns the response from the Injection API.
        /// </summary>
        /// <param name="message">A <c>BulkMessage</c> object to be sent.</param>
        /// <param name="cancellationToken">A <c>CancellationToken</c> to handle cancellation between async threads.</param>
        /// <returns>A <c>SendResponse</c> of an SocketLabsClient send request.</returns>
        /// <example>
        /// This sample shows you how to Send a Bulk Message
        /// <code>
        /// var client = new SocketLabsClient(00000, "apiKey");
        ///
        /// var message = new BulkMessage();
        ///
        /// message.PlainTextBody = "This is the body of my message sent to ##Name##";
        /// message.HtmlBody = "<html>This is the HtmlBody of my message sent to ##Name##</html>";
        /// message.Subject = "Sending a test message";
        /// message.From.Email = "*****@*****.**";
        ///
        /// var recipient1 = message.To.Add("*****@*****.**");
        /// recipient1.MergeData.Add("Name", "Recipient1");
        ///
        /// var recipient2 = message.To.Add("*****@*****.**");
        /// recipient2.MergeData.Add("Name", "Recipient2");
        ///
        /// var response = await client.Send(message);
        ///
        /// if (response.Result != SendResult.Success)
        /// {
        ///     // Handle Error
        /// }
        ///</code>
        /// </example>
        public async Task <SendResponse> SendAsync(IBulkMessage message, CancellationToken cancellationToken)
        {
            var validator = new SendValidator();

            var validationResult = validator.ValidateCredentials(_serverId, _apiKey);

            if (validationResult.Result != SendResult.Success)
            {
                return(validationResult);
            }

            validationResult = validator.ValidateMessage(message);
            if (validationResult.Result != SendResult.Success)
            {
                return(validationResult);
            }

            var factory          = new InjectionRequestFactory(_serverId, _apiKey);
            var injectionRequest = factory.GenerateRequest(message);
            var json             = injectionRequest.GetAsJson();

            var retryHandler = new RetryHandler(_httpClient, EndpointUrl, new RetrySettings(NumberOfRetries));
            var httpResponse = await retryHandler.SendAsync(json, cancellationToken);

            var response = new InjectionResponseParser().Parse(httpResponse);

            return(response);
        }
Esempio n. 6
0
        public async Task Send_NoTransientExceptionOnRetryWindowsOnly_ShouldReturnTheResponseCorrectly()
        {
            var retryCount   = 0;
            var retryHandler = new RetryHandler(5, 2, 10, RetryHandler.BackOffStrategy.Exponential)
            {
                BackOffFunc = seconds =>
                {
                    retryCount++;
                    return(Task.FromResult(0));
                }
            };

            dynamic restClient = new RestClient("http://test.test", new Config(retryHandler).UseUnitTestHandler(
                                                    request =>
            {
                if (retryCount == 4)
                {
                    return new HttpResponseMessage {
                        Content = new StringContent("{ 'foo' : 'bar' }")
                    }
                }
                ;

                throw new HttpRequestException(WebExceptionStatus.SendFailure.ToString(), new Win32Exception((int)RetryHandler.WinHttpNativeErrorCode.ERROR_WINHTTP_CONNECTION_ERROR));
            }));

            var result = await restClient.Get();

            Assert.That(result.foo, Is.EqualTo("bar"));
        }
Esempio n. 7
0
        public void Send_TransientExceptionEncounteredWindowsOnly_ShouldBeRetried(int winHttpNativeErrorCode)
        {
            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(winHttpNativeErrorCode.ToString(), new Win32Exception(winHttpNativeErrorCode));
            }));

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

            Assert.That(exception.Data["IsTransient"], Is.EqualTo(true));
            Assert.That(win32Exception?.NativeErrorCode, Is.EqualTo(winHttpNativeErrorCode));
            Assert.That(retryCount, Is.EqualTo(numberTimesToRetry));
        }
Esempio n. 8
0
        public void RetryHandlerReturnBadRequest()
        {
            var retryFunc = new Func <HttpResponseMessage, bool>(r =>
            {
                if (r.StatusCode == HttpStatusCode.BadRequest)
                {
                    return(true);
                }

                return(false);
            }
                                                                 );
            var retryHandler = new RetryHandler(retryFunc)
            {
                InnerHandler = new TestHandler((c, r) =>
                {
                    return(Task.Factory.StartNew(
                               () =>
                    {
                        var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
                        return response;
                    }));
                })
            };

            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://test.com");
            var client             = new HttpClient(retryHandler);
            var result             = client.SendAsync(httpRequestMessage).Result;

            Assert.AreEqual <HttpStatusCode>(HttpStatusCode.BadRequest, result.StatusCode);
        }
        private async Task RetryHandlerDontRetryOnStatusCode(
            HttpStatusCode statusCode,
            SubStatusCodes subStatusCode = SubStatusCodes.Unknown)
        {
            int         handlerCalls = 0;
            TestHandler testHandler  = new TestHandler((request, response) => {
                handlerCalls++;

                if (handlerCalls == 0)
                {
                    return(TestHandler.ReturnStatusCode(statusCode, subStatusCode));
                }

                return(TestHandler.ReturnSuccess());
            });

            CosmosClient client       = MockDocumentClient.CreateMockCosmosClient();
            RetryHandler retryHandler = new RetryHandler(client.DocumentClient.ResetSessionTokenRetryPolicy);

            retryHandler.InnerHandler = testHandler;

            RequestInvokerHandler invoker = new RequestInvokerHandler(client);

            invoker.InnerHandler = retryHandler;
            CosmosRequestMessage requestMessage = new CosmosRequestMessage(HttpMethod.Delete, RetryHandlerTests.TestUri);

            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType  = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            await invoker.SendAsync(requestMessage, new CancellationToken());

            int expectedHandlerCalls = 1;

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
        public override void OnCreate(Android.OS.Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            if (savedInstanceState != null)
            {
                mRetryCounter              = savedInstanceState.GetInt(KEY_RETRY_COUNTER);
                mRetryLoadFullWalletCount  = savedInstanceState.GetInt(KEY_RETRY_FULL_WALLET_COUNTER);
                mHandleFullWalletWhenReady =
                    savedInstanceState.GetBoolean(KEY_HANDLE_FULL_WALLET_WHEN_READY);
            }
            mActivityLaunchIntent = Activity.Intent;
            mItemId       = mActivityLaunchIntent.GetIntExtra(Constants.EXTRA_ITEM_ID, 0);
            mMaskedWallet = mActivityLaunchIntent.GetParcelableExtra(Constants.EXTRA_MASKED_WALLET).JavaCast <MaskedWallet> ();

            var accountName = ((BikestoreApplication)Activity.Application).AccountName;

            // Set up an API client;
            mGoogleApiClient = new GoogleApiClient.Builder(Activity)
                               .AddConnectionCallbacks(this)
                               .AddOnConnectionFailedListener(this)
                               .SetAccountName(accountName)
                               .AddApi(WalletClass.API, new WalletClass.WalletOptions.Builder()
                                       .SetEnvironment(Constants.WALLET_ENVIRONMENT)
                                       .SetTheme(WalletConstants.ThemeLight)
                                       .Build())
                               .Build();

            mRetryHandler = new RetryHandler(this);
        }
        public void IsRetriableRequest_NotMarked()
        {
            var request     = new ListRequest(new BigqueryService());
            var httpRequest = request.CreateRequest();

            Assert.False(RetryHandler.IsRetriableRequest(httpRequest));
        }
 public void Setup()
 {
     this.testHttpMessageHandler = new MockRedirectHandler();
     handlers[0] = new RetryHandler();
     handlers[1] = new RedirectHandler();
     handlers[2] = new AuthenticationHandler(authenticationProvider.Object);
 }
Esempio n. 13
0
        public void Should_CreatePipeline_Without_CompressionHandler()
        {
            using (AuthenticationHandler authenticationHandler = (AuthenticationHandler)GraphClientFactory.CreatePipeline(handlers))
                using (RetryHandler retryHandler = (RetryHandler)authenticationHandler.InnerHandler)
                    using (RedirectHandler redirectHandler = (RedirectHandler)retryHandler.InnerHandler)
#if iOS
                        using (NSUrlSessionHandler innerMost = (NSUrlSessionHandler)redirectHandler.InnerHandler)
#elif macOS
                        using (Foundation.NSUrlSessionHandler innerMost = (Foundation.NSUrlSessionHandler)redirectHandler.InnerHandler)
#endif
                        {
                            Assert.NotNull(authenticationHandler);
                            Assert.NotNull(retryHandler);
                            Assert.NotNull(redirectHandler);
                            Assert.NotNull(innerMost);
                            Assert.IsType <AuthenticationHandler>(authenticationHandler);
                            Assert.IsType <RetryHandler>(retryHandler);
                            Assert.IsType <RedirectHandler>(redirectHandler);
#if iOS
                            Assert.IsType <NSUrlSessionHandler>(innerMost);
#elif macOS
                            Assert.IsType <Foundation.NSUrlSessionHandler>(innerMost);
#endif
                        }
        }
Esempio n. 14
0
        public void RetryHandler_RetryOnException_ThenThrowException()
        {
            int       count    = 0;
            Exception thrownEx = null;

            try
            {
                var result = new RetryHandler()
                             .RetryCount(3)
                             .RetryOnException <InvalidOperationException>()
                             .RetryAsync <bool>(
                    () =>
                {
                    count++;
                    throw new InvalidOperationException();
                },
                    (r) =>
                {
                    return(false);
                }).Result;
            }
            catch (AggregateException ex)
            {
                thrownEx = ex.Flatten().InnerException;
            }

            Assert.AreEqual(3, count);
            Assert.AreEqual(typeof(InvalidOperationException), thrownEx.GetType());
        }
        public async Task RetryHandlerRetriesOn429()
        {
            CosmosClient client = MockDocumentClient.CreateMockCosmosClient();

            RetryHandler retryHandler         = new RetryHandler(client.DocumentClient.ResetSessionTokenRetryPolicy);
            int          handlerCalls         = 0;
            int          expectedHandlerCalls = 2;
            TestHandler  testHandler          = new TestHandler((request, cancellationToken) => {
                if (handlerCalls == 0)
                {
                    handlerCalls++;
                    return(TestHandler.ReturnStatusCode((HttpStatusCode)StatusCodes.TooManyRequests));
                }

                handlerCalls++;
                return(TestHandler.ReturnSuccess());
            });

            retryHandler.InnerHandler = testHandler;
            RequestInvokerHandler invoker = new RequestInvokerHandler(client);

            invoker.InnerHandler = retryHandler;
            CosmosRequestMessage requestMessage = new CosmosRequestMessage(HttpMethod.Delete, RetryHandlerTests.TestUri);

            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType  = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            await invoker.SendAsync(requestMessage, new CancellationToken());

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
Esempio n. 16
0
        public async Task ExecutionWithoutRetry()
        {
            RetryHandler retryHandler = new RetryHandler(5, 15, 7, false);

            retryHandler
            .ExcludeForRetry <NullReferenceException>();

            short retryCount = -1;
            short errorCount = 0;

            await retryHandler.ExecuteAsync(async() =>
            {
                retryCount++;

                await Task.Delay(20);

                throw new NullReferenceException();
            },
                                            async (exception, retryIndex, retryLimit) =>
            {
                errorCount++;

                await Task.Delay(10);

                Assert.NotNull(exception);
                Assert.Equal(0, retryIndex);
                Assert.Equal(0, retryLimit);
            });

            Assert.Equal(0, retryCount);
            Assert.Equal(1, errorCount);
        }
Esempio n. 17
0
        /// <summary>
        /// Perform a transaction, with the option to automatically retry on failure.
        /// Also returning a result from the supplied transaction function.
        /// </summary>
        /// <param name="db"> <seealso cref="GraphDatabaseService"/> to apply the transaction on. </param>
        /// <param name="commit"> whether or not to call <seealso cref="Transaction.success()"/> in the end. </param>
        /// <param name="retry"> <seealso cref="RetryHandler"/> deciding what type of failures to retry on. </param>
        /// <param name="transaction"> <seealso cref="Function"/> containing the transaction logic and returning a result. </param>
        /// <returns> result from transaction <seealso cref="Function"/>. </returns>
//JAVA TO C# CONVERTER TODO TASK: There is no .NET equivalent to the Java 'super' constraint:
//ORIGINAL LINE: public static <T> T tx(org.neo4j.graphdb.GraphDatabaseService db, boolean commit, RetryHandler retry, System.Func<? super org.neo4j.graphdb.GraphDatabaseService, T> transaction)
        public static T Tx <T, T1>(GraphDatabaseService db, bool commit, RetryHandler retry, System.Func <T1> transaction)
        {
            while (true)
            {
                try
                {
                    using (Transaction tx = Db.beginTx())
                    {
                        T result = transaction(db);
                        if (commit)
                        {
                            tx.Success();
                        }
                        return(result);
                    }
                }
                catch (Exception t)
                {
                    if (!retry(t))
                    {
                        throw t;
                    }
                    // else continue one more time
                }
            }
        }
        public async Task RetryHandlerDoesNotRetryOnSuccess()
        {
            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();

            RetryHandler retryHandler         = new RetryHandler(client);
            int          handlerCalls         = 0;
            int          expectedHandlerCalls = 1;
            TestHandler  testHandler          = new TestHandler((request, cancellationToken) => {
                handlerCalls++;
                return(TestHandler.ReturnSuccess());
            });

            retryHandler.InnerHandler = testHandler;
            RequestInvokerHandler invoker = new RequestInvokerHandler(client, requestedClientConsistencyLevel: null);

            invoker.InnerHandler = retryHandler;
            RequestMessage requestMessage = new RequestMessage(HttpMethod.Delete, RetryHandlerTests.TestUri);

            requestMessage.Headers.Add(HttpConstants.HttpHeaders.PartitionKey, "[]");
            requestMessage.ResourceType  = ResourceType.Document;
            requestMessage.OperationType = OperationType.Read;
            await invoker.SendAsync(requestMessage, new CancellationToken());

            Assert.AreEqual(expectedHandlerCalls, handlerCalls);
        }
Esempio n. 19
0
 public void RedtryHandler_Constructor()
 {
     using (RetryHandler retry = new RetryHandler())
     {
         Assert.IsNull(retry.InnerHandler, "HttpMessageHandler initialized.");
         Assert.IsInstanceOfType(retry, typeof(RetryHandler), "Unexpected redtry handler set.");
     }
 }
 public GraphClientFactoryTests()
 {
     this.testHttpMessageHandler = new MockRedirectHandler();
     handlers    = new DelegatingHandler[3];
     handlers[0] = new RetryHandler();
     handlers[1] = new RedirectHandler();
     handlers[2] = new AuthenticationHandler(authenticationProvider.Object);
 }
 public void Dispose()
 {
     Reset();
     foreach (var handler in RetryHandler?.GetInvocationList() ?? new Delegate[] { })
     {
         RetryHandler -= (EventHandler)handler;
     }
 }
Esempio n. 22
0
 public void retryHandler_Constructor()
 {
     using (RetryHandler retry = new RetryHandler())
     {
         Assert.Null(retry.InnerHandler);
         Assert.IsType(typeof(RetryHandler), retry);
     }
 }
        /// <summary>
        ///     Copies the value click.
        /// </summary>
        /// <param name="field">The field.</param>
        private void CopyValueClick(IFieldInfo field)
        {
            RetryHandler.Retry(() =>
            {
                Clipboard.SetData(DataFormats.Text, field.Data.ToString( ));

                PluginSettings.Channel.SendMessage(new StatusTextMessage(@"Value copied to clipboard...", 2000).ToString( ));
            }, exceptionHandler: e => PluginSettings.EventLog.WriteException(e));
        }
Esempio n. 24
0
        /// <summary>
        ///     Copies the value click.
        /// </summary>
        /// <param name="app">The application.</param>
        private void CopyValueClick(TenantApp app)
        {
            RetryHandler.Retry(() =>
            {
                Clipboard.SetData(DataFormats.Text, app.ApplicationId.ToString("B"));

                PluginSettings.Channel.SendMessage(new StatusTextMessage(@"Value copied to clipboard...", 2000).ToString( ));
            }, exceptionHandler: e => PluginSettings.EventLog.WriteException(e));
        }
 public void CreatePipelineWithoutPipeline()
 {
     GraphClientFactory.DefaultHttpHandler = () => this.testHttpMessageHandler;
     using (RetryHandler handler = (RetryHandler)GraphClientFactory.CreatePipeline(handlers: handlers))
     {
         Assert.IsNotNull(handler, "Create a middleware pipeline failed.");
         Assert.IsInstanceOfType(handler, typeof(RetryHandler), "Inner most HttpMessageHandler class error.");
     }
 }
 public BaseFunctionalTests(string baseUrl)
 {
     // Arrange
     RetryHandler = new RetryHandler(new HttpClientHandler());
     Client       = new HttpClient(RetryHandler)
     {
         BaseAddress = new Uri(baseUrl)
     };
 }
Esempio n. 27
0
        /// <summary>
        ///
        /// </summary>
        public Handler()
        {
            PipelineHandler handler;

            handler = new ApiHandler();
            handler = new WeAPPHandler(handler);
            handler = new RetryHandler(handler);
            inner   = handler;
        }
        /// <summary>
        ///     Copies the identifier click.
        /// </summary>
        /// <param name="account">The application.</param>
        private void CopyIdClick(Account account)
        {
            RetryHandler.Retry(() =>
            {
                Clipboard.SetData(DataFormats.Text, account.Id.ToString( ));

                PluginSettings.Channel.SendMessage(new StatusTextMessage(@"Id copied to clipboard...", 2000).ToString( ));
            }, exceptionHandler: e => PluginSettings.EventLog.WriteException(e));
        }
Esempio n. 29
0
 void Start()
 {
     enemyShips   = new List <List <GameObject> >();
     retryHandler = GetComponent <RetryHandler>();
     mover        = GetComponent <EnemyMover>();
     CreatePlayer();
     InitiateStageOne();
     SuspendShips();
 }
        /// <summary>
        ///     Copies the reverse relationship click.
        /// </summary>
        /// <param name="obj">The object.</param>
        private void CopyReverseRelationshipClick(ReverseRelationship obj)
        {
            RetryHandler.Retry(() =>
            {
                Clipboard.SetData(DataFormats.Text, string.Format("Type Id: {0}\nTenant Id: {1}\nFrom Id: {2}\nTo Id: {3}", obj.TypeId, obj.TenantId, obj.FromId, SelectedEntityId));

                PluginSettings.Channel.SendMessage(new StatusTextMessage(@"Relationship data copied to clipboard...", 2000).ToString( ));
            }, exceptionHandler: e => PluginSettings.EventLog.WriteException(e));
        }
Esempio n. 31
0
        static void Main(string[] args)
        {
            var bus = new Bus(new Dispatcher.Dispatcher());
            var printers = new[] { new Printer(bus, 1), new Printer(bus, 2), new Printer(bus, 3), new Printer(bus, 4) };

            var printerPool = printers
                .Select(printer => new WideningHandler<PrintJob, Message>(printer))
                .Select(printer => new QueuedHandler(printer, bus) { MaxQueueLength = 1 })
                .ToArray();

            var refillPool = printers
                .Select(printer => new WideningHandler<RefillPaper, Message>(printer))
                .Select(printer => new QueuedHandler(printer, bus) { MaxQueueLength = 1 })
                .ToArray();

            foreach (var printer in refillPool)
            {
                bus.Subscribe<RefillPaper>(new NarrowingHandler<RefillPaper, Message>(printer));
                // subscribe the printer directly to RefillPaper as we don't want to distribute that with the print jobs
            }

            var office = Enumerable.Range(0, 50)
                .Select(i => new Employee(bus, i))
                .ToArray();

            var loadBalancer = new RoundRobinLoadBalancer(printerPool);
            var printerRetryHandler = new RetryHandler(loadBalancer, bus);
            var retryManager = new RetryManager(bus);
            var timerService = new TimerService(bus);

            bus.Subscribe<FutureMessage>(timerService);
            bus.Subscribe<RetryMessage>(retryManager);
            bus.Subscribe<SuccessMessage>(retryManager);

            bus.Subscribe(new NarrowingHandler<PrintJob, Message>(printerRetryHandler));

            var console = new QueuedHandler(new WideningHandler<LogMessage, Message>(new ConsoleHandler()), bus);
            bus.Subscribe<LogMessage>(new NarrowingHandler<LogMessage, Message>(console));

            var porter = new Porter(bus);
            bus.Subscribe(porter);

            var converter = new LogConverter(bus);
            bus.Subscribe<PrintJob>(converter);
            bus.Subscribe<OutOfPaper>(converter);
            bus.Subscribe<PagePrinted>(converter);
            bus.Subscribe<RetryMessage>(converter);
        }
Esempio n. 32
0
        public bool Retry(RetryHandler retryHandler, params object[] args)
        {
            bool retry = true;
            int retryCount = -1;

            while (retry)
            {
                retryCount++;
                try
                {
                    retryHandler(args);
                    return true;
                }
                catch (Exception e)
                {
                    retry = NotifyExceptionOccured(e, retryCount);
                }
            }
            return false;
        }
        public override void OnCreate (Android.OS.Bundle savedInstanceState)
        {
            base.OnCreate (savedInstanceState);
        
            if (savedInstanceState != null) {
                mRetryCounter = savedInstanceState.GetInt (KEY_RETRY_COUNTER);
                mRetryLoadFullWalletCount = savedInstanceState.GetInt (KEY_RETRY_FULL_WALLET_COUNTER);
                mHandleFullWalletWhenReady =
                    savedInstanceState.GetBoolean (KEY_HANDLE_FULL_WALLET_WHEN_READY);
            }
            mActivityLaunchIntent = Activity.Intent;
            mItemId = mActivityLaunchIntent.GetIntExtra (Constants.EXTRA_ITEM_ID, 0);
            mMaskedWallet = mActivityLaunchIntent.GetParcelableExtra (Constants.EXTRA_MASKED_WALLET).JavaCast<MaskedWallet> ();

            var accountName = ((BikestoreApplication) Activity.Application).AccountName;

            // Set up an API client;
            mGoogleApiClient = new GoogleApiClient.Builder (Activity)
                .AddConnectionCallbacks (this)
                .AddOnConnectionFailedListener (this)
                .SetAccountName (accountName)
                .AddApi (WalletClass.API, new WalletClass.WalletOptions.Builder ()
                    .SetEnvironment (Constants.WALLET_ENVIRONMENT)
                    .SetTheme (WalletConstants.ThemeLight)
                    .Build ())
                .Build ();

            mRetryHandler = new RetryHandler (this);
        }