Skip to content

Instantly share code, notes, and snippets.

@sakapon
Last active July 31, 2017 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakapon/608a817c849bd5a2cf3cba473aa52cef to your computer and use it in GitHub Desktop.
Save sakapon/608a817c849bd5a2cf3cba473aa52cef to your computer and use it in GitHub Desktop.
ProxySample/ProxyableConsole/ProxyableExtension.cs
using System;
using System.Transactions;
namespace ProxyableConsole
{
class Program
{
static void Main(string[] args)
{
var units = NorthwindBusiness.SelectUnitsInStock();
NorthwindBusiness.InsertCategory("Books");
try
{
NorthwindBusiness.ErrorTest();
}
catch (Exception)
{
}
}
}
public static class NorthwindBusiness
{
public static short SelectUnitsInStock() =>
Proxyable.Body(() =>
{
Console.WriteLine("SelectUnitsInStock");
// cf. https://sakapon.wordpress.com/2011/10/02/dirtyread2/
using (var context = new NorthwindEntities())
{
var product = context.Products.Single(p => p.ProductID == 1);
return product.UnitsInStock;
}
})
.TransactionScope()
.TraceLog()
.Execute();
public static void InsertCategory(string name) =>
Proxyable.Body(() =>
{
Console.WriteLine("InsertCategory");
// cf. https://sakapon.wordpress.com/2011/12/14/phantomread2/
using (var context = new NorthwindEntities())
{
context.AddToCategories(Category.CreateCategory(0, name));
context.SaveChanges();
}
})
.TransactionScope(IsolationLevel.Serializable)
.TraceLog()
.Execute();
public static void ErrorTest() =>
Proxyable.Body(() => throw new InvalidOperationException("This is an error test."))
.TraceLog()
.Execute();
}
}
using System;
using System.Runtime.CompilerServices;
using System.Transactions;
namespace ProxyableConsole
{
public static class ProxyableExtension
{
public static IProxyable<TResult> TraceLog<TResult>(this IProxyable<TResult> source, [CallerMemberName]string caller = "") =>
source.Aspect(f =>
{
try
{
Console.WriteLine($"Begin: {caller}");
var result = f();
Console.WriteLine($"Success: {caller}");
return result;
}
catch (Exception ex)
{
Console.WriteLine($"Error: {caller}");
Console.WriteLine(ex);
throw;
}
});
public static IProxyable<TResult> TransactionScope<TResult>(this IProxyable<TResult> source,
IsolationLevel isolationLevel = IsolationLevel.ReadCommitted,
double timeoutInSeconds = 30,
TransactionScopeOption scopeOption = TransactionScopeOption.Required)
{
var transactionOptions = new TransactionOptions
{
IsolationLevel = isolationLevel,
Timeout = TimeSpan.FromSeconds(timeoutInSeconds),
};
return source.Aspect(f =>
{
using (var scope = new TransactionScope(scopeOption, transactionOptions))
{
var result = f();
scope.Complete();
return result;
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment