本文整理汇总了C#中System.Transactions.TransactionScope.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# TransactionScope.Dispose方法的具体用法?C# TransactionScope.Dispose怎么用?C# TransactionScope.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Transactions.TransactionScope
的用法示例。
在下文中一共展示了TransactionScope.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RetrieveMoney
static void RetrieveMoney(decimal amount, string cardNumber, string cardPin)
{
if (cardNumber == null)
{
throw new ArgumentNullException("cardNumber", "Provided card number cannot be null!");
}
if (cardPin == null)
{
throw new ArgumentNullException("cardPIN", "Provided card PIN cannot be null!");
}
if (cardNumber.Length != 10)
{
throw new ArgumentException(
"Provided card number is invalid! Card number must consist of 10 digits!");
}
if (cardPin.Length != 4)
{
throw new ArgumentException(
"Provided card PIN is invalid! Card PIN must consist of 4 digits!");
}
using (var scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions() { IsolationLevel = IsolationLevel.RepeatableRead }))
{
using (var atmContext = new ATMEntities())
{
var cardAccount = atmContext.CardAccounts.FirstOrDefault(
ca => ca.CardNumber.CompareTo(cardNumber) == 0 &&
ca.CardPIN.CompareTo(cardPin) == 0);
if (cardAccount == null)
{
scope.Dispose();
throw new TransactionException(
"There is no card account with provided card number and PIN!");
}
if (cardAccount.CardCash < amount)
{
scope.Dispose();
throw new TransactionException(
"There is no enough money in the account to retrive the requested amount!");
}
cardAccount.CardCash -= amount;
atmContext.SaveChanges();
}
scope.Complete();
}
}
示例2: RetrievesMoney
public static void RetrievesMoney(ATMContext db)
{
Console.WriteLine("Enter card number:");
string cNumber = Console.ReadLine();
Console.WriteLine("Enter PIN:");
string pin = Console.ReadLine();
Console.WriteLine("Enter money:");
decimal money = decimal.Parse(Console.ReadLine());
using (db)
{
using (var tran = new TransactionScope())
{
var firstCheck = db.CardAccounts.Where(x => x.Number == cNumber).Where(x => x.PIN == pin);
if (firstCheck.Count() != 1)
{
tran.Dispose();
Console.WriteLine("More");
}
else
{
var a = db.CardAccounts.Where(x => x.Number == cNumber).First();
if (a.Cash >= money)
{
try
{
a.Cash -= money;
db.SaveChanges();
tran.Complete();
Console.WriteLine("OK");
AddToHistory(cNumber, DateTime.Now, money, db);
}
catch (Exception ex)
{
Console.WriteLine(ex);
tran.Dispose();
Console.WriteLine("No");
}
}
}
}
}
}
示例3: InsertNewPost
/// <summary>
/// Create new post
/// </summary>
/// <param name="id"></param>
/// <param name="postTitle"></param>
/// <param name="memberId"></param>
/// <param name="fileName"></param>
/// <param name="fileUpload"></param>
/// <param name="fileType"></param>
/// <param name="postStory"></param>
/// <param name="postTags"></param>
/// <param name="deviceInfo"></param>
/// <param name="locationInfo"></param>
/// <returns></returns>
public int InsertNewPost(string postTitle, string memberId, string fileName, String fileUpload,string fileType, string postStory,
string postTags, string deviceInfo, string locationInfo)
{
using (var tx = new TransactionScope())
{
try
{
var upload = UploadFile(fileUpload, fileName, out fileName);
if (!upload)
{
tx.Dispose();
return -1; // Upload image fail
}
// Insert new post
var post = new Post
{
PostId = Guid.NewGuid(),
PostTitle = postTitle,
PostMemberId = new Guid(memberId),
PostImage = fileName,
PostStory = postStory,
PostTags = postTags,
DeviceInfo = deviceInfo,
LocationInfo = locationInfo,
PostCreated = DateTime.Now,
PostImageType = fileType,
Status = 1
};
DataContext.Posts.Add(post);
var i = DataContext.SaveChanges();
tx.Complete();
return i;
}
catch (Exception)
{
tx.Dispose();
return -2; // Create post fail
}
}
}
示例4: Explicit_rollback_can_be_used_to_rollback_a_transaction
public void Explicit_rollback_can_be_used_to_rollback_a_transaction()
{
EnsureDatabaseInitialized(() => new SimpleModelContext());
using (var tx = new TransactionScope())
{
using (var context = new SimpleModelContext())
{
var product = new Product
{
Name = "BestTea"
};
context.Products.Add(product);
context.SaveChanges();
Assert.Equal(1, GetTransactionCount(context.Database.Connection));
Assert.True(context.Products.Where(p => p.Name == "BestTea").AsNoTracking().Any());
// Rollback System Transaction
tx.Dispose();
Assert.False(context.Products.Where(p => p.Name == "BestTea").AsNoTracking().Any());
}
}
}
示例5: Alterar
public ActionResult Alterar()
{
if (Session["ADMINISTRADOR"] != null)
{
using (TransactionScope transacao = new TransactionScope())
{
try
{
using (CarOnlineEntities DB = new CarOnlineEntities())
{
DB.SaveChanges();
transacao.Complete();
return View("Consulta");
}
}
catch (Exception ex)
{
transacao.Dispose();
return View("Cadastro");
}
}
}
else
return RedirectToAction("Index", "Login", new { area = "administrativo" });
}
示例6: Save_on_new_UserNeed_creates_record_in_table
public void Save_on_new_UserNeed_creates_record_in_table()
{
using (TransactionScope scope = new TransactionScope()) {
// Given: an existing Need
Need existingNeed = GetExistingNeed(_churchID, CategoryEnum.Clothes, _userID, "I need clothes", "Because I am NAKED", "75240", new DateTime(2009, 5, 15), 1);
// When: I create a UserNeed
Model.DataContext = GetNewDataContext();
UserNeed userNeed = Model.New<UserNeed>();
userNeed.EntityState = EntityStateEnum.Added;
userNeed.UserID = _userID;
userNeed.NeedID = existingNeed.ID;
userNeed.UserNeedStatusID = (int)UserNeedStatusEnum.Interested;
userNeed.Save();
// Then: it should be present in the db
Model.DataContext = GetNewDataContext();
UserNeed retrievedUserNeed = Model.New<UserNeed>().GetByKey(userNeed.UserID, userNeed.NeedID);
Assert.AreEqual(userNeed.UserID, retrievedUserNeed.UserID);
Assert.AreEqual(userNeed.NeedID, retrievedUserNeed.NeedID);
Assert.AreEqual(userNeed.Created.ToString(), retrievedUserNeed.Created.ToString());
scope.Dispose();
}
}
示例7: AlterarParametroCargo
public ActionResult AlterarParametroCargo(int idCargo, string ativo)
{
string mensagem = "";
using (TransactionScope transacao = new TransactionScope())
{
tblCargo cargo = new tblCargo();
try
{
using (CarOnlineEntities DB = new CarOnlineEntities())
{
cargo = DB.tblCargo.FirstOrDefault(c => c.idCargo.Equals(idCargo));
cargo.ativo = ativo;
DB.SaveChanges();
transacao.Complete();
return Json("");
}
}
catch
{
transacao.Dispose();
mensagem = "Não foi possível salvar o parâmetro.Contate o administrador e tente mais tarde";
var data = new { mensagem };
return Json(data);
}
}
}
示例8: GetSalesHistory
public static List<SalesHistoryData> GetSalesHistory()
{
List<SalesHistoryData> result = new List<SalesHistoryData>();
try
{
// The encrypted list will timeout for slightly large lists (in the hundreds), so the list is
// being grabbed in smaller chunks. Transaction logic is used to lock the list while the list is being
// grabbed.
TransactionOptions transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.RepeatableRead;
transactionOptions.Timeout = new TimeSpan(0, 2, 0);
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOptions))
{
Console.WriteLine("Test 1: List all Sales Orders");
int take = 5;
int count = UserSession.Current.Client.GetSalesOrderListCount();
for (int skip = 0; skip < count; skip = skip + take)
{
List<SalesHistoryData> salesOrders = UserSession.Current.Client.GetSalesHistory(take, skip).ToList();
result = result.Union(salesOrders).ToList();
}
result = result.OrderByDescending(so => so.SalesOrderNumber).ThenBy(so => so.SortOrder).ToList();
//No scope.Complete here as no write tasks are being scoped.
scope.Dispose();
}
}
catch (Exception) { throw; }
return result;
}
示例9: Distribute
public void Distribute(Guid saleId)
{
using (var transaction = new TransactionScope())
{
try
{
Sale sale = this.uow.SaleRepository.FindById(saleId);
if (sale == null)
throw new ArgumentException("Trying to distribute commissino on non-existing Sale");
IList<SalesPerson> salesPersonsToReceiveCommissions = this.uow
.SalesPersonRepository
.GetUplineHierarchy(sale.SalesPersonId);
IList<SaleCommission> commissionsToDistribute = new List<SaleCommission>();
foreach (var salesPerson in salesPersonsToReceiveCommissions)
{
SaleCommission distributedCommission = commissionCalculator.ComputeCommission(sale, salesPerson);
this.uow.SaleCommissionRepository.Add(distributedCommission);
}
this.uow.Commit();
transaction.Complete();
}
catch (Exception ex)
{
transaction.Dispose();
throw ex;
}
}
}
示例10: AddUserToGroup
static bool AddUserToGroup(string userName, string groupName)
{
using (UsersGroupsEntities context = new UsersGroupsEntities())
{
using (TransactionScope scope = new TransactionScope())
{
if (!context.Groups.Where(g => g.Name == groupName).Any())
{
context.Groups.Add(new Group() { Name = groupName });
context.SaveChanges();
}
Group groupToAddIn = context.Groups.Where(g => g.Name == groupName).First();
if (groupToAddIn.Users.Where(u => u.Name == userName).Any())
{
scope.Dispose();
return false;
}
else
{
User newUser = new User() { Name = userName };
groupToAddIn.Users.Add(newUser);
context.SaveChanges();
scope.Complete();
return true;
}
}
}
}
示例11: On_ActionDelete
protected override void On_ActionDelete(object sender, EventArgs e)
{
TransactionScope ts = new TransactionScope( );
SharedDbConnectionScope ss = new SharedDbConnectionScope( );
try
{
int cashID = Utilities.ToInt(EVENTARGUMENT);
string message;
if (OrderBLL.DeleteMemberCash(cashID, AppContext.Context.Company, out message))
{
OrderBLL.UpdateBalance( );
ts.Complete( );
}
txtMessage.InnerHtml = message;
}
catch (Exception ex)
{
Logging.Log("FinanceList->On_ActionDelete", ex, true);
txtMessage.InnerHtml = ex.Message;
}
finally
{
ss.Dispose( );
ts.Dispose( );
}
On_ActionQuery(sender, e);
}
示例12: AddArticle
public int AddArticle(ArticleM article)
{
var tran = new TransactionScope();
try
{
//把文章数据写入数据库
var articleDa = new ArticleDA();
articleDa.AddArticle(article);
//为新增加的文章生成静态页面
//文章作者增加积分
//写日志
//提交事务
tran.Complete();
}
catch(Exception ex)
{
throw ex;
}
finally
{
tran.Dispose();
}
return 1;
}
示例13: When_using_DTC_HiLo_knows_to_create_isolated_DTC_transaction
public void When_using_DTC_HiLo_knows_to_create_isolated_DTC_transaction()
{
object scalar1, scalar2;
using (var session = sessions.OpenSession())
using (var command = session.Connection.CreateCommand())
{
command.CommandText = "select next_hi from hibernate_unique_key with (updlock, rowlock)";
scalar1 = command.ExecuteScalar();
}
using (var tx = new TransactionScope())
{
var generator = sessions.GetIdentifierGenerator(typeof(Person).FullName);
Assert.That(generator, Is.InstanceOf<TableHiLoGenerator>());
using(var session = sessions.OpenSession())
{
var id = generator.Generate((ISessionImplementor) session, new Person());
}
// intentionally dispose without committing
tx.Dispose();
}
using (var session = sessions.OpenSession())
using (var command = session.Connection.CreateCommand())
{
command.CommandText = "select next_hi from hibernate_unique_key with (updlock, rowlock)";
scalar2 = command.ExecuteScalar();
}
Assert.AreNotEqual(scalar1, scalar2,"HiLo must run with in its own transaction");
}
示例14: ExpenseCzar_Should_Generate
public void ExpenseCzar_Should_Generate()
{
int staffid = BusinessUser.Current == null ? -1 : Convert.ToInt32(BusinessUser.Current.UserKey);
staffid = BusinessUser.Current == null ? -1 : Convert.ToInt32(BusinessUser.Current.UserKey);
//var isolation = IsolationLevel.ReadUncommitted;
using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(1, 1, 1)))
{
var generationDao = DataAccessFactory.Create<GenericDao>();
TestDao testDao = new TestDao(generationDao);
int queueId = new ReportGenerationQueueBuilder()
.WithGenerationDao(DataAccessFactory.CreateWithSameContext<GenerationDao>(generationDao))
.WithPeriod(201101)
.WithReforecastQuarterName("Q0")
.WithReportId(testDao.GetReportIdByName("Andre's Unit Test01"))
.Build();
AbstractReportGenerator reportGenerator = ReportGeneratorFactory.GetReportGenerator(queueId);
Assert.AreEqual(reportGenerator.GetType(), typeof(ExpenseCzarReportGenerator), "expected the report to use the expense czar generator");
reportGenerator.GenerateReport();
transaction.Dispose();
}
}
示例15: ValidateUserByActiveDirectory
public void ValidateUserByActiveDirectory()
{
using (TransactionScope scope = new TransactionScope())
{
Assert.IsTrue(User.VerifyCredentials("[email protected]", "xrZ40uye"));
scope.Dispose();
}
}