Skip to content

Instantly share code, notes, and snippets.

@jpv001
Created September 11, 2016 06:24
Show Gist options
  • Save jpv001/721f11574d3fdac67b07f1c514defae0 to your computer and use it in GitHub Desktop.
Save jpv001/721f11574d3fdac67b07f1c514defae0 to your computer and use it in GitHub Desktop.
void Main()
{
var policy = Policy
.Handle<TimeoutException>()
.Or<SqlException>(ex => (new[] { 40613, 40501, 40197, 10929, 10928, 10060, 10054, 10053, 233, 64, 20 }).Contains(ex.Number))
.WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt) / 2),
(ex, count) =>
{
count.Dump();
//log
});
var test = new SqlConnFailureTester();
policy.Execute(() => test.ThrowsATransientError().Dump());
}
public class SqlConnFailureTester
{
private int FailureTriggered { get; set;} = 0;
public string ThrowsATimeoutError()
{
if(FailureTriggered > 0) return $"Success after {FailureTriggered} failures";
FailureTriggered++;
throw new TimeoutException();
}
public string ThrowsATransientError()
{
if(FailureTriggered > 0) return $"Success after {FailureTriggered} failures";
FailureTriggered++;
throw CreateSqlException(20);
}
private SqlException CreateSqlException(int number)
{
var collectionConstructor = typeof(SqlErrorCollection).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
var addMethod = typeof(SqlErrorCollection).GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance);
var errorCollection = (SqlErrorCollection)collectionConstructor.Invoke(null);
var errorConstructor = typeof(SqlError).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[]
{
typeof (int), typeof (byte), typeof (byte), typeof (string), typeof(string), typeof (string),
typeof (int), typeof (uint)
}, null);
var error = errorConstructor.Invoke(new object[] { number, (byte)0, (byte)0, "server", "errMsg", "proccedure", 100, (uint)0 });
addMethod.Invoke(errorCollection, new[] { error });
var constructor = typeof(SqlException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[]
{
typeof(string), typeof(SqlErrorCollection), typeof(Exception), typeof(Guid)
}, null);
return (SqlException)constructor.Invoke(new object[] { "Error message", errorCollection, new DataException(), Guid.NewGuid() });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment