From 011f5c52b7d022a2529e84549236e1a2135761f9 Mon Sep 17 00:00:00 2001 From: Dixin Date: Thu, 25 Jan 2024 01:36:08 -0800 Subject: [PATCH] Update internal APIs to align with .NET 8.0 convention. --- .../RetryManagerCachingExtensions.cs | 10 +-- .../ConfigurationExtensions.cs | 18 ++-- .../RetryConfiguration.cs | 6 +- .../RetryManagerOptionsExtensions.cs | 2 +- .../RetryPolicyFactory.cs | 14 +-- .../RetryStrategyOptions.cs | 18 ++-- .../RetryStrategyOptionsExtensions.cs | 6 +- .../TransientFaultHandling.Core/Argument.cs | 90 ++++++++++--------- .../ExponentialBackoff.cs | 14 ++- .../FixedInterval.cs | 35 ++++---- .../Incremental.cs | 6 +- .../Retry.Execute.cs | 8 +- .../Retry.ExponentialBackoff.cs | 8 +- .../Retry.FixedInterval.cs | 8 +- .../Retry.Incremental.cs | 8 +- .../Retry.Policy.cs | 12 +-- .../RetryManager.cs | 12 +-- .../RetryPolicy.cs | 14 +-- .../RetryingEventArgs.cs | 2 +- .../ReliableSqlConnection.Legacy.cs | 4 +- .../ReliableSqlConnection.cs | 4 +- .../RetryManagerSqlExtensions.cs | 8 +- .../SqlCommandExtensions.Legacy.cs | 10 +-- .../SqlCommandExtensions.cs | 10 +-- .../SqlCommandFactory.cs | 8 +- .../SqlConnectionExtensions.Legacy.cs | 4 +- .../SqlConnectionExtensions.cs | 2 +- .../SqlXmlReader.cs | 2 +- .../ConfigurationTests.cs | 42 ++++----- .../RetryManagers/Context.cs | 18 ++-- 30 files changed, 201 insertions(+), 202 deletions(-) diff --git a/Source/TransientFaultHandling.Caching.Core/RetryManagerCachingExtensions.cs b/Source/TransientFaultHandling.Caching.Core/RetryManagerCachingExtensions.cs index 1985098..034e563 100644 --- a/Source/TransientFaultHandling.Caching.Core/RetryManagerCachingExtensions.cs +++ b/Source/TransientFaultHandling.Caching.Core/RetryManagerCachingExtensions.cs @@ -10,7 +10,7 @@ public static class RetryManagerCachingExtensions /// /// The technology name that can be used to get the default Caching retry strategy name. /// - public const string DefaultStrategyTechnologyName = "Caching"; + public const string DefaultStrategyTechnologyName = nameof(Caching); /// /// Returns the default retry strategy for Windows Azure Caching. @@ -19,7 +19,7 @@ public static class RetryManagerCachingExtensions [Obsolete("Use GetDefaultCachingRetryStrategy instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public static RetryStrategy GetDefaultAzureCachingRetryStrategy(this RetryManager retryManager) => - retryManager.NotNull().GetDefaultRetryStrategy(DefaultStrategyTechnologyName); + retryManager.ThrowIfNull().GetDefaultRetryStrategy(DefaultStrategyTechnologyName); /// /// Returns the default retry policy dedicated to handling transient conditions with Windows Azure Caching. @@ -27,19 +27,19 @@ public static class RetryManagerCachingExtensions /// The retry policy for Windows Azure Caching with the corresponding default strategy (or the default strategy if no retry strategy definition assigned to Windows Azure Caching was found). [Obsolete("Use GetDefaultCachingRetryPolicy instead.")] public static RetryPolicy GetDefaultAzureCachingRetryPolicy(this RetryManager retryManager) => - new (new CacheTransientErrorDetectionStrategy(), retryManager.NotNull().GetDefaultCachingRetryStrategy()); + new (new CacheTransientErrorDetectionStrategy(), retryManager.ThrowIfNull().GetDefaultCachingRetryStrategy()); /// /// Returns the default retry strategy for Windows Azure Caching. /// /// The default Windows Azure Caching retry strategy (or the default strategy if no default could be found for Windows Azure Caching). public static RetryStrategy GetDefaultCachingRetryStrategy(this RetryManager retryManager) => - retryManager.NotNull().GetDefaultRetryStrategy(DefaultStrategyTechnologyName); + retryManager.ThrowIfNull().GetDefaultRetryStrategy(DefaultStrategyTechnologyName); /// /// Returns the default retry policy dedicated to handling transient conditions with Windows Azure Caching. /// /// The retry policy for Windows Azure Caching with the corresponding default strategy (or the default strategy if no retry strategy definition for Windows Azure Caching was found). public static RetryPolicy GetDefaultCachingRetryPolicy(this RetryManager retryManager) => - new (new CacheTransientErrorDetectionStrategy(), retryManager.NotNull().GetDefaultCachingRetryStrategy()); + new (new CacheTransientErrorDetectionStrategy(), retryManager.ThrowIfNull().GetDefaultCachingRetryStrategy()); } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Configuration.Core/ConfigurationExtensions.cs b/Source/TransientFaultHandling.Configuration.Core/ConfigurationExtensions.cs index 6177f1b..ec64e99 100644 --- a/Source/TransientFaultHandling.Configuration.Core/ConfigurationExtensions.cs +++ b/Source/TransientFaultHandling.Configuration.Core/ConfigurationExtensions.cs @@ -27,7 +27,7 @@ public static class ConfigurationExtensions string key = RetryConfiguration.DefaultConfigurationKeyRetryStrategy, Func? getCustomRetryStrategy = null) { - IConfigurationSection section = configuration.NotNull().GetSection(key.NotNullOrEmpty()); + IConfigurationSection section = configuration.ThrowIfNull().GetSection(key.ThrowIfNullOrEmpty()); return section.Exists() ? section.GetRetryStrategies(getCustomRetryStrategy) : throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ConfigurationKeyNotFOund, key), nameof(key)); @@ -42,7 +42,7 @@ public static class ConfigurationExtensions public static IDictionary GetRetryStrategies( this IConfigurationSection configurationSection, Func? getCustomRetryStrategy = null) => - configurationSection.NotNull().Exists() + configurationSection.ThrowIfNull().Exists() ? configurationSection.GetChildren().ToDictionary( childSection => childSection.Key, childSection => childSection.GetRetryStrategy(getCustomRetryStrategy)) @@ -54,7 +54,7 @@ public static class ConfigurationExtensions /// The retry strategy. public static RetryStrategy GetRetryStrategy(this IConfigurationSection configurationSection, Func? getCustomRetryStrategy = null) { - if (!configurationSection.NotNull().Exists()) + if (!configurationSection.ThrowIfNull().Exists()) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ConfigurationSectionNotExist, configurationSection.Path), nameof(configurationSection)); } @@ -74,7 +74,7 @@ public static RetryStrategy GetRetryStrategy(this IConfigurationSection configur /// The retry strategy. public static FixedInterval GetFixedInterval(this IConfigurationSection configurationSection) { - if (!configurationSection.NotNull().Exists()) + if (!configurationSection.ThrowIfNull().Exists()) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ConfigurationSectionNotExist, configurationSection.Path), nameof(configurationSection)); } @@ -92,7 +92,7 @@ public static FixedInterval GetFixedInterval(this IConfigurationSection configur /// The retry strategy. public static Incremental GetIncremental(this IConfigurationSection configurationSection) { - if (!configurationSection.NotNull().Exists()) + if (!configurationSection.ThrowIfNull().Exists()) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ConfigurationSectionNotExist, configurationSection.Path), nameof(configurationSection)); } @@ -110,7 +110,7 @@ public static Incremental GetIncremental(this IConfigurationSection configuratio /// The retry strategy. public static ExponentialBackoff GetExponentialBackoff(this IConfigurationSection configurationSection) { - if (!configurationSection.NotNull().Exists()) + if (!configurationSection.ThrowIfNull().Exists()) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ConfigurationSectionNotExist, configurationSection.Path), nameof(configurationSection)); } @@ -138,7 +138,7 @@ public static ExponentialBackoff GetExponentialBackoff(this IConfigurationSectio where TRetryStrategy : RetryStrategy { Func? covariance = getCustomRetryStrategy; - return GetRetryStrategies(configuration.NotNull(), key.NotNullOrEmpty(), covariance) + return GetRetryStrategies(configuration.ThrowIfNull(), key.ThrowIfNullOrEmpty(), covariance) .Where(pair => pair.Value is not null and TRetryStrategy) .ToDictionary(pair => pair.Key, pair => (TRetryStrategy)pair.Value); } @@ -155,7 +155,7 @@ public static ExponentialBackoff GetExponentialBackoff(this IConfigurationSectio string key = RetryConfiguration.DefaultConfigurationKeyRetryManager, Func? getCustomRetryStrategy = null) { - IConfigurationSection section = configuration.NotNull().GetSection(key.NotNullOrEmpty()); + IConfigurationSection section = configuration.ThrowIfNull().GetSection(key.ThrowIfNullOrEmpty()); return section.Exists() ? section.GetRetryManager(getCustomRetryStrategy) : throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ConfigurationKeyNotFOund, key), nameof(key)); @@ -170,7 +170,7 @@ public static ExponentialBackoff GetExponentialBackoff(this IConfigurationSectio public static RetryManager GetRetryManager( this IConfigurationSection configurationSection, Func? getCustomRetryStrategy = null) => - configurationSection.NotNull().Exists() + configurationSection.ThrowIfNull().Exists() ? configurationSection.Get(buildOptions => buildOptions.BindNonPublicProperties = true).ToRetryManager(getCustomRetryStrategy) : throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.ConfigurationSectionNotExist, configurationSection.Path), nameof(configurationSection)); } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Configuration.Core/RetryConfiguration.cs b/Source/TransientFaultHandling.Configuration.Core/RetryConfiguration.cs index c6b7ba0..049418b 100644 --- a/Source/TransientFaultHandling.Configuration.Core/RetryConfiguration.cs +++ b/Source/TransientFaultHandling.Configuration.Core/RetryConfiguration.cs @@ -31,7 +31,7 @@ public static class RetryConfiguration string configurationFile = DefaultConfigurationFile, string configurationKey = DefaultConfigurationKeyRetryStrategy, Func? getCustomRetryStrategy = null) => - GetConfiguration(configurationFile.NotNullOrEmpty()).GetRetryStrategies(configurationKey.NotNullOrEmpty(), getCustomRetryStrategy); + GetConfiguration(configurationFile.ThrowIfNullOrEmpty()).GetRetryStrategies(configurationKey.ThrowIfNullOrEmpty(), getCustomRetryStrategy); /// /// ets the retry manager from the specified configuration file and key. @@ -44,14 +44,14 @@ public static class RetryConfiguration string configurationFile = DefaultConfigurationFile, string configurationKey = DefaultConfigurationKeyRetryManager, Func? getCustomRetryStrategy = null) => - GetConfiguration(configurationFile.NotNullOrEmpty()).GetRetryManager(configurationKey.NotNullOrEmpty(), getCustomRetryStrategy); + GetConfiguration(configurationFile.ThrowIfNullOrEmpty()).GetRetryManager(configurationKey.ThrowIfNullOrEmpty(), getCustomRetryStrategy); /// Gets the configuration from the specified file. /// The specified configuration file. /// The configuration. public static IConfiguration GetConfiguration(string configurationFile = DefaultConfigurationFile) { - configurationFile.NotNullOrEmpty(); + configurationFile.ThrowIfNullOrEmpty(); IConfigurationBuilder builder = new ConfigurationBuilder(); builder = Path.GetExtension(configurationFile).ToUpperInvariant() switch diff --git a/Source/TransientFaultHandling.Configuration.Core/RetryManagerOptionsExtensions.cs b/Source/TransientFaultHandling.Configuration.Core/RetryManagerOptionsExtensions.cs index d06e321..bf9bcb2 100644 --- a/Source/TransientFaultHandling.Configuration.Core/RetryManagerOptionsExtensions.cs +++ b/Source/TransientFaultHandling.Configuration.Core/RetryManagerOptionsExtensions.cs @@ -13,7 +13,7 @@ public static class RetryManagerOptionsExtensions /// public static RetryManager ToRetryManager(this RetryManagerOptions options, Func? getCustomRetryStrategy = null) { - if (options.NotNull().RetryStrategy is null || !options.RetryStrategy.Exists()) + if (options.ThrowIfNull().RetryStrategy is null || !options.RetryStrategy.Exists()) { throw new ArgumentException(Resources.RetryStrategySectionNotFoundInRetryManager, nameof(options)); } diff --git a/Source/TransientFaultHandling.Configuration.Core/RetryPolicyFactory.cs b/Source/TransientFaultHandling.Configuration.Core/RetryPolicyFactory.cs index 37112b9..f9bc042 100644 --- a/Source/TransientFaultHandling.Configuration.Core/RetryPolicyFactory.cs +++ b/Source/TransientFaultHandling.Configuration.Core/RetryPolicyFactory.cs @@ -21,7 +21,7 @@ public static class RetryPolicyFactory public static RetryManager CreateDefault( string configurationFile = RetryConfiguration.DefaultConfigurationFile, string configurationKey = nameof(RetryManager), Func? getCustomRetryStrategy = null) { - RetryManager manager = RetryConfiguration.GetRetryManager(configurationFile.NotNullOrEmpty(), configurationKey.NotNullOrEmpty(), getCustomRetryStrategy); + RetryManager manager = RetryConfiguration.GetRetryManager(configurationFile.ThrowIfNullOrEmpty(), configurationKey.ThrowIfNullOrEmpty(), getCustomRetryStrategy); RetryManager.SetDefault(manager); return manager; } @@ -33,7 +33,7 @@ public static class RetryPolicyFactory [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "As designed")] public static RetryPolicy GetDefaultSqlConnectionRetryPolicy( string configurationFile = RetryConfiguration.DefaultConfigurationFile, string configurationKey = nameof(RetryManager), Func? getCustomRetryStrategy = null) => - GetOrCreateRetryManager(configurationKey.NotNullOrEmpty(), configurationKey, getCustomRetryStrategy) + GetOrCreateRetryManager(configurationKey.ThrowIfNullOrEmpty(), configurationKey, getCustomRetryStrategy) .GetDefaultSqlConnectionRetryPolicy(); /// @@ -43,7 +43,7 @@ public static class RetryPolicyFactory [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "As designed")] public static RetryPolicy GetDefaultSqlCommandRetryPolicy( string configurationFile = RetryConfiguration.DefaultConfigurationFile, string configurationKey = nameof(RetryManager), Func? getCustomRetryStrategy = null) => - GetOrCreateRetryManager(configurationFile.NotNullOrEmpty(nameof(configurationFile)), configurationKey.NotNullOrEmpty(), getCustomRetryStrategy) + GetOrCreateRetryManager(configurationFile.ThrowIfNullOrEmpty(nameof(configurationFile)), configurationKey.ThrowIfNullOrEmpty(), getCustomRetryStrategy) .GetDefaultSqlCommandRetryPolicy(); // TODO. @@ -86,7 +86,7 @@ public static class RetryPolicyFactory public static RetryPolicy GetRetryPolicy( string configurationFile = RetryConfiguration.DefaultConfigurationFile, string configurationKey = nameof(RetryManager), Func? getCustomRetryStrategy = null) where T : ITransientErrorDetectionStrategy, new() => - GetOrCreateRetryManager(configurationFile.NotNullOrEmpty(), configurationKey.NotNullOrEmpty(), getCustomRetryStrategy) + GetOrCreateRetryManager(configurationFile.ThrowIfNullOrEmpty(), configurationKey.ThrowIfNullOrEmpty(), getCustomRetryStrategy) .GetRetryPolicy(); /// @@ -102,7 +102,7 @@ public static class RetryPolicyFactory string configurationFile = RetryConfiguration.DefaultConfigurationFile, string configurationKey = nameof(RetryManager), Func? getCustomRetryStrategy = null) => - GetOrCreateRetryManager(configurationFile.NotNullOrEmpty(), configurationKey.NotNullOrEmpty(), getCustomRetryStrategy).GetRetryPolicy(errorDetectionStrategy.NotNull()); + GetOrCreateRetryManager(configurationFile.ThrowIfNullOrEmpty(), configurationKey.ThrowIfNullOrEmpty(), getCustomRetryStrategy).GetRetryPolicy(errorDetectionStrategy.ThrowIfNull()); /// /// Returns an instance of the object for a given error detection strategy and retry strategy. @@ -119,7 +119,7 @@ public static class RetryPolicyFactory string configurationFile = RetryConfiguration.DefaultConfigurationFile, string configurationKey = nameof(RetryManager), Func? getCustomRetryStrategy = null) where T : ITransientErrorDetectionStrategy, new() => - GetOrCreateRetryManager(configurationFile.NotNullOrEmpty(), configurationKey.NotNullOrEmpty(), getCustomRetryStrategy).GetRetryPolicy(retryStrategyName.NotNullOrEmpty()); + GetOrCreateRetryManager(configurationFile.ThrowIfNullOrEmpty(), configurationKey.ThrowIfNullOrEmpty(), getCustomRetryStrategy).GetRetryPolicy(retryStrategyName.ThrowIfNullOrEmpty()); /// /// Returns an instance of the object for a given error detection strategy and retry strategy. @@ -137,7 +137,7 @@ public static class RetryPolicyFactory string configurationFile = RetryConfiguration.DefaultConfigurationFile, string configurationKey = nameof(RetryManager), Func? getCustomRetryStrategy = null) => - GetOrCreateRetryManager(configurationFile.NotNullOrEmpty(), configurationKey.NotNullOrEmpty(), getCustomRetryStrategy).GetRetryPolicy(retryStrategyName.NotNullOrEmpty(), errorDetectionStrategy.NotNull()); + GetOrCreateRetryManager(configurationFile.ThrowIfNullOrEmpty(), configurationKey.ThrowIfNullOrEmpty(), getCustomRetryStrategy).GetRetryPolicy(retryStrategyName.ThrowIfNullOrEmpty(), errorDetectionStrategy.ThrowIfNull()); private static RetryManager GetOrCreateRetryManager( string configurationFile, string configurationKey, Func? getCustomRetryStrategy = null) diff --git a/Source/TransientFaultHandling.Configuration.Core/RetryStrategyOptions.cs b/Source/TransientFaultHandling.Configuration.Core/RetryStrategyOptions.cs index f062539..b31b74c 100644 --- a/Source/TransientFaultHandling.Configuration.Core/RetryStrategyOptions.cs +++ b/Source/TransientFaultHandling.Configuration.Core/RetryStrategyOptions.cs @@ -29,7 +29,7 @@ public FixedIntervalOptions() : this(true, default, default) public int RetryCount { get => this.retryCount; - init => this.retryCount = value.NotNegative(); + init => this.retryCount = value.ThrowIfNegative(); } /// @@ -38,7 +38,7 @@ public int RetryCount public TimeSpan RetryInterval { get => this.retryInterval; - init => this.retryInterval = value.NotNegative(); + init => this.retryInterval = value.ThrowIfNegative(); } } @@ -66,7 +66,7 @@ public IncrementalOptions() : this(true, default, default, default) public int RetryCount { get => this.retryCount; - init => this.retryCount = value.NotNegative(); + init => this.retryCount = value.ThrowIfNegative(); } /// @@ -75,7 +75,7 @@ public int RetryCount public TimeSpan InitialInterval { get => this.initialInterval; - init => this.initialInterval = value.NotNegative(); + init => this.initialInterval = value.ThrowIfNegative(); } /// @@ -84,7 +84,7 @@ public TimeSpan InitialInterval public TimeSpan Increment { get => this.increment; - init => this.increment = value.NotNegative(); + init => this.increment = value.ThrowIfNegative(); } } @@ -115,7 +115,7 @@ public ExponentialBackoffOptions() : this(true, default, default, default, defau public int RetryCount { get => this.retryCount; - init => this.retryCount = value.NotNegative(); + init => this.retryCount = value.ThrowIfNegative(); } /// @@ -124,7 +124,7 @@ public int RetryCount public TimeSpan MinBackOff { get => this.minBackOff; - init => this.minBackOff = value.NotNegative(); + init => this.minBackOff = value.ThrowIfNegative(); } /// @@ -133,7 +133,7 @@ public TimeSpan MinBackOff public TimeSpan MaxBackOff { get => this.maxBackOff; - init => this.maxBackOff = value.NotNegative(); + init => this.maxBackOff = value.ThrowIfNegative(); } /// @@ -142,6 +142,6 @@ public TimeSpan MaxBackOff public TimeSpan DeltaBackOff { get => this.deltaBackOff; - init => this.deltaBackOff = value.NotNegative(); + init => this.deltaBackOff = value.ThrowIfNegative(); } } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Configuration.Core/RetryStrategyOptionsExtensions.cs b/Source/TransientFaultHandling.Configuration.Core/RetryStrategyOptionsExtensions.cs index 4a07658..9cd4c3d 100644 --- a/Source/TransientFaultHandling.Configuration.Core/RetryStrategyOptionsExtensions.cs +++ b/Source/TransientFaultHandling.Configuration.Core/RetryStrategyOptionsExtensions.cs @@ -12,7 +12,7 @@ public static class RetryStrategyOptionsExtensions /// The name of the retry strategy. /// The converted retry strategy. public static FixedInterval ToFixedInterval(this FixedIntervalOptions options, string name) => - new (name, options.NotNull().RetryCount, options.RetryInterval, options.FastFirstRetry); + new (name, options.ThrowIfNull().RetryCount, options.RetryInterval, options.FastFirstRetry); /// /// Converts instance to retry strategy. @@ -21,7 +21,7 @@ public static class RetryStrategyOptionsExtensions /// The name of the retry strategy. /// The converted retry strategy. public static Incremental ToIncremental(this IncrementalOptions options, string name) => - new (name, options.NotNull().RetryCount, options.InitialInterval, options.Increment, options.FastFirstRetry); + new (name, options.ThrowIfNull().RetryCount, options.InitialInterval, options.Increment, options.FastFirstRetry); /// /// Converts instance to retry strategy. @@ -30,7 +30,7 @@ public static class RetryStrategyOptionsExtensions /// The name of the retry strategy. /// The converted retry strategy. public static ExponentialBackoff ToExponentialBackoff(this ExponentialBackoffOptions options, string name) => - new (name, options.NotNull().RetryCount, options.MinBackOff, options.MaxBackOff, options.DeltaBackOff, options.FastFirstRetry); + new (name, options.ThrowIfNull().RetryCount, options.MinBackOff, options.MaxBackOff, options.DeltaBackOff, options.FastFirstRetry); /// /// Converts instance to retry strategy. diff --git a/Source/TransientFaultHandling.Core/Argument.cs b/Source/TransientFaultHandling.Core/Argument.cs index 35eee61..b9f09f2 100644 --- a/Source/TransientFaultHandling.Core/Argument.cs +++ b/Source/TransientFaultHandling.Core/Argument.cs @@ -8,75 +8,81 @@ internal static class Argument { /// - /// Checks a string argument to ensure that it isn't null or empty. + /// Throws an exception if is null or empty. /// - /// The argument value to check. - /// The name of the argument. - /// The return value should be ignored. It is intended to be used only when validating arguments during instance creation (for example, when calling the base constructor). - public static string NotNullOrEmpty([NotNull] this string? value, [CallerArgumentExpression("value")] string name = "") => - string.IsNullOrEmpty(value) - ? throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeEmpty, name), name) - : value; + /// The string argument to validate as non-null and non-empty. + /// The name of the parameter with which corresponds. + /// is null. + /// is empty. + /// The string argument to validate as non-null and non-empty. + public static string ThrowIfNullOrEmpty([NotNull] this string? argument, [CallerArgumentExpression(nameof(argument))] string paramName = "") => + string.IsNullOrEmpty(argument.ThrowIfNull()) + ? throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.StringCannotBeEmpty, paramName), paramName) + : argument; /// - /// Checks an argument to ensure that it isn't null. + /// Throws an if is null. /// - /// The argument value to check. - /// The name of the argument. - /// The return value should be ignored. It is intended to be used only when validating arguments during instance creation (for example, when calling the base constructor). - public static T NotNull([NotNull] this T? value, [CallerArgumentExpression("value")] string name = "") where T : class => - value ?? throw new ArgumentNullException(name); + /// The reference type argument to validate as non-null. + /// The name of the parameter with which corresponds. + /// The reference type argument to validate as non-null. + public static T ThrowIfNull([NotNull] this T? argument, [CallerArgumentExpression(nameof(argument))] string paramName = "") where T : class => + argument ?? throw new ArgumentNullException(paramName); /// /// Checks an argument to ensure that its 32-bit signed value isn't negative. /// /// The value of the argument. - /// The name of the argument for diagnostic purposes. - public static int NotNegative(this int value, [CallerArgumentExpression("value")] string name = "") => + /// The name of the argument for diagnostic purposes. + public static int ThrowIfNegative(this int value, [CallerArgumentExpression(nameof(value))] string paramName = "") => value < 0 - ? throw new ArgumentOutOfRangeException(name, value, string.Format(CultureInfo.CurrentCulture, Resources.ArgumentCannotBeNegative, name)) + ? throw new ArgumentOutOfRangeException(paramName, value, string.Format(CultureInfo.CurrentCulture, Resources.ArgumentCannotBeNegative, paramName)) : value; /// - /// Checks an argument to ensure that its 64-bit signed value isn't negative. + /// Throws an if is negative. /// - /// The value of the argument. - /// The name of the argument for diagnostic purposes. - public static long NotNegative(this long value, [CallerArgumentExpression("value")] string name = "") => + /// The argument to validate as non-negative. + /// The name of the parameter with which corresponds. + /// The argument to validate as non-negative. + public static long ThrowIfNegative(this long value, [CallerArgumentExpression(nameof(value))] string paramName = "") => value < 0L - ? throw new ArgumentOutOfRangeException(name, value, string.Format(CultureInfo.CurrentCulture, Resources.ArgumentCannotBeNegative, name)) + ? throw new ArgumentOutOfRangeException(paramName, value, string.Format(CultureInfo.CurrentCulture, Resources.ArgumentCannotBeNegative, paramName)) : value; /// - /// Checks an argument to ensure that its value doesn't exceed the specified ceiling baseline. + /// Throws an if is greater than . /// - /// The value of the argument. - /// The ceiling value of the argument. - /// The name of the argument for diagnostic purposes. - public static double NotGreaterThan(this double value, double ceiling, [CallerArgumentExpression("value")] string name = "") => - value > ceiling - ? throw new ArgumentOutOfRangeException(name, value, string.Format(CultureInfo.CurrentCulture, Resources.ArgumentCannotBeGreaterThanBaseline, name, ceiling)) + /// The argument to validate as less or equal than . + /// The value to compare with . + /// The name of the parameter with which corresponds. + /// The argument to validate as less or equal than . + public static T ThrowIfGreaterThan(this T value, T other, [CallerArgumentExpression(nameof(value))] string paramName = "") where T : IComparable => + value.CompareTo(other) > 0 + ? throw new ArgumentOutOfRangeException(paramName, value, string.Format(CultureInfo.CurrentCulture, Resources.ArgumentCannotBeGreaterThanBaseline, paramName, other)) : value; /// - /// Checks an argument to ensure that its 64-bit signed value isn't negative. + /// Throws an if is less than or greater than . /// - /// The value of the argument. - /// The min value. - /// The max value. - /// The name of the argument for diagnostic purposes. - public static TimeSpan InRange(this TimeSpan value, TimeSpan min, TimeSpan max, [CallerArgumentExpression("value")] string name = "") => - value < min || value > max - ? throw new ArgumentOutOfRangeException(name, value, string.Format(CultureInfo.CurrentCulture, Resources.ArgumentCannotBeOutOutRange, name, min, max)) + /// The argument to validate as greater or equal than and less or equal than . + /// The min value to compare with . + /// The max value to compare with . + /// The name of the parameter with which corresponds. + /// The argument to validate as greater or equal than and less or equal than . + public static T ThrowIfOutOfRange(this T value, T min, T max, [CallerArgumentExpression(nameof(value))] string paramName = "") where T : IComparable => + value.CompareTo(min) < 0 || value.CompareTo(max) > 0 + ? throw new ArgumentOutOfRangeException(paramName, value, string.Format(CultureInfo.CurrentCulture, Resources.ArgumentCannotBeOutOutRange, paramName, min, max)) : value; /// - /// Checks an argument to ensure that its 64-bit signed value isn't negative. + /// Throws an if is negative. /// - /// The value of the argument. - /// The name of the argument for diagnostic purposes. - public static TimeSpan NotNegative(this TimeSpan value, [CallerArgumentExpression("value")] string name = "") => + /// The argument to validate as non-negative. + /// The name of the parameter with which corresponds. + /// The argument to validate as non-negative. + public static TimeSpan ThrowIfNegative(this TimeSpan value, [CallerArgumentExpression(nameof(value))] string paramName = "") => value < TimeSpan.Zero - ? throw new ArgumentOutOfRangeException(name, value, string.Format(CultureInfo.CurrentCulture, Resources.ArgumentCannotBeNegative, name)) + ? throw new ArgumentOutOfRangeException(paramName, value, string.Format(CultureInfo.CurrentCulture, Resources.ArgumentCannotBeNegative, paramName)) : value; } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Core/ExponentialBackoff.cs b/Source/TransientFaultHandling.Core/ExponentialBackoff.cs index 642d0f5..0ee26a1 100644 --- a/Source/TransientFaultHandling.Core/ExponentialBackoff.cs +++ b/Source/TransientFaultHandling.Core/ExponentialBackoff.cs @@ -58,19 +58,18 @@ public class ExponentialBackoff : RetryStrategy public ExponentialBackoff(string? name, int retryCount, TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan deltaBackoff, bool firstFastRetry) : base(name, firstFastRetry) { - this.retryCount = retryCount.NotNegative(); - this.minBackoff = minBackoff.InRange(TimeSpan.Zero, maxBackoff); - this.maxBackoff = maxBackoff.NotNegative(); - this.deltaBackoff = deltaBackoff.NotNegative(); + this.retryCount = retryCount.ThrowIfNegative(); + this.minBackoff = minBackoff.ThrowIfOutOfRange(TimeSpan.Zero, maxBackoff); + this.maxBackoff = maxBackoff.ThrowIfNegative(); + this.deltaBackoff = deltaBackoff.ThrowIfNegative(); } /// /// Returns the corresponding ShouldRetry delegate. /// /// The ShouldRetry delegate. - public override ShouldRetry GetShouldRetry() - { - return (int currentRetryCount, Exception lastException, out TimeSpan retryInterval) => + public override ShouldRetry GetShouldRetry() => + (int currentRetryCount, Exception lastException, out TimeSpan retryInterval) => { if (currentRetryCount < this.retryCount) { @@ -84,5 +83,4 @@ public override ShouldRetry GetShouldRetry() retryInterval = TimeSpan.Zero; return false; }; - } } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Core/FixedInterval.cs b/Source/TransientFaultHandling.Core/FixedInterval.cs index fb6378f..0b2f696 100644 --- a/Source/TransientFaultHandling.Core/FixedInterval.cs +++ b/Source/TransientFaultHandling.Core/FixedInterval.cs @@ -55,35 +55,30 @@ public FixedInterval(int retryCount) : this(retryCount, DefaultRetryInterval) public FixedInterval(string? name, int retryCount, TimeSpan retryInterval, bool firstFastRetry) : base(name, firstFastRetry) { - this.retryCount = retryCount.NotNegative(); - this.retryInterval = retryInterval.NotNegative(); + this.retryCount = retryCount.ThrowIfNegative(); + this.retryInterval = retryInterval.ThrowIfNegative(); } /// /// Returns the corresponding ShouldRetry delegate. /// /// The ShouldRetry delegate. - public override ShouldRetry GetShouldRetry() - { - if (this.retryCount == 0) - { - return (int currentRetryCount, Exception lastException, out TimeSpan interval) => + public override ShouldRetry GetShouldRetry() => + this.retryCount == 0 + ? (int currentRetryCount, Exception lastException, out TimeSpan interval) => { interval = TimeSpan.Zero; return false; - }; - } - - return (int currentRetryCount, Exception lastException, out TimeSpan interval) => - { - if (currentRetryCount < this.retryCount) - { - interval = this.retryInterval; - return true; } + : (int currentRetryCount, Exception lastException, out TimeSpan interval) => + { + if (currentRetryCount < this.retryCount) + { + interval = this.retryInterval; + return true; + } - interval = TimeSpan.Zero; - return false; - }; - } + interval = TimeSpan.Zero; + return false; + }; } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Core/Incremental.cs b/Source/TransientFaultHandling.Core/Incremental.cs index e8c4dbf..3bb8c7d 100644 --- a/Source/TransientFaultHandling.Core/Incremental.cs +++ b/Source/TransientFaultHandling.Core/Incremental.cs @@ -49,9 +49,9 @@ public Incremental(string? name, int retryCount, TimeSpan initialInterval, TimeS /// true to immediately retry in the first attempt; otherwise, false. The subsequent retries will remain subject to the configured retry interval. public Incremental(string? name, int retryCount, TimeSpan initialInterval, TimeSpan increment, bool firstFastRetry) : base(name, firstFastRetry) { - this.retryCount = retryCount.NotNegative(); - this.initialInterval = initialInterval.NotNegative(); - this.increment = increment.NotNegative(); + this.retryCount = retryCount.ThrowIfNegative(); + this.initialInterval = initialInterval.ThrowIfNegative(); + this.increment = increment.ThrowIfNegative(); } /// diff --git a/Source/TransientFaultHandling.Core/Retry.Execute.cs b/Source/TransientFaultHandling.Core/Retry.Execute.cs index 701d71a..abf0ad7 100644 --- a/Source/TransientFaultHandling.Core/Retry.Execute.cs +++ b/Source/TransientFaultHandling.Core/Retry.Execute.cs @@ -21,7 +21,7 @@ public static partial class Retry Func? isTransient = null, EventHandler? retryingHandler = null) { - func.NotNull(); + func.ThrowIfNull(); return CreateRetryPolicy(retryStrategy, isTransient, retryingHandler).ExecuteAction(func); } @@ -40,7 +40,7 @@ public static partial class Retry Func? isTransient = null, EventHandler? retryingHandler = null) { - action.NotNull(); + action.ThrowIfNull(); CreateRetryPolicy(retryStrategy, isTransient, retryingHandler).ExecuteAction(action); } @@ -63,7 +63,7 @@ public static partial class Retry EventHandler? retryingHandler = null, CancellationToken cancellationToken = default) { - func.NotNull(); + func.ThrowIfNull(); return CreateRetryPolicy(retryStrategy, isTransient, retryingHandler).ExecuteAsync(func, cancellationToken); } @@ -85,7 +85,7 @@ public static partial class Retry EventHandler? retryingHandler = null, CancellationToken cancellationToken = default) { - func.NotNull(); + func.ThrowIfNull(); return CreateRetryPolicy(retryStrategy, isTransient, retryingHandler).ExecuteAsync(func, cancellationToken); } diff --git a/Source/TransientFaultHandling.Core/Retry.ExponentialBackoff.cs b/Source/TransientFaultHandling.Core/Retry.ExponentialBackoff.cs index f9af122..70c926f 100644 --- a/Source/TransientFaultHandling.Core/Retry.ExponentialBackoff.cs +++ b/Source/TransientFaultHandling.Core/Retry.ExponentialBackoff.cs @@ -26,7 +26,7 @@ public static partial class Retry TimeSpan? deltaBackoff = null, bool? firstFastRetry = null) => Execute( - func.NotNull(), + func.ThrowIfNull(), WithExponentialBackoff(retryCount, minBackoff, maxBackoff, deltaBackoff, firstFastRetry), isTransient, retryingHandler); @@ -53,7 +53,7 @@ public static partial class Retry TimeSpan? deltaBackoff = null, bool? firstFastRetry = null) => Execute( - action.NotNull(), + action.ThrowIfNull(), WithExponentialBackoff(retryCount, minBackoff, maxBackoff, deltaBackoff, firstFastRetry), isTransient, retryingHandler); @@ -84,7 +84,7 @@ public static partial class Retry bool? firstFastRetry = null, CancellationToken cancellationToken = default) => ExecuteAsync( - func.NotNull(), + func.ThrowIfNull(), WithExponentialBackoff(retryCount, minBackoff, maxBackoff, deltaBackoff, firstFastRetry), isTransient, retryingHandler, @@ -115,7 +115,7 @@ public static partial class Retry bool? firstFastRetry = null, CancellationToken cancellationToken = default) => ExecuteAsync( - func.NotNull(), + func.ThrowIfNull(), WithExponentialBackoff(retryCount, minBackoff, maxBackoff, deltaBackoff, firstFastRetry), isTransient, retryingHandler, diff --git a/Source/TransientFaultHandling.Core/Retry.FixedInterval.cs b/Source/TransientFaultHandling.Core/Retry.FixedInterval.cs index 48bcf07..7fcc3b8 100644 --- a/Source/TransientFaultHandling.Core/Retry.FixedInterval.cs +++ b/Source/TransientFaultHandling.Core/Retry.FixedInterval.cs @@ -22,7 +22,7 @@ public static partial class Retry TimeSpan? retryInterval = null, bool? firstFastRetry = null) => Execute( - func.NotNull(), + func.ThrowIfNull(), WithFixedInterval(retryCount, retryInterval, firstFastRetry), isTransient, retryingHandler); @@ -45,7 +45,7 @@ public static partial class Retry TimeSpan? retryInterval = null, bool? firstFastRetry = null) => Execute( - action.NotNull(), + action.ThrowIfNull(), WithFixedInterval(retryCount, retryInterval, firstFastRetry), isTransient, retryingHandler); @@ -72,7 +72,7 @@ public static partial class Retry bool? firstFastRetry = null, CancellationToken cancellationToken = default) => ExecuteAsync( - func.NotNull(), + func.ThrowIfNull(), WithFixedInterval(retryCount, retryInterval, firstFastRetry), isTransient, retryingHandler, @@ -99,7 +99,7 @@ public static partial class Retry bool? firstFastRetry = null, CancellationToken cancellationToken = default) => ExecuteAsync( - func.NotNull(), + func.ThrowIfNull(), WithFixedInterval(retryCount, retryInterval, firstFastRetry), isTransient, retryingHandler, diff --git a/Source/TransientFaultHandling.Core/Retry.Incremental.cs b/Source/TransientFaultHandling.Core/Retry.Incremental.cs index 1d3e24a..80f1d4c 100644 --- a/Source/TransientFaultHandling.Core/Retry.Incremental.cs +++ b/Source/TransientFaultHandling.Core/Retry.Incremental.cs @@ -24,7 +24,7 @@ public static partial class Retry TimeSpan? increment = null, bool? firstFastRetry = null) => Execute( - func.NotNull(), + func.ThrowIfNull(), WithIncremental(retryCount, initialInterval, increment, firstFastRetry), isTransient, retryingHandler); @@ -49,7 +49,7 @@ public static partial class Retry TimeSpan? increment = null, bool? firstFastRetry = null) => Execute( - action.NotNull(), + action.ThrowIfNull(), WithIncremental(retryCount, initialInterval, increment, firstFastRetry), isTransient, retryingHandler); @@ -78,7 +78,7 @@ public static partial class Retry bool? firstFastRetry = null, CancellationToken cancellationToken = default) => ExecuteAsync( - func.NotNull(), + func.ThrowIfNull(), WithIncremental(retryCount, initialInterval, increment, firstFastRetry), isTransient, retryingHandler, @@ -107,7 +107,7 @@ public static partial class Retry bool? firstFastRetry = null, CancellationToken cancellationToken = default) => ExecuteAsync( - func.NotNull(), + func.ThrowIfNull(), WithIncremental(retryCount, initialInterval, increment, firstFastRetry), isTransient, retryingHandler, diff --git a/Source/TransientFaultHandling.Core/Retry.Policy.cs b/Source/TransientFaultHandling.Core/Retry.Policy.cs index 13c59e5..5ac8009 100644 --- a/Source/TransientFaultHandling.Core/Retry.Policy.cs +++ b/Source/TransientFaultHandling.Core/Retry.Policy.cs @@ -30,7 +30,7 @@ public static partial class Retry /// The predicate function to detect whether the specified exception is transient. /// A new instance of the class. public static RetryPolicy Catch(this RetryStrategy retryStrategy, Func? isTransient = null) => - CreateRetryPolicy(retryStrategy.NotNull(), isTransient); + CreateRetryPolicy(retryStrategy.ThrowIfNull(), isTransient); /// /// Create a new instance of the class with the specified retry policy. @@ -39,7 +39,7 @@ public static partial class Retry /// The predicate function to detect whether the specified exception is transient. /// A new instance of the class. public static RetryPolicy Catch(this RetryPolicy retryPolicy, Func? isTransient = null) => - Catch(retryPolicy.NotNull(), isTransient); + Catch(retryPolicy.ThrowIfNull(), isTransient); /// /// Create a new instance of the class with the specified retry strategy. @@ -52,7 +52,7 @@ public static partial class Retry this RetryStrategy retryStrategy, Func? isTransient = null) where TException : Exception => CreateRetryPolicy( - retryStrategy.NotNull(), + retryStrategy.ThrowIfNull(), isTransient is null ? exception => exception is TException : exception => exception is TException specifiedException && isTransient(specifiedException)); @@ -68,7 +68,7 @@ public static partial class Retry this RetryPolicy retryPolicy, Func? isTransient = null) where TException : Exception => CreateRetryPolicy( - retryPolicy.NotNull().RetryStrategy, + retryPolicy.ThrowIfNull().RetryStrategy, isTransient is null ? exception => retryPolicy.ErrorDetectionStrategy.IsTransient(exception) || exception is TException @@ -83,7 +83,7 @@ public static partial class Retry /// The callback function that will be invoked whenever a retry condition is encountered. /// A new instance of the class. public static RetryPolicy HandleWith(this RetryStrategy retryStrategy, EventHandler retryingHandler) => - CreateRetryPolicy(retryStrategy.NotNull()).HandleWith(retryingHandler.NotNull()); + CreateRetryPolicy(retryStrategy.ThrowIfNull()).HandleWith(retryingHandler.ThrowIfNull()); /// /// Create a new instance of the class based on the specified retry policy. @@ -93,7 +93,7 @@ public static partial class Retry /// A new instance of the class. public static RetryPolicy HandleWith(this RetryPolicy retryPolicy, EventHandler retryingHandler) { - retryPolicy.NotNull().Retrying += retryingHandler.NotNull(); + retryPolicy.ThrowIfNull().Retrying += retryingHandler.ThrowIfNull(); return retryPolicy; } } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Core/RetryManager.cs b/Source/TransientFaultHandling.Core/RetryManager.cs index 5659d2d..939d79c 100644 --- a/Source/TransientFaultHandling.Core/RetryManager.cs +++ b/Source/TransientFaultHandling.Core/RetryManager.cs @@ -23,7 +23,7 @@ public class RetryManager /// The names of the default strategies for different technologies. public RetryManager(IEnumerable retryStrategies, string? defaultRetryStrategyName = null, IDictionary? defaultRetryStrategyNamesMap = null) { - this.retryStrategies = retryStrategies.NotNull().ToDictionary(retryStrategy => + this.retryStrategies = retryStrategies.ThrowIfNull().ToDictionary(retryStrategy => retryStrategy.Name ?? throw new ArgumentException(Resources.RetryStrategyNameCannotBeEmpty, nameof(retryStrategies))); this.DefaultRetryStrategyName = defaultRetryStrategyName; this.defaultRetryStrategiesMap = new Dictionary(); @@ -113,7 +113,7 @@ public static void SetDefault(RetryManager? retryManager, bool throwIfSet = true /// The retry strategy name, as defined in the configuration. /// A new retry policy with the specified error detection strategy and the default retry strategy defined in the configuration. public virtual RetryPolicy GetRetryPolicy(string retryStrategyName) where T : ITransientErrorDetectionStrategy, new() => - new (this.GetRetryStrategy(retryStrategyName.NotNullOrEmpty())); + new (this.GetRetryStrategy(retryStrategyName.ThrowIfNullOrEmpty())); /// /// Returns a retry policy with the specified error detection strategy and the default retry strategy defined in the configuration. @@ -121,7 +121,7 @@ public static void SetDefault(RetryManager? retryManager, bool throwIfSet = true /// A new retry policy with the specified error detection strategy and the default retry strategy defined in the configuration. public virtual RetryPolicy GetRetryPolicy(ITransientErrorDetectionStrategy errorDetectionStrategy) => new ( - errorDetectionStrategy.NotNull(), + errorDetectionStrategy.ThrowIfNull(), this.GetRetryStrategy() ?? throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.DefaultRetryStrategyNotFound, string.Empty))); /// @@ -131,7 +131,7 @@ public static void SetDefault(RetryManager? retryManager, bool throwIfSet = true /// The that is responsible for detecting transient conditions. /// A new retry policy with the specified error detection strategy and the default retry strategy defined in the configuration. public virtual RetryPolicy GetRetryPolicy(string retryStrategyName, ITransientErrorDetectionStrategy errorDetectionStrategy) => - new (errorDetectionStrategy.NotNull(), this.GetRetryStrategy(retryStrategyName.NotNullOrEmpty())); + new (errorDetectionStrategy.ThrowIfNull(), this.GetRetryStrategy(retryStrategyName.ThrowIfNullOrEmpty())); /// /// Returns the default retry strategy defined in the configuration. @@ -146,7 +146,7 @@ public static void SetDefault(RetryManager? retryManager, bool throwIfSet = true /// The retry strategy that matches the specified name. public virtual RetryStrategy GetRetryStrategy(string retryStrategyName) { - if (!this.retryStrategies.TryGetValue(retryStrategyName.NotNullOrEmpty(), out RetryStrategy? result)) + if (!this.retryStrategies.TryGetValue(retryStrategyName.ThrowIfNullOrEmpty(), out RetryStrategy? result)) { throw new ArgumentOutOfRangeException( string.Format(CultureInfo.CurrentCulture, Resources.RetryStrategyNotFound, retryStrategyName)); @@ -161,7 +161,7 @@ public virtual RetryStrategy GetRetryStrategy(string retryStrategyName) /// The technology to get the default retry strategy for. /// The retry strategy for the specified technology. public virtual RetryStrategy GetDefaultRetryStrategy(string technology) => - this.defaultRetryStrategiesMap.TryGetValue(technology.NotNullOrEmpty(), out RetryStrategy? retryStrategy) + this.defaultRetryStrategiesMap.TryGetValue(technology.ThrowIfNullOrEmpty(), out RetryStrategy? retryStrategy) ? retryStrategy : this.defaultStrategy ?? throw new ArgumentOutOfRangeException( string.Format(CultureInfo.CurrentCulture, Resources.DefaultRetryStrategyNotFound, technology)); diff --git a/Source/TransientFaultHandling.Core/RetryPolicy.cs b/Source/TransientFaultHandling.Core/RetryPolicy.cs index 5e03711..dafe89e 100644 --- a/Source/TransientFaultHandling.Core/RetryPolicy.cs +++ b/Source/TransientFaultHandling.Core/RetryPolicy.cs @@ -14,8 +14,8 @@ public class RetryPolicy /// The strategy to use for this retry policy. public RetryPolicy(ITransientErrorDetectionStrategy errorDetectionStrategy, RetryStrategy retryStrategy) { - this.ErrorDetectionStrategy= errorDetectionStrategy.NotNull(); - this.RetryStrategy = retryStrategy.NotNull(); + this.ErrorDetectionStrategy= errorDetectionStrategy.ThrowIfNull(); + this.RetryStrategy = retryStrategy.ThrowIfNull(); } /// @@ -108,7 +108,7 @@ public RetryPolicy(ITransientErrorDetectionStrategy errorDetectionStrategy, Retr /// A delegate that represents the executable action that doesn't return any results. public virtual void ExecuteAction(Action action) { - action.NotNull(); + action.ThrowIfNull(); this.ExecuteAction(() => { @@ -125,7 +125,7 @@ public virtual void ExecuteAction(Action action) /// The result from the action. public virtual TResult ExecuteAction(Func func) { - func.NotNull(); + func.ThrowIfNull(); int retryCount = 0; ShouldRetry shouldRetry = this.RetryStrategy.GetShouldRetry(); @@ -150,7 +150,7 @@ public virtual TResult ExecuteAction(Func func) } #pragma warning disable CS8603 // Possible null reference return. - return default(TResult); + return default; #pragma warning restore CS8603 // Possible null reference return. } catch (Exception ex) @@ -190,7 +190,7 @@ public virtual TResult ExecuteAction(Func func) /// the retry limit is reached, the returned task will transition to a faulted state and the exception must be observed. /// public Task ExecuteAsync(Func taskAction, CancellationToken cancellationToken = default) => - new AsyncExecution(taskAction.NotNull(), this.RetryStrategy.GetShouldRetry(), this.ErrorDetectionStrategy.IsTransient, this.OnRetrying, this.RetryStrategy.FastFirstRetry, cancellationToken).ExecuteAsync(); + new AsyncExecution(taskAction.ThrowIfNull(), this.RetryStrategy.GetShouldRetry(), this.ErrorDetectionStrategy.IsTransient, this.OnRetrying, this.RetryStrategy.FastFirstRetry, cancellationToken).ExecuteAsync(); /// /// Repeatedly executes the specified asynchronous task while it satisfies the current retry policy. @@ -203,7 +203,7 @@ public virtual TResult ExecuteAction(Func func) /// the retry limit is reached, the returned task will transition to a faulted state and the exception must be observed. /// public Task ExecuteAsync(Func> taskFunc, CancellationToken cancellationToken = default) => - new AsyncExecution(taskFunc.NotNull(), this.RetryStrategy.GetShouldRetry(), this.ErrorDetectionStrategy.IsTransient, this.OnRetrying, this.RetryStrategy.FastFirstRetry, cancellationToken).ExecuteAsync(); + new AsyncExecution(taskFunc.ThrowIfNull(), this.RetryStrategy.GetShouldRetry(), this.ErrorDetectionStrategy.IsTransient, this.OnRetrying, this.RetryStrategy.FastFirstRetry, cancellationToken).ExecuteAsync(); /// /// Notifies the subscribers whenever a retry condition is encountered. diff --git a/Source/TransientFaultHandling.Core/RetryingEventArgs.cs b/Source/TransientFaultHandling.Core/RetryingEventArgs.cs index d76b45f..85c60ac 100644 --- a/Source/TransientFaultHandling.Core/RetryingEventArgs.cs +++ b/Source/TransientFaultHandling.Core/RetryingEventArgs.cs @@ -30,6 +30,6 @@ public RetryingEventArgs(int currentRetryCount, TimeSpan delay, Exception lastEx { this.CurrentRetryCount = currentRetryCount; this.Delay = delay; - this.LastException = lastException.NotNull(); + this.LastException = lastException.ThrowIfNull(); } } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Data.Core/ReliableSqlConnection.Legacy.cs b/Source/TransientFaultHandling.Data.Core/ReliableSqlConnection.Legacy.cs index 1ccca18..db89049 100644 --- a/Source/TransientFaultHandling.Data.Core/ReliableSqlConnection.Legacy.cs +++ b/Source/TransientFaultHandling.Data.Core/ReliableSqlConnection.Legacy.cs @@ -179,7 +179,7 @@ public SqlConnection Open(RetryPolicy? retryPolicy) [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposed by client code")] public T? ExecuteCommand(IDbCommand command, RetryPolicy? retryPolicy, CommandBehavior behavior = CommandBehavior.Default) { - command.NotNull(); + command.ThrowIfNull(); bool hasOpenedConnection = false; try @@ -283,7 +283,7 @@ public SqlConnection Open(RetryPolicy? retryPolicy) /// The number of rows affected. public int ExecuteCommand(IDbCommand command, RetryPolicy? retryPolicy) { - NonQueryResult result = this.ExecuteCommand(command.NotNull(), retryPolicy); + NonQueryResult result = this.ExecuteCommand(command.ThrowIfNull(), retryPolicy); return result.RecordsAffected; } #endregion diff --git a/Source/TransientFaultHandling.Data.Core/ReliableSqlConnection.cs b/Source/TransientFaultHandling.Data.Core/ReliableSqlConnection.cs index 9d1a270..d6b8d3c 100644 --- a/Source/TransientFaultHandling.Data.Core/ReliableSqlConnection.cs +++ b/Source/TransientFaultHandling.Data.Core/ReliableSqlConnection.cs @@ -178,7 +178,7 @@ public SqlConnection Open(RetryPolicy? retryPolicy) [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Disposed by client code")] public T? ExecuteCommand(IDbCommand command, RetryPolicy? retryPolicy, CommandBehavior behavior = CommandBehavior.Default) { - command.NotNull(); + command.ThrowIfNull(); bool hasOpenedConnection = false; try @@ -282,7 +282,7 @@ public SqlConnection Open(RetryPolicy? retryPolicy) /// The number of rows affected. public int ExecuteCommand(IDbCommand command, RetryPolicy? retryPolicy) { - NonQueryResult result = this.ExecuteCommand(command.NotNull(), retryPolicy); + NonQueryResult result = this.ExecuteCommand(command.ThrowIfNull(), retryPolicy); return result.RecordsAffected; } #endregion diff --git a/Source/TransientFaultHandling.Data.Core/RetryManagerSqlExtensions.cs b/Source/TransientFaultHandling.Data.Core/RetryManagerSqlExtensions.cs index 3bce312..2fbd5b9 100644 --- a/Source/TransientFaultHandling.Data.Core/RetryManagerSqlExtensions.cs +++ b/Source/TransientFaultHandling.Data.Core/RetryManagerSqlExtensions.cs @@ -20,14 +20,14 @@ public static class RetryManagerSqlExtensions /// /// The default retry strategy for SQL commands (or the default strategy, if no default could be found). public static RetryStrategy GetDefaultSqlCommandRetryStrategy(this RetryManager retryManager) => - retryManager.NotNull().GetDefaultRetryStrategy(DefaultStrategyCommandTechnologyName); + retryManager.ThrowIfNull().GetDefaultRetryStrategy(DefaultStrategyCommandTechnologyName); /// /// Returns the default retry policy dedicated to handling transient conditions with SQL commands. /// /// The retry policy for SQL commands with the corresponding default strategy (or the default strategy, if no retry strategy assigned to SQL commands was found). public static RetryPolicy GetDefaultSqlCommandRetryPolicy(this RetryManager retryManager) => - new (new SqlDatabaseTransientErrorDetectionStrategy(), retryManager.NotNull().GetDefaultSqlCommandRetryStrategy()); + new (new SqlDatabaseTransientErrorDetectionStrategy(), retryManager.ThrowIfNull().GetDefaultSqlCommandRetryStrategy()); /// /// Returns the default retry strategy for SQL connections. @@ -37,7 +37,7 @@ public static RetryStrategy GetDefaultSqlConnectionRetryStrategy(this RetryManag { try { - return retryManager.NotNull().GetDefaultRetryStrategy(DefaultStrategyConnectionTechnologyName); + return retryManager.ThrowIfNull().GetDefaultRetryStrategy(DefaultStrategyConnectionTechnologyName); } catch (ArgumentOutOfRangeException) { @@ -50,5 +50,5 @@ public static RetryStrategy GetDefaultSqlConnectionRetryStrategy(this RetryManag /// /// The retry policy for SQL connections with the corresponding default strategy (or the default strategy, if no retry strategy for SQL connections was found). public static RetryPolicy GetDefaultSqlConnectionRetryPolicy(this RetryManager retryManager) => - new (new SqlDatabaseTransientErrorDetectionStrategy(), retryManager.NotNull().GetDefaultSqlConnectionRetryStrategy()); + new (new SqlDatabaseTransientErrorDetectionStrategy(), retryManager.ThrowIfNull().GetDefaultSqlConnectionRetryStrategy()); } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Data.Core/SqlCommandExtensions.Legacy.cs b/Source/TransientFaultHandling.Data.Core/SqlCommandExtensions.Legacy.cs index 57b417c..b194e09 100644 --- a/Source/TransientFaultHandling.Data.Core/SqlCommandExtensions.Legacy.cs +++ b/Source/TransientFaultHandling.Data.Core/SqlCommandExtensions.Legacy.cs @@ -32,7 +32,7 @@ public static partial class SqlCommandExtensions [Obsolete("Use ExecuteNonQueryWithRetry for Microsoft.Data.SqlClient.SqlCommand in Microsoft.Data.SqlClient.")] public static int ExecuteNonQueryWithRetry(this SqlCommand command, RetryPolicy? cmdRetryPolicy, RetryPolicy? conRetryPolicy = null) { - command.NotNull().ConnectionNotNull(); + command.ThrowIfNull().ConnectionNotNull(); // Check if retry policy was specified, if not, use the default retry policy. return (cmdRetryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(() => @@ -79,7 +79,7 @@ public static int ExecuteNonQueryWithRetry(this SqlCommand command, RetryPolicy? [Obsolete("Use ExecuteReaderWithRetry for Microsoft.Data.SqlClient.SqlCommand in Microsoft.Data.SqlClient.")] public static SqlDataReader ExecuteReaderWithRetry(this SqlCommand command, RetryPolicy cmdRetryPolicy, RetryPolicy? conRetryPolicy = null) { - return ExecuteReaderWithRetry(command.NotNull().ConnectionNotNull(), CommandBehavior.Default, cmdRetryPolicy, conRetryPolicy); + return ExecuteReaderWithRetry(command.ThrowIfNull().ConnectionNotNull(), CommandBehavior.Default, cmdRetryPolicy, conRetryPolicy); } /// @@ -106,7 +106,7 @@ public static SqlDataReader ExecuteReaderWithRetry(this SqlCommand command, Retr [Obsolete("Use ExecuteReaderWithRetry for Microsoft.Data.SqlClient.SqlCommand in Microsoft.Data.SqlClient.")] public static SqlDataReader ExecuteReaderWithRetry(this SqlCommand command, CommandBehavior behavior, RetryPolicy? cmdRetryPolicy, RetryPolicy? conRetryPolicy = null) { - command.NotNull().ConnectionNotNull(); + command.ThrowIfNull().ConnectionNotNull(); // Check if retry policy was specified, if not, use the default retry policy. return (cmdRetryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(() => @@ -154,7 +154,7 @@ public static SqlDataReader ExecuteReaderWithRetry(this SqlCommand command, Comm [Obsolete("Use ExecuteScalarWithRetry for Microsoft.Data.SqlClient.SqlCommand in Microsoft.Data.SqlClient.")] public static object ExecuteScalarWithRetry(this SqlCommand command, RetryPolicy? cmdRetryPolicy, RetryPolicy? conRetryPolicy = null) { - command.NotNull().ConnectionNotNull(); + command.ThrowIfNull().ConnectionNotNull(); // Check if retry policy was specified, if not, use the default retry policy. return (cmdRetryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(() => @@ -199,7 +199,7 @@ public static object ExecuteScalarWithRetry(this SqlCommand command, RetryPolicy [Obsolete("Use ExecuteXmlReaderWithRetry for Microsoft.Data.SqlClient.SqlCommand in Microsoft.Data.SqlClient.")] public static XmlReader ExecuteXmlReaderWithRetry(this SqlCommand command, RetryPolicy? cmdRetryPolicy, RetryPolicy? conRetryPolicy = null) { - command.NotNull().ConnectionNotNull(); + command.ThrowIfNull().ConnectionNotNull(); // Check if retry policy was specified, if not, use the default retry policy. return (cmdRetryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(() => diff --git a/Source/TransientFaultHandling.Data.Core/SqlCommandExtensions.cs b/Source/TransientFaultHandling.Data.Core/SqlCommandExtensions.cs index 8188c5e..787633f 100644 --- a/Source/TransientFaultHandling.Data.Core/SqlCommandExtensions.cs +++ b/Source/TransientFaultHandling.Data.Core/SqlCommandExtensions.cs @@ -30,7 +30,7 @@ public static partial class SqlCommandExtensions /// The number of rows affected. public static int ExecuteNonQueryWithRetry(this SqlCommand command, RetryPolicy? cmdRetryPolicy, RetryPolicy? conRetryPolicy = null) { - command.NotNull().ConnectionNotNull(); + command.ThrowIfNull().ConnectionNotNull(); // Check if retry policy was specified, if not, use the default retry policy. return (cmdRetryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(() => @@ -74,7 +74,7 @@ public static int ExecuteNonQueryWithRetry(this SqlCommand command, RetryPolicy? /// The connection retry policy that determines whether to re-establish a connection if it drops while executing the command. /// A System.Data.SqlClient.SqlDataReader object. public static SqlDataReader ExecuteReaderWithRetry(this SqlCommand command, RetryPolicy cmdRetryPolicy, RetryPolicy? conRetryPolicy = null) => - ExecuteReaderWithRetry(command.NotNull().ConnectionNotNull(), CommandBehavior.Default, cmdRetryPolicy, conRetryPolicy); + ExecuteReaderWithRetry(command.ThrowIfNull().ConnectionNotNull(), CommandBehavior.Default, cmdRetryPolicy, conRetryPolicy); /// /// Sends the specified command to the connection and builds a SqlDataReader object by using the specified @@ -98,7 +98,7 @@ public static int ExecuteNonQueryWithRetry(this SqlCommand command, RetryPolicy? /// A System.Data.SqlClient.SqlDataReader object. public static SqlDataReader ExecuteReaderWithRetry(this SqlCommand command, CommandBehavior behavior, RetryPolicy? cmdRetryPolicy, RetryPolicy? conRetryPolicy = null) { - command.NotNull().ConnectionNotNull(); + command.ThrowIfNull().ConnectionNotNull(); // Check if retry policy was specified, if not, use the default retry policy. return (cmdRetryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(() => @@ -144,7 +144,7 @@ public static SqlDataReader ExecuteReaderWithRetry(this SqlCommand command, Comm /// The first column of the first row in the result set, or a null reference if the result set is empty. Returns a maximum of 2033 characters. public static object ExecuteScalarWithRetry(this SqlCommand command, RetryPolicy? cmdRetryPolicy, RetryPolicy? conRetryPolicy = null) { - command.NotNull().ConnectionNotNull(); + command.ThrowIfNull().ConnectionNotNull(); // Check if retry policy was specified, if not, use the default retry policy. return (cmdRetryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(() => @@ -187,7 +187,7 @@ public static object ExecuteScalarWithRetry(this SqlCommand command, RetryPolicy /// An System.Xml.XmlReader object. public static XmlReader ExecuteXmlReaderWithRetry(this SqlCommand command, RetryPolicy? cmdRetryPolicy, RetryPolicy? conRetryPolicy = null) { - command.NotNull().ConnectionNotNull(); + command.ThrowIfNull().ConnectionNotNull(); // Check if retry policy was specified, if not, use the default retry policy. return (cmdRetryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(() => diff --git a/Source/TransientFaultHandling.Data.Core/SqlCommandFactory.cs b/Source/TransientFaultHandling.Data.Core/SqlCommandFactory.cs index 708eb9f..71cd9a5 100644 --- a/Source/TransientFaultHandling.Data.Core/SqlCommandFactory.cs +++ b/Source/TransientFaultHandling.Data.Core/SqlCommandFactory.cs @@ -22,7 +22,7 @@ public static class SqlCommandFactory /// A new SQL command that is initialized with the Stored Procedure command type and initial settings. public static IDbCommand CreateCommand(IDbConnection connection) { - IDbCommand command = connection.NotNull().CreateCommand(); + IDbCommand command = connection.ThrowIfNull().CreateCommand(); command.CommandType = CommandType.StoredProcedure; command.CommandTimeout = DefaultCommandTimeoutSeconds; return command; @@ -37,10 +37,10 @@ public static IDbCommand CreateCommand(IDbConnection connection) [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "As designed. User must review")] public static IDbCommand CreateCommand(IDbConnection connection, string commandText) { - IDbCommand command = CreateCommand(connection.NotNull()); + IDbCommand command = CreateCommand(connection.ThrowIfNull()); try { - command.CommandText = commandText.NotNullOrEmpty(); + command.CommandText = commandText.ThrowIfNullOrEmpty(); return command; } catch @@ -60,7 +60,7 @@ public static IDbCommand CreateCommand(IDbConnection connection, string commandT [SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "As designed. User must review")] public static IDbCommand CreateGetContextInfoCommand(IDbConnection connection) { - IDbCommand command = CreateCommand(connection.NotNull()); + IDbCommand command = CreateCommand(connection.ThrowIfNull()); try { command.CommandType = CommandType.Text; diff --git a/Source/TransientFaultHandling.Data.Core/SqlConnectionExtensions.Legacy.cs b/Source/TransientFaultHandling.Data.Core/SqlConnectionExtensions.Legacy.cs index 206648a..372383a 100644 --- a/Source/TransientFaultHandling.Data.Core/SqlConnectionExtensions.Legacy.cs +++ b/Source/TransientFaultHandling.Data.Core/SqlConnectionExtensions.Legacy.cs @@ -14,7 +14,7 @@ public static partial class SqlConnectionExtensions /// The connection object that is required for the extension method declaration. [Obsolete("Use OpenWithRetry for Microsoft.Data.SqlClient.SqlConnection in Microsoft.Data.SqlClient.")] public static void OpenWithRetry(this SqlConnection connection) => - OpenWithRetry(connection.NotNull(), RetryManager.Instance.GetDefaultSqlConnectionRetryPolicy()); + OpenWithRetry(connection.ThrowIfNull(), RetryManager.Instance.GetDefaultSqlConnectionRetryPolicy()); /// /// Opens a database connection with the connection settings specified in the ConnectionString property of the connection object. @@ -24,5 +24,5 @@ public static partial class SqlConnectionExtensions /// The retry policy that defines whether to retry a request if the connection fails. [Obsolete("Use OpenWithRetry for Microsoft.Data.SqlClient.SqlConnection in Microsoft.Data.SqlClient.")] public static void OpenWithRetry(this SqlConnection connection, RetryPolicy? retryPolicy) => - (retryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(connection.NotNull().Open); + (retryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(connection.ThrowIfNull().Open); } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Data.Core/SqlConnectionExtensions.cs b/Source/TransientFaultHandling.Data.Core/SqlConnectionExtensions.cs index 3880f3a..1a947aa 100644 --- a/Source/TransientFaultHandling.Data.Core/SqlConnectionExtensions.cs +++ b/Source/TransientFaultHandling.Data.Core/SqlConnectionExtensions.cs @@ -22,5 +22,5 @@ public static partial class SqlConnectionExtensions /// The connection object that is required for the extension method declaration. /// The retry policy that defines whether to retry a request if the connection fails. public static void OpenWithRetry(this SqlConnection connection, RetryPolicy? retryPolicy) => - (retryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(connection.NotNull().Open); + (retryPolicy ?? RetryPolicy.NoRetry).ExecuteAction(connection.ThrowIfNull().Open); } \ No newline at end of file diff --git a/Source/TransientFaultHandling.Data.Core/SqlXmlReader.cs b/Source/TransientFaultHandling.Data.Core/SqlXmlReader.cs index c59f708..fe39280 100644 --- a/Source/TransientFaultHandling.Data.Core/SqlXmlReader.cs +++ b/Source/TransientFaultHandling.Data.Core/SqlXmlReader.cs @@ -19,7 +19,7 @@ internal class SqlXmlReader : XmlReader /// The SQL connection that provides access to the XML data for this reader. /// The original XML reader that is to be wrapped by this instance. public SqlXmlReader(IDbConnection connection, XmlReader innerReader) => - (this.connection, this.innerReader) = (connection.NotNull(), innerReader.NotNull()); + (this.connection, this.innerReader) = (connection.ThrowIfNull(), innerReader.ThrowIfNull()); /// /// Returns the number of attributes on the current node. diff --git a/Tests/TransientFaultHandling.Tests.Core/ConfigurationTests.cs b/Tests/TransientFaultHandling.Tests.Core/ConfigurationTests.cs index 3f0178e..d7f44df 100644 --- a/Tests/TransientFaultHandling.Tests.Core/ConfigurationTests.cs +++ b/Tests/TransientFaultHandling.Tests.Core/ConfigurationTests.cs @@ -21,7 +21,7 @@ public void Cleanup() [Ignore] // REVIEW = Negative retry counts are not allowed by configuration. public void NegativeRetryCount() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "NegativeRetryCount"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.NegativeRetryCount)); int execCount = 0; double totalDuration = 0; @@ -50,7 +50,7 @@ public void NegativeRetryCount() [Ignore] // REVIEW public void ZeroRetryCount() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "ZeroRetryCount"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.ZeroRetryCount)); int execCount = 0; double totalDuration = 0; @@ -79,7 +79,7 @@ public void ZeroRetryCount() [ExpectedException(typeof(ArgumentOutOfRangeException))] public void NegativeRetryInterval() { - RetryPolicy negativeRetryCountRetryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "NegativeRetryInterval"); + RetryPolicy negativeRetryCountRetryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.NegativeRetryInterval)); int execCount = 0; try @@ -101,7 +101,7 @@ public void NegativeRetryInterval() [TestMethod] public void ZeroRetryInterval() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "ZeroRetryInterval"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.ZeroRetryInterval)); int execCount = 0; double totalDuration = 0; @@ -130,7 +130,7 @@ public void ZeroRetryInterval() [Ignore] // REVIEW - Negative values are not allowed by configuration public void NegativeRetryIncrement() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "NegativeRetryIncrement"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.NegativeRetryIncrement)); int execCount = 0; double totalDuration = 0; @@ -158,7 +158,7 @@ public void NegativeRetryIncrement() [TestMethod] public void ZeroRetryIncrement() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "ZeroRetryIncrement"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.ZeroRetryIncrement)); int execCount = 0; double totalDuration = 0; @@ -186,7 +186,7 @@ public void ZeroRetryIncrement() [TestMethod] public void NegativeMinBackoff() { - const string Key = "NegativeMinBackoff"; + const string Key = nameof(this.NegativeMinBackoff); IConfigurationSection section = RetryConfiguration.GetConfiguration().GetSection("causeError").GetSection(Key); Assert.IsNotNull(section); Assert.IsTrue(section.Exists()); @@ -206,7 +206,7 @@ public void NegativeMinBackoff() [TestMethod] public void ZeroMinBackoff() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "ZeroMinBackoff"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.ZeroMinBackoff)); int execCount = 0; try @@ -231,7 +231,7 @@ public void ZeroMinBackoff() [ExpectedException(typeof(ArgumentOutOfRangeException))] public void NegativeMaxBackoff() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "NegativeMaxBackoff"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.NegativeMaxBackoff)); int execCount = 0; try @@ -253,7 +253,7 @@ public void NegativeMaxBackoff() [TestMethod] public void ZeroMaxBackoff() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "ZeroMaxBackoff"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.ZeroMaxBackoff)); int execCount = 0; double totalDuration = 0; @@ -282,7 +282,7 @@ public void ZeroMaxBackoff() [ExpectedException(typeof(ArgumentOutOfRangeException))] public void NegativeDeltaBackoff() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "NegativeDeltaBackoff"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.NegativeDeltaBackoff)); int execCount = 0; try @@ -304,7 +304,7 @@ public void NegativeDeltaBackoff() [TestMethod] public void ZeroDeltaBackoff() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "ZeroDeltaBackoff"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.ZeroDeltaBackoff)); int execCount = 0; double totalDuration = 0; @@ -332,7 +332,7 @@ public void ZeroDeltaBackoff() [TestMethod] public void MinBackoffEqualsMax() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "MinBackoffEqualsMax"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.MinBackoffEqualsMax)); int execCount = 0; double totalDuration = 0; @@ -360,7 +360,7 @@ public void MinBackoffEqualsMax() [TestMethod] public void MinBackoffGreaterThanMax() { - const string Key = "MinBackoffGreaterThanMax"; + const string Key = nameof(this.MinBackoffGreaterThanMax); IConfigurationSection section = RetryConfiguration.GetConfiguration().GetSection("causeError").GetSection(Key); Assert.IsNotNull(section); Assert.IsTrue(section.Exists()); @@ -381,7 +381,7 @@ public void MinBackoffGreaterThanMax() [TestMethod] public void LargeDeltaBackoff() { - RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: "LargeDeltaBackoff"); + RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy(retryStrategyName: nameof(this.LargeDeltaBackoff)); int execCount = 0; double totalDuration = 0; @@ -409,7 +409,7 @@ public void LargeDeltaBackoff() [TestMethod] public void FixedInterval_MissingRetryInterval() { - const string Key = "FixedInterval_MissingRetryInterval"; + const string Key = nameof(this.FixedInterval_MissingRetryInterval); IConfigurationSection section = RetryConfiguration.GetConfiguration().GetSection("causeError").GetSection(Key); Assert.IsNotNull(section); Assert.IsTrue(section.Exists()); @@ -429,7 +429,7 @@ public void FixedInterval_MissingRetryInterval() [TestMethod] public void IncrementalInterval_MissingRetryInterval() { - const string Key = "IncrementalInterval_MissingRetryInterval"; + const string Key = nameof(this.IncrementalInterval_MissingRetryInterval); IConfigurationSection section = RetryConfiguration.GetConfiguration().GetSection("causeError").GetSection(Key); Assert.IsNotNull(section); Assert.IsTrue(section.Exists()); @@ -449,7 +449,7 @@ public void IncrementalInterval_MissingRetryInterval() [TestMethod] public void ExponentialInterval_MissingMinBackoff() { - const string Key = "ExponentialInterval_MissingMinBackoff"; + const string Key = nameof(this.ExponentialInterval_MissingMinBackoff); IConfigurationSection section = RetryConfiguration.GetConfiguration().GetSection("causeError").GetSection(Key); Assert.IsNotNull(section); Assert.IsTrue(section.Exists()); @@ -469,7 +469,7 @@ public void ExponentialInterval_MissingMinBackoff() [TestMethod] public void ExponentialInterval_MissingMaxBackoff() { - const string Key = "ExponentialInterval_MissingMaxBackoff"; + const string Key = nameof(this.ExponentialInterval_MissingMaxBackoff); IConfigurationSection section = RetryConfiguration.GetConfiguration().GetSection("causeError").GetSection(Key); Assert.IsNotNull(section); Assert.IsTrue(section.Exists()); @@ -489,7 +489,7 @@ public void ExponentialInterval_MissingMaxBackoff() [TestMethod] public void ExponentialInterval_MissingDeltaBackoff() { - const string Key = "ExponentialInterval_MissingDeltaBackoff"; + const string Key = nameof(this.ExponentialInterval_MissingDeltaBackoff); IConfigurationSection section = RetryConfiguration.GetConfiguration().GetSection("causeError").GetSection(Key); Assert.IsNotNull(section); Assert.IsTrue(section.Exists()); @@ -509,7 +509,7 @@ public void ExponentialInterval_MissingDeltaBackoff() [TestMethod] public void NonExist() { - const string Key = "NonExist"; + const string Key = nameof(this.NonExist); IConfigurationSection section = RetryConfiguration.GetConfiguration().GetSection("causeError").GetSection(Key); Assert.IsNotNull(section); Assert.IsFalse(section.Exists()); diff --git a/Tests/TransientFaultHandling.Tests.Core/RetryManagers/Context.cs b/Tests/TransientFaultHandling.Tests.Core/RetryManagers/Context.cs index 49f7687..babe829 100644 --- a/Tests/TransientFaultHandling.Tests.Core/RetryManagers/Context.cs +++ b/Tests/TransientFaultHandling.Tests.Core/RetryManagers/Context.cs @@ -19,9 +19,9 @@ protected override void Arrange() this.otherStrategy = new Incremental("other", 5, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(10)); this.defaultSqlConnectionStrategy = new FixedInterval("defaultSqlConnection", 5, TimeSpan.FromMilliseconds(10)); this.defaultSqlCommandStrategy = new FixedInterval("defaultSqlCommand", 5, TimeSpan.FromMilliseconds(10)); - this.defaultAzureServiceBusStrategy = new FixedInterval("defaultAzureServiceBusStrategy", 5, TimeSpan.FromMilliseconds(10)); - this.defaultAzureCachingStrategy = new FixedInterval("defaultAzureCachingStrategy", 5, TimeSpan.FromMilliseconds(10)); - this.defaultAzureStorageStrategy = new FixedInterval("defaultAzureStorageStrategy", 5, TimeSpan.FromMilliseconds(10)); + this.defaultAzureServiceBusStrategy = new FixedInterval(nameof(this.defaultAzureServiceBusStrategy), 5, TimeSpan.FromMilliseconds(10)); + this.defaultAzureCachingStrategy = new FixedInterval(nameof(this.defaultAzureCachingStrategy), 5, TimeSpan.FromMilliseconds(10)); + this.defaultAzureStorageStrategy = new FixedInterval(nameof(this.defaultAzureStorageStrategy), 5, TimeSpan.FromMilliseconds(10)); this.managerWithAllDefaults = new RetryManager( new[] @@ -36,11 +36,11 @@ protected override void Arrange() "default", new Dictionary { - { "SQL", "defaultSqlCommand" }, - { "SQLConnection", "defaultSqlConnection" }, - { "ServiceBus", "defaultAzureServiceBusStrategy" }, - { "Caching", "defaultAzureCachingStrategy" }, - { "WindowsAzure.Storage", "defaultAzureStorageStrategy" }, + ["SQL"] = "defaultSqlCommand", + ["SQLConnection"] = "defaultSqlConnection", + ["ServiceBus"] = nameof(this.defaultAzureServiceBusStrategy), + [nameof(Caching)] = nameof(this.defaultAzureCachingStrategy), + ["WindowsAzure.Storage"] = nameof(this.defaultAzureStorageStrategy), }); this.managerWithOnlyDefault = new RetryManager( @@ -52,7 +52,7 @@ protected override void Arrange() this.otherStrategy, this.defaultAzureServiceBusStrategy, this.defaultAzureCachingStrategy, this.defaultAzureStorageStrategy - }, +}, "default"); } }