Пример #1
0
        public void RetriesToExecuteActionWhenSqlExceptionDuringCommandExecution()
        {
            RetryManager.SetDefault(this.retryPolicySettings.BuildRetryManager(), false);
            var connectionString   = ConfigurationManager.ConnectionStrings["TestDatabase"].ConnectionString;
            var reliableConnection = new ReliableSqlConnection(connectionString);

            int count = 0;

            try
            {
                var retryPolicy = this.retryManager.GetRetryPolicy <SqlDatabaseTransientErrorDetectionStrategy>("Retry 5 times");

                retryPolicy.ExecuteAction(() =>
                {
                    SqlCommand command = new SqlCommand("FAIL");
                    count = reliableConnection.ExecuteCommand(command);
                });

                Assert.AreEqual(-1, count);
            }
            catch (SqlException)
            {
                Assert.AreEqual <ConnectionState>(ConnectionState.Closed, reliableConnection.Current.State);
            }
            catch (Exception)
            {
                Assert.Fail();
            }
        }
Пример #2
0
        public void ExecutesXmlReaderWithRetryPolicy()
        {
            RetryManager.SetDefault(this.retryPolicySettings.BuildRetryManager(), false);
            var connectionString   = ConfigurationManager.ConnectionStrings["TestDatabase"].ConnectionString;
            var reliableConnection = new ReliableSqlConnection(connectionString);

            XmlReader reader;
            int       count = 0;

            try
            {
                var retryPolicy = this.retryManager.GetRetryPolicy <SqlDatabaseTransientErrorDetectionStrategy>("Retry 5 times");

                retryPolicy.ExecuteAction(() =>
                {
                    SqlCommand command = new SqlCommand("SELECT 1 FOR XML AUTO", reliableConnection.Current);
                    reader             = command.ExecuteXmlReaderWithRetry(retryPolicy);

                    while (reader.Read())
                    {
                        reader.MoveToFirstAttribute();
                        reader.ReadAttributeValue();
                        count = reader.ReadContentAsInt();
                    }
                });

                Assert.AreEqual(1, count);
            }
            catch (SqlException)
            { }
            catch (Exception)
            {
                Assert.Fail();
            }
        }
Пример #3
0
        public void ExecutesNonQuerySqlCommandWithConnectionRetryPolicyAndSqlCommandRetryPolicy()
        {
            RetryManager.SetDefault(this.retryPolicySettings.BuildRetryManager(), false);
            var connectionString   = ConfigurationManager.ConnectionStrings["TestDatabase"].ConnectionString;
            var reliableConnection = new ReliableSqlConnection(connectionString);

            int count = 0;

            try
            {
                var retryPolicy = this.retryManager.GetRetryPolicy <SqlDatabaseTransientErrorDetectionStrategy>("Retry 5 times");

                retryPolicy.ExecuteAction(() =>
                {
                    SqlCommand command = new SqlCommand("SELECT 1", reliableConnection.Current);
                    count = (int)command.ExecuteNonQueryWithRetry(retryPolicy, retryPolicy);
                });

                Assert.AreEqual(-1, count);
            }
            catch (SqlException)
            { }
            catch (Exception)
            {
                Assert.Fail();
            }
        }
Пример #4
0
        public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace)
        {
            SelectionData state = null;
            SegmentedList <HistoryMemento> actions = new SegmentedList <HistoryMemento>();

            if (!historyWorkspace.Selection.IsEmpty)
            {
                state = historyWorkspace.Selection.Save();
                HistoryMemento memento3 = new DeselectFunction().Execute(historyWorkspace);
                actions.Add(memento3);
            }
            ReplaceDocumentHistoryMemento item = new ReplaceDocumentHistoryMemento(null, null, historyWorkspace);

            actions.Add(item);
            CompoundHistoryMemento memento2 = new CompoundHistoryMemento(StaticName, PdnResources.GetImageResource("Icons.MenuImageFlattenIcon.png"), actions);
            Document document = RetryManager.RunMemorySensitiveOperation <Document>(() => historyWorkspace.Document.Flatten());

            base.EnterCriticalRegion();
            historyWorkspace.Document = document;
            if (state != null)
            {
                SelectionHistoryMemento newHA = new SelectionHistoryMemento(null, null, historyWorkspace);
                historyWorkspace.Selection.Restore(state);
                memento2.AddMemento(newHA);
            }
            return(memento2);
        }
