コード例 #1
1
        [Ignore]    // REVIEW
        public void TestSqlAzureTransientErrorDetectionStrategyWithRetryableError()
        {
            int[] errors = new int[] { 40197, 40501, 40540, 10053, 10054, 10060, 40549, 40550, 40551, 40552, 40553, 40613, 40143, 233, 64 };
            Type type = typeof(SqlDatabaseTransientErrorDetectionStrategy).GetNestedType("ProcessNetLibErrorCode", BindingFlags.NonPublic);
            errors = errors.AddRange((int[])Enum.GetValues(type));

            Exception[] exceptions = FakeSqlExceptionGenerator.GenerateFakeSqlExceptions(errors);
            exceptions = exceptions.AddRange(new TimeoutException(), new EntityException("Forced Exception"));

            RetryPolicy defaultPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(exceptions.Length - 1, RetryStrategy.DefaultRetryInterval);
            int execCount = 0;

            try
            {
                defaultPolicy.ExecuteAction(() =>
                {
                    Exception ex = exceptions[execCount];
                    execCount++;
                    throw ex;
                });
            }
            catch (EntityException ex)
            {
                Assert.AreEqual("Forced Exception", ex.Message);
            }

            Assert.AreEqual<int>(exceptions.Length, execCount, "The action was not executed the expected amount of times");
        }
コード例 #2
0
        public SimulatedLdapProfileStore(Database database)
        {
            this.accessor = database.CreateSprocAccessor<ProfileStoreData>("aexpense_ProfileStore_GetProfileFromUser");
            this.retryPolicy = RetryPolicyFactory.GetRetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>();

            AExpenseEvents.Log.ProfileStoreInitialized();
        }
コード例 #3
0
ファイル: CloudBlobStorage.cs プロジェクト: project-hu/hu
        /// <summary />
        /// <param name="account"></param>
        /// <param name="rootContainerName"></param>
        public CloudBlobStorage(CloudStorageAccount account, string rootContainerName)
        {
            try
            {

            this.account = account;
            this.rootContainerName = rootContainerName;

            this.blobClient = account.CreateCloudBlobClient();

            this.readRetryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(new Incremental(1, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)));
            this.readRetryPolicy.Retrying += (s, e) => Trace.TraceWarning("An error occurred in attempt number {1} to read from blob storage: {0}", e.LastException.Message, e.CurrentRetryCount);
            this.writeRetryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(new FixedInterval(1, TimeSpan.FromSeconds(10)) { FastFirstRetry = false });
            this.writeRetryPolicy.Retrying += (s, e) => Trace.TraceWarning("An error occurred in attempt number {1} to write to blob storage: {0}", e.LastException.Message, e.CurrentRetryCount);

            var containerReference = this.blobClient.GetContainerReference(this.rootContainerName);

            this.writeRetryPolicy.ExecuteAction(() => containerReference.CreateIfNotExists());

            }
              catch (Exception ex)
              {

              string msg = ex.Message;
              throw;
              }
        }
コード例 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TopicSender"/> class, 
        /// automatically creating the given topic if it does not exist.
        /// </summary>
        protected TopicSender(MessagingSettings settings, string topic, RetryStrategy retryStrategy)
        {
            this.settings = settings;
            this.topic = topic;

            this.tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            this.serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);

            try
            {
                new NamespaceManager(this.serviceUri, this.tokenProvider)
                    .CreateTopic(
                        new TopicDescription(topic)
                        {
                            RequiresDuplicateDetection = true,
                            DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(30)
                        });
            }
            catch (MessagingEntityAlreadyExistsException)
            { }

            // TODO: This could be injected.
            this.retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            this.retryPolicy.Retrying +=
                (s, e) =>
                {
                    Trace.TraceError("An error occurred in attempt number {1} to send a message: {0}", e.LastException.Message, e.CurrentRetryCount);
                };

            var factory = MessagingFactory.Create(this.serviceUri, this.tokenProvider);
            this.topicClient = factory.CreateTopicClient(this.topic);
        }
コード例 #5
0
ファイル: Instance.cs プロジェクト: invertedtomato/Amos2
        public Instance(Configuration configuration, string domain, Index index = null)
        {
            // Set instance on configuration
            Configuration = configuration;

            // Init things
            ObjDb = new Db(Configuration.Object.Database.ConnectionString); // Database
            CacheObj = new MemoryCache("instance-obj-" + domain); // Cache
            //CacheQ = new MemoryCache("instance-q-" + domain); // Cache

            if (null == index) {
                // Create new index
                Index = new Index(Configuration.Schema);

                // Build base index
                var retry = new RetryPolicy<DbRetryStrategy>(3, new TimeSpan(0, 0, 1));
                using (var rdr = ObjDb.Query("SELECT [uid],[type],[serial],[properties] FROM [obj] WHERE [oid] NOT IN (SELECT [predecessor] FROM [obj])").ExecuteReaderWithRetry(retry)) {
                    while (rdr.Read()) {
                        Index.Set((string)rdr["uid"], (string)rdr["type"], (long)rdr["serial"], (string)rdr["properties"]);
                    }
                }
            } else {
                Index = index;
            }

            // Init mode
            Mode = Amos.ImplementationMode.Mode.Select(Configuration.Mode, this);
        }
コード例 #6
0
 private static RetryPolicy<SqlAzureTransientErrorDetectionStrategy> MakeRetryPolicy()
 {
     var fromMilliseconds = TimeSpan.FromMilliseconds(DelayMs);
     var policy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>
         (MaxRetry, fromMilliseconds);
     return policy;
 }
コード例 #7
0
 private static RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy> MakeRetryPolicy()
 {
     var fromMilliseconds = TimeSpan.FromMilliseconds(DELAY_MS);
     var policy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>
         (MAX_RETRY, fromMilliseconds);
     return policy;
 }
コード例 #8
0
ファイル: Program.cs プロジェクト: jorgeds001/CodeSamples
        private static void RetryPolityUsingCode(IUnityContainer container, IBlockService service)
        {
            System.Diagnostics.Trace.WriteLine("Begin sample: RetryPolityUsingCode");
            // Define your retry strategy: retry 5 times, starting 1 second apart
            // and adding 2 seconds to the interval each retry.
            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));

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

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

            System.Diagnostics.Trace.WriteLine("End sample: RetryPolityUsingCode");
        }
        static void Main(string[] args)
        {
            DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            sampleRootPath = di.Parent.Parent.FullName;

            //Register the data source container
            string jsonContainerTemplate = new StreamReader(string.Format(@"{0}\AdHocContainerSample.json", sampleRootPath)).ReadToEnd();
            string jsonContainerPayload = string.Format(jsonContainerTemplate, DateTime.UtcNow);

            retryPolicy = new RetryPolicy(
                new HttpRequestTransientErrorDetectionStrategy(),
                5,
                TimeSpan.FromMilliseconds(100),
                TimeSpan.FromMilliseconds(500)
                );

            //To register a container, use "containers" as view type
            string containerId = RegisterDataAsset(catalogName, jsonContainerPayload, "containers");

            RegisterDataAssets(containerId);

            Console.WriteLine();
            Console.WriteLine("Data assets registered from Excel table. Press Enter");
            Console.ReadLine();
        }
