예제 #1
0
        public ApiDownloaderService()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));

            _retryPolicy = new RetryPolicy <BGGTransientErrorDetectionStrategy>(retryStrategy);
        }
예제 #2
0
        public void Initialize()
        {
            var retryStrategy    = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            var retryPolicy      = new RetryPolicy <ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            var tokenProvider    = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            var serviceUri       = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
            var namespaceManager = new NamespaceManager(serviceUri, tokenProvider);

            this.settings.Topics.AsParallel().ForAll(topic =>
            {
                retryPolicy.ExecuteAction(() => CreateTopicIfNotExists(namespaceManager, topic));
                topic.Subscriptions.AsParallel().ForAll(subscription =>
                {
                    retryPolicy.ExecuteAction(() => CreateSubscriptionIfNotExists(namespaceManager, topic, subscription));
                    retryPolicy.ExecuteAction(() => UpdateRules(namespaceManager, topic, subscription));
                });
            });

            // Execute migration support actions only after all the previous ones have been completed.
            foreach (var topic in this.settings.Topics)
            {
                foreach (var action in topic.MigrationSupport)
                {
                    retryPolicy.ExecuteAction(() => UpdateSubscriptionIfExists(namespaceManager, topic, action));
                }
            }

            this.initialized = true;
        }
예제 #3
0
        public override void Commit()
        {
            //此處手動進行相關邏輯的校驗,故需要全局關閉SaveChanges時自動的校驗:
            //Configuration.ValidateOnSaveEnabled = false;
            var errors = dbContext.GetValidationErrors();

            if (errors.Any())
            {
                var errorMsgs = GetErrors(errors);
                throw new EfRepositoryException(errorMsgs);
            }

            RetryPolicy <SqlDatabaseTransientErrorDetectionStrategy> retryPolicy;
            var incremental = new Incremental(5, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1.5))
            {
                FastFirstRetry = true
            };

            retryPolicy = new RetryPolicy <SqlDatabaseTransientErrorDetectionStrategy>(incremental);

            retryPolicy.Retrying += (s, e) =>
                                    Trace.TraceWarning("An error occurred in attempt number {1} to access the database in ConferenceService: {0}",
                                                       e.LastException.Message, e.CurrentRetryCount);

            retryPolicy.ExecuteAction(() => dbContext.SaveChanges());
        }
예제 #4
0
        private static void RetryPolityUsingCode(IUnityContainer container, IBlockService service)
        {
            System.Diagnostics.Trace.WriteLine("Begin sample: RetryPolityUsingCode");
            // Define your retry strategy: retry 5 times, starting 1 second apart
            // and adding 2 seconds to the interval each retry.
            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));

            // Define your retry policy using the retry strategy and the Windows Azure storage
            // transient fault detection strategy.
            var retryPolicy = new RetryPolicy <BlockServiceExceptionDetectionStrategy>(retryStrategy);

            // Do some work that may result in a transient fault.
            System.Threading.Tasks.Parallel.For(0, 100, index =>
            {
                try
                {
                    retryPolicy.Retrying += OnRetryPolicyRetrying;
                    retryPolicy.ExecuteAction(() =>
                    {
                        _blockService.PutBlock(index.ToString(), index);
                    });
                    retryPolicy.Retrying -= OnRetryPolicyRetrying;
                }
                catch (Exception exception)
                {
                    // All the retries failed.
                    System.Diagnostics.Trace.WriteLine(string.Format("An Exception has been thrown:\n{0}", exception));
                }
            });

            System.Diagnostics.Trace.WriteLine("End sample: RetryPolityUsingCode");
        }
예제 #5
0
        public void Sample3_Level300_AutomaticRetry_ServiceConsumerRetryPolicy_UsingMicrosoftTransientFaultHandling_UsingOperationsProperty()
        {
            var microsoftRetryStrategy = new Incremental(5, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));
            var microsoftRetryPolicy   = new RetryPolicy <SoapFaultWebServiceTransientErrorDetectionStrategy>(microsoftRetryStrategy);

            var serviceConsumerRetryPolicy = microsoftRetryPolicy.ForServiceConsumer(); // extension method

            // or var serviceConsumerRetryPolicy = new ChannelAdam.TransientFaultHandling.RetryPolicyAdapter(microsoftRetryPolicy);
            // or var serviceConsumerRetryPolicy = (ChannelAdam.TransientFaultHandling.IRetryPolicyFunction)microsoftRetryPolicy;
            using (var service = ServiceConsumerFactory.Create <IFakeService>(() => new FakeServiceClient(), serviceConsumerRetryPolicy))
            {
                try
                {
                    int actual = service.Operations.AddIntegers(1, 1);

                    Console.WriteLine("Actual: " + actual);
                    Assert.AreEqual(2, actual);

                    return;
                }
                catch (FaultException fe)
                {
                    Console.WriteLine("Service operation threw a fault: " + fe.ToString());
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Technical error occurred while calling the service operation: " + ex.ToString());
                }

                Assert.Fail("Service operation was not successfully called");
            }
        }
        /// <summary>
        ///     Gets the specified key.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public T Get <T>(string key)
        {
            var cachedData    = default(T);
            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
            var retryPolicy   = new RetryPolicy <StorageTransientErrorDetectionStrategy>(retryStrategy);

            // Do some work that may result in a transient fault.
            try
            {
                retryPolicy.ExecuteAction(() =>
                {
                    var database = _connectionMultiplexer.GetDatabase();
                    var data     = database.StringGet(key);
                    if (data.HasValue)
                    {
                        cachedData = JsonSerializer.Deserialize <T>(database.StringGet(key));
                    }
                });
            }
            catch (Exception ex)
            {
                //Logger.Error(ex, $"{GetType().FullName} / {MethodBase.GetCurrentMethod().Name}");
            }
            return(cachedData);
        }
예제 #7
0
        public InMemoryRetryMiddleware(Middleware <TContext> middleware)
        {
            this.middleware = middleware;
            var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(100));//Total 3 Retrues

            retryPolicy = new RetryPolicy(new TransientErrorCatchAllStrategy(), retryStrategy);
        }
예제 #8
0
        public void Initialize()
        {
            var retryStrategy    = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            var retryPolicy      = new RetryPolicy <ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            var namespaceManager = NamespaceManager.CreateFromConnectionString(settings.ConnectionString);

            this.settings.Topics.AsParallel().ForAll(topic =>
            {
                retryPolicy.ExecuteAction(() => CreateTopicIfNotExists(namespaceManager, topic));
                topic.Subscriptions.AsParallel().ForAll(subscription =>
                {
                    retryPolicy.ExecuteAction(() => CreateSubscriptionIfNotExists(namespaceManager, topic, subscription));
                    retryPolicy.ExecuteAction(() => UpdateRules(namespaceManager, this.settings.ConnectionString, topic, subscription));
                });
            });

            // Execute migration support actions only after all the previous ones have been completed.
            foreach (var topic in this.settings.Topics)
            {
                foreach (var action in topic.MigrationSupport)
                {
                    retryPolicy.ExecuteAction(() => UpdateSubscriptionIfExists(namespaceManager, this.settings.ConnectionString, topic, action));
                }
            }

            this.initialized = true;
        }
예제 #9
0
        public InMemoryRetryWorkflow(Workflow <TContext> workflow)
        {
            this.workflow = workflow;
            var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMilliseconds(1000));//Total 3 Retrues

            retryPolicy = new RetryPolicy(new TransientErrorCatchAllStrategy(), retryStrategy);
        }
예제 #10
0
        // GET api/nextsession
        public Session Get()
        {
            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
            var retryPolicy   = new RetryPolicy <SqlAzureTransientErrorDetectionStrategy>(retryStrategy);

            Session nextSession = new Session();

            using (VidPackEntities db = new VidPackEntities())
            {
                retryPolicy.ExecuteAction(() =>
                {
                    db.Database.Connection.Open();
                });

                ExistingSession dbSession = retryPolicy.ExecuteAction <ExistingSession>(() =>
                                                                                        db.ExistingSession.Where(item => item.IsNextSession == 1).FirstOrDefault()
                                                                                        );

                if (dbSession != null)
                {
                    nextSession = new VidPackModel.Session()
                    {
                        SessionDate         = dbSession.SessionDate.ToString(),
                        SessionDescription  = dbSession.SessionDescription,
                        SessionSubTitle     = dbSession.SessionSubTitle,
                        SessionThumbnailUrl = String.Format("{0}{1}", ThumbnailStorageUrl, dbSession.SessionThumbnailUri),
                        SessionTitle        = dbSession.SessionSubTitle,
                        SessionVideoUrl     = dbSession.SessionVideoUri == null ? "" : dbSession.SessionVideoUri,
                        Speaker             = dbSession.Speaker
                    }
                }
                ;
            }
            return(nextSession);
        }
예제 #11
0
        public void Sample3_Level300_AutomaticRetry_StaticServiceConsumerRetryPolicy_UsingMicrosoftTransientFaultHandling_WithConsumeMethod()
        {
            var microsoftRetryStrategy = new Incremental(5, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));
            var microsoftRetryPolicy   = new RetryPolicy <SoapFaultWebServiceTransientErrorDetectionStrategy>(microsoftRetryStrategy);

            ServiceConsumerFactory.DefaultRetryPolicy = microsoftRetryPolicy.ForServiceConsumer(); // extension method
            // or ServiceConsumerFactory.DefaultRetryPolicy = new ChannelAdam.TransientFaultHandling.RetryPolicyAdapter(microsoftRetryPolicy);
            // or ServiceConsumerFactory.DefaultRetryPolicy = (ChannelAdam.TransientFaultHandling.IRetryPolicyFunction)microsoftRetryPolicy;

            using (var service = ServiceConsumerFactory.Create <IFakeService>(() => new FakeServiceClient()))
            {
                var result = service.Consume(operation => operation.AddIntegers(1, 1));

                if (result.HasNoException)
                {
                    Console.WriteLine("Actual: " + result.Value);
                    Assert.AreEqual(2, result.Value);
                }
                else
                {
                    if (result.HasFaultException)
                    {
                        Console.WriteLine("Service operation threw a fault: " + result.Exception.ToString());
                    }
                    else if (result.HasException)
                    {
                        Console.WriteLine("Technical error occurred while calling the service operation: " + result.Exception.ToString());
                    }

                    Assert.Fail("Service operation was not successfully called");
                }
            }
        }
        public void MediaServicesCredentialsAcsEndPointCustomRetryPolicy()
        {
            string account                       = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountName;
            string key                           = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountKey;
            var    retryStrategy                 = new Incremental(1, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
            var    errorDetectionStrategy        = new ErrorDetectionStrategyForRefreshToken();
            MediaServicesCredentials credentials = new MediaServicesCredentials(account, key,
                                                                                WindowsAzureMediaServicesTestConfiguration.MediaServicesAccessScope,
                                                                                new List <string>
            {
                "http://dummyacsendpoint"
            })
            {
                RefreshTokenRetryPolicy = new RetryPolicy(errorDetectionStrategy, retryStrategy)
            };

            Assert.IsNull(credentials.AccessToken);
            Assert.IsTrue(credentials.TokenExpiration < DateTime.UtcNow);
            try
            {
                credentials.RefreshToken();
            }
            catch (WebException)
            {
                Assert.IsTrue(errorDetectionStrategy.Invoked);
                throw;
            }
        }
        public void CreatesDefaultRetryPolicyFromConfiguration()
        {
            RetryPolicy retryPolicy   = RetryPolicyFactory.GetRetryPolicy <MockErrorDetectionStrategy>();
            Incremental retryStrategy = retryPolicy.RetryStrategy as Incremental;

            Assert.AreEqual("Default Retry Strategy", retryStrategy.Name);
        }
        public void CreatesDefaultSqlConnectionPolicyFromConfiguration()
        {
            RetryPolicy retryPolicy   = RetryPolicyFactory.GetDefaultSqlConnectionRetryPolicy();
            Incremental retryStrategy = retryPolicy.RetryStrategy as Incremental;

            Assert.AreEqual("Default SqlConnection Retry Strategy", retryStrategy.Name);
        }
예제 #15
0
        private void HandleBadDataCacheBug(Action action)
        {
            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));

            var retryPolicy =
                new RetryPolicy <CacheRetryPolicy>(retryStrategy);

            try
            {
                retryPolicy.ExecuteAction(action);
            }
            catch (DataCacheException ex)
            {
                if (ex.ErrorCode == DataCacheErrorCode.ConnectionTerminated || ex.ErrorCode == DataCacheErrorCode.Timeout ||
                    ex.ErrorCode == DataCacheErrorCode.RetryLater)
                {
                    ErrorLogUtils.AddError(
                        new Exception(
                            "DataCache connection was lost. Trying to reinitialize DataCache through DataCacheFactory and retrying last operation.",
                            ex));
                    InitDataCache();
                    retryPolicy.ExecuteAction(action);
                }
                else
                {
                    throw;
                }
            }
        }