Пример #5
0
        public async Task <SessionInfo> GetResourceInfo(SessionAttachInfo attachInfo, TimeSpan timeout)
        {
            this.client.InnerChannel.OperationTimeout = timeout;
            RetryManager retry = SoaHelper.GetDefaultExponentialRetryManager();

            SessionInfo info;
            DateTime    startTime = DateTime.Now;

            if (attachInfo.TransportScheme == TransportScheme.Http)
            {
                info = Utility.BuildSessionInfoFromDataContract(
                    await RetryHelper <SessionInfoContract> .InvokeOperationAsync(
                        async() => await this.client.GetInfoAsync(SessionLauncherClient.HttpsEndpointPrefix, attachInfo.SessionId).ConfigureAwait(false),
                        (e, r) =>
                {
                    var remainingTime = GetRemainingTime(timeout, startTime);
                    if ((e is EndpointNotFoundException || (e is CommunicationException && !(e is FaultException <SessionFault>))) && remainingTime > TimeSpan.Zero)
                    {
                        Utility.SafeCloseCommunicateObject(this.client);
                        this.client = new SessionLauncherClient(attachInfo, this.binding);
                        this.client.InnerChannel.OperationTimeout = remainingTime;
                    }
                    else
                    {
                        r.MaxRetryCount = 0;
                    }

                    return(Task.CompletedTask);
                },
                        retry)
                    .ConfigureAwait(false));
            }
            else
            {
                info = Utility.BuildSessionInfoFromDataContract(
                    await RetryHelper <SessionInfoContract> .InvokeOperationAsync(
                        async() => await this.client.GetInfoAsync(SessionLauncherClient.EndpointPrefix, attachInfo.SessionId).ConfigureAwait(false),
                        (e, r) =>
                {
                    var remainingTime = GetRemainingTime(timeout, startTime);

                    if ((e is EndpointNotFoundException || (e is CommunicationException && !(e is FaultException <SessionFault>))) && remainingTime > TimeSpan.Zero)
                    {
                        Utility.SafeCloseCommunicateObject(this.client);
                        this.client = new SessionLauncherClient(attachInfo, this.binding);
                        this.client.InnerChannel.OperationTimeout = remainingTime;
                    }
                    else
                    {
                        r.MaxRetryCount = 0;
                    }

                    return(Task.CompletedTask);
                },
                        retry)
                    .ConfigureAwait(false));
            }

            return(info);
        }
Пример #6
0
        /// <summary>
        /// Gets SOA configurations
        /// </summary>
        /// <param name="keys">indicating the keys</param>
        /// <returns>returns the values</returns>
        public async Task <Dictionary <string, string> > GetSOAConfigurations(List <string> keys)
        {
            RetryManager retry = SoaHelper.GetDefaultExponentialRetryManager();

            return(await RetryHelper <Dictionary <string, string> > .InvokeOperationAsync(
                       async() =>
            {
                using (BrokerIdentity identity = new BrokerIdentity())
                {
                    identity.Impersonate();
                    return await this.sessionLauncherClient.Value.GetSOAConfigurationsAsync(keys);
                }
            },
                       async (e, r) =>
            {
                TraceHelper.TraceEvent(
                    TraceEventType.Warning,
                    "[SchedulerHelper] Failed to get SOA configuration, Key:{0}, Retry:{1}, Error:{2}",
                    string.Join(",", keys),
                    r.RetryCount,
                    e);
                await this.RenewSessionLauncherClientAsync();
            },
                       retry));
        }
 static RetryPolicyFactory()
 {
     var strategy = new FixedInterval("fixed", 10, TimeSpan.FromSeconds(3));
     var strategies = new List<RetryStrategy> { strategy };
     var manager = new RetryManager(strategies, "fixed");
     RetryManager.SetDefault(manager);
 }
    public void RetryConfigurationTest()
    {
        RetryManager retryManager = RetryConfiguration.GetRetryManager();

        Assert.IsNotNull(retryManager);

        try
        {
            retryManager = RetryConfiguration.GetRetryManager("app.ini");
            Assert.Fail();
        }
        catch (ArgumentException exception)
        {
            Trace.WriteLine(exception);
        }

        try
        {
            retryManager = RetryConfiguration.GetRetryManager("app.json");
            Assert.Fail();
        }
        catch (ArgumentException exception)
        {
            Trace.WriteLine(exception);
        }

        try
        {
            retryManager = RetryConfiguration.GetRetryManager("app.xml");
            Assert.Fail();
        }
        catch (ArgumentException exception)
        {
            Trace.WriteLine(exception);
        }

        IDictionary <string, RetryStrategy> retryStrategies;

        try
        {
            retryStrategies = RetryConfiguration.GetRetryStrategies();
            Assert.Fail();
        }
        catch (ArgumentException exception)
        {
            Trace.WriteLine(exception);
        }

        retryStrategies = RetryConfiguration.GetRetryStrategies("app.ini");
        Assert.IsNotNull(retryStrategies);
        Assert.IsTrue(retryStrategies.Count > 0);

        retryStrategies = RetryConfiguration.GetRetryStrategies("app.json");
        Assert.IsNotNull(retryStrategies);
        Assert.IsTrue(retryStrategies.Count > 0);

        retryStrategies = RetryConfiguration.GetRetryStrategies("app.xml");
        Assert.IsNotNull(retryStrategies);
        Assert.IsTrue(retryStrategies.Count > 0);
    }
Пример #9
0
        /// <summary>
        /// Log authentication errors, reauthorization events and request errors
        /// </summary>
        /// <param name="logger"></param>
        /// <returns></returns>
        public Client SetLogger(ISwiftLogger logger)
        {
            _logger = logger;
            RetryManager.SetLogger(logger);

            return(this);
        }
Пример #10
0
        public void TransactionsCanBeOpenedInParallel()
        {
            // Clear the retry manager as one of the things this test tests
            // is a race condition setting the retry manager when RetryManager.Instance is called
            RetryManager.SetDefault(null, false);

            Enumerable.Range(0, 5)
            .AsParallel()
            .WithDegreeOfParallelism(10)
            .ForAll(
                x =>
            {
                try
                {
                    using var trn = Store.BeginTransaction(name: "Transaction " + x);
                    Console.WriteLine($"Transaction {x}: Opened");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Transaction {x}: Failed {e.Message}");
                    throw;
                }
            }
                );
        }
        private static RetryManager GetDefaultRetryManager()
        {
            const int retryCount = 4;
            const int minBackoffDelayMilliseconds = 2000;
            const int maxBackoffDelayMilliseconds = 8000;
            const int deltaBackoffMilliseconds    = 2000;

            var exponentialBackoffStrategy =
                new ExponentialBackoff(
                    "exponentialBackoffStrategy",
                    retryCount,
                    TimeSpan.FromMilliseconds(minBackoffDelayMilliseconds),
                    TimeSpan.FromMilliseconds(maxBackoffDelayMilliseconds),
                    TimeSpan.FromMilliseconds(deltaBackoffMilliseconds)
                    );

            var manager = new RetryManager(
                new List <RetryStrategy>
            {
                exponentialBackoffStrategy
            },
                exponentialBackoffStrategy.Name
                );

            return(manager);
        }
        protected override void Arrange()
        {
            this.defaultStrategy = new FixedIntervalRetryStrategy("default", 5, TimeSpan.FromMilliseconds(10));
            this.otherStrategy   = new IncrementalRetryStrategy("other", 5, TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(10));
            this.defaultSqlConnectionStrategy = new FixedIntervalRetryStrategy("defaultSqlConnection", 5, TimeSpan.FromMilliseconds(10));
            this.defaultSqlCommandStrategy    = new FixedIntervalRetryStrategy("defaultSqlCommand", 5, TimeSpan.FromMilliseconds(10));

            this.managerWithAllDefaults = new RetryManager(
                new[]
            {
                this.defaultStrategy,
                this.defaultSqlConnectionStrategy,
                this.defaultSqlCommandStrategy,
                this.otherStrategy,
            },
                "default",
                new Dictionary <string, string>
            {
                { "SQL", "defaultSqlCommand" },
                { "SQLConnection", "defaultSqlConnection" },
            });

            this.managerWithOnlyDefault = new RetryManager(
                new[]
            {
                this.defaultStrategy,
                this.defaultSqlConnectionStrategy,
                this.defaultSqlCommandStrategy,
                this.otherStrategy,
            },
                "default");
        }
Пример #13
0
        public DatabaseConnections()
        {
            _masterDatabaseName   = "master";
            _platformDatabaseName = "Platform";
            _accountsDatabaseName = "Accounts";
            //_membershipTableName = ""; // <-- Set based on Account Partition
            //_accountDatabasePartitionName = ""; //< -- Set based on user
            //_inventoryUserName = ""; //< -- Set based on user

            //Retry Policies=================================
            // Get an instance of the RetryManager class.
            //var retryManager = EnterpriseLibraryContainer.Current.GetInstance<RetryManager>();

            // Create a retry policy that uses a default retry strategy from the
            // configuration.
            retryPolicy = new RetryPolicy <DefaultRetryStrategy>(5, new TimeSpan(0, 0, 3));

            var retryInterval = TimeSpan.FromSeconds(3);
            var strategy      = new FixedInterval("fixed", 4, retryInterval);
            var strategies    = new List <RetryStrategy> {
                strategy
            };
            var manager = new RetryManager(strategies, "fixed");

            RetryManager.SetDefault(manager);
        }
Пример #14
0
        public void Execute()
        {
            var publisher = new PublishingWebService(output,
                                                     webServiceRootUrl,
                                                     webServiceControllerPath,
                                                     webServiceLogin,
                                                     webServicePassword);
            var slacker = new SlackService(output, slackIntegrationSubUrl);

            var binDir = new DirectoryInfo(packageBinPath);

            var targetVersionDatFile = new FileInfo(Path.Combine(binDir.FullName, "version.dat"));

            File.WriteAllText(targetVersionDatFile.FullName, version.ConvertIntoVersionDatContents());

            var zipper  = new FastZip();
            var zipFile = new FileInfo(Path.Combine(tempDir, string.Format("{0}.zip", BuildFileName())));

            zipper.CreateZip(zipFile.FullName, binDir.FullName, true, null);

            RetryManager.AutoRetry(() => publisher.Publish(zipFile, version.BuildCode, version.BuildNumber));
            output.Write("Publishing operation completed.");

            RetryManager.AutoRetry(
                () => slacker.SendMessage(string.Format("Published {0} to {1}", BuildFileName(), webServiceRootUrl)));
        }