コード例 #10
0
        public static RetryPolicy GetDefaultSqlConnectionRetryPolicy()
        {
            var retryStrategy = RetryStrategy.DefaultExponential;
            var retryPolicy = new RetryPolicy(new NetworkConnectivityErrorDetectionStrategy(), retryStrategy);

            return retryPolicy;
        }
コード例 #11
0
        public void Initialize()
        {
            var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
            var retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            var serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);
            var namespaceManager = new NamespaceManager(serviceUri, tokenProvider);

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

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

            this.initialized = true;
        }
コード例 #12
0
        public static RetryPolicy GetDefaultSqlAzureCommandRetryPolicy()
        {
            var retryStrategy = RetryStrategy.DefaultFixed;
            var retryPolicy = new RetryPolicy(new SqlAzureTransientErrorDetectionStrategy(), retryStrategy);

            return retryPolicy;
        }
コード例 #13
0
        public static RetryPolicy GetDefaultSqlCommandRetryPolicy()
        {
            var retryStrategy = RetryStrategy.DefaultFixed;
            var retryPolicy = new RetryPolicy(new NetworkConnectivityErrorDetectionStrategy(), retryStrategy);

            return retryPolicy;
        }
コード例 #14
0
 public UpdateSessionManagerRetryDecorator(IUpdateSessionManager updateSessionManager,
     RetryStrategy retryStrategy,
     ITransientErrorDetectionStrategy errorDetectionStrategy)
 {
     _updateSessionManager = updateSessionManager;
     _retryPolicy = new RetryPolicy(errorDetectionStrategy, retryStrategy);
 }
コード例 #15
0
 public ReliableTopicClient(string sbNamespace, TokenProvider tokenProvider, string path, RetryPolicy<ServiceBusTransientErrorDetectionStrategy> policy)
     : base(sbNamespace, tokenProvider, path, policy)
 {
     //create the queue if it doesn't exist
     bool needsCreation = false;
     try
     {
         needsCreation = !mRetryPolicy.ExecuteAction<bool>(() => mNamespaceManager.TopicExists(path));
     }
     catch (MessagingEntityNotFoundException)
     {
         needsCreation = true;
     }
     if (needsCreation)
     {
         try
         {
             mRetryPolicy.ExecuteAction<TopicDescription>(() => mNamespaceManager.CreateTopic(path));
         }
         catch (MessagingEntityAlreadyExistsException)
         {
             //ignore this exception because queue already exists
         }
     }
     mRetryPolicy.ExecuteAction(() => mTopicClient = mMessagingFactory.CreateTopicClient(path));
 }
コード例 #16
0
        /// <summary>
        /// Create an exponential backoff retry policy given a detection strategy.
        /// </summary>
        /// <param name="strategy"></param>
        /// <returns></returns>
        private static RetryPolicy Exponential(ITransientErrorDetectionStrategy strategy, int retryCount)
        {
            if (retryCount == 0)
                return RetryPolicy.NoRetry;

            if (retryCount == 1)
            {
                var retryPolicy = new RetryPolicy(strategy, 1);
                retryPolicy.RetryStrategy.FastFirstRetry = true;

                return retryPolicy;
            }

            var minBackoff = TimeSpan.FromSeconds(1);
            var maxBackoff = TimeSpan.FromSeconds(10);
            var deltaBackoff = TimeSpan.FromSeconds(5);

            // if retryCount is equal to Int16.MaxValue (32767)
            // then increase the backoff intervals.
            if (retryCount == Int16.MaxValue)
            {
                minBackoff = TimeSpan.FromSeconds(1);
                maxBackoff = TimeSpan.FromSeconds(300);
                deltaBackoff = TimeSpan.FromSeconds(10);
            }

            // 30 60 120 240

            var exponentialBackoff = new ExponentialBackoff(retryCount, minBackoff, maxBackoff, deltaBackoff);

            return new RetryPolicy(strategy, exponentialBackoff);
        }
コード例 #17
0
        // GET api/nextsession
        public Session Get()
        {
            var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
            var retryPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(retryStrategy);
            
            Session nextSession = new Session();
            using (VidPackEntities db = new VidPackEntities())
            {
                retryPolicy.ExecuteAction(() =>
                {
                    db.Database.Connection.Open();
                });

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

                if (dbSession != null)
                    nextSession = new VidPackModel.Session()
                    {
                        SessionDate = dbSession.SessionDate.ToString(),
                        SessionDescription = dbSession.SessionDescription,
                        SessionSubTitle = dbSession.SessionSubTitle,
                        SessionThumbnailUrl = String.Format("{0}{1}", ThumbnailStorageUrl, dbSession.SessionThumbnailUri),
                        SessionTitle = dbSession.SessionSubTitle,
                        SessionVideoUrl = dbSession.SessionVideoUri == null ? "" : dbSession.SessionVideoUri,
                        Speaker = dbSession.Speaker
                    };
            }
            return nextSession; 
        }
コード例 #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TopicSender"/> class, 
        /// automatically creating the given topic if it does not exist.
        /// </summary>
        protected TopicSender(ServiceBusSettings settings, string topic, RetryStrategy retryStrategy)
        {
            this.settings = settings;
            this.topic = topic;

            this.tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(settings.TokenIssuer, settings.TokenAccessKey);
            this.serviceUri = ServiceBusEnvironment.CreateServiceUri(settings.ServiceUriScheme, settings.ServiceNamespace, settings.ServicePath);

            // TODO: This could be injected.
            this.retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy);
            this.retryPolicy.Retrying +=
                (s, e) =>
                {
                    var handler = this.Retrying;
                    if (handler != null)
                    {
                        handler(this, EventArgs.Empty);
                    }

                    Trace.TraceWarning("An error occurred in attempt number {1} to send a message: {0}", e.LastException.Message, e.CurrentRetryCount);
                };

            var factory = MessagingFactory.Create(this.serviceUri, this.tokenProvider);
            this.topicClient = factory.CreateTopicClient(this.topic);
        }
コード例 #19
0
 public ReliableClientBase(string sbNamespace, TokenProvider tokenProvider, string path, RetryPolicy<ServiceBusTransientErrorDetectionStrategy> policy)
 {
     mRetryPolicy = policy;
     Uri address = ServiceBusEnvironment.CreateServiceUri("sb", sbNamespace, string.Empty);
     mNamespaceManager = new NamespaceManager(address, tokenProvider);
     mMessagingFactory = MessagingFactory.Create(address, tokenProvider);
 }
コード例 #20
0
ファイル: PostBackup.cs プロジェクト: tzkwizard/ELS
 public PostBackup(CloudStorageAccount storageAccount, string endpointUrl, string authorizationKey)
 {
     _iDbService = new DbService(endpointUrl,authorizationKey);
     CloudTableClient c = storageAccount.CreateCloudTableClient();
     _table = c.GetTableReference("Post");
     _table.CreateIfNotExists();
     _retryPolicy = _iDbService.GetRetryPolicy();
 }
