public static void RaiseException <TException>(
     this ContextualPolicy policy,
     IDictionary <string, object> contextData,
     Action <TException, int> configureException = null) where TException : Exception, new()
 {
     policy.RaiseException(1, contextData, configureException);
 }
        public void Executing_the_policy_function_should_should_throw_when_context_data_is_null()
        {
            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .RetryAsync((_, __, ___) => { });

            policy.Invoking(p => p.ExecuteAsync(() => Task.FromResult(2), null))
            .ShouldThrow <ArgumentNullException>().And
            .ParamName.Should().Be("contextData");
        }
示例#3
0
        public void Execute_and_capturing_the_policy_function_should_throw_when_context_data_is_null()
        {
            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .Retry((_, __, ___) => { });

            policy.Invoking(p => p.ExecuteAndCapture(() => 2, null))
            .ShouldThrow <ArgumentNullException>().And
            .ParamName.Should().Be("contextData");
        }
        public async Task Executing_the_policy_function_should_execute_the_specified_async_function_and_return_the_result()
        {
            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .RetryAsync((_, __, ___) => { });

            int result = await policy.ExecuteAsync(() => Task.FromResult(2));

            result.Should()
            .Be(2);
        }
示例#5
0
        public void Executing_the_policy_function_should_execute_the_specified_function_and_return_the_result()
        {
            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .Retry((_, __, ___) => { });

            var result = policy.Execute(() => 2);

            result.Should()
            .Be(2);
        }
示例#6
0
        public void Executing_the_policy_action_should_execute_the_specified_action()
        {
            var executed = false;

            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .Retry((_, __, ___) => { });

            policy.Execute(() => executed = true);

            executed.Should()
            .BeTrue();
        }
示例#7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageGateway"/> class.
        /// Use if you need to inject a test logger
        /// <param name="connection">The amqp uri and exchange to connect to</param>
        /// </summary>
        protected MessageGateway(RmqMessagingGatewayConnection connection)
        {
            Connection = connection;

            var connectionPolicyFactory = new ConnectionPolicyFactory(Connection);

            _retryPolicy = connectionPolicyFactory.RetryPolicy;
            _circuitBreakerPolicy = connectionPolicyFactory.CircuitBreakerPolicy;

            _connectionFactory = new ConnectionFactory { Uri = Connection.AmpqUri.Uri.ToString(), RequestedHeartbeat = 30 };

            DelaySupported = this is IAmAMessageGatewaySupportingDelay && Connection.Exchange.SupportDelay;
        }
示例#8
0
        public void Context_should_be_empty_if_execute_not_called_with_any_data()
        {
            Context capturedContext = null;

            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .RetryForeverAsync((_, context) => capturedContext = context);

            policy.RaiseExceptionAsync <DivideByZeroException>();

            capturedContext.Should()
            .BeEmpty();
        }
示例#9
0
        public static Task <TResult> RaiseResultSequenceAsync <TResult>(this ContextualPolicy <TResult> policy, IDictionary <string, object> contextData, CancellationToken cancellationToken, IEnumerable <TResult> resultsToRaise)
        {
            var enumerator = resultsToRaise.GetEnumerator();

            return(policy.ExecuteAsync(ct =>
            {
                if (!enumerator.MoveNext())
                {
                    throw new ArgumentOutOfRangeException("resultsToRaise", "Not enough TResult values in resultsToRaise.");
                }

                return Task.FromResult(enumerator.Current);
            }, contextData, cancellationToken));
        }
示例#10
0
        public MessageGateway(ILog logger)
        {
            this.Logger   = logger;
            Configuration = RMQMessagingGatewayConfigurationSection.GetConfiguration();

            var connectionPolicyFactory = new ConnectionPolicyFactory(logger);

            retryPolicy          = connectionPolicyFactory.RetryPolicy;
            circuitBreakerPolicy = connectionPolicyFactory.CircuitBreakerPolicy;

            connectionFactory = new ConnectionFactory {
                Uri = Configuration.AMPQUri.Uri.ToString(), RequestedHeartbeat = 30
            };
        }
示例#11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageGateway"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        public MessageGateway(ILog logger)
        {
            Logger = logger;
            Configuration = RMQMessagingGatewayConfigurationSection.GetConfiguration();

            var connectionPolicyFactory = new ConnectionPolicyFactory(logger);

            _retryPolicy = connectionPolicyFactory.RetryPolicy;
            _circuitBreakerPolicy = connectionPolicyFactory.CircuitBreakerPolicy;

            _connectionFactory = new ConnectionFactory { Uri = Configuration.AMPQUri.Uri.ToString(), RequestedHeartbeat = 30 };

            DelaySupported = (this is IAmAMessageGatewaySupportingDelay) && Configuration.Exchange.SupportDelay;
        }