예제 #16
0
        private static RetryPolicy GetRetryPolicy()
        {
            var retryStrategy = new Incremental(5, new TimeSpan(0, 0, 1), new TimeSpan(0, 0, 1));
            var retryPolicy   = new RetryPolicy(new EventHubInvalidationErrorDetectionStrategy(), retryStrategy);

            return(retryPolicy);
        }
        private async Task <int> PublishEventsAsync(IList <EventEntry> collection)
        {
            var publishedEventCount = collection.Count;

            try
            {
                var content = collection.Count == 1 ?
                              CreateSingleMessageContent(collection.First()) :
                              CreateBatchMessageContent(collection, out publishedEventCount);

                var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(0.5), TimeSpan.FromSeconds(1));
                var retryPolicy   = new RetryPolicy <HttpTransientErrorDetectionStrategy>(retryStrategy);
                await retryPolicy.ExecuteAsync(() => PostMessageContentAsync(content));

                return(publishedEventCount);
            }
            catch (OperationCanceledException)
            {
                return(0);
            }
            catch (Exception ex)
            {
                if (cancellationTokenSource.IsCancellationRequested)
                {
                    return(0);
                }

                LogSinkFaultMessage(ex.ToString());
                throw;
            }
        }
예제 #18
0
        /// <summary>
        ///     Http request with transient fault handling block.
        /// </summary>
        /// <param name="httpClient">Http client</param>
        /// <param name="uri">Resource uri</param>
        /// <returns>Returned data</returns>
        public static Task <HttpResponseMessage> HttpRequestWithRetryAsync(HttpClient httpClient, string uri)
        {
            // Retry strategy: retry 3 times, starting 1 second apart and adding 2 seconds to the interval each retry.
            var retryStrategy = new Incremental(3, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));

            // Retry policy using the retry strategy and the http transient fault detection strategy.
            var retryPolicy = new RetryPolicy <HttpTransientErrorDetectionStrategy>(retryStrategy);

            // Receive notifications about retries.
            retryPolicy.Retrying += (sender, args) =>
            {
                // Log details of the retry.
                Trace.WriteLine($"Retry - Count: {args?.CurrentRetryCount}, Delay: {args?.Delay}, Exception: {args?.LastException?.Message}", "Information");
            };

            // Call http service with and retry in transient fault.
            return(retryPolicy.ExecuteAsync(async() =>
            {
                var response = await httpClient.GetAsync(uri);

                if (!response.IsSuccessStatusCode)
                {
                    var responseBody = await response.Content.ReadAsStringAsync();
                    throw new HttpException((int)response.StatusCode, responseBody);
                }

                return response;
            }));
        }
        /// <summary>
        ///     Sets the specified key and data.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">The key.</param>
        /// <param name="data">The data.</param>
        /// <param name="returnIfExists">if set to <c>true</c> [return if exists].</param>
        public T Set <T>(string key, T data, bool returnIfExists)
        {
            // Define your retry strategy: retry 3 times, 1 second apart.
            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));

            // Define your retry policy using the retry strategy and the Windows Azure storage
            // transient fault detection strategy.
            var retryPolicy = new RetryPolicy <StorageTransientErrorDetectionStrategy>(retryStrategy);

            // Do some work that may result in a transient fault.
            try
            {
                // Call a method that uses Windows Azure storage and which may
                // throw a transient exception.
                retryPolicy.ExecuteAction(
                    () =>
                {
                    var database = _connectionMultiplexer.GetDatabase();
                    database.StringSet(key, JsonSerializer.Serialize(data), ConfigurationHelper.SessionPoolTimeOut);
                });
            }
            catch (Exception ex)
            {
                //Logger.Error(ex, $"{GetType().FullName} / {MethodBase.GetCurrentMethod().Name}");
            }

            return(returnIfExists ? Get <T>(key) : data);
        }
        public void CreatesDefaultSqlCommandPolicyFromConfiguration()
        {
            RetryPolicy retryPolicy   = RetryPolicyFactory.GetDefaultSqlCommandRetryPolicy();
            Incremental retryStrategy = retryPolicy.RetryStrategy as Incremental;

            Assert.AreEqual("Default SqlCommand Retry Strategy", retryStrategy.Name);
            Assert.IsInstanceOfType(retryPolicy.ErrorDetectionStrategy, typeof(SqlDatabaseTransientErrorDetectionStrategy));
        }
예제 #21
0
        /// <summary>
        ///     为容器注册公用依赖(log4net 和 RabbitMQ Iconnection),然后启动新服务
        /// </summary>
        /// <param name="args">服务启动参数</param>
        /// <param name="container">IoC 容器</param>
        /// <typeparam name="TService">要启动的服务类型</typeparam>
        public static void Run <TService>(string[] args, Container container) where TService : KeylolService
        {
            // 公用服务注册点

            // log4net
            container.RegisterConditional(typeof(ILogProvider),
                                          c => typeof(LogProvider <>).MakeGenericType(c.Consumer?.ImplementationType ?? typeof(KeylolService)),
                                          Lifestyle.Singleton,
                                          c => true);

            // RabbitMQ IConnection
            container.RegisterSingleton <MqClientProvider>();

            // Transient Fault Handling Retry Policy
            container.RegisterSingleton <RetryPolicy>(() =>
            {
                // 首次失败立即重试,之后重试每次增加 2 秒间隔
                var strategy = new Incremental(6, TimeSpan.Zero, TimeSpan.FromSeconds(2));
                return(new RetryPolicy <SoapFaultWebServiceTransientErrorDetectionStrategy>(strategy));
            });

            // 自身也注册进入容器
            container.RegisterSingleton <KeylolService, TService>();

            container.Verify();

            var service = container.GetInstance <KeylolService>();

            if (service.UseSelfInstaller(args))
            {
                container.Dispose();
                return;
            }

            SetupLogger(service.EventLog.Source);
            service.Stopped += (sender, eventArgs) => container.Dispose();

            if (Environment.UserInteractive) // 作为控制台应用启动
            {
                Console.Title =
                    $"Service Console: {(string.IsNullOrWhiteSpace(service.ServiceName) ? "(unnamed)" : service.ServiceName)}";
                Console.WriteLine("Running in console mode. Press Ctrl-Q to stop.");
                service.OnStart(args);
                while (true)
                {
                    var key = Console.ReadKey();
                    if (key.Modifiers == ConsoleModifiers.Control && key.Key == ConsoleKey.Q)
                    {
                        break;
                    }
                }
                service.OnStop();
            }
            else // 作为 Windows 服务启动
            {
                Run(service);
            }
        }
예제 #22
0
        /// <summary>
        ///     Returns a retry policy for use in accessing the database.
        /// </summary>
        /// <returns> A retry policy for use in accessing the database. </returns>
        internal static RetryPolicy <SqlAzureTransientErrorDetectionStrategy> GetRetryPolicy()
        {
            // SQL Azure retry strategy
            var retryStrategy = new Incremental(NumberOfRetries, RetryDelay, RetryIncrement);
            var retryPolicy   = new RetryPolicy <SqlAzureTransientErrorDetectionStrategy>(retryStrategy);

            retryPolicy.Retrying += (sender, args) => Log.Verbose("Retry - Count:{0}, Delay:{1}, Exception:{2}", args.CurrentRetryCount, args.Delay, args.LastException);
            return(retryPolicy);
        }
예제 #23
0
        public AppDataPortalBusOptions(WebAppSettings webAppSettings)
        {
            var retryStrategy = new Incremental(5, new TimeSpan(0, 0, 1), new TimeSpan(0, 0, 1));

            this.AppDataPath = "~/App_Data/Adxstudio.Xrm.AspNet.PortalBus/" + typeof(TMessage).Name;
            this.InstanceId  = webAppSettings.InstanceId;
            this.Timeout     = TimeSpan.FromMinutes(5);
            this.RetryPolicy = retryStrategy.CreateRetryPolicy();
        }