コード例 #21
0
 /// <summary>
 /// Opens a database connection with the connection settings specified in the ConnectionString property of the connection object.
 /// Uses the specified retry policy when opening the connection.
 /// </summary>
 /// <param name="connection">The connection object that is required as per extension method declaration.</param>
 /// <param name="retryPolicy">The retry policy defining whether to retry a request if the connection fails to be opened.</param>
 public static void OpenWithRetry(this SqlConnection connection, RetryPolicy retryPolicy)
 {
     // Check if retry policy was specified, if not, use the default retry policy.
     (retryPolicy != null ? retryPolicy : RetryPolicy.NoRetry).ExecuteAction(() =>
     {
         connection.Open();
     });
 }
コード例 #22
0
ファイル: JobPurgeTimer.cs プロジェクト: Teleopti/Stardust
		public JobPurgeTimer(RetryPolicyProvider retryPolicyProvider, ManagerConfiguration managerConfiguration) : base(managerConfiguration.PurgeJobsIntervalHours*60*60*1000)
		{
			_managerConfiguration = managerConfiguration;
			_retryPolicy = retryPolicyProvider.GetPolicy();
			_connectionString = managerConfiguration.ConnectionString;
			Elapsed += PurgeTimer_elapsed;
			Purge();
		}
コード例 #23
0
 public SubscriptionDisposer(string topic, string subscription, bool isTransient, NamespaceManager namespaceManager, RetryPolicy retryPolicy)
 {
     _topic = topic;
     _subscription = subscription;
     _isTransient = isTransient;
     _namespaceManager = namespaceManager;
     _retryPolicy = retryPolicy;
 }
コード例 #24
0
ファイル: ChatBackup.cs プロジェクト: tzkwizard/ELS
 public ChatBackup(CloudStorageAccount storageAccount)
 {
     var client = storageAccount.CreateCloudTableClient();
     _table = client.GetTableReference("Chat");
     _table.CreateIfNotExists();
     _iDbService = new DbService();
     _retryPolicy = _iDbService.GetRetryPolicy();
 }
コード例 #25
0
        public static async void Throws_WhenCancellationTokenIsAlreadyCancelled()
        {
            var logger = Substitute.For<ILog>();
            var retryHandler = new RetryPolicy(logger);

            var ex = await Assert.ThrowsAsync<TaskCanceledException>(() => retryHandler.ExecuteAsync(async c => { await Task.Delay(5000, c); return true; }, (b, e) => true,  cancellationToken: new CancellationToken(true)));
            Assert.True(ex.Task.IsCanceled);
        }
コード例 #26
0
ファイル: PostBackup.cs プロジェクト: tzkwizard/Azure
 public PostBackup(CloudStorageAccount storageAccount)
 {
     _iDbService = new DbService();
     CloudTableClient c = storageAccount.CreateCloudTableClient();
     _table = c.GetTableReference("Post");
     _table.CreateIfNotExists();
     _retryPolicy = RetryService.GetRetryPolicy();
 }
コード例 #27
0
        public void TestNegativeRetryCount()
        {
            try
            {
                // First, instantiate a policy directly bypassing the configuration data validation.
                RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy> retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(-1);
                Assert.Fail("When the RetryCount is negative, the retry policy should throw an exception.");
            }
            catch (ArgumentOutOfRangeException ex)
            {
                Assert.AreEqual("retryCount", ex.ParamName, String.Format("A wrong argument has caused the {0} exception", ex.GetType().Name));
            }

            // Removed - different approach when dealing with the factory.
            ////try
            ////{
            ////    // Second, attempt to instantiate a retry policy from configuration with invalid settings.
            ////    RetryPolicy retryPolicy = RetryPolicyFactory.GetRetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>("NegativeRetryCount");
            ////    Assert.Fail("When the RetryCount is negative, the retry policy should throw an exception.");
            ////}
            ////catch (ConfigurationErrorsException ex)
            ////{
            ////    Assert.IsTrue(ex.Message.Contains("maxRetryCount"), String.Format("A wrong argument has caused the {0} exception", ex.GetType().Name));
            ////}

            try
            {
                // And last, instantiate a policy description with invalid settings.
                new FixedIntervalData { MaxRetryCount = -1 };
                Assert.Fail("When the RetryCount is negative, the retry policy should throw an exception.");
            }
            catch (ConfigurationErrorsException ex)
            {
                Assert.IsTrue(ex.Message.Contains("maxRetryCount"), String.Format("A wrong argument has caused the {0} exception", ex.GetType().Name));
            }

            try
            {
                // And last, instantiate a policy description with invalid settings.
                new IncrementalData { MaxRetryCount = -1 };
                Assert.Fail("When the RetryCount is negative, the retry policy should throw an exception.");
            }
            catch (ConfigurationErrorsException ex)
            {
                Assert.IsTrue(ex.Message.Contains("maxRetryCount"), String.Format("A wrong argument has caused the {0} exception", ex.GetType().Name));
            }

            try
            {
                // And last, instantiate a policy description with invalid settings.
                new ExponentialBackoffData { MaxRetryCount = -1 };
                Assert.Fail("When the RetryCount is negative, the retry policy should throw an exception.");
            }
            catch (ConfigurationErrorsException ex)
            {
                Assert.IsTrue(ex.Message.Contains("maxRetryCount"), String.Format("A wrong argument has caused the {0} exception", ex.GetType().Name));
            }
        }
コード例 #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RetryDelegatingHandler"/> class. 
 /// </summary>
 /// <param name="retryPolicy">Retry policy to use.</param>
 /// <param name="innerHandler">Inner http handler.</param>
 public RetryDelegatingHandler(RetryPolicy retryPolicy, DelegatingHandler innerHandler)
     : base(innerHandler)
 {
     if (retryPolicy == null)
     {
         throw new ArgumentNullException("retryPolicy");
     }
     RetryPolicy = retryPolicy;
 }
コード例 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RetryDelegatingHandler"/> class. 
 /// Sets default retry policty base on Exponential Backoff.
 /// </summary>
 public RetryDelegatingHandler()
 {
     var retryStrategy = new ExponentialBackoffRetryStrategy(
         DefaultNumberOfAttempts,
         DefaultMinBackoff,
         DefaultMaxBackoff,
         DefaultBackoffDelta);
     RetryPolicy = new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(retryStrategy);
 }
コード例 #30
0
        protected override void Arrange()
        {
            base.Arrange();

            this.detectionStrategyMock = new Mock<ITransientErrorDetectionStrategy>();
            this.detectionStrategyMock.Setup(ds => ds.IsTransient(It.Is<Exception>(e => e is InvalidOperationException))).Returns(true);

            this.retryPolicy = new RetryPolicy(this.detectionStrategyMock.Object, 2);
        }
コード例 #31
0
 public PolicyProvider()
 {
     IdPSearchServiceRetryPolicy = _idPSearchServicePolicyBuilder.RetryAsync(3);
     IdPSearchServiceErrorPolicy = _idPSearchServicePolicyBuilder.CircuitBreakerAsync(3, TimeSpan.FromMinutes(5));
     IdPSearchServicePolicy      = IdPSearchServiceRetryPolicy.WrapAsync(IdPSearchServiceErrorPolicy);
 }
コード例 #32
0
ファイル: PolicyFactory.cs プロジェクト: waodng/VSIX
        public static RetryPolicy GetPolicy(ITransientErrorDetectionStrategy strategy, int retryCount)
        {
            RetryPolicy policy = new RetryPolicy(strategy, retryCount, TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(50));

            return(policy);
        }
コード例 #33
0
 /// <summary>
 /// Creates a new AMQP MessageSender.
 /// </summary>
 /// <param name="connectionStringBuilder">The <see cref="ServiceBusConnectionStringBuilder"/> having entity level connection details.</param>
 /// <param name="retryPolicy">The <see cref="RetryPolicy"/> that will be used when communicating with Service Bus. Defaults to <see cref="RetryPolicy.Default"/></param>
 /// <remarks>Creates a new connection to the entity, which is opened during the first operation.</remarks>
 public MessageSender(
     ServiceBusConnectionStringBuilder connectionStringBuilder,
     RetryPolicy retryPolicy = null)
     : this(connectionStringBuilder?.GetNamespaceConnectionString(), connectionStringBuilder?.EntityPath, retryPolicy)
 {
 }
コード例 #34
0
 protected ServiceBusConnection(TimeSpan operationTimeout, RetryPolicy retryPolicy)
 {
     this.OperationTimeout = operationTimeout;
     this.RetryPolicy      = retryPolicy;
 }
コード例 #35
0
 internal RetrySession(RetryPolicy retryPolicy)
 {
     _retryPolicy = retryPolicy ?? throw new ArgumentNullException(nameof(retryPolicy));
     _waitTime    = retryPolicy.InitialInterval;
 }
コード例 #36
0
ファイル: Retry.cs プロジェクト: Xamla/graph_system
 public static Task <T> WithPolicyAsync <T>(Func <Task <T> > block, RetryPolicy policy)
 {
     return(WithPolicyAsync(c => block(), policy));
 }
コード例 #37
0
        public HttpResponseMessage Post(SelItemListAllInputParams p)
        {
            // try decrypt data
            if (!string.IsNullOrEmpty(p.token) && globalVal.CloudBreadCryptSetting == "AES256")
            {
                try
                {
                    string decrypted = Crypto.AES_decrypt(p.token, globalVal.CloudBreadCryptKey, globalVal.CloudBreadCryptIV);
                    p = JsonConvert.DeserializeObject <SelItemListAllInputParams>(decrypted);
                }
                catch (Exception ex)
                {
                    ex = (Exception)Activator.CreateInstance(ex.GetType(), "Decrypt Error", ex);
                    throw ex;
                }
            }

            // Get the sid or memberID of the current user.
            string sid = CBAuth.getMemberID(p.MemberID, this.User as ClaimsPrincipal);

            p.MemberID = sid;

            Logging.CBLoggers logMessage = new Logging.CBLoggers();
            string            jsonParam  = JsonConvert.SerializeObject(p);

            List <SelItemListAllModel> result   = new List <SelItemListAllModel>();
            HttpResponseMessage        response = new HttpResponseMessage();
            EncryptedData encryptedResult       = new EncryptedData();

            try
            {
                /// Database connection retry policy
                RetryPolicy retryPolicy = new RetryPolicy <SqlAzureTransientErrorDetectionStrategy>(globalVal.conRetryCount, TimeSpan.FromSeconds(globalVal.conRetryFromSeconds));
                using (SqlConnection connection = new SqlConnection(globalVal.DBConnectionString))
                {
                    using (SqlCommand command = new SqlCommand("uspSelItemListAll", connection))
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.Add("@Page", SqlDbType.BigInt).Value     = p.Page;
                        command.Parameters.Add("@PageSize", SqlDbType.BigInt).Value = p.PageSize;
                        connection.OpenWithRetry(retryPolicy);

                        using (SqlDataReader dreader = command.ExecuteReaderWithRetry(retryPolicy))
                        {
                            while (dreader.Read())
                            {
                                SelItemListAllModel workItem = new SelItemListAllModel()
                                {
                                    ROWNUM          = dreader[0].ToString(),
                                    ItemListID      = dreader[1].ToString(),
                                    ItemName        = dreader[2].ToString(),
                                    ItemDescription = dreader[3].ToString(),
                                    ItemPrice       = dreader[4].ToString(),
                                    ItemSellPrice   = dreader[5].ToString(),
                                    ItemCategory1   = dreader[6].ToString(),
                                    ItemCategory2   = dreader[7].ToString(),
                                    ItemCategory3   = dreader[8].ToString(),
                                    sCol1           = dreader[9].ToString(),
                                    sCol2           = dreader[10].ToString(),
                                    sCol3           = dreader[11].ToString(),
                                    sCol4           = dreader[12].ToString(),
                                    sCol5           = dreader[13].ToString(),
                                    sCol6           = dreader[14].ToString(),
                                    sCol7           = dreader[15].ToString(),
                                    sCol8           = dreader[16].ToString(),
                                    sCol9           = dreader[17].ToString(),
                                    sCol10          = dreader[18].ToString()
                                };
                                result.Add(workItem);
                            }
                            dreader.Close();
                        }
                        connection.Close();
                    }

                    /// Encrypt the result response
                    if (globalVal.CloudBreadCryptSetting == "AES256")
                    {
                        try
                        {
                            encryptedResult.token = Crypto.AES_encrypt(JsonConvert.SerializeObject(result), globalVal.CloudBreadCryptKey, globalVal.CloudBreadCryptIV);
                            response = Request.CreateResponse(HttpStatusCode.OK, encryptedResult);
                            return(response);
                        }
                        catch (Exception ex)
                        {
                            ex = (Exception)Activator.CreateInstance(ex.GetType(), "Encrypt Error", ex);
                            throw ex;
                        }
                    }

                    response = Request.CreateResponse(HttpStatusCode.OK, result);
                    return(response);
                }
            }

            catch (Exception ex)
            {
                // error log
                logMessage.memberID  = p.MemberID;
                logMessage.Level     = "ERROR";
                logMessage.Logger    = "CBSelItemListAllController";
                logMessage.Message   = jsonParam;
                logMessage.Exception = ex.ToString();
                Logging.RunLog(logMessage);

                throw ex;
            }
        }
コード例 #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RetryPolicyAdapter"/> class.
 /// </summary>
 /// <param name="retryPolicy">The retry policy.</param>
 public RetryPolicyAdapter(RetryPolicy retryPolicy)
 {
     this.retryPolicy = retryPolicy;
 }
コード例 #39
0
 /// <summary>
 /// Initializes request Id, Timeout, and the request option
 /// </summary>
 /// <param name="requestId">request Id</param>
 /// <param name="timeOut">Time out</param>
 /// <param name="rp">Retry policy</param>
 public RequestOptions(string requestId, TimeSpan timeOut, RetryPolicy rp)
 {
     RequestId   = requestId;
     TimeOut     = timeOut;
     RetryOption = rp;
 }
コード例 #40
0
 /// <summary>
 /// Creates an adapter from a Microsoft Practices <see cref="RetryPolicy"/>.
 /// </summary>
 /// <param name="retryPolicy">The retry policy.</param>
 /// <returns>A <see cref="RetryPolicyAdapter"/>.</returns>
 public static RetryPolicyAdapter CreateFrom(RetryPolicy retryPolicy)
 {
     return(new RetryPolicyAdapter(retryPolicy));
 }