示例#12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageGateway"/> class.
        /// Use if you need to inject a test logger
        /// <param name="connection">The amqp uri and exchange to connect to</param>
        /// </summary>
        protected MessageGateway(RmqMessagingGatewayConnection connection)
        {
            Connection = connection;

            var connectionPolicyFactory = new ConnectionPolicyFactory(Connection);

            _retryPolicy          = connectionPolicyFactory.RetryPolicy;
            _circuitBreakerPolicy = connectionPolicyFactory.CircuitBreakerPolicy;

            _connectionFactory = new ConnectionFactory {
                Uri = Connection.AmpqUri.Uri.ToString(), RequestedHeartbeat = 30
            };

            DelaySupported = this is IAmAMessageGatewaySupportingDelay && Connection.Exchange.SupportDelay;
        }
示例#13
0
        public void Should_not_call_onretry_when_retry_count_is_zero_with_context()
        {
            bool retryInvoked = false;

            Action <Exception, TimeSpan, Context> onRetry = (_, __, ___) => { retryInvoked = true; };

            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .WaitAndRetry(0, retryAttempt => TimeSpan.FromSeconds(1), onRetry);

            policy.Invoking(x => x.RaiseException <DivideByZeroException>())
            .ShouldThrow <DivideByZeroException>();

            retryInvoked.Should().BeFalse();
        }
示例#14
0
        private MessageGateway(ILog logger, RMQMessagingGatewayConfigurationSection configuration)
        {
            Logger        = logger;
            Configuration = configuration;

            var connectionPolicyFactory = new ConnectionPolicyFactory(logger, Configuration);

            _retryPolicy          = connectionPolicyFactory.RetryPolicy;
            _circuitBreakerPolicy = connectionPolicyFactory.CircuitBreakerPolicy;

            _connectionFactory = new ConnectionFactory {
                Uri = Configuration.AMPQUri.Uri.ToString(), RequestedHeartbeat = 30
            };

            DelaySupported = (this is IAmAMessageGatewaySupportingDelay) && Configuration.Exchange.SupportDelay;
        }
示例#15
0
        public static TResult RaiseResultSequence <TResult>(this ContextualPolicy <TResult> policy,
                                                            IDictionary <string, object> contextData,
                                                            IEnumerable <TResult> resultsToRaise)
        {
            var enumerator = resultsToRaise.GetEnumerator();

            return(policy.Execute(() =>
            {
                if (!enumerator.MoveNext())
                {
                    throw new ArgumentOutOfRangeException("resultsToRaise", "Not enough TResult values in resultsToRaise.");
                }

                return enumerator.Current;
            }, contextData));
        }
示例#16
0
        public void Should_call_onretry_on_each_retry_with_the_passed_context()
        {
            IDictionary <string, object> contextData = null;

            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .RetryForeverAsync((_, context) => contextData = context);

            policy.RaiseExceptionAsync <DivideByZeroException>(
                new { key1 = "value1", key2 = "value2" }.AsDictionary()
                );

            contextData.Should()
            .ContainKeys("key1", "key2").And
            .ContainValues("value1", "value2");
        }
示例#17
0
        public void Should_call_onretry_with_the_passed_context_when_execute_and_capture()
        {
            IDictionary <string, object> contextData = null;

            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .Retry((_, __, context) => contextData = context);

            policy.Invoking(p => p.ExecuteAndCapture(() => { throw new DivideByZeroException(); },
                                                     new { key1 = "value1", key2 = "value2" }.AsDictionary()))
            .ShouldNotThrow();

            contextData.Should()
            .ContainKeys("key1", "key2").And
            .ContainValues("value1", "value2");
        }
        public async Task Executing_the_policy_action_should_execute_the_specified_async_action()
        {
            bool executed = false;

            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .RetryAsync((_, __, ___) => { });

            await policy.ExecuteAsync(() =>
            {
                executed = true;
                return(Task.FromResult(true) as Task);
            });

            executed.Should()
            .BeTrue();
        }
示例#19
0
        public void Context_should_be_empty_if_execute_not_called_with_any_data()
        {
            Context capturedContext = null;

            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .WaitAndRetryAsync(new[]
            {
                1.Seconds(),
                2.Seconds(),
                3.Seconds()
            }, (_, __, context) => capturedContext = context);

            policy.RaiseExceptionAsync <DivideByZeroException>();

            capturedContext.Should()
            .BeEmpty();
        }
