public MessageCode SaveWincountPrize(NbManagerEntity manager, LeagueWincountrecordEntity leagueWincountRecord, ItemPackageFrame package, int point, int coin) { try { using (var transactionManager = new TransactionManager(Dal.ConnectionFactory.Instance.GetConnectionString(EnumDbType.Main))) { transactionManager.BeginTransaction(); var messageCode = Tran_SaveWincountPrizePrize(transactionManager.TransactionObject, manager, leagueWincountRecord, package, point, coin); if (messageCode == MessageCode.Success) { transactionManager.Commit(); } else { transactionManager.Rollback(); } return(messageCode); } } catch (Exception ex) { SystemlogMgr.ErrorByZone("SavePrize", ex); return(MessageCode.Exception); } }
public static int DelReportList(string idlist) { //删除报表设置 string sqlstr = "delete from defdba.ReportTable where ID in ( " + idlist + " )"; //删除菜单 string[] arr = idlist.Split(','); for (int i = 0; i < arr.Length; i++) { sqlstr += ";" + "delete from defdba.CustomModule where PropertyValue='Pages/Office/DefManager/ReportTableList.aspx?reportid=" + arr[i] + "'"; } TransactionManager tran = new TransactionManager(); tran.BeginTransaction(); try { int num = SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, sqlstr); tran.Commit(); return(num); } catch { tran.Rollback(); return(0); } }
/// <summary> /// 添加请示单 /// </summary> /// <param name="rd"></param> /// <param name="list"></param> /// <returns></returns> //public bool AddGeneralReimburse(Entities.Reimburse rd, TList<ReceiptInfo> list, decimal Balance, string strBankAccount, Employee CurrentEmployee) public bool AddInstructionOfPkurg(InstructionOfPkurg rd) { string methodName = "AddInstructionOfPkurg"; Logger.Write(this.GetType(), EnumLogLevel.Info, className + ":" + methodName + ":" + MessageType.IN + ":" + string.Format("InstructionOfPkurg={0}", rd)); TransactionManager transaction = DataRepository.Provider.CreateTransaction(); try { transaction.BeginTransaction(); //插入请示单 bool result = DataRepository.InstructionOfPkurgProvider.Insert(transaction, rd); transaction.Commit(); return(true); } catch (Exception exp) { transaction.Rollback(); Logger.Write(this.GetType(), EnumLogLevel.Fatal, className + ":" + methodName + ":" + MessageType.Exception + ":" + string.Format("Exception={0}", exp)); throw exp; } }
MessageCode SaveAttachment(List <MailInfoEntity> mails, ItemPackageFrame package, NbManagerEntity manager, int coin, int sophicate, int point, int prestige, int bindPoint, int addGoldBar, Guid managerId, int addluckyCoin, int addGameCoin) { if (mails == null || mails.Count <= 0) { return(MessageCode.NbUpdateFail); } try { using (var transactionManager = new TransactionManager(Dal.ConnectionFactory.Instance.GetDefault())) { transactionManager.BeginTransaction(); var messageCode = Tran_SaveAttachment(transactionManager.TransactionObject, mails, package, manager, coin, sophicate, point, prestige, bindPoint, addGoldBar, managerId, addluckyCoin, addGameCoin); if (messageCode == ShareUtil.SuccessCode) { transactionManager.Commit(); if (coin > 0) { ManagerCore.Instance.UpdateCoinAfter(manager); } } else { transactionManager.Rollback(); } return(messageCode); } } catch (Exception ex) { SystemlogMgr.Error("SaveTourMatch", ex); return(MessageCode.Exception); } }
public static bool Update(VoucherTemplateModel voucherTemplateModel, List <VoucherTemplateDetailModel> voucherTemplateDetailModelList, out string strMsg) { bool isSucc = false;//是否添加成功 strMsg = ""; string strSql = "delete from officedba.VoucherTemplateDetail where TemNo =@TemNo and CompanyCD=@CompanyCD"; SqlParameter[] paras = { new SqlParameter("@TemNo ", voucherTemplateModel.TemNo), new SqlParameter("@CompanyCD", voucherTemplateModel.CompanyCD) }; TransactionManager tran = new TransactionManager(); tran.BeginTransaction(); try { UpdateVoucherTemplate(voucherTemplateModel, tran); SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, strSql.ToString(), paras); InsertVoucherTemplateDetail(voucherTemplateDetailModelList, tran); tran.Commit(); isSucc = true; strMsg = "保存成功!"; } catch (Exception ex) { tran.Rollback(); strMsg = "保存失败,请联系系统管理员!"; throw ex; } return(isSucc); }
/// <summary> /// Executes a delegate inside a DSL transaction. /// </summary> /// <param name="manager">The manager.</param> /// <param name="action">The action.</param> /// <param name="transactionName">Name of the transaction.</param> /// <param name="serializing">Whether the transaction is a serialization one.</param> public static void DoWithinTransaction(this TransactionManager manager, Action action, string transactionName, bool serializing) { Guard.NotNull(() => manager, manager); Guard.NotNull(() => action, action); var transacName = transactionName; if (string.IsNullOrEmpty(transacName)) { transacName = string.Format(CultureInfo.CurrentCulture, Resources.TransactionManagerExtensions_DoWithinTransactionDescription, action.Method.Name, DateTime.Now.ToString()); } if (manager.Store.InUndoRedoOrRollback || manager.InTransaction || (manager.CurrentTransaction != null && manager.CurrentTransaction.InRollback)) { // Do not create nested transaction in rollback scenarios. action(); } else { using (var tx = manager.BeginTransaction(transacName, serializing)) { action(); tx.Commit(); } } }
/// <summary> /// 删除单据 /// </summary> /// <param name="orderNos"></param> /// <returns></returns> public static bool DelOrder(string orderIDs) { string strCompanyCD = string.Empty;//单位编号 bool isSucc = false; System.Text.StringBuilder sb = new System.Text.StringBuilder(); TransactionManager tran = new TransactionManager(); strCompanyCD = ((UserInfoUtil)SessionUtil.Session["UserInfo"]).CompanyCD; tran.BeginTransaction(); try { SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, "DELETE FROM officedba.AdversarySell WHERE ID IN ( " + orderIDs + " ) and CompanyCD='" + strCompanyCD + "'", null); tran.Commit(); isSucc = true; } catch (Exception ex) { tran.Rollback(); isSucc = false; throw ex; } return(isSucc); }
public void DeletePDCompetencyKSAFactor(long positionCompetencyKSAID, int userId) { TransactionManager currentTransaction = new TransactionManager(base.CurrentDatabase); currentTransaction.BeginTransaction(); DbCommand commandWrapper = GetDbCommand("spr_DeletePositionCompetencyKSAFactor"); try { commandWrapper.Parameters.Add(new SqlParameter("@PositionCompetencyKSAID", positionCompetencyKSAID)); commandWrapper.Parameters.Add(new SqlParameter("@userId", userId)); if (currentTransaction != null) { DatabaseUtility.ExecuteNonQuery(currentTransaction, commandWrapper); } else { ExecuteNonQuery(commandWrapper); } currentTransaction.Commit(); } catch (Exception ex) { currentTransaction.Rollback(); HandleException(ex); } }
MessageCode Save_TranReceiveBindPoint(PayUserEntity payUser, InvestManagerEntity investInfo) { try { using (var transactionManager = new TransactionManager(Dal.ConnectionFactory.Instance.GetDefault())) { transactionManager.BeginTransaction(); var code = Tran_ReceiveBindPoint(payUser, investInfo, transactionManager.TransactionObject); if (code == ShareUtil.SuccessCode) { transactionManager.Commit(); } else { transactionManager.Rollback(); } return(code); } } catch (Exception ex) { SystemlogMgr.Error("ReceiveBindPoint", ex); return(MessageCode.Exception); } }
public static bool Insert(SellReportModel sellrptModel, List <SellReportDetailModel> sellRptDetailModellList, out string strMsg) { bool isSucc = false;//是否添加成功 int billID = 0; strMsg = ""; TransactionManager tran = new TransactionManager(); tran.BeginTransaction(); try { billID = InsertSellReport(sellrptModel, tran); InsertSellReportDetail(sellRptDetailModellList, billID, tran); tran.Commit(); isSucc = true; strMsg = "保存成功!|" + billID; } catch (Exception ex) { tran.Rollback(); strMsg = "保存失败,请联系系统管理员!"; throw ex; } return(isSucc); }
/// <summary> /// 删除销售汇报 /// </summary> /// <param name="ids"></param> /// <returns></returns> public static bool DelSellRpt(string ids, string strCompanyCD, out string strMsg, out string strFieldText) { bool isSucc = false; strMsg = ""; strFieldText = ""; System.Text.StringBuilder sb = new System.Text.StringBuilder(); TransactionManager tran = new TransactionManager(); tran.BeginTransaction(); try { SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, "DELETE FROM officedba.SellReport WHERE id IN ( " + ids + " ) and CompanyCD='" + strCompanyCD + "'", null); SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, "DELETE FROM officedba.sellerRate WHERE sellreportID IN ( " + ids + " ) and CompanyCD='" + strCompanyCD + "'", null); tran.Commit(); isSucc = true; strMsg = "删除成功!"; } catch (Exception ex) { tran.Rollback(); strMsg = "删除失败,请联系系统管理员!"; isSucc = false; throw ex; } return(isSucc); }
/// <summary> /// 更新销售发汇报 /// </summary> /// <returns></returns> public static bool UpdateSellReport(SellReportModel sellrptModel, List <SellReportDetailModel> sellRptDetailModellList, out string strMsg) { bool isSucc = false;//是否添加成功 strMsg = ""; string strSql = "delete from officedba.sellerRate where sellreportID=@sellreportID and CompanyCD=@CompanyCD"; SqlParameter[] paras = { new SqlParameter("@sellreportID", sellrptModel.ID), new SqlParameter("@CompanyCD", sellrptModel.CompanyCD) }; TransactionManager tran = new TransactionManager(); tran.BeginTransaction(); try { UpdateSellReportMain(sellrptModel, tran); SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, strSql.ToString(), paras); InsertSellReportDetail(sellRptDetailModellList, sellrptModel.ID, tran); tran.Commit(); strMsg = "保存成功!"; isSucc = true; } catch (Exception ex) { tran.Rollback(); strMsg = "保存失败,请联系系统管理员!"; throw ex; } return(isSucc); }
static MessageCode InnerSaveMixNew(NbManagerEntity manager, Guid mid, SkillBagWrap bag, int coin, string setSkills = null) { int errorCode = (int)MessageCode.FailUpdate; using (var tranMgr = new TransactionManager(Dal.ConnectionFactory.Instance.GetDefault())) { tranMgr.BeginTransaction(); do { var mess = ManagerCore.Instance.CostCoin(manager, coin, EnumCoinConsumeSourceType.SkillUpgrade, ShareUtil.GenerateComb().ToString(), tranMgr.TransactionObject); if (mess != MessageCode.Success) { break; } NbManagerskillbagMgr.MixUpTran(false, mid, setSkills, bag.SetMap, "", bag.RawBag.RowVersion, ref errorCode); }while (false); if (errorCode == (int)MessageCode.Success) { tranMgr.Commit(); } else { tranMgr.Rollback(); } } return((MessageCode)errorCode); }
static MessageCode InnerSaveMix(Guid mid, ItemPackageFrame pack, SkillBagWrap bag, ItemInfoEntity mixItems, string setSkills = null) { string itemMap = mixItems.ItemId.ToString(); int errorCode = (int)MessageCode.FailUpdate; using (var tranMgr = new TransactionManager(Dal.ConnectionFactory.Instance.GetDefault())) { tranMgr.BeginTransaction(); do { if (null != pack && !pack.Save(tranMgr.TransactionObject)) { break; } NbManagerskillbagMgr.MixUpTran(false, mid, setSkills, bag.SetMap, itemMap, bag.RawBag.RowVersion, ref errorCode); }while (false); if (errorCode == (int)MessageCode.Success) { tranMgr.Commit(); } else { tranMgr.Rollback(); } } itemMap = null; return((MessageCode)errorCode); }
// MessageCode SaveLottery(Guid matchId, Guid managerId, ItemPackageFrame package, MailBuilder mail, int lotteryRepeatCode) MessageCode SaveLottery(Guid matchId, Guid managerId, int lotteryRepeatCode, ItemPackageFrame package, MailBuilder mail, int point) { try { using (var transactionManager = new TransactionManager(Dal.ConnectionFactory.Instance.GetDefault())) { transactionManager.BeginTransaction(); //var messageCode = Tran_SaveLottery(transactionManager.TransactionObject, matchId, managerId, package, mail, lotteryRepeatCode); var messageCode = Tran_SaveLottery(transactionManager.TransactionObject, matchId, managerId, lotteryRepeatCode, package, mail, point); if (messageCode == ShareUtil.SuccessCode) { transactionManager.Commit(); } else { transactionManager.Rollback(); } return(messageCode); } } catch (Exception ex) { SystemlogMgr.Error("SavePlayerKillLottery", ex); return(MessageCode.Exception); } }
/// <summary> /// 跟新单据单据 /// </summary> /// <param name="sellChanceModel">销售机会表实体</param> /// <param name="sellChancePushModel">销售阶段表实体</param> /// <returns>是否添加成功</returns> public static bool UpdateOrder(AdversaryInfoModel adversaryInfoModel, List <AdversaryDynamicModel> adversaryDynamicModelList) { bool isSucc = false;//是否添加成功 string strSql = "delete from officedba.AdversaryDynamic where CustNo=@CustNo and CompanyCD=@CompanyCD"; SqlParameter[] paras = { new SqlParameter("@CustNo", adversaryInfoModel.CustNo), new SqlParameter("@CompanyCD", adversaryInfoModel.CompanyCD) }; TransactionManager tran = new TransactionManager(); tran.BeginTransaction(); try { UpdateAdversaryInfo(adversaryInfoModel, tran); SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, strSql.ToString(), paras); InsertAdversaryDynamic(adversaryDynamicModelList, tran); tran.Commit(); isSucc = true; } catch (Exception ex) { tran.Rollback(); isSucc = false; throw ex; } return(isSucc); }
public static int Update(XBase.Model.Office.SellReport.UserProductInfo model) { int num = 0; string sqlstr = "update officedba.UserProductInfo set productNum=@productNum,productName=@productName,price=@price,bref=@bref,memo=@memo where id=@id"; TransactionManager tran = new TransactionManager(); tran.BeginTransaction(); SqlParameter[] param = { new SqlParameter("@CompanyCD", SqlDbType.VarChar, 50), new SqlParameter("@productNum", SqlDbType.VarChar, 50), new SqlParameter("@productName", SqlDbType.VarChar, 200), new SqlParameter("@price", SqlDbType.Decimal), new SqlParameter("@bref", SqlDbType.VarChar, 500), new SqlParameter("@memo", SqlDbType.VarChar, 1000), new SqlParameter("@id", SqlDbType.Int, 4) }; param[0].Value = model.CompanyCD; param[1].Value = model.productNum; param[2].Value = model.productName; param[3].Value = model.price; param[4].Value = model.bref; param[5].Value = model.memo; param[6].Value = model.id; try { num = SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, sqlstr, param); tran.Commit(); } catch { tran.Rollback(); } return(num); }
public static int AddSubBudgetInfo(SubBudgetModel subBudgetModel, XBase.Common.UserInfoUtil userinfo) { StringBuilder sqlstr = new StringBuilder(); sqlstr.Append("insert into officedba.SubBudget(CompanyCD,projectid,BudgetName) values(@CompanyCD,@projectid,@BudgetName)"); SqlParameter[] param = { new SqlParameter("@CompanyCD", SqlDbType.VarChar, 50), new SqlParameter("@projectid", SqlDbType.Int), new SqlParameter("@BudgetName", SqlDbType.VarChar, 200) }; param[0].Value = userinfo.CompanyCD; param[1].Value = subBudgetModel.Projectid; param[2].Value = subBudgetModel.BudgetName; TransactionManager tran = new TransactionManager(); int num = 0; tran.BeginTransaction(); try { num = SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, sqlstr.ToString(), param); tran.Commit(); } catch { tran.Rollback(); } return(num); }
MessageCode SaveExchange(LadderManagerEntity ladderManager, ItemPackageFrame package, LadderExchangerecordEntity ladderExchangerecord) { if (ladderManager == null || package == null || ladderExchangerecord == null) { return(MessageCode.NbUpdateFail); } try { using (var transactionManager = new TransactionManager(Dal.ConnectionFactory.Instance.GetDefault())) { transactionManager.BeginTransaction(); var messageCode = Tran_SaveExchange(transactionManager.TransactionObject, ladderManager, package, ladderExchangerecord); if (messageCode == ShareUtil.SuccessCode) { transactionManager.Commit(); } else { transactionManager.Rollback(); } return(messageCode); } } catch (Exception ex) { SystemlogMgr.Error("SaveExchange", ex); return(MessageCode.Exception); } }
/// <summary> /// 删除审批步骤 /// </summary> /// <param name="contractID"></param> /// <param name="CurrentEmployee"></param> /// <returns></returns> public bool DeleteWorkFlowInstance(string WorkFlowInstanceID) { string methodName = "DeleteWorkFlowInstance"; Logger.Write(this.GetType(), EnumLogLevel.Info, className + ":" + methodName + ":" + MessageType.IN + ":" + string.Format("WorkFlowInstance={0}", WorkFlowInstanceID)); TransactionManager transaction = DataRepository.Provider.CreateTransaction(); try { transaction.BeginTransaction(); //删除该合同下计价方式 bool result = DataRepository.WorkFlowInstanceProvider.Delete(transaction, WorkFlowInstanceID); transaction.Commit(); return(true); } catch (Exception exp) { transaction.Rollback(); Logger.Write(this.GetType(), EnumLogLevel.Fatal, className + ":" + methodName + ":" + MessageType.Exception + ":" + string.Format("Exception={0}", exp)); throw exp; } }
public bool Alterar(DataRow dtrAlterar) { TransactionManager objTransaction = null; try { objTransaction = new TransactionManager(TransactionManager.OpcoesDeDataSource.ServidoDaLojaAtual); objTransaction.BeginTransaction(); this.Alterar(dtrAlterar, ref objTransaction); if (objTransaction != null) { objTransaction.Commit(); } return(true); } catch (Exception) { if (objTransaction != null) { objTransaction.RollBack(); } throw; } }
public void Incluir(DataRow dtrIncluir) { TransactionManager objTransaction = null; try { objTransaction = new TransactionManager(TransactionManager.OpcoesDeDataSource.ServidoDaLojaAtual); objTransaction.BeginTransaction(); this.Incluir(dtrIncluir, ref objTransaction); if (objTransaction != null) { objTransaction.Commit(); } } catch (Exception) { if (objTransaction != null) { objTransaction.RollBack(); } throw; } }
MessageCode SaveMatch(NbManagerEntity manager, NbManagerextraEntity managerex, BaseMatchData pkmatchData, Guid lotteryMatchId, int win, int lose, int draw, int prizeExp, int prizeCoin, int prizeItemCode, string prizeItemString , bool isrevenge, long revengeRecordId, ref long outRevengeRecordId, PlayerkillInfoEntity info, int pointCount) { if (manager == null) { return(MessageCode.NbUpdateFail); } try { using (var transactionManager = new TransactionManager(Dal.ConnectionFactory.Instance.GetDefault())) { transactionManager.BeginTransaction(); var messageCode = Tran_SaveMatch(transactionManager.TransactionObject, manager, managerex, pkmatchData, lotteryMatchId, win, lose, draw, prizeExp, prizeCoin, prizeItemCode, prizeItemString , isrevenge, revengeRecordId, ref outRevengeRecordId, info, pointCount); if (messageCode == ShareUtil.SuccessCode) { transactionManager.Commit(); } else { transactionManager.Rollback(); } return(messageCode); } } catch (Exception ex) { SystemlogMgr.Error("SavePlayerKillMatch", ex); return(MessageCode.Exception); } }
public static int EditSubBudget(SubBudgetModel subBudgetModel, XBase.Common.UserInfoUtil userinfo) { StringBuilder sqlstr = new StringBuilder(); sqlstr.Append("update officedba.SubBudget set BudgetName=@BudgetName,projectid=@projectid where ID=@ID"); SqlParameter[] param = { new SqlParameter("@BudgetName", SqlDbType.VarChar, 200), new SqlParameter("@projectid", SqlDbType.Int, 4), new SqlParameter("@ID", SqlDbType.Int) }; param[0].Value = subBudgetModel.BudgetName; param[1].Value = subBudgetModel.Projectid; param[2].Value = subBudgetModel.ID; TransactionManager tran = new TransactionManager(); int num = 0; tran.BeginTransaction(); try { num = SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, sqlstr.ToString(), param); tran.Commit(); } catch { tran.Rollback(); } return(num); }
public static int Add(XBase.Model.Office.SellReport.UserProductInfo model) { int num = 0; string sqlstr = "insert into officedba.UserProductInfo(CompanyCD,productNum,productName,price,bref,memo) values(@CompanyCD,@productNum,@productName,@price,@bref,@memo)"; TransactionManager tran = new TransactionManager(); tran.BeginTransaction(); SqlParameter[] param = { new SqlParameter("@CompanyCD", SqlDbType.VarChar, 50), new SqlParameter("@productNum", SqlDbType.VarChar, 50), new SqlParameter("@productName", SqlDbType.VarChar, 200), new SqlParameter("@price", SqlDbType.Decimal), new SqlParameter("@bref", SqlDbType.VarChar, 500), new SqlParameter("@memo", SqlDbType.VarChar, 1000) }; param[0].Value = model.CompanyCD; param[1].Value = model.productNum; param[2].Value = model.productName; param[3].Value = model.price; param[4].Value = model.bref; param[5].Value = model.memo; try { num = SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, sqlstr, param); tran.Commit(); } catch { tran.Rollback(); } return(num); }
/// <summary> /// 删除回款计划 /// </summary> /// <param name="strIDS"></param> /// <returns></returns> public static bool DelSellGathering(string strIDS, out string strMsg) { bool isSucc = false;//是否添加成功 string strSql = "delete from officedba.SellGathering where ID = @ID"; string[] strId = strIDS.Split(','); strMsg = ""; TransactionManager tran = new TransactionManager(); tran.BeginTransaction(); try { for (int i = 0; i < strId.Length; i++) { SqlParameter[] para = { new SqlParameter("@ID", Convert.ToInt32(strId[i])) }; SqlHelper.ExecuteNonQuery(tran.Trans, CommandType.Text, strSql, para); } tran.Commit(); isSucc = true; strMsg = "删除成功!"; } catch (Exception ex) { tran.Rollback(); strMsg = "删除失败,请联系系统管理员!"; isSucc = false; throw ex; } return(isSucc); }
IEnumerator InitiateTransaction(BaseTransaction transaction) { // Gets the handle of the transaction. var deferredResult = TransactionManager.BeginTransaction(transaction); try { // Waits for the process to finish while (!deferredResult.isDone) { yield return(null); } // The process failed if (!deferredResult.isFulfilled) { Debug.LogException(deferredResult.error); } // The process succeeded else { var result = deferredResult.result; DisplayResult(result); } } finally { // A process handle can be released. deferredResult.Release(); } }
public async Task <Unit> Handle(TransactionalCommand request, CancellationToken cancellationToken) { try { _transactionManager.BeginTransaction(); foreach (var command in request.commands.Where(x => x != null)) { await _mediator.Send(command, cancellationToken); } _transactionManager.CommitTransaction(); } catch (Exception e) { _transactionManager.RollbackTransaction(); throw e; } finally { _transactionManager.Dispose(); } return(Unit.Value); }
int SendItemByType(NbManagershareEntity shareEntity, List <ConfigMallgiftbagEntity> prizeList) { if (prizeList.Count <= 0) { return((int)MessageCode.NbParameterError); } var mail = new MailBuilder(shareEntity.ManagerId, "分享礼包", 0, prizeList, EnumMailType.Share, 0, 0); // var mail = new MailBuilder(shareEntity.ManagerId, point, coin, itemList, EnumMailType.Share); using (var transactionManager = new TransactionManager(Dal.ConnectionFactory.Instance.GetDefault())) { transactionManager.BeginTransaction(); var f = true; if (!mail.Save(transactionManager.TransactionObject)) { f = false; } if (!NbManagershareMgr.Update(shareEntity, transactionManager.TransactionObject)) { f = false; } if (f) { transactionManager.Commit(); } else { transactionManager.Rollback(); return((int)MessageCode.Exception); } } return((int)MessageCode.Success); }
public bool Excluir(String strSitefStatusID) { TransactionManager objTransaction = null; try { objTransaction = new TransactionManager(TransactionManager.OpcoesDeDataSource.ServidoDaLojaAtual); objTransaction.BeginTransaction(); this.Excluir(strSitefStatusID, ref objTransaction); if (objTransaction != null) { objTransaction.Commit(); } return(true); } catch (Exception) { if (objTransaction != null) { objTransaction.RollBack(); } throw; } }
private void Instead01(TransactionManager tm, Customer cus) { MessageBox.Show("Something..."); // Begin the transaction after the message box, // e.g. if you want to prompt them to do something before saving. tm.BeginTransaction(); DataRepository.CustomerProvider.Insert(tm, cus); tm.Commit(); }
private void Instead02(TransactionManager tm, Customer cus) { tm.BeginTransaction(); DataRepository.CustomerProvider.Insert(tm, cus); tm.Commit(); // Or, show the message box after the transaction completed, // e.g. to notify them of an event after saving MessageBox.Show("Something..."); }
// SAMPLE 01 // // As mentioned in "C01_TransactionManager," the idea behind transactions // is that it should surround a block of code that either saves everything // or nothing. // // Here is the thing to remember: While the transaction is open it will prevent // anything from accessing the database tables that you are busy with. This is // to prevent "dirty" or incomplete records. // // The caveat: you want your transaction to execute as fast as possible. Be // like a ninja: get in, do your thing, and get out. // private void BadlyMisplacedCode(TransactionManager tm, Customer cus) { tm.BeginTransaction(); DataRepository.CustomerProvider.Insert(tm, cus); MessageBox.Show("Something..."); tm.Commit(); // Can you see it? // This code will block the Customer table on the entire branch until the user // clicks "OK" on the message box. The impact of this is enourmous. }
public void TransactionManagerCommitsChildTransactions() { var seed = new Seed32(); var hits = 0; using (var manager = new TransactionManager<int, MockClassA>() ) { manager.TransactionCommitted += new TransactionCommit<int, MockClassA> (delegate(ITransaction<int, MockClassA> transaction) { Assert.AreEqual(3, transaction.GetEnlistedActions().Count()); hits++; transaction.MarkComplete(); }); var testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); using (var tLock1 = manager.BeginTransaction()) { foreach (var entity in testEntities) tLock1.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock2 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock2.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock3 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock3.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock4 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock4.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock5 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock5.Transaction.Enlist(Action.Create, entity.Id, entity); tLock1.Transaction.Commit(); } } } } } } Assert.AreEqual(5, hits); }
public void TransactionManagerRollsbackAll() { var seed = new Seed32(); using (var manager = new TransactionManager<int, MockClassA>() ) { manager.TransactionCommitted += new TransactionCommit<int, MockClassA> (delegate(ITransaction<int, MockClassA> transaction) { transaction.MarkComplete(); Assert.Fail(); }); var testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); using (var tLock1 = manager.BeginTransaction()) { foreach (var entity in testEntities) tLock1.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock2 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock2.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock3 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock3.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock4 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock4.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock5 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock5.Transaction.Enlist(Action.Create, entity.Id, entity); manager.RollBackAll(true); while (manager.HasActiveTransactions) Thread.Sleep(100); Assert.IsTrue(tLock5.Transaction.IsComplete); } Assert.IsTrue(tLock4.Transaction.IsComplete); } Assert.IsTrue(tLock3.Transaction.IsComplete); } Assert.IsTrue(tLock2.Transaction.IsComplete); } Assert.IsTrue(tLock1.Transaction.IsComplete); } } }
public void TransactionManagerCommitAllCommitsAllTransactions() { var sync = new object(); var seed = new Seed32(); var hits = 0; using (var manager = new TransactionManager<int, MockClassA>()) { manager.TransactionCommitted += new TransactionCommit<int, MockClassA> (delegate(ITransaction<int, MockClassA> transaction) { Assert.AreEqual(3, transaction.GetEnlistedActions().Count()); hits++; transaction.MarkComplete(); }); var transList = new List<TransactionLock<int, MockClassA>>(); Parallel.For(0, 5, delegate(int i) { var testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); var trans = manager.BeginTransaction(); foreach (var entity in testEntities) trans.Transaction.Enlist(Action.Create, entity.Id, entity); if (i == 1) { lock (sync) transList.Add(trans); Assert.AreEqual(3, manager.GetCached().Count()); } else trans.Transaction.Commit(); }); manager.CommitAll(true); Assert.AreEqual(0, manager.GetCached().Count()); } Assert.AreEqual(5, hits); }
public void TransactionLockAutoCommitsTransactions() { var seed = new Seed32(); int committed = 0; using (var manager = new TransactionManager<int, MockClassA>() ) { manager.TransactionCommitted += new TransactionCommit<int, MockClassA> (delegate(ITransaction<int, MockClassA> transaction) { Assert.AreEqual(3, transaction.GetEnlistedActions().Count()); committed += transaction.GetEnlistedActions().Count(); transaction.MarkComplete(); }); var testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); using (var tLock1 = manager.BeginTransaction()) { foreach (var entity in testEntities) tLock1.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock2 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock2.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock3 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock3.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock4 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock4.Transaction.Enlist(Action.Create, entity.Id, entity); using (var tLock5 = manager.BeginTransaction()) { testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); foreach (var entity in testEntities) tLock5.Transaction.Enlist(Action.Create, entity.Id, entity); } } } } tLock1.Transaction.Commit(); var sw = new Stopwatch(); while (!tLock1.Transaction.IsComplete && sw.ElapsedMilliseconds < 1000) Thread.Sleep(100); sw.Stop(); Assert.AreEqual(15, committed); Assert.IsTrue(tLock1.Transaction.IsComplete); } } }
public void AfmRebuildsOnFailedTransaction() { _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString(); var formatter = new BSONFormatter(); var core = new FileCore<int, long>() { IdSeed = new Seed32(999), SegmentSeed = new Seed64(), MinimumCoreStride = 512 }; var entity = TestResourceFactory.CreateRandom() as MockClassC; var largeEntity = TestResourceFactory.CreateRandom().WithName(new String('a', 2000)) as MockClassC; IDictionary<int, long> returnSegments = null; using (var fLock = new ManagedFileLock(_testName)) { Cleanup(); using (var afm = new AtomicFileManager<MockClassA>(_testName + ".database", core, formatter)) { afm.Load<int>(); using (var manager = new TransactionManager<int, MockClassA> (new MockTransactionFactory<int, MockClassA>() , new TransactionSynchronizer<int, MockClassA>())) { manager.TransactionCommitted += new TransactionCommit<int, MockClassA>( delegate(ITransaction<int, MockClassA> tranny) { returnSegments = afm.CommitTransaction(tranny, new Dictionary<int, long>()); while (afm.FileFlushQueueActive) Thread.Sleep(100); tranny.MarkComplete(); afm.SaveCore<int>(); }); using (var tLock = manager.BeginTransaction()) { tLock.Transaction.Enlist(Action.Create, entity.Id, entity); tLock.Transaction.Commit(); } } } using (var afm = new AtomicFileManager<MockClassA>(_testName + ".database", formatter)) { afm.Load<int>(); using (var manager = new TransactionManager<int, MockClassA> (new MockTransactionFactory<int, MockClassA>() , new TransactionSynchronizer<int, MockClassA>())) { manager.TransactionCommitted += new TransactionCommit<int, MockClassA>( delegate(ITransaction<int, MockClassA> tranny) { returnSegments = afm.CommitTransaction(tranny, returnSegments); while (afm.FileFlushQueueActive) Thread.Sleep(100); tranny.MarkComplete(); afm.SaveCore<int>(); }); using (var tLock = manager.BeginTransaction()) { tLock.Transaction.Enlist(Action.Update, largeEntity.Id, largeEntity); tLock.Transaction.Commit(); } } } using (var afm = new AtomicFileManager<MockClassA>(_testName + ".database", formatter)) { afm.Load<int>(); Assert.Greater(afm.Stride, 2200); Assert.AreEqual(1024, afm.CorePosition); var obj = afm.LoadSegmentFrom(returnSegments.First().Value) as MockClassC; Assert.IsNotNull(obj); Assert.AreEqual(largeEntity.Id, obj.Id); Assert.AreEqual(largeEntity.Name, obj.Name); Assert.AreEqual(largeEntity.GetSomeCheckSum, obj.GetSomeCheckSum); Assert.AreEqual(largeEntity.Location.X, obj.Location.X); Assert.AreEqual(largeEntity.Location.Y, obj.Location.Y); Assert.AreEqual(largeEntity.Location.Z, obj.Location.Z); Assert.AreEqual(largeEntity.Location.W, obj.Location.W); Assert.AreEqual(largeEntity.ReferenceCode, obj.ReferenceCode); Assert.AreEqual(largeEntity.ReplicationID, obj.ReplicationID); } } }
public void TransactionManagerRollsbackOnDispose() { var seed = new Seed32(); using (var manager = new TransactionManager<int, MockClassA>() ) { manager.TransactionCommitted += new TransactionCommit<int, MockClassA> (delegate(ITransaction<int, MockClassA> transaction) { transaction.MarkComplete(); Assert.Fail(); }); var testEntities = TestResourceFactory.GetMockClassAObjects(3).ToList(); testEntities.ForEach(e => e.Id = seed.Increment()); using (var tLock1 = manager.BeginTransaction()) { foreach (var entity in testEntities) tLock1.Transaction.Enlist(Action.Create, entity.Id, entity); tLock1.Transaction.Dispose(); Assert.IsTrue(tLock1.Transaction.IsComplete); } } }
public void AfmCommitsComplexTransaction() { _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString(); Cleanup(); var formatter = new BSONFormatter(); var core = new FileCore<int, long>() { IdSeed = new Seed32(999), SegmentSeed = new Seed64(), Stride = 32 }; var addEntities = TestResourceFactory.GetMockClassAObjects(25).ToList(); foreach (var entity in addEntities) entity.Id = core.IdSeed.Increment(); var updateEntities = new List<MockClassC>(); IDictionary<int, long> returnSegments = null; using (var afm = new AtomicFileManager<MockClassA>(_testName + ".database", core, formatter)) { afm.Load<int>(); using (var manager = new TransactionManager<int, MockClassA> (new MockTransactionFactory<int, MockClassA>() , new TransactionSynchronizer<int, MockClassA>())) { afm.Rebuilt += new Rebuild<MockClassA>(delegate(Guid transactionId, int newStride, long newLength, int newSeedStride) { var c = (IFileCore<int, long>)afm.Core; c.Stride = newStride; c.MinimumCoreStride = newSeedStride; afm.SaveCore<int>(); }); manager.TransactionCommitted += new TransactionCommit<int, MockClassA>( delegate(ITransaction<int, MockClassA> tranny) { returnSegments = afm.CommitTransaction(tranny, new Dictionary<int, long>()); tranny.MarkComplete(); }); using (var tLock = manager.BeginTransaction()) { addEntities.ForEach(delegate(MockClassA entity) { tLock.Transaction.Enlist(Action.Create, entity.Id, entity); }); tLock.Transaction.Commit(); Assert.AreEqual(25, afm.Length); } } } using (var afm = new AtomicFileManager<MockClassA>(_testName + ".database", formatter)) { afm.Load<int>(); Assert.AreEqual(25, afm.Length); using (var manager = new TransactionManager<int, MockClassA> (new MockTransactionFactory<int, MockClassA>() , new TransactionSynchronizer<int, MockClassA>())) { afm.Rebuilt += new Rebuild<MockClassA>(delegate(Guid transactionId, int newStride, long newLength, int newSeedStride) { var c = (IFileCore<int, long>)afm.Core; c.Stride = newStride; c.MinimumCoreStride = newSeedStride; afm.SaveCore<int>(); }); manager.TransactionCommitted += new TransactionCommit<int, MockClassA>( delegate(ITransaction<int, MockClassA> tranny) { returnSegments = afm.CommitTransaction(tranny, returnSegments); tranny.MarkComplete(); }); using (var tLock = manager.BeginTransaction()) { foreach (var kvp in returnSegments) updateEntities.Add(afm.LoadSegmentFrom(kvp.Value) as MockClassC); updateEntities.ForEach(u => u.Name = (u.Location.X + u.Location.Y).ToString() + u.Name); updateEntities.ForEach(u => tLock.Transaction.Enlist(Action.Update, u.Id, u)); var insert = TestResourceFactory.CreateRandom().WithName("numb nugget") as MockClassC; insert.Id = core.IdSeed.Increment(); updateEntities.Add(insert); tLock.Transaction.Enlist(Action.Create, insert.Id, insert); tLock.Transaction.Commit(); Assert.AreEqual(26, afm.Length); } } } using (var afm = new AtomicFileManager<MockClassA>(_testName + ".database", formatter)) { afm.Load<int>(); Assert.LessOrEqual(461, afm.Stride); Assert.AreEqual(10240, afm.CorePosition); foreach (var entity in updateEntities) { var obj = afm.LoadSegmentFrom(returnSegments[entity.Id]) as MockClassC; Assert.IsNotNull(obj); Assert.AreEqual(entity.Id, obj.Id); Assert.AreEqual(entity.Name, obj.Name); Assert.AreEqual(entity.GetSomeCheckSum, obj.GetSomeCheckSum); Assert.AreEqual(entity.Location.X, obj.Location.X); Assert.AreEqual(entity.Location.Y, obj.Location.Y); Assert.AreEqual(entity.Location.Z, obj.Location.Z); Assert.AreEqual(entity.Location.W, obj.Location.W); Assert.AreEqual(entity.ReferenceCode, obj.ReferenceCode); Assert.AreEqual(entity.ReplicationID, obj.ReplicationID); } } }
public void AfmRebuildsWithNewSeedSize() { _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString(); Cleanup(); var formatter = new BSONFormatter(); var core = new FileCore<int, long>() { IdSeed = new Seed32(999), SegmentSeed = new Seed64(), MinimumCoreStride = 512 }; var addEntities = TestResourceFactory.GetMockClassAObjects(20480).ToList(); foreach (var entity in addEntities) entity.Id = core.IdSeed.Increment(); var updateEntities = new List<MockClassC>(); IDictionary<int, long> returnSegments = null; IDictionary<int, long> deletedSegments = new Dictionary<int, long>(); using (var afm = new AtomicFileManager<MockClassA>(_testName + ".database", core)) { afm.Load<int>(); using (var manager = new TransactionManager<int, MockClassA> (new MockTransactionFactory<int, MockClassA>() , new TransactionSynchronizer<int, MockClassA>())) { manager.TransactionCommitted += new TransactionCommit<int, MockClassA>( delegate(ITransaction<int, MockClassA> tranny) { returnSegments = afm.CommitTransaction(tranny, new Dictionary<int, long>()); while (afm.FileFlushQueueActive) Thread.Sleep(100); tranny.MarkComplete(); afm.SaveCore<int>(); }); using (var tLock = manager.BeginTransaction()) { addEntities.ForEach(delegate(MockClassA entity) { tLock.Transaction.Enlist(Action.Create, entity.Id, entity); }); Assert.AreEqual(20480, tLock.Transaction.EnlistCount); tLock.Transaction.Commit(); Assert.AreEqual(20480, afm.Length); } } } using (var afm = new AtomicFileManager<MockClassA>(_testName + ".database", core)) { afm.Load<int>(); Assert.AreEqual(20480, afm.Length); using (var manager = new TransactionManager<int, MockClassA> (new MockTransactionFactory<int, MockClassA>() , new TransactionSynchronizer<int, MockClassA>())) { manager.TransactionCommitted += new TransactionCommit<int, MockClassA>( delegate(ITransaction<int, MockClassA> tranny) { returnSegments = afm.CommitTransaction(tranny, returnSegments); while (afm.FileFlushQueueActive) Thread.Sleep(100); tranny.MarkComplete(); afm.SaveCore<int>(); core.MinimumCoreStride = (int)formatter.FormatObjStream(core).Length; }); using (var tLock = manager.BeginTransaction()) { deletedSegments = returnSegments.Take(9000).ToDictionary(k => k.Key, k => k.Value); foreach (var kvp in deletedSegments) updateEntities.Add(afm.LoadSegmentFrom(kvp.Value) as MockClassC); updateEntities.ForEach(u => tLock.Transaction.Enlist(Action.Delete, u.Id, u)); tLock.Transaction.Commit(); afm.SaveCore<int>(); } Assert.AreEqual(512, afm.Stride); //Deleting items from the database adds those idsToDelete to the segmentSeed'aqn open Ids list, increasing it'aqn size. It'aqn an easy way to check for segmentSeed rebuilding. Assert.Greater(afm.Core.MinimumCoreStride, 23000); } } }
public void AfmReturnsRightNumberOfJObjects() { _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString(); Cleanup(); var formatter = new BSONFormatter(); var core = new FileCore<int, long>() { IdSeed = new Seed32(999), SegmentSeed = new Seed64(), MinimumCoreStride = 512 }; var addEntities = TestResourceFactory.GetMockClassAObjects(10000).ToList(); foreach (var entity in addEntities) entity.Id = _seed.Increment(); IDictionary<int, long> returnSegments = null; using (var afm = new AtomicFileManager<MockClassA>(_testName + ".database", core)) { afm.Load<int>(); using (var manager = new TransactionManager<int, MockClassA> (new MockTransactionFactory<int, MockClassA>() , new TransactionSynchronizer<int, MockClassA>())) { manager.TransactionCommitted += new TransactionCommit<int, MockClassA>( delegate(ITransaction<int, MockClassA> tranny) { returnSegments = afm.CommitTransaction(tranny, new Dictionary<int, long>()); tranny.MarkComplete(); }); using (var tLock1 = manager.BeginTransaction()) { addEntities.ForEach(delegate(MockClassA entity) { tLock1.Transaction.Enlist(Action.Create, entity.Id, entity); }); tLock1.Transaction.Commit(); Assert.AreEqual(10000, afm.Length); } foreach (var group in afm.AsEnumerable()) { var match = group.Where(i => i.SelectToken("Id").Value<int>() > 9999).ToList(); if (match == null || !match.Any()) continue; var result = match.First(r => r.Value<int>("Id") == 10000).ToObject<MockClassC>(); Assert.IsNotNull(result); Assert.AreEqual(10000, result.Id); break; } } } }