コード例 #41
0
 public AzureServiceBusMessageBusOptionsBuilder SubscriptionRetryPolicy(RetryPolicy subscriptionRetryPolicy)
 {
     Target.SubscriptionRetryPolicy = subscriptionRetryPolicy ?? throw new ArgumentNullException(nameof(subscriptionRetryPolicy));
     return(this);
 }
コード例 #42
0
        public HttpResponseMessage Post(COMUdtMemberInputParams p)
        {
            // try decrypt data
            if (!string.IsNullOrEmpty(p.token) && globalVal.CloudBreadCryptSetting == "AES256")
            {
                try
                {
                    string decrypted = Crypto.AES_decrypt(p.token, globalVal.CloudBreadCryptKey, globalVal.CloudBreadCryptIV);
                    p = JsonConvert.DeserializeObject <COMUdtMemberInputParams>(decrypted);
                }
                catch (Exception ex)
                {
                    ex = (Exception)Activator.CreateInstance(ex.GetType(), "Decrypt Error", ex);
                    throw ex;
                }
            }

            // Get the sid or memberID of the current user.
            string sid = CBAuth.getMemberID(p.MemberID, this.User as ClaimsPrincipal);

            p.MemberID = sid;

            Logging.CBLoggers logMessage = new Logging.CBLoggers();
            string            jsonParam  = JsonConvert.SerializeObject(p);

            RowcountResult      rowcountResult  = new RowcountResult();
            HttpResponseMessage response        = new HttpResponseMessage();
            EncryptedData       encryptedResult = new EncryptedData();

            try
            {
                // start task log
                //logMessage.memberID = p.MemberID;
                //logMessage.Level = "INFO";
                //logMessage.Logger = "CBCOMUdtMemberController";
                //logMessage.Message = jsonParam;
                //Logging.RunLog(logMessage);

                /// Database connection retry policy
                RetryPolicy retryPolicy = new RetryPolicy <SqlAzureTransientErrorDetectionStrategy>(globalVal.conRetryCount, TimeSpan.FromSeconds(globalVal.conRetryFromSeconds));
                using (SqlConnection connection = new SqlConnection(globalVal.DBConnectionString))
                {
                    using (SqlCommand command = new SqlCommand("uspComUdtMember", connection))
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.Add("@MemberID", SqlDbType.NVarChar, -1).Value         = p.MemberID;
                        command.Parameters.Add("@MemberPWD", SqlDbType.NVarChar, -1).Value        = p.MemberPWD;
                        command.Parameters.Add("@EmailAddress", SqlDbType.NVarChar, -1).Value     = p.EmailAddress;
                        command.Parameters.Add("@EmailConfirmedYN", SqlDbType.NVarChar, -1).Value = p.EmailConfirmedYN;
                        command.Parameters.Add("@PhoneNumber1", SqlDbType.NVarChar, -1).Value     = p.PhoneNumber1;
                        command.Parameters.Add("@PhoneNumber2", SqlDbType.NVarChar, -1).Value     = p.PhoneNumber2;
                        command.Parameters.Add("@PINumber", SqlDbType.NVarChar, -1).Value         = p.PINumber;
                        command.Parameters.Add("@Name1", SqlDbType.NVarChar, -1).Value            = p.Name1;
                        command.Parameters.Add("@Name2", SqlDbType.NVarChar, -1).Value            = p.Name2;
                        command.Parameters.Add("@Name3", SqlDbType.NVarChar, -1).Value            = p.Name3;
                        command.Parameters.Add("@DOB", SqlDbType.NVarChar, -1).Value            = p.DOB;
                        command.Parameters.Add("@RecommenderID", SqlDbType.NVarChar, -1).Value  = p.RecommenderID;
                        command.Parameters.Add("@MemberGroup", SqlDbType.NVarChar, -1).Value    = p.MemberGroup;
                        command.Parameters.Add("@LastDeviceID", SqlDbType.NVarChar, -1).Value   = p.LastDeviceID;
                        command.Parameters.Add("@LastIPaddress", SqlDbType.NVarChar, -1).Value  = p.LastIPaddress;
                        command.Parameters.Add("@LastLoginDT", SqlDbType.NVarChar, -1).Value    = p.LastLoginDT;
                        command.Parameters.Add("@LastLogoutDT", SqlDbType.NVarChar, -1).Value   = p.LastLogoutDT;
                        command.Parameters.Add("@LastMACAddress", SqlDbType.NVarChar, -1).Value = p.LastMACAddress;

                        command.Parameters.Add("@AccountBlockYN", SqlDbType.NVarChar, -1).Value    = p.AccountBlockYN;
                        command.Parameters.Add("@AccountBlockEndDT", SqlDbType.NVarChar, -1).Value = p.AccountBlockEndDT;
                        command.Parameters.Add("@AnonymousYN", SqlDbType.NVarChar, -1).Value       = p.AnonymousYN;

                        command.Parameters.Add("@3rdAuthProvider", SqlDbType.NVarChar, -1).Value          = p._3rdAuthProvider;
                        command.Parameters.Add("@3rdAuthID", SqlDbType.NVarChar, -1).Value                = p._3rdAuthID;
                        command.Parameters.Add("@3rdAuthParam", SqlDbType.NVarChar, -1).Value             = p._3rdAuthParam;
                        command.Parameters.Add("@PushNotificationID", SqlDbType.NVarChar, -1).Value       = p.PushNotificationID;
                        command.Parameters.Add("@PushNotificationProvider", SqlDbType.NVarChar, -1).Value = p.PushNotificationProvider;
                        command.Parameters.Add("@PushNotificationGroup", SqlDbType.NVarChar, -1).Value    = p.PushNotificationGroup;

                        command.Parameters.Add("@sCol1", SqlDbType.NVarChar, -1).Value       = p.sCol1;
                        command.Parameters.Add("@sCol2", SqlDbType.NVarChar, -1).Value       = p.sCol2;
                        command.Parameters.Add("@sCol3", SqlDbType.NVarChar, -1).Value       = p.sCol3;
                        command.Parameters.Add("@sCol4", SqlDbType.NVarChar, -1).Value       = p.sCol4;
                        command.Parameters.Add("@sCol5", SqlDbType.NVarChar, -1).Value       = p.sCol5;
                        command.Parameters.Add("@sCol6", SqlDbType.NVarChar, -1).Value       = p.sCol6;
                        command.Parameters.Add("@sCol7", SqlDbType.NVarChar, -1).Value       = p.sCol7;
                        command.Parameters.Add("@sCol8", SqlDbType.NVarChar, -1).Value       = p.sCol8;
                        command.Parameters.Add("@sCol9", SqlDbType.NVarChar, -1).Value       = p.sCol9;
                        command.Parameters.Add("@sCol10 ", SqlDbType.NVarChar, -1).Value     = p.sCol10;
                        command.Parameters.Add("@TimeZoneID ", SqlDbType.NVarChar, -1).Value = p.TimeZoneID;

                        connection.OpenWithRetry(retryPolicy);
                        using (SqlDataReader dreader = command.ExecuteReaderWithRetry(retryPolicy))
                        {
                            while (dreader.Read())
                            {
                                rowcountResult.result = dreader[0].ToString();
                            }
                            dreader.Close();
                        }
                        connection.Close();

                        // end task log
                        logMessage.memberID = p.MemberID;
                        logMessage.Level    = "INFO";
                        logMessage.Logger   = "CBCOMUdtMemberController";
                        logMessage.Message  = jsonParam;
                        Logging.RunLog(logMessage);

                        /// Encrypt the result response
                        if (globalVal.CloudBreadCryptSetting == "AES256")
                        {
                            try
                            {
                                encryptedResult.token = Crypto.AES_encrypt(JsonConvert.SerializeObject(rowcountResult), globalVal.CloudBreadCryptKey, globalVal.CloudBreadCryptIV);
                                response = Request.CreateResponse(HttpStatusCode.OK, encryptedResult);
                                return(response);
                            }
                            catch (Exception ex)
                            {
                                ex = (Exception)Activator.CreateInstance(ex.GetType(), "Encrypt Error", ex);
                                throw ex;
                            }
                        }

                        response = Request.CreateResponse(HttpStatusCode.OK, rowcountResult);
                        return(response);
                    }
                }
            }

            catch (Exception ex)
            {
                // error log
                logMessage.memberID  = p.MemberID;
                logMessage.Level     = "ERROR";
                logMessage.Logger    = "CBCOMUdtMemberController";
                logMessage.Message   = jsonParam;
                logMessage.Exception = ex.ToString();
                Logging.RunLog(logMessage);

                throw;
            }
        }
