public static async Task Insert(CloudTable table) { CustomerEntity customer1 = new CustomerEntity("Harp", "Walters") { Email = "*****@*****.**", PhoneNumber = "425-555-0101" }; CustomerEntity customer2 = new CustomerEntity("Harp", "Ben") { Email = "*****@*****.**", PhoneNumber = "425-555-0102" }; TableBatchOperation batchOperation = new TableBatchOperation(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation = TableOperation.Insert(customer1); batchOperation.Insert(customer1); batchOperation.Insert(customer2); // Execute the insert operation. Incremental retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)); ExponentialBackoff retryStrategy2=new ExponentialBackoff(5,TimeSpan.FromSeconds(1),TimeSpan.FromSeconds(5),TimeSpan.FromSeconds(2)); TimeSpan back = TimeSpan.FromSeconds(31); // Define your retry policy using the retry strategy and the Azure storage // transient fault detection strategy. RetryPolicy<StorageTransientErrorDetectionStrategy> retryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy); RetryPolicy<StorageTransientErrorDetectionStrategy> r = new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy2); // Receive notifications about retries. retryPolicy.Retrying += (sender, args) => { Console.WriteLine("Information"); // Log details of the retry. var msg = String.Format("Retry - Count:{0}, Delay:{1}, Exception:{2}", args.CurrentRetryCount, args.Delay, args.LastException); Console.WriteLine(msg, "Information"); }; try { // Do some work that may result in a transient fault. await retryPolicy.ExecuteAsync( () => table.ExecuteBatchAsync(batchOperation)); } catch (Exception e) { var z = e; } Console.ReadLine(); /* // Create a new customer entity. CustomerEntity customer1 = new CustomerEntity("Harp", "Walters") { Email = "*****@*****.**", PhoneNumber = "425-555-0101" }; CustomerEntity customer2 = new CustomerEntity("Harp", "Ben") { Email = "*****@*****.**", PhoneNumber = "425-555-0102" }; TableBatchOperation batchOperation = new TableBatchOperation(); // Create the TableOperation object that inserts the customer entity. TableOperation insertOperation = TableOperation.Insert(customer1); batchOperation.Insert(customer1); batchOperation.Insert(customer2); // Execute the insert operation. try { IList<TableResult> z = await table.ExecuteBatchAsync(batchOperation); foreach (var i in z) { CustomerEntity y = (CustomerEntity)i.Result; Console.WriteLine(y.PartitionKey); } var x = z; } catch (StorageException e) { var z = e.RequestInformation.HttpStatusCode; var zz = 3; }*/ }
// 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; }
public void MediaServicesCredentialsAcsEndPointCustomRetryPolicy() { string account = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountName; string key = WindowsAzureMediaServicesTestConfiguration.MediaServiceAccountKey; var retryStrategy = new Incremental(1, TimeSpan.FromSeconds(1),TimeSpan.FromSeconds(2)); var errorDetectionStrategy = new ErrorDetectionStrategyForRefreshToken(); MediaServicesCredentials credentials = new MediaServicesCredentials(account, key, WindowsAzureMediaServicesTestConfiguration.MediaServicesAccessScope, new List<string> { "http://dummyacsendpoint" }) { RefreshTokenRetryPolicy = new RetryPolicy(errorDetectionStrategy, retryStrategy) }; Assert.IsNull(credentials.AccessToken); Assert.IsTrue(credentials.TokenExpiration < DateTime.UtcNow); try { credentials.RefreshToken(); } catch (WebException) { Assert.IsTrue(errorDetectionStrategy.Invoked); throw; } }
public void 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; }
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"); }
public EventStore(CloudStorageAccount account, string tableName) { if (account == null) throw new ArgumentNullException("account"); if (tableName == null) throw new ArgumentNullException("tableName"); if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentException("tableName"); this.account = account; this.tableName = tableName; this.tableClient = account.CreateCloudTableClient(); this.tableClient.RetryPolicy = RetryPolicies.NoRetry(); // TODO: This could be injected. var backgroundRetryStrategy = new ExponentialBackoff(10, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(1)); var blockingRetryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); this.pendingEventsQueueRetryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(backgroundRetryStrategy); this.pendingEventsQueueRetryPolicy.Retrying += (s, e) => { var handler = this.Retrying; if (handler != null) { handler(this, EventArgs.Empty); } Trace.TraceWarning("An error occurred in attempt number {1} to access table storage (PendingEventsQueue): {0}", e.LastException.Message, e.CurrentRetryCount); }; this.eventStoreRetryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(blockingRetryStrategy); this.eventStoreRetryPolicy.Retrying += (s, e) => Trace.TraceWarning( "An error occurred in attempt number {1} to access table storage (EventStore): {0}", e.LastException.Message, e.CurrentRetryCount); this.eventStoreRetryPolicy.ExecuteAction(() => tableClient.CreateTableIfNotExist(tableName)); }
public given_a_topic_and_subscription() { System.Diagnostics.Trace.Listeners.Clear(); this.Topic = "cqrsjourney-test-" + Guid.NewGuid().ToString(); this.Subscription = "test-" + Guid.NewGuid().ToString(); var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); this.retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy); // Creates the topic too. this.retryPolicy.ExecuteAction(() => this.Settings.CreateSubscription(this.Topic, this.Subscription)); }
public DynamicModel(string connectionStringName, string tableName = "", string primaryKeyField = "", string descriptorField = "") { TableName = tableName == "" ? this.GetType().Name : tableName; PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField; DescriptorField = descriptorField; var _providerName = "System.Data.SqlClient"; if (ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName != null) _providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName; ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; var strategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)); policy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(strategy); }
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); foreach (var topic in this.settings.Topics) { retryPolicy.ExecuteAction(() => CreateTopicIfNotExists(namespaceManager, topic)); foreach (var subscription in topic.Subscriptions) { retryPolicy.ExecuteAction(() => CreateSubscriptionIfNotExists(namespaceManager, topic, subscription)); } } this.initialized = true; }
public EventStore(CloudStorageAccount account, string tableName) { if (account == null) throw new ArgumentNullException("account"); if (tableName == null) throw new ArgumentNullException("tableName"); if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentException("tableName"); this.account = account; this.tableName = tableName; this.tableClient = account.CreateCloudTableClient(); this.tableClient.RetryPolicy = RetryPolicies.NoRetry(); // TODO: This could be injected. var backgroundRetryStrategy = new ExponentialBackoff(10, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(1)); var blockingRetryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); this.pendingEventsQueueRetryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(backgroundRetryStrategy); this.eventStoreRetryPolicy = new RetryPolicy<StorageTransientErrorDetectionStrategy>(blockingRetryStrategy); this.eventStoreRetryPolicy.ExecuteAction(() => tableClient.CreateTableIfNotExist(tableName)); }
public given_service_bus_config() { System.Diagnostics.Trace.Listeners.Clear(); this.settings = InfrastructureSettings.Read("Settings.xml").ServiceBus; foreach (var topic in this.settings.Topics) { topic.Path = topic.Path + Guid.NewGuid().ToString(); } var tokenProvider = TokenProvider.CreateSharedSecretTokenProvider(this.settings.TokenIssuer, this.settings.TokenAccessKey); var serviceUri = ServiceBusEnvironment.CreateServiceUri(this.settings.ServiceUriScheme, this.settings.ServiceNamespace, this.settings.ServicePath); this.namespaceManager = new NamespaceManager(serviceUri, tokenProvider); var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); this.retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy); this.sut = new ServiceBusConfig(this.settings); Cleanup(); }
// GET api/notification public IEnumerable<NotificationInfo> Get() { var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)); var retryPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(retryStrategy); List<NotificationInfo> notifications = new List<NotificationInfo>(); using (VidPackEntities db = new VidPackEntities()) { retryPolicy.ExecuteAction(() => { db.Database.Connection.Open(); }); notifications = retryPolicy.ExecuteAction<List<NotificationInfo>>(() => db.Notification.Select(item => new NotificationInfo() { NotificationTag = item.NotificationTag, }).ToList<NotificationInfo>() ); } return notifications; }
private static void RetryPolityUsingCode(IUnityContainer container, IService service, OutputWriterService writer) { writer.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<FileSystemTransientErrorDetectionStrategy>(retryStrategy); try { // Do some work that may result in a transient fault. retryPolicy.ExecuteAction(service.DoSlowAndImportantTask); } catch (Exception exception) { // All the retries failed. writer.WriteLine("An Exception has been thrown:\n{0}", exception); } writer.WriteLine("End sample: RetryPolityUsingCode"); }
public void Configure(string collectorName, XElement configElement, ISystemMetricsService systemMetrics) { _completionTask = new Task(() => IsActive = false); _log = SuperCheapIOC.Resolve<ILog>(); _systemMetrics = systemMetrics; var config = new LibratoBackendConfiguration( email: configElement.Attribute("email").Value, token: configElement.Attribute("token").Value, numRetries: configElement.ToInt("numRetries"), retryDelay: Utility.ConvertToTimespan(configElement.Attribute("retryDelay").Value), postTimeout: Utility.ConvertToTimespan(configElement.Attribute("postTimeout").Value), maxBatchSize: configElement.ToInt("maxBatchSize"), countersAsGauges: configElement.ToBoolean("countersAsGauges") ); _config = config; _source = collectorName; _serviceVersion = Assembly.GetEntryAssembly().GetName().Version.ToString(); _preprocessorBlock = new ActionBlock<Bucket>(bucket => ProcessBucket(bucket), Utility.UnboundedExecution()); _batchBlock = new BatchBlock<LibratoMetric>(_config.MaxBatchSize); _outputBlock = new ActionBlock<LibratoMetric[]>(lines => PostToLibrato(lines), Utility.OneAtATimeExecution()); _batchBlock.LinkTo(_outputBlock); _client = new RestClient(LIBRATO_API_URL); _client.Authenticator = new HttpBasicAuthenticator(_config.Email, _config.Token); _client.Timeout = (int)_config.PostTimeout.TotalMilliseconds; _retryPolicy = new RetryPolicy<LibratoErrorDetectionStrategy>(_config.NumRetries); _retryPolicy.Retrying += (sender, args) => { _log.Warn(String.Format("Retry {0} failed. Trying again. Delay {1}, Error: {2}", args.CurrentRetryCount, args.Delay, args.LastException.Message), args.LastException); _systemMetrics.LogCount("backends.librato.retry"); }; _retryStrategy = new Incremental(_config.NumRetries, _config.RetryDelay, TimeSpan.FromSeconds(2)); IsActive = true; }
// GET api/session public IEnumerable<Session> Get(ODataQueryOptions<Session> queryOptions) { var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)); var retryPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy>(retryStrategy); List<Session> session = new List<Session>(); try { using (VidPackEntities db = new VidPackEntities()) { retryPolicy.ExecuteAction(() => { db.Database.Connection.Open(); }); var listSession = retryPolicy.ExecuteAction(() => db.ExistingSession.Include("DownloadItem").Select(item => new { SessionDate = item.SessionDate, SessionDescription = item.SessionDescription, SessionSubTitle = item.SessionSubTitle, SessionThumbnailUrl = item.SessionThumbnailUri, SessionTitle = item.SessionSubTitle, SessionVideoUrl = item.SessionVideoUri == null ? "" : item.SessionVideoUri, Speaker = item.Speaker, isActual = item.IsActualSession, DownloadItem = item.DownloadItem.Select(_ => new { Caption = _.Caption, Description = _.Description, Url = _.Url, }) }).ToList() ); //ToString() / String.Format() is not know within projection session = listSession.Select(item => new Session() { SessionDate = Convert.ToString(item.SessionDate), SessionDescription = item.SessionDescription, SessionSubTitle = item.SessionSubTitle, SessionThumbnailUrl = String.Format("{0}{1}", ThumbnailStorageUrl, item.SessionThumbnailUrl), SessionTitle = item.SessionSubTitle, SessionVideoUrl = item.SessionVideoUrl, Speaker = item.Speaker, SessionDownloadItem = item.DownloadItem.Select(_ => new DownloadItemInfo() { Caption = _.Caption, Description = _.Description, Url = _.Url, }).ToList<DownloadItemInfo>(), }).ToList<Session>(); return session; } } catch (Exception ex) { //TODO: Implement Error Handling return new List<Session>(); } }
public EventProcessor CreateEventProcessor(string topic, string subscription, SubscriptionSettings subscriptionSettings, IEventHandler handler, ITextSerializer serializer, bool instrumentationEnabled = false) { var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); var retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy); var namespaceManager = settings.GetNamespaceManager(); var topicSettings = new TopicSettings { IsEventBus = true, DuplicateDetectionHistoryTimeWindow = new TimeSpan(0, 30, 0), Path = topic }; retryPolicy.ExecuteAction(() => CreateSubscriptionIfNotExists(namespaceManager, topicSettings, subscriptionSettings)); retryPolicy.ExecuteAction(() => UpdateRules(namespaceManager, topicSettings, subscriptionSettings, settings.GetMessagingFactory())); IMessageReceiver receiver; if (subscriptionSettings.RequiresSession) { var instrumentation = new SessionSubscriptionReceiverInstrumentation(subscription, instrumentationEnabled); try { receiver = (IMessageReceiver)new SessionSubscriptionReceiver(this.settings, topic, subscription, true, instrumentation); } catch { instrumentation.Dispose(); throw; } } else { var instrumentation = new SubscriptionReceiverInstrumentation(subscription, instrumentationEnabled); try { receiver = (IMessageReceiver)new SubscriptionReceiver(this.settings, topic, subscription, true, instrumentation); } catch { instrumentation.Dispose(); throw; } } EventProcessor processor; try { processor = new EventProcessor(receiver, serializer); } catch { using (receiver as IDisposable) { } throw; } try { processor.Register(handler); return processor; } catch { processor.Dispose(); throw; } }
private void InitialiseRetryHandling() { _retryStrategy = new Incremental(_retries, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2)); _retryPolicy = new RetryPolicy<SqlServerErrorDetectionStrategy>(_retries); _retryPolicy.Retrying += (sender, args) => { _log.Warn(String.Format("Retry {0} failed. Trying again. Delay {1}, Error: {2}", args.CurrentRetryCount, args.Delay, args.LastException.Message), args.LastException); _systemMetrics.LogCount("backends.sqlserver.retry"); }; }
public void RegisterTopicsAndSubscriptions(List<TopicSettings> topics) { var namespaceManager = settings.GetNamespaceManager(); var retryStrategy = new Incremental(3, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1)); var retryPolicy = new RetryPolicy<ServiceBusTransientErrorDetectionStrategy>(retryStrategy); 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, settings.GetMessagingFactory())); }); }); // Execute migration support actions only after all the previous ones have been completed. foreach (var topic in topics) { foreach (var action in topic.MigrationSupport) { retryPolicy.ExecuteAction(() => UpdateSubscriptionIfExists(namespaceManager, topic, action, settings.GetMessagingFactory())); } } }