예제 #24
0
        /// <summary>
        /// The retry policy.
        /// </summary>
        /// <returns>
        /// The <see cref="RetryPolicy"/>.
        /// </returns>
        private RetryPolicy GetRetryPolicy()
        {
            // SQL Azure retry strategy
            var retryStrategy = new Incremental("EmailRenderingClient", 3, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
            var retryPolicy   = new RetryPolicy <AllTransientStrategy>(retryStrategy);

            retryPolicy.Retrying += (sender, args) => Log.Verbose("Retry - Count:{0}, Delay:{1}, Exception:{2}", args.CurrentRetryCount, args.Delay, args.LastException);
            return(retryPolicy);
        }
예제 #25
0
 private void InitialiseRetryHandling()
 {
     _retryStrategy         = new Incremental(_retries, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
     _retryPolicy           = new RetryPolicy <SqlServerErrorDetectionStrategy>(_retries);
     _retryPolicy.Retrying += (sender, args) =>
     {
         _log.Warn(String.Format("Retry {0} failed. Trying again. Delay {1}, Error: {2}", args.CurrentRetryCount, args.Delay, args.LastException.Message), args.LastException);
         _systemMetrics.LogCount("backends.sqlserver.retry");
     };
 }
        public void PolicyInstancesAreNotSingletons()
        {
            RetryPolicy connPolicy         = RetryPolicyFactory.GetDefaultSqlConnectionRetryPolicy();
            Incremental nonDefaultIncRetry = connPolicy.RetryStrategy as Incremental;

            RetryPolicy connPolicy1         = RetryPolicyFactory.GetDefaultSqlConnectionRetryPolicy();
            Incremental nonDefaultIncRetry1 = connPolicy1.RetryStrategy as Incremental;

            Assert.AreNotSame(connPolicy, connPolicy1);
        }
예제 #27
0
        private static RetryPolicy CreateIncrementalPolicy()
        {
            const int retryCount      = 3;
            var       initialInterval = TimeSpan.FromMilliseconds(10);
            var       increment       = TimeSpan.FromMilliseconds(200);

            var incrementalRetryStrategy = new Incremental(null, retryCount, initialInterval, increment, true);

            return(new RetryPolicy(new SqlDatabaseTransientErrorDetectionStrategy(), incrementalRetryStrategy));
        }
예제 #28
0
        public List <Product> GetProductsWithRetry(Action <string> logAction)
        {
            var res = new List <Product>();

            var retryStrategy = new Incremental("incr1", 120, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));

            //ITransientErrorDetectionStrategy
            //SqlAzureTransientErrorDetectionStrategy
            var retryPolicy = new RetryPolicy <SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);

            var cmd = "SELECT * FROM Products" + Environment.NewLine + "WAITFOR DELAY '00:05'";

            retryPolicy.Retrying += (sender, eventArgs) =>
            {
                //Debugger.Launch();
                logAction(String.Format("Retrying, CurrentRetryCount = {0} , Exception = {1}",
                                        eventArgs.CurrentRetryCount, eventArgs.LastException.Message));
                if (eventArgs.CurrentRetryCount > 1)
                {
                    cmd = "SELECT * FROM Products";
                }
            };

            using (var reliableConnection = new ReliableSqlConnection(ConnectionString, retryPolicy, retryPolicy))
            {
                using (var connection = reliableConnection.Open())
                {
                    retryPolicy.ExecuteAction(() =>
                    {
                        try
                        {
                            var command = new SqlCommand(cmd, connection);
                            using (var reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    res.Add(new Product()
                                    {
                                        Id = reader.GetInt32(0), Name = reader.GetString(1)
                                    });
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            var to = exception is TimeoutException;

                            throw new TimeoutException(exception.Message);
                        }
                    });
                }
            }

            return(res);
        }
예제 #29
0
        protected BaseDataRepository(EscarGoContext context)
        {
            Context = context;

            // On recommence jusqu'à 5 fois, au bout d'une seconde pour la première fois
            // on incrémente de 2 secondes supplémentaires à chaque essai successif
            Incremental retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));

            // Active la stratégie de réitération pour les pannes concernant SQL Azure
            SqlAzureRetry = new RetryPolicy <SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);
        }
    /// <summary>
    /// Initialize the retryPolicy
    /// Load the connection string from App.config
    /// </summary>
    public ReliableAzureConnection()
    {
        ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        //This means, 3 retries, first error, wait 0.5 secs and the next errors, increment 1 second the waiting
        Incremental RetryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1));

        // You can use one of the built-in detection strategies for
        //SQL Azure, Windows Azure Storage, Windows Azure Caching, or the Windows Azure Service Bus.
        //You can also define detection strategies for any other services that your application uses.
        RetryPolicy = new RetryPolicy <StorageTransientErrorDetectionStrategy>(RetryStrategy);
    }