Пример #15
0
 private void InitRetryPolicy()
 {
     // Get an instance of the RetryManager class.
     _retryManager    = _retryManager ?? RetryPolicyFactory.CreateDefault();
     _connRetryPolicy = _retryManager.GetDefaultSqlConnectionRetryPolicy();
     _cmdRetryPolicy  = _retryManager.GetDefaultSqlCommandRetryPolicy();
 }
Пример #16
0
        public async Task FreeResource(SessionStartInfo startInfo, string sessionId)
        {
            try
            {
                if (!sessionId.Equals("0"))
                {
                    RetryManager retry = SoaHelper.GetDefaultExponentialRetryManager();

                    await RetryHelper <object> .InvokeOperationAsync(
                        async() =>
                    {
                        await this.client.TerminateAsync(sessionId).ConfigureAwait(false);
                        return(null);
                    },
                        (e, r) =>
                    {
                        if (e is EndpointNotFoundException)
                        {
                            Utility.SafeCloseCommunicateObject(this.client);
                            this.client = new SessionLauncherClient(startInfo, this.binding);
                        }
                        else
                        {
                            r.MaxRetryCount = 0;
                        }
                        return(Task.CompletedTask);
                    },
                        retry).ConfigureAwait(false);
                }
            }
            catch
            {
                // if terminate the session failed, then do nothing here.
            }
        }
Пример #17
0
        /// <summary>
        /// Gets the custom broker registration from service registration file
        /// </summary>
        /// <param name="serviceRegistrationPath">indicating the path of the service registration file</param>
        /// <returns>returns the instance of CustomBrokerRegistration class</returns>
        private static CustomBrokerRegistration GetCustomBroker(string serviceRegistrationPath)
        {
            try
            {
                ExeConfigurationFileMap map = new ExeConfigurationFileMap();
                map.ExeConfigFilename = serviceRegistrationPath;
                Configuration config = null;
                RetryManager.RetryOnceAsync(
                    () => config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None),
                    TimeSpan.FromSeconds(1),
                    ex => ex is ConfigurationErrorsException)
                .GetAwaiter()
                .GetResult();
                BrokerConfigurations brokerConfig = BrokerConfigurations.GetSectionGroup(config);
                if (brokerConfig == null)
                {
                    return(null);
                }
                else
                {
                    return(brokerConfig.CustomBroker);
                }
            }
            catch (ConfigurationErrorsException e)
            {
                ThrowHelper.ThrowSessionFault(SOAFaultCode.ConfigFile_Invalid,
                                              "{0}",
                                              e.ToString());

                return(null);
            }
        }
    /// <summary>
    /// Creates a retry manager from the system configuration.
    /// </summary>
    /// <returns></returns>
    public static RetryManager CreateDefault(
        string configurationFile = RetryConfiguration.DefaultConfigurationFile, string configurationKey = nameof(RetryManager), Func <IConfigurationSection, RetryStrategy>?getCustomRetryStrategy = null)
    {
        RetryManager manager = RetryConfiguration.GetRetryManager(configurationFile.NotNullOrEmpty(), configurationKey.NotNullOrEmpty(), getCustomRetryStrategy);

        RetryManager.SetDefault(manager);
        return(manager);
    }
Пример #19
0
 public static RetryPolicy GetRetryPolicy(this RetryManager retryManager)
 {
     if (retryManager == null)
     {
         throw new ArgumentNullException("retryManager");
     }
     return(retryManager.GetRetryPolicy <AcceptAllErrorsDetectionStrategy>());
 }
 public AzureActivityRepository()
 {
     // set up retry strategy [EnterpriseLibrary Transient Fault Handling Block]
     var strategy = new FixedInterval("fixed", 10, TimeSpan.FromSeconds(3));
     var strategies = new List<RetryStrategy> { strategy };
     var manager = new RetryManager(strategies, "fixed");
     RetryManager.SetDefault(manager, false);
 }