コード例 #43
0
ファイル: Retry.cs プロジェクト: Xamla/graph_system
 public static Task WithPolicyAsync(Func <CancellationToken, Task> block, RetryPolicy policy, CancellationToken cancel)
 {
     return(WithPolicyAsync <int>(async c => { await block(c); return 0; }, policy, cancel));
 }
コード例 #44
0
ファイル: Retry.cs プロジェクト: Xamla/graph_system
 public static void WithPolicy(Action block, RetryPolicy policy)
 {
     WithPolicy <int>(() => { block(); return(0); }, policy);
 }
コード例 #45
0
 protected MessageReceiver(ReceiveMode receiveMode, TimeSpan operationTimeout, RetryPolicy retryPolicy)
     : base(nameof(MessageReceiver) + StringUtility.GetRandomString(), retryPolicy ?? RetryPolicy.Default)
 {
     this.ReceiveMode                = receiveMode;
     this.operationTimeout           = operationTimeout;
     this.lastPeekedSequenceNumber   = Constants.DefaultLastPeekedSequenceNumber;
     this.messageReceivePumpSyncLock = new object();
 }
コード例 #46
0
 public MessagingFactoryCache(Uri serviceUri, MessagingFactorySettings settings, RetryPolicy retryPolicy)
     : base(new MessagingFactoryContextFactory(serviceUri, settings, retryPolicy))
 {
     _description = $"MessagingFactoryCache (serviceUri: {serviceUri})";
 }
コード例 #47
0
ファイル: Retry.cs プロジェクト: Xamla/graph_system
        public static async Task <T> WithPolicyAsync <T>(Func <CancellationToken, Task <T> > block, RetryPolicy policy, CancellationToken cancel = default(CancellationToken))
        {
            for (int retry = 0; ; ++retry)
            {
                cancel.ThrowIfCancellationRequested();

                TimeSpan?delay;
                try
                {
                    return(await block(cancel).ConfigureAwait(false));
                }
                catch (Exception e)
                {
                    delay = policy(e, retry);
                    if (!delay.HasValue)
                    {
                        throw;
                    }
                }

                await Task.Delay(delay.Value, cancel);
            }
        }
コード例 #48
0
 public SqlServerTransientRetryPolicy(RetryPolicy retryPolicy) : base(retryPolicy)
 {
 }
コード例 #49
0
ファイル: Retry.cs プロジェクト: Xamla/graph_system
 public static Task WithPolicyAsync(Func <Task> block, RetryPolicy policy)
 {
     return(WithPolicyAsync <int>(async c => { await block(); return 0; }, policy));
 }
コード例 #50
0
        /// <summary>
        ///   Receives a batch of <see cref="EventData" /> from the Event Hub partition.
        /// </summary>
        ///
        /// <param name="maximumEventCount">The maximum number of messages to receive in this batch.</param>
        /// <param name="maximumWaitTime">The maximum amount of time to wait for events to become available, if no events can be read from the prefetch queue.  If not specified, the per-try timeout specified by the retry policy will be used.</param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        /// <returns>The batch of <see cref="EventData" /> from the Event Hub partition this consumer is associated with.  If no events are present, an empty set is returned.</returns>
        ///
        /// <remarks>
        ///   When events are available in the prefetch queue, they will be used to form the batch as quickly as possible without waiting for additional events from the
        ///   Event Hubs service to try and meet the requested <paramref name="maximumEventCount" />.  When no events are available in prefetch, the receiver will wait up
        ///   to the <paramref name="maximumWaitTime"/> for events to be read from the service.  Once any events are available, they will be used to form the batch immediately.
        /// </remarks>
        ///
        public override async Task <IReadOnlyList <EventData> > ReceiveAsync(int maximumEventCount,
                                                                             TimeSpan?maximumWaitTime,
                                                                             CancellationToken cancellationToken)
        {
            Argument.AssertNotClosed(_closed, nameof(AmqpConsumer));
            Argument.AssertNotClosed(ConnectionScope.IsDisposed, nameof(EventHubConnection));
            Argument.AssertAtLeast(maximumEventCount, 1, nameof(maximumEventCount));

            var receivedEventCount = 0;
            var failedAttemptCount = 0;
            var tryTimeout         = RetryPolicy.CalculateTryTimeout(0);
            var waitTime           = (maximumWaitTime ?? tryTimeout);
            var operationId        = Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture);
            var link              = default(ReceivingAmqpLink);
            var retryDelay        = default(TimeSpan?);
            var receivedEvents    = default(List <EventData>);
            var lastReceivedEvent = default(EventData);

            var stopWatch = ValueStopwatch.StartNew();

            try
            {
                while ((!cancellationToken.IsCancellationRequested) && (!_closed))
                {
                    try
                    {
                        // Creation of the link happens without explicit knowledge of the cancellation token
                        // used for this operation; validate the token state before attempting link creation and
                        // again after the operation completes to provide best efforts in respecting it.

                        EventHubsEventSource.Log.EventReceiveStart(EventHubName, ConsumerGroup, PartitionId, operationId);

                        if (!ReceiveLink.TryGetOpenedObject(out link))
                        {
                            link = await ReceiveLink.GetOrCreateAsync(UseMinimum(ConnectionScope.SessionTimeout, tryTimeout), cancellationToken).ConfigureAwait(false);
                        }

                        cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
                        var messagesReceived = await link.ReceiveMessagesAsync(maximumEventCount, ReceiveBuildBatchInterval, waitTime, cancellationToken).ConfigureAwait(false);

                        // If no messages were received, then just return the empty set.

                        if (messagesReceived == null)
                        {
                            return(EmptyEventSet);
                        }

                        // If event messages were received, then package them for consumption and
                        // return them.

                        foreach (AmqpMessage message in messagesReceived)
                        {
                            receivedEvents ??= new List <EventData>();

                            link.DisposeDelivery(message, true, AmqpConstants.AcceptedOutcome);
                            receivedEvents.Add(MessageConverter.CreateEventFromMessage(message));
                            message.Dispose();

                            receivedEventCount = receivedEvents.Count;
                        }

                        if (receivedEventCount > 0)
                        {
                            lastReceivedEvent = receivedEvents[receivedEventCount - 1];

                            if (lastReceivedEvent.Offset > long.MinValue)
                            {
                                CurrentEventPosition = EventPosition.FromOffset(lastReceivedEvent.Offset, false);
                            }

                            if (TrackLastEnqueuedEventProperties)
                            {
                                LastReceivedEvent = lastReceivedEvent;
                            }
                        }

                        return(receivedEvents ?? EmptyEventSet);
                    }
                    catch (EventHubsException ex) when(ex.Reason == EventHubsException.FailureReason.ServiceTimeout)
                    {
                        // Because the timeout specified with the request is intended to be the maximum
                        // amount of time to wait for events, a timeout isn't considered an error condition,
                        // rather a sign that no events were available in the requested period.

                        return(EmptyEventSet);
                    }
                    catch (Exception ex)
                    {
                        Exception activeEx = ex.TranslateServiceException(EventHubName);

                        // If the partition was stolen determine the correct action to take for
                        // capturing it with respect to whether the consumer should be invalidated.
                        //
                        // In either case, it is a terminal exception and will not trigger a retry;
                        // allow the normal error handling flow to surface the exception.

                        if (ex.IsConsumerPartitionStolenException())
                        {
                            // If the consumer should be invalidated, capture the exception
                            // and force-close the link.  This will ensure that the next operation
                            // will surface it.

                            if (InvalidateConsumerWhenPartitionStolen)
                            {
                                _activePartitionStolenException = ex;
                                CloseConsumerLink(link);
                            }
                            else
                            {
                                // If the consumer should not be invalidated, clear any previously captured exception to avoid
                                // surfacing the failure multiple times.  If the link is stolen after this operation, it will
                                // be intercepted and handled as needed.

                                _activePartitionStolenException = null;
                            }
                        }

                        // Determine if there should be a retry for the next attempt; if so enforce the delay but do not quit the loop.
                        // Otherwise, bubble the exception.

                        ++failedAttemptCount;
                        retryDelay = RetryPolicy.CalculateRetryDelay(activeEx, failedAttemptCount);

                        if ((retryDelay.HasValue) && (!ConnectionScope.IsDisposed) && (!_closed) && (!cancellationToken.IsCancellationRequested))
                        {
                            EventHubsEventSource.Log.EventReceiveError(EventHubName, ConsumerGroup, PartitionId, operationId, activeEx.Message);
                            await Task.Delay(UseMinimum(retryDelay.Value, waitTime.CalculateRemaining(stopWatch.GetElapsedTime())), cancellationToken).ConfigureAwait(false);

                            tryTimeout = RetryPolicy.CalculateTryTimeout(failedAttemptCount);
                        }
                        else if (ex is AmqpException)
                        {
                            ExceptionDispatchInfo.Capture(activeEx).Throw();
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                // If no value has been returned nor exception thrown by this point,
                // then cancellation has been requested.

                throw new TaskCanceledException();
            }
            catch (TaskCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                EventHubsEventSource.Log.EventReceiveError(EventHubName, ConsumerGroup, PartitionId, operationId, ex.Message);
                throw;
            }
            finally
            {
                EventHubsEventSource.Log.EventReceiveComplete(EventHubName, ConsumerGroup, PartitionId, operationId, failedAttemptCount, receivedEventCount);
            }
        }
コード例 #51
0
        void ValidateRetryPolicyBuiltIn()
        {
            String      clientId = "someClientEntity";
            RetryPolicy retry    = RetryPolicy.Default;

            retry.IncrementRetryCount(clientId);
            TimeSpan?firstRetryInterval = retry.GetNextRetryInterval(clientId, new ServerBusyException(string.Empty), TimeSpan.FromSeconds(60));

            Log("firstRetryInterval: " + firstRetryInterval);
            Assert.True(firstRetryInterval != null);

            retry.IncrementRetryCount(clientId);
            TimeSpan?secondRetryInterval = retry.GetNextRetryInterval(clientId, new ServerBusyException(string.Empty), TimeSpan.FromSeconds(60));

            Log("secondRetryInterval: " + secondRetryInterval);

            Assert.True(secondRetryInterval != null);
            Assert.True(secondRetryInterval?.TotalMilliseconds > firstRetryInterval?.TotalMilliseconds);

            retry.IncrementRetryCount(clientId);
            TimeSpan?thirdRetryInterval = retry.GetNextRetryInterval(clientId, new ServerBusyException(string.Empty), TimeSpan.FromSeconds(60));

            Log("thirdRetryInterval: " + thirdRetryInterval);

            Assert.True(thirdRetryInterval != null);
            Assert.True(thirdRetryInterval?.TotalMilliseconds > secondRetryInterval?.TotalMilliseconds);

            retry.IncrementRetryCount(clientId);
            TimeSpan?fourthRetryInterval = retry.GetNextRetryInterval(clientId, new ServerBusyException(string.Empty), TimeSpan.FromSeconds(60));

            Log("fourthRetryInterval: " + fourthRetryInterval);

            Assert.True(fourthRetryInterval != null);
            Assert.True(fourthRetryInterval?.TotalMilliseconds > thirdRetryInterval?.TotalMilliseconds);

            retry.IncrementRetryCount(clientId);
            TimeSpan?fifthRetryInterval = retry.GetNextRetryInterval(clientId, new ServerBusyException(string.Empty), TimeSpan.FromSeconds(60));

            Log("fifthRetryInterval: " + fifthRetryInterval);

            Assert.True(fifthRetryInterval != null);
            Assert.True(fifthRetryInterval?.TotalMilliseconds > fourthRetryInterval?.TotalMilliseconds);

            retry.IncrementRetryCount(clientId);
            TimeSpan?sixthRetryInterval = retry.GetNextRetryInterval(clientId, new ServerBusyException(string.Empty), TimeSpan.FromSeconds(60));

            Log("sixthRetryInterval: " + sixthRetryInterval);

            Assert.True(sixthRetryInterval != null);
            Assert.True(sixthRetryInterval?.TotalMilliseconds > fifthRetryInterval?.TotalMilliseconds);

            retry.IncrementRetryCount(clientId);
            TimeSpan?seventhRetryInterval = retry.GetNextRetryInterval(clientId, new ServerBusyException(string.Empty), TimeSpan.FromSeconds(60));

            Log("seventhRetryInterval: " + seventhRetryInterval);

            Assert.True(seventhRetryInterval != null);
            Assert.True(seventhRetryInterval?.TotalMilliseconds > sixthRetryInterval?.TotalMilliseconds);

            retry.IncrementRetryCount(clientId);
            TimeSpan?nextRetryInterval = retry.GetNextRetryInterval(clientId, new EventHubsException(false), TimeSpan.FromSeconds(60));

            Assert.True(nextRetryInterval == null);

            retry.ResetRetryCount(clientId);
            retry.IncrementRetryCount(clientId);
            TimeSpan?firstRetryIntervalAfterReset = retry.GetNextRetryInterval(clientId, new ServerBusyException(string.Empty), TimeSpan.FromSeconds(60));

            Assert.True(firstRetryInterval.Equals(firstRetryIntervalAfterReset));

            retry = RetryPolicy.NoRetry;
            retry.IncrementRetryCount(clientId);
            TimeSpan?noRetryInterval = retry.GetNextRetryInterval(clientId, new ServerBusyException(string.Empty), TimeSpan.FromSeconds(60));

            Assert.True(noRetryInterval == null);
        }
コード例 #52
0
ファイル: ServerProxy.cs プロジェクト: orf53975/hadoop.net
        protected internal static T CreateRetriableProxy <T>(Configuration conf, UserGroupInformation
                                                             user, YarnRPC rpc, IPEndPoint serverAddress, RetryPolicy retryPolicy)
        {
            System.Type protocol = typeof(T);
            T           proxy    = user.DoAs(new _PrivilegedAction_89(rpc, protocol, serverAddress, conf));

            return((T)RetryProxy.Create(protocol, proxy, retryPolicy));
        }
コード例 #53
0
 public StoppableMessageReceiver(ServiceBusConnection serviceBusConnection, string entityPath, ReceiveMode receiveMode = ReceiveMode.PeekLock, RetryPolicy retryPolicy = null, int prefetchCount = 0) : base(serviceBusConnection, entityPath, receiveMode, retryPolicy, prefetchCount)
 {
 }
コード例 #54
0
 /// <summary>
 /// Initializes request Id as GUID (default), Timeout and the request option as supplied by consumer
 /// </summary>
 /// <param name="timeOut"></param>
 /// <param name="rp"></param>
 public RequestOptions(TimeSpan timeOut, RetryPolicy rp) : this(null, timeOut, rp)
 {
 }
コード例 #55
0
        /// <summary>
        ///   Creates the AMQP link to be used for consumer-related operations.
        /// </summary>
        ///
        /// <param name="consumerGroup">The consumer group of the Event Hub to which the link is bound.</param>
        /// <param name="partitionId">The identifier of the Event Hub partition to which the link is bound.</param>
        /// <param name="consumerIdentifier">The identifier associated with the consumer.</param>
        /// <param name="eventStartingPosition">The place within the partition's event stream to begin consuming events.</param>
        /// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested.</param>
        /// <param name="prefetchSizeInBytes">The cache size of the prefetch queue. When set, the link makes a best effort to ensure prefetched messages fit into the specified size.</param>
        /// <param name="ownerLevel">The relative priority to associate with the link; for a non-exclusive link, this value should be <c>null</c>.</param>
        /// <param name="trackLastEnqueuedEventProperties">Indicates whether information on the last enqueued event on the partition is sent as events are received.</param>
        /// <param name="timeout">The timeout to apply for creating the link.</param>
        /// <param name="cancellationToken">The cancellation token to consider when creating the link.</param>
        ///
        /// <returns>The AMQP link to use for consumer-related operations.</returns>
        ///
        protected async Task <ReceivingAmqpLink> CreateConsumerLinkAsync(string consumerGroup,
                                                                         string partitionId,
                                                                         string consumerIdentifier,
                                                                         EventPosition eventStartingPosition,
                                                                         uint prefetchCount,
                                                                         long?prefetchSizeInBytes,
                                                                         long?ownerLevel,
                                                                         bool trackLastEnqueuedEventProperties,
                                                                         TimeSpan timeout,
                                                                         CancellationToken cancellationToken)
        {
            // Determine if there is an active is an active exception that needs to be surfaced,
            // do so now.
            //
            // Note that this is a benign race; it is possible that multiple threads
            // will observe the active exception and surface it, even if the consumer is not
            // considered invalid.  This is reasonable behavior for this scenario as the underlying
            // condition is itself a race condition between multiple consumers.

            var activeException = _activePartitionStolenException;

            if (activeException != null)
            {
                // If the consumer should not be considered invalid, clear the active exception if
                // it hasn't already been reset.

                if (!InvalidateConsumerWhenPartitionStolen)
                {
                    Interlocked.CompareExchange(ref _activePartitionStolenException, null, activeException);
                }

                EventHubsEventSource.Log.AmqpConsumerLinkCreateCapturedErrorThrow(EventHubName, consumerGroup, partitionId, ownerLevel?.ToString(CultureInfo.InvariantCulture), eventStartingPosition.ToString(), activeException.Message);
                ExceptionDispatchInfo.Capture(activeException).Throw();
            }

            // Create and open the consumer link.

            var link       = default(ReceivingAmqpLink);
            var tryTimeout = RetryPolicy.CalculateTryTimeout(0);

            try
            {
                link = await ConnectionScope.OpenConsumerLinkAsync(
                    consumerGroup,
                    partitionId,
                    eventStartingPosition,
                    tryTimeout,
                    timeout,
                    prefetchCount,
                    prefetchSizeInBytes,
                    ownerLevel,
                    trackLastEnqueuedEventProperties,
                    consumerIdentifier,
                    cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                ExceptionDispatchInfo.Capture(ex.TranslateConnectionCloseDuringLinkCreationException(EventHubName)).Throw();
            }

            return(link);
        }
コード例 #56
0
 /// <summary>
 /// Initializes request Id as GUID (default), Timeout as 60 seconds (default), and the request option
 /// </summary>
 /// <param name="rp">Retry option</param>
 public RequestOptions(RetryPolicy rp) : this(null, TimeSpan.Zero, rp)
 {
 }
コード例 #57
0
 /// <summary>
 /// This is the default constructor.
 /// </summary>
 /// <param name="sasToken">The service bus sas token based connection string.</param>
 /// <param name="receiveMode">The default receive mode.</param>
 /// <param name="retryPolicy">The default retry policy.</param>
 public AzureServiceBusFabricBridge(string sasToken
                                    , ReceiveMode receiveMode = ReceiveMode.PeekLock
                                    , RetryPolicy retryPolicy = null)
     : this(new ServiceBusConnectionStringBuilder(sasToken), receiveMode, retryPolicy)
 {
 }
コード例 #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BotFrameworkAdapter"/> class,
 /// using an application ID and secret.
 /// </summary>
 /// <param name="appId">The application ID of the bot.</param>
 /// <param name="appPassword">The application secret for the bot.</param>
 /// <param name="connectorClientRetryPolicy">Retry policy for retrying HTTP operations.</param>
 /// <param name="httpClient">The HTTP client.</param>
 /// <param name="middleware">The middleware to initially add to the adapter.</param>
 /// <remarks>Use a <see cref="MiddlewareSet"/> object to add multiple middleware
 /// components in the conustructor. Use the <see cref="Use(IMiddleware)"/> method to
 /// add additional middleware to the adapter after construction.
 /// </remarks>
 public BotFrameworkAdapter(string appId, string appPassword, RetryPolicy connectorClientRetryPolicy = null, HttpClient httpClient = null, IMiddleware middleware = null)
     : this(new SimpleCredentialProvider(appId, appPassword), connectorClientRetryPolicy, httpClient, middleware)
 {
 }
コード例 #59
0
 public void GetErrorNumberWithNullExceptionTest()
 {
     Assert.Null(RetryPolicy.GetErrorNumber(null));
 }
コード例 #60
0
 public CatalogController()
 {
     _httpRetryPolicy =
         Policy.HandleResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode)
         .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt) / 2));
 }