示例#20
0
        public void Should_create_new_context_for_each_call_to_execute()
        {
            string contextValue = null;

            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .RetryForeverAsync((_, context) => contextValue = context["key"].ToString());

            policy.RaiseExceptionAsync <DivideByZeroException>(
                new { key = "original_value" }.AsDictionary()
                );

            contextValue.Should().Be("original_value");

            policy.RaiseExceptionAsync <DivideByZeroException>(
                new { key = "new_value" }.AsDictionary()
                );

            contextValue.Should().Be("new_value");
        }
示例#21
0
        public void Should_create_new_context_for_each_call_to_execute_and_capture()
        {
            string contextValue = null;

            ContextualPolicy policy = Policy
                                      .Handle <DivideByZeroException>()
                                      .Retry((_, __, context) => contextValue = context["key"].ToString());

            policy.Invoking(p => p.ExecuteAndCapture(() => { throw new DivideByZeroException(); },
                                                     new { key = "original_value" }.AsDictionary()))
            .ShouldNotThrow();

            contextValue.Should().Be("original_value");

            policy.Invoking(p => p.ExecuteAndCapture(() => { throw new DivideByZeroException(); },
                                                     new { key = "new_value" }.AsDictionary()))
            .ShouldNotThrow();

            contextValue.Should().Be("new_value");
        }
        public static Task RaiseExceptionAsync <TException>(this ContextualPolicy policy, int numberOfTimesToRaiseException, IDictionary <string, object> contextData, Action <TException, int> configureException = null, CancellationToken cancellationToken = default(CancellationToken)) where TException : Exception, new()
        {
            int counter = 0;

            return(policy.ExecuteAsync(ct =>
            {
                if (counter < numberOfTimesToRaiseException)
                {
                    counter++;

                    var exception = new TException();

                    if (configureException != null)
                    {
                        configureException(exception, counter);
                    }

                    throw exception;
                }
                return Task.FromResult(true) as Task;
            }, contextData, cancellationToken));
        }
        public static void RaiseException <TException>(this ContextualPolicy policy,
                                                       int numberOfTimesToRaiseException,
                                                       Action <TException, int> configureException = null) where TException : Exception, new()
        {
            int counter = 0;

            policy.Execute(() =>
            {
                if (counter < numberOfTimesToRaiseException)
                {
                    counter++;

                    var exception = new TException();

                    if (configureException != null)
                    {
                        configureException(exception, counter);
                    }

                    throw exception;
                }
            });
        }
示例#24
0
 public static TResult RaiseResultSequence <TResult>(this ContextualPolicy <TResult> policy,
                                                     IDictionary <string, object> contextData,
                                                     params TResult[] resultsToRaise)
 {
     return(policy.RaiseResultSequence(contextData, resultsToRaise.ToList()));
 }
 public static void RaiseException <TException>(
     this ContextualPolicy policy,
     Action <TException, int> configureException = null) where TException : Exception, new()
 {
     policy.RaiseException(1, configureException);
 }
示例#26
0
 public static Task <TResult> RaiseResultSequenceAsync <TResult>(this ContextualPolicy <TResult> policy,
                                                                 IDictionary <string, object> contextData,
                                                                 params TResult[] resultsToRaise)
 {
     return(policy.RaiseResultSequenceAsync(contextData, CancellationToken.None, resultsToRaise.ToList()));
 }
示例#27
0
 public static Task <PolicyResult <TResult> > RaiseResultSequenceOnExecuteAndCaptureAsync <TResult>(this ContextualPolicy <TResult> policy, IDictionary <string, object> contextData, params TResult[] resultsToRaise)
 {
     return(policy.RaiseResultSequenceOnExecuteAndCaptureAsync(contextData, resultsToRaise.ToList()));
 }
示例#28
0
 public static Func <Task <TResult> > Awaiting <TResult>(this ContextualPolicy <TResult> policy, Func <ContextualPolicy <TResult>, Task <TResult> > action)
 {
     return((Func <Task <TResult> >)(() => action(policy)));
 }
 public static Task RaiseExceptionAsync <TException>(this ContextualPolicy policy, IDictionary <string, object> contextData, Action <TException, int> configureException = null, CancellationToken cancellationToken = default(CancellationToken)) where TException : Exception, new()
 {
     return(policy.RaiseExceptionAsync(1, contextData, configureException, cancellationToken));
 }
示例#30
0
 public static Func <Task> Awaiting(this ContextualPolicy policy, Func <ContextualPolicy, Task> action)
 {
     return((Func <Task>)(() => action(policy)));
 }