Пример #21
0
        /// <summary>
        /// Returns the default retry policy dedicated to handling transient conditions with Npgsql commands.
        /// </summary>
        /// <returns>The retry policy for Npgsql commands with the corresponding default strategy (or the default strategy, if no retry strategy assigned to Npgsql commands was found).</returns>
        public static RetryPolicy GetDefaultNpgsqlCommandRetryPolicy(this RetryManager retryManager)
        {
            if (retryManager == null)
            {
                throw new ArgumentNullException("retryManager");
            }

            return(new RetryPolicy(new PostgreSqlDatabaseTransientErrorDetectionStrategy(), retryManager.GetDefaultNpgsqlCommandRetryStrategy()));
        }
        /// <summary>
        /// Returns the default retry strategy for Oracle commands.
        /// </summary>
        /// <returns>The default retry strategy for Oracle commands (or the default strategy, if no default could be found).</returns>
        public static RetryStrategy GetDefaultOracleCommandRetryStrategy(this RetryManager retryManager)
        {
            if (retryManager == null)
            {
                throw new ArgumentNullException("retryManager");
            }

            return(retryManager.GetDefaultRetryStrategy(DefaultStrategyCommandTechnologyName));
        }
        /// <summary>
        /// Returns the default retry policy dedicated to handling transient conditions with Oracle connections.
        /// </summary>
        /// <returns>The retry policy for Oracle connections with the corresponding default strategy (or the default strategy, if no retry strategy for Oracle connections was found).</returns>
        public static RetryPolicy GetDefaultOracleConnectionRetryPolicy(this RetryManager retryManager)
        {
            if (retryManager == null)
            {
                throw new ArgumentNullException("retryManager");
            }

            return(new RetryPolicy(new OracleDatabaseTransientErrorDetectionStrategy(), retryManager.GetDefaultOracleConnectionRetryStrategy()));
        }
            /// <summary>
            /// Sets the specified retry manager as the default retry manager.
            /// </summary>
            /// <param name="retryManager">The retry manager.</param>
            /// <param name="throwIfSet">true to throw an exception if the manager is already set; otherwise, false. Defaults to <see langword="true"/>.</param>
            /// <exception cref="InvalidOperationException">The singleton is already set and <paramref name="throwIfSet"/> is true.</exception>
            public static void SetDefault(RetryManager retryManager, bool throwIfSet = true)
            {
                if (s_defaultRetryManager != null && throwIfSet && retryManager != s_defaultRetryManager)
                {
                    throw new InvalidOperationException(Resources.ExceptionRetryManagerAlreadySet);
                }

                s_defaultRetryManager = retryManager;
            }
Пример #25
0
        static RetryPolicyFactory()
        {
            var strategy   = new FixedInterval("fixed", 10, TimeSpan.FromSeconds(3));
            var strategies = new List <RetryStrategy> {
                strategy
            };
            var manager = new RetryManager(strategies, "fixed");

            RetryManager.SetDefault(manager);
        }
Пример #26
0
        /// <summary>
        /// Initialize the Sql Azure settings and connections
        /// </summary>
        public void InitializeSqlAzure()
        {
            this.SqlConnectionString = ConfigurationManager.AppSettings["SqlAzureConnectionString"];
            if (String.IsNullOrWhiteSpace(this.SqlConnectionString))
            {
                throw new ArgumentException("A required AppSetting cannot be null or empty", "SqlAzureConnectionString");
            }

            this.SqlTableName = ConfigurationManager.AppSettings["SqlAzureTableName"];
            if (String.IsNullOrWhiteSpace(this.SqlTableName))
            {
                throw new ArgumentException("A required AppSetting cannot be null or empty", "SqlAzureTableName");
            }

            var columns = ConfigurationManager.AppSettings["SqlAzureTableColumns"];

            if (String.IsNullOrWhiteSpace(columns))
            {
                throw new ArgumentException("A required AppSetting cannot be null or empty", "SqlAzureTableColumns");
            }

            this.SqlTableColumns = columns.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries).Select(c => c.Trim()).ToList();

            //Reference: https://msdn.microsoft.com/en-us/library/azure/dn864744.aspx
            //1. Define an Exponential Backoff retry strategy for Azure SQL Database throttling (ExponentialBackoff Class). An exponential back-off strategy will gracefully back off the load on the service.
            int retryCount = 4;
            int minBackoffDelayMilliseconds = 2000;
            int maxBackoffDelayMilliseconds = 8000;
            int deltaBackoffMilliseconds    = 2000;

            ExponentialBackoff exponentialBackoffStrategy =
                new ExponentialBackoff("exponentialBackoffStrategy",
                                       retryCount,
                                       TimeSpan.FromMilliseconds(minBackoffDelayMilliseconds),
                                       TimeSpan.FromMilliseconds(maxBackoffDelayMilliseconds),
                                       TimeSpan.FromMilliseconds(deltaBackoffMilliseconds));

            //2. Set a default strategy to Exponential Backoff.
            RetryManager manager = new RetryManager(
                new List <RetryStrategy>
            {
                exponentialBackoffStrategy
            },
                "exponentialBackoffStrategy");

            //3. Set a default Retry Manager. A RetryManager provides retry functionality, or if you are using declarative configuration, you can invoke the RetryPolicyFactory.CreateDefault
            RetryManager.SetDefault(manager);

            //4. Define a default SQL Connection retry policy and SQL Command retry policy. A policy provides a retry mechanism for unreliable actions and transient conditions.
            ConnectionRetryPolicy = manager.GetDefaultSqlConnectionRetryPolicy();
            CommandRetryPolicy    = manager.GetDefaultSqlCommandRetryPolicy();

            //5. Create a function that will retry the connection using a ReliableSqlConnection.
            InitializeSqlAzureConnection();
        }
Пример #27
0
        static void RetryTest()
        {
            int    count  = 0;
            Action action = () =>
            {
                count++;
                throw new Exception("123");
            };

            RetryManager.AutoRetry(action);
        }
Пример #28
0
        public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace)
        {
            GeometryList cachedClippingMask = historyWorkspace.Selection.GetCachedClippingMask();

            if (historyWorkspace.Selection.IsEmpty || (cachedClippingMask.Bounds.Area < 1.0))
            {
                return(null);
            }
            Document document = historyWorkspace.Document;
            List <HistoryMemento> mementos   = new List <HistoryMemento>(document.Layers.Count);
            RectInt32             b          = cachedClippingMask.Bounds.GetInt32Bound(1E-05);
            RectInt32             sourceRect = RectInt32.Intersect(document.Bounds(), b);
            Document document2 = new Document(sourceRect.Width, sourceRect.Height);

            document2.ReplaceMetadataFrom(document);
            RectInt32 rect = new RectInt32(0, 0, sourceRect.Width, sourceRect.Height);
            IRenderer <ColorAlpha8> cachedClippingMaskRenderer = historyWorkspace.Selection.GetCachedClippingMaskRenderer(historyWorkspace.ToolSettings.Selection.RenderingQuality.Value);
            IRenderer <ColorAlpha8> newClipMaskRenderer        = new ClippedRenderer <ColorAlpha8>(cachedClippingMaskRenderer, sourceRect);
            SelectionHistoryMemento item = new SelectionHistoryMemento(null, null, historyWorkspace);

            mementos.Add(item);
            base.EnterCriticalRegion();
            int count = document.Layers.Count;

            while (document.Layers.Count > 0)
            {
                BitmapLayer layer          = (BitmapLayer)document.Layers[0];
                Surface     croppedSurface = layer.Surface.CreateWindow(sourceRect);
                BitmapLayer newLayer       = RetryManager.RunMemorySensitiveOperation <BitmapLayer>(() => new BitmapLayer(croppedSurface));
                newLayer.LoadProperties(layer.SaveProperties());
                HistoryMemento deleteLayerMemento = new DeleteLayerFunction(0).Execute(historyWorkspace);
                mementos.Add(deleteLayerMemento);
                Task task = Task.Factory.StartNew(delegate {
                    deleteLayerMemento.Flush();
                }, TaskCreationOptions.LongRunning);
                Parallel.ForEach <RectInt32>(rect.GetTiles(TilingStrategy.Tiles, 7), delegate(RectInt32 newTileRect) {
                    ISurface <ColorBgra> surface = newLayer.Surface.CreateWindow(newTileRect);
                    IRenderer <ColorAlpha8> mask = new ClippedRenderer <ColorAlpha8>(newClipMaskRenderer, newTileRect);
                    surface.MultiplyAlphaChannel(mask);
                });
                document2.Layers.Add(newLayer);
                task.Wait();
                if (document2.Layers.Count > count)
                {
                    ExceptionUtil.ThrowInternalErrorException("newDocument.Layers.Count > oldLayerCount");
                }
            }
            ReplaceDocumentHistoryMemento memento2 = new ReplaceDocumentHistoryMemento(null, null, historyWorkspace);

            mementos.Add(memento2);
            historyWorkspace.Document = document2;
            return(HistoryMemento.Combine(HistoryMementoName, HistoryMementoImage, mementos));
        }
Пример #29
0
        public static void LoadConfigSqlRetry()
        {
            if (gbInitialized)
            {
                return;
            }
            lock (goLock)
            {
                if (gbInitialized)
                {
                    return;
                }

                int      connRetries      = 3;
                TimeSpan connMinBackoff   = TimeSpan.FromSeconds(5);
                TimeSpan connMaxBackoff   = TimeSpan.FromSeconds(10);
                TimeSpan connDeltaBackoff = TimeSpan.FromSeconds(2);

                int      commRetries      = 3;
                TimeSpan commMinBackoff   = TimeSpan.FromSeconds(5);
                TimeSpan commMaxBackoff   = TimeSpan.FromSeconds(10);
                TimeSpan commDeltaBackoff = TimeSpan.FromSeconds(2);

                RetryStrategy retryStrategyConnection = new ExponentialBackoff(
                    ConnectionStrategyName,
                    connRetries,
                    connMinBackoff,
                    connMaxBackoff,
                    connDeltaBackoff);

                RetryStrategy retryStrategyCommand = new ExponentialBackoff(
                    CommandStrategyName,
                    commRetries,
                    commMinBackoff,
                    commMaxBackoff,
                    commDeltaBackoff);

                var dictApplications = new Dictionary <string, string>
                {
                    { RetryManagerSqlExtensions.DefaultStrategyConnectionTechnologyName, retryStrategyConnection.Name },
                    { RetryManagerSqlExtensions.DefaultStrategyCommandTechnologyName, retryStrategyCommand.Name }
                };

                var retryManager = new RetryManager(
                    new[] { retryStrategyConnection, retryStrategyCommand },
                    retryStrategyCommand.Name,
                    dictApplications);

                RetryManager.SetDefault(retryManager, false);

                gbInitialized = true;
            }
        }
Пример #30
0
        private static void InitializeRetryPolicies()
        {
            if (RetryManager == null)
            {
                RetryManager = EnterpriseLibraryContainer.Current.GetInstance <RetryManager>();
            }

            if (StorageRetryPolicy == null)
            {
                StorageRetryPolicy = RetryManager.GetDefaultAzureStorageRetryPolicy();
            }
        }
Пример #31
0
        public override HistoryMemento OnExecute(IHistoryWorkspace historyWorkspace)
        {
            BitmapLayer layer  = RetryManager.RunMemorySensitiveOperation <BitmapLayer>(() => new BitmapLayer(historyWorkspace.Document.Width, historyWorkspace.Document.Height));
            string      format = PdnResources.GetString("AddNewBlankLayer.LayerName.Format");

            layer.Name = string.Format(format, (1 + historyWorkspace.Document.Layers.Count).ToString());
            int layerIndex = historyWorkspace.ActiveLayerIndex + 1;
            NewLayerHistoryMemento memento = new NewLayerHistoryMemento(PdnResources.GetString("AddNewBlankLayer.HistoryMementoName"), PdnResources.GetImageResource("Icons.MenuLayersAddNewLayerIcon.png"), historyWorkspace, layerIndex);

            base.EnterCriticalRegion();
            historyWorkspace.Document.Layers.Insert(layerIndex, layer);
            return(memento);
        }
Пример #32
0
        /// <summary>
        /// Resolve the session node from the context with infinite retries
        /// </summary>
        /// <returns>The resolved session node name</returns>
        private async Task <string> ResolveSessionNodeWithRetries()
        {
            RetryManager retry = SoaHelper.GetDefaultInfinitePeriodRertyManager();

            return(await RetryHelper <string> .InvokeOperationAsync(
                       async() => await this.context.ResolveSessionLauncherNodeAsync(),
                       async (e, r) =>
            {
                TraceHelper.TraceWarning("0", "[SchedulerHelper] Failed to ResolveSessionLauncherNodeAsync: {0}\nRetryCount = {1}", e, r.RetryCount);
                await Task.CompletedTask;
            },
                       retry));
        }
Пример #33
0
 public void ExecuteAsync_Action_ForceThrowException()
 {
     try
     {
         var retryPolicy = new Mock<IRetryPolicy>();
         retryPolicy.Setup(policy => policy.ShouldRetryAfter(It.IsAny<Exception>())).Returns(false);
         var localRetryManager = new RetryManager(retryPolicy.Object);
         localRetryManager.ExecuteAsync((Action)(() => { throw new Exception(); }), CancellationToken.None, (attempt, nextDelay) => { }, this.executionPolicy).Wait();
     }
     catch (Exception)
     {
         Assert.AreEqual(0, this.executionPolicy.CurrentAttempt);
         throw;
     }
 }
Пример #34
0
        static void Main(string[] args)
        {
            var bus = new Bus(new Dispatcher.Dispatcher());
            var printers = new[] { new Printer(bus, 1), new Printer(bus, 2), new Printer(bus, 3), new Printer(bus, 4) };

            var printerPool = printers
                .Select(printer => new WideningHandler<PrintJob, Message>(printer))
                .Select(printer => new QueuedHandler(printer, bus) { MaxQueueLength = 1 })
                .ToArray();

            var refillPool = printers
                .Select(printer => new WideningHandler<RefillPaper, Message>(printer))
                .Select(printer => new QueuedHandler(printer, bus) { MaxQueueLength = 1 })
                .ToArray();

            foreach (var printer in refillPool)
            {
                bus.Subscribe<RefillPaper>(new NarrowingHandler<RefillPaper, Message>(printer));
                // subscribe the printer directly to RefillPaper as we don't want to distribute that with the print jobs
            }

            var office = Enumerable.Range(0, 50)
                .Select(i => new Employee(bus, i))
                .ToArray();

            var loadBalancer = new RoundRobinLoadBalancer(printerPool);
            var printerRetryHandler = new RetryHandler(loadBalancer, bus);
            var retryManager = new RetryManager(bus);
            var timerService = new TimerService(bus);

            bus.Subscribe<FutureMessage>(timerService);
            bus.Subscribe<RetryMessage>(retryManager);
            bus.Subscribe<SuccessMessage>(retryManager);

            bus.Subscribe(new NarrowingHandler<PrintJob, Message>(printerRetryHandler));

            var console = new QueuedHandler(new WideningHandler<LogMessage, Message>(new ConsoleHandler()), bus);
            bus.Subscribe<LogMessage>(new NarrowingHandler<LogMessage, Message>(console));

            var porter = new Porter(bus);
            bus.Subscribe(porter);

            var converter = new LogConverter(bus);
            bus.Subscribe<PrintJob>(converter);
            bus.Subscribe<OutOfPaper>(converter);
            bus.Subscribe<PagePrinted>(converter);
            bus.Subscribe<RetryMessage>(converter);
        }
Пример #35
0
 public MainWindow()
 {
     InitializeComponent();
     concertWorker.DoWork += concertWorker_DoWork;
     concertWorker.RunWorkerCompleted += concertWorker_RunWorkerCompleted;
     concertWorker.ProgressChanged += worker_ProgressChanged;
     levelWorker.DoWork += levelWorker_DoWork;
     levelWorker.RunWorkerCompleted += levelWorker_RunWorkerCompleted;
     levelWorker.ProgressChanged += worker_ProgressChanged;
     customerWorker.DoWork += customerWorker_DoWork;
     customerWorker.RunWorkerCompleted += customerWorker_RunWorkerCompleted;
     customerWorker.ProgressChanged += worker_ProgressChanged;
     purchaseWorker.DoWork += purchaseWorker_DoWork;
     purchaseWorker.RunWorkerCompleted += purchaseWorker_RunWorkerCompleted;
     purchaseWorker.ProgressChanged += worker_ProgressChanged;
     RetryManager manager = new RetryManager(new List<RetryStrategy> { exponentialBackoffStrategy }, "exponentialBackoffStrategy");
     RetryManager.SetDefault(manager);
     ticketsPurchasedCounter = new TicketsPurchasedCounter(0);            
 }
Пример #36
0
        protected override void Arrange()
        {
            this.defaultStrategy = new FixedInterval("default", 5, TimeSpan.FromMilliseconds(10));
            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.managerWithAllDefaults = new RetryManager(
                new[]
                {
                    this.defaultStrategy,
                    this.defaultSqlConnectionStrategy,
                    this.defaultSqlCommandStrategy,
                    this.otherStrategy,
                    this.defaultAzureServiceBusStrategy,
                    this.defaultAzureCachingStrategy, this.defaultAzureStorageStrategy
                },
                "default",
                new Dictionary<string, string> 
                { 
                    { "SQL", "defaultSqlCommand" },
                    { "SQLConnection", "defaultSqlConnection" },
                    { "ServiceBus", "defaultAzureServiceBusStrategy" },
                    { "Caching", "defaultAzureCachingStrategy" },
                    { "WindowsAzure.Storage", "defaultAzureStorageStrategy" },
                });

            this.managerWithOnlyDefault = new RetryManager(
              new[]
                {
                    this.defaultStrategy,
                    this.defaultSqlConnectionStrategy,
                    this.defaultSqlCommandStrategy,
                    this.otherStrategy,
                    this.defaultAzureServiceBusStrategy,
                    this.defaultAzureCachingStrategy, this.defaultAzureStorageStrategy
                },
              "default");
        }
        /// <summary>
        /// Initialize the Sql Azure settings and connections
        /// </summary>
        public void InitializeSqlAzure()
        {
            this.SqlConnectionString = ConfigurationManager.AppSettings["SqlAzureConnectionString"];
            if(String.IsNullOrWhiteSpace(this.SqlConnectionString))
            {
                throw new ArgumentException("A required AppSetting cannot be null or empty", "SqlAzureConnectionString");
            }

            this.SqlTableName = ConfigurationManager.AppSettings["SqlAzureTableName"];
            if (String.IsNullOrWhiteSpace(this.SqlTableName))
            {
                throw new ArgumentException("A required AppSetting cannot be null or empty", "SqlAzureTableName");
            }

            var columns = ConfigurationManager.AppSettings["SqlAzureTableColumns"];
            if (String.IsNullOrWhiteSpace(columns))
            {
                throw new ArgumentException("A required AppSetting cannot be null or empty", "SqlAzureTableColumns");
            }

            this.SqlTableColumns = columns.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries).Select(c => c.Trim()).ToList();

            //Reference: https://msdn.microsoft.com/en-us/library/azure/dn864744.aspx
            //1. Define an Exponential Backoff retry strategy for Azure SQL Database throttling (ExponentialBackoff Class). An exponential back-off strategy will gracefully back off the load on the service.
            int retryCount = 4;
            int minBackoffDelayMilliseconds = 2000;
            int maxBackoffDelayMilliseconds = 8000;
            int deltaBackoffMilliseconds = 2000;

            ExponentialBackoff exponentialBackoffStrategy = 
                new ExponentialBackoff("exponentialBackoffStrategy",
                    retryCount,
                    TimeSpan.FromMilliseconds(minBackoffDelayMilliseconds), 
                    TimeSpan.FromMilliseconds(maxBackoffDelayMilliseconds),
                    TimeSpan.FromMilliseconds(deltaBackoffMilliseconds));

            //2. Set a default strategy to Exponential Backoff.
            RetryManager manager = new RetryManager(
                new List<RetryStrategy>
                {  
                    exponentialBackoffStrategy 
                },
                "exponentialBackoffStrategy");

            //3. Set a default Retry Manager. A RetryManager provides retry functionality, or if you are using declarative configuration, you can invoke the RetryPolicyFactory.CreateDefault
            RetryManager.SetDefault(manager);

            //4. Define a default SQL Connection retry policy and SQL Command retry policy. A policy provides a retry mechanism for unreliable actions and transient conditions.
            ConnectionRetryPolicy = manager.GetDefaultSqlConnectionRetryPolicy();
            CommandRetryPolicy = manager.GetDefaultSqlCommandRetryPolicy();

            //5. Create a function that will retry the connection using a ReliableSqlConnection.
            InitializeSqlAzureConnection();
        }
 protected override void Act()
 {
     retryManager = settings.BuildRetryManager();
 }