public StandardTransaction(TransactionDelegate onTransactionCommitted, TransactionDelegate onTransactionRolledback, TransactionMode transactionMode, IsolationMode isolationMode, bool distributedTransaction) : this(transactionMode, isolationMode, distributedTransaction) { this.onTransactionCommitted = onTransactionCommitted; this.onTransactionRolledback = onTransactionRolledback; }
private void Initialize(TransactionDelegate transactionDelegate, RetryDelegate retryDelegate, TransactionOptions options) { _options = options; State = TransactionState.Active; TransactionDelegate = transactionDelegate; RetryDelegate = retryDelegate; }
public void UpdateDB(List <SaveParam> p) { st2.Reset(); TransactionDelegate t = new TransactionDelegate(); t.ProcessEventHandler += AddList_ProcessEventHandler; t.BeginTransaction(t, p); }
protected void RaiseTransactionCommitted(ITransaction transaction) { TransactionDelegate eventDelegate = (TransactionDelegate)_events[TransactionCommittedEvent]; if (eventDelegate != null) { eventDelegate(transaction); } }
protected void RaiseTransactionRolledback(ITransaction transaction) { TransactionDelegate eventDelegate = (TransactionDelegate)_events[TransactionRolledbackEvent]; if (eventDelegate != null) { eventDelegate(transaction); } }
/// <summary> /// The actual transaction recorded by Shopify after having processed the payment with the gateway. /// </summary> public PaymentQuery transaction(TransactionDelegate buildQuery) { Query.Append("transaction "); Query.Append("{"); buildQuery(new TransactionQuery(Query)); Query.Append("}"); return(this); }
public static Transaction ExecuteTransaction(TransactionDelegate transactionDelegate, RetryDelegate retryDelegate, TransactionOptions options) { _trasaction = new Transaction(transactionDelegate, retryDelegate); _trasaction.TransactionDelegate.Invoke(_trasaction); while (_trasaction.State == TransactionState.Aborted && _trasaction.RetryDelegate != null && _trasaction.RetryDelegate.Invoke(_trasaction)) { _trasaction.TransactionDelegate.Invoke(_trasaction); } return(_trasaction); }
public static void UsingTransaction(TransactionDelegate action) { using (var tr = Active.Database.TransactionManager.StartTransaction()) { try { action(tr); tr.Commit(); } catch (System.Exception) { tr.Abort(); throw; } } }
/// <summary> /// Executes the the action specified by the given delegate callback within a transaction. /// </summary> /// <param name="transactionMethod">The delegate that specifies the transactional action.</param> /// <returns> /// A result object returned by the callback, or <code>null</code> if one /// </returns> /// <remarks>Allows for returning a result object created within the transaction, that is, /// a domain object or a collection of domain objects. An exception thrown by the callback /// is treated as a fatal exception that enforces a rollback. Such an exception gets /// propagated to the caller of the template. /// </remarks> /// <exception cref="Spring.Transaction.TransactionException"> /// In case of initialization or system errors. /// </exception> public object Execute(TransactionDelegate transactionMethod) { ITransactionStatus status = _platformTransactionManager.GetTransaction(this); object result; try { result = transactionMethod(status); } catch (Exception ex) { rollbackOnException(status, ex); throw; } _platformTransactionManager.Commit(status); return(result); }
private void AddList_ProcessEventHandler(TransactionDelegate trd, dynamic dy) { string temStr = string.Empty; List <SaveParam> p = (List <SaveParam>)dy; if (this.isHaveError) { return; } re = 0; int count = 0; foreach (SaveParam item in p) { if (this.isHaveError) { return; } count++; if (string.IsNullOrEmpty(item.Content1) || string.IsNullOrEmpty(item.Content2) || item.Content1.Length > strMaxLength || item.Content1.Length > strMaxLength) { continue; } guidList.Add(item.guid); guidList1.Add(item.guid1); guidList2.Add(item.guid2); contentList1.Add(item.Content1); contentList2.Add(item.Content2); originalList.Add(this.Original); HW_RelevanceList.Add(this.HW_RELEVANCE); if (count % commitCount == 0 && guidList.Count > 0) { SaveHelperStatus = string.Format("布隆耗时{0}:{1}s,执行SQL中", guidList.Count.ToString(), (st2.ElapsedMilliseconds).ToString()); NewMethod(trd); } } if (guidList.Count > 0) { SaveHelperStatus = string.Format("最后一次布隆耗时{0}:{1}s,执行SQL中", guidList.Count.ToString(), (st2.ElapsedMilliseconds).ToString()); NewMethod(trd); } p.Clear(); IsBusy = false; }
private void Transact(string sqlString, TransactionDelegate transactionDelegate) { using (var connection = new SQLiteConnection(_connectionString)) { connection.Open(); using (var transaction = connection.BeginTransaction()) { var command = new SQLiteCommand(connection); command.CommandText = sqlString; transactionDelegate(command); transaction.Commit(); } connection.Close(); } }
public long CreateUser(TransactionDelegate tranDelegate, int seconds, double sucessRate) { for (int i = 0; i < seconds; i++) { _logger?.LogInformation("正在创建用户,{0}%", i * 10); Thread.Sleep(1000); } tranDelegate.CommitAction = () => { var val = Random.Next(1000); if (val / 1000.0 > sucessRate) { throw new Exception("提交失败"); } _logger.LogInformation("事务提交成功"); }; tranDelegate.RollbackAction = () => _logger.LogInformation("事务回滚了"); return(DateTime.Now.Ticks); }
public long CreateBankAccount(TransactionDelegate tranDelegate, long userid, int seconds, double sucessRate) { if (userid == 0) { throw new Exception("用户id无效"); } for (int i = 0; i < seconds; i++) { _logger?.LogInformation("正在创建银行账号,{0}%", i * 10); Thread.Sleep(1000); } tranDelegate.CommitAction = () => { var val = Random.Next(1000); if (val / 1000.0 > sucessRate) { throw new Exception("提交失败"); } _logger.LogInformation("事务提交成功"); }; tranDelegate.RollbackAction = () => _logger.LogInformation("事务回滚了"); return(userid); }
void retry(InvokeCommand cmd, object userContent) { TransactionDelegate transactionDelegate = null; MicroServiceControllerBase controller = null; object[] parameters = null; try { MicroServiceControllerBase.RequestingCommand.Value = cmd; var controllerTypeInfo = _microServiceHost.ServiceNames[cmd.Service]; controller = (MicroServiceControllerBase)_microServiceHost.ServiceProvider.GetService(controllerTypeInfo.Type); controller.UserContent = userContent; controller._keyLocker = _microServiceHost.ServiceProvider.GetService <IKeyLocker>(); var methodInfo = controllerTypeInfo.Methods.FirstOrDefault(m => m.Method.Name == cmd.Method); if (methodInfo == null) { throw new Exception($"{cmd.Service}没有提供{cmd.Method}方法"); } MicroServiceControllerBase.Current = controller; var parameterInfos = methodInfo.Method.GetParameters(); object result = null; int startPIndex = 0; if (parameterInfos.Length > 0) { parameters = new object[parameterInfos.Length]; if (parameterInfos[0].ParameterType == typeof(TransactionDelegate)) { startPIndex = 1; parameters[0] = transactionDelegate = new TransactionDelegate(cmd.Header["TranId"]); transactionDelegate.RequestCommand = cmd; } } controller.OnBeforeAction(cmd.Method, parameters); if (parameterInfos.Length > 0) { for (int i = startPIndex, index = 0; i < parameters.Length && index < cmd.Parameters.Length; i++, index++) { string pvalue = cmd.Parameters[index]; if (pvalue == null) { continue; } parameters[i] = Newtonsoft.Json.JsonConvert.DeserializeObject(pvalue, parameterInfos[i].ParameterType); } } result = methodInfo.Method.Invoke(controller, parameters); controller.OnAfterAction(cmd.Method, parameters); if (transactionDelegate != null && (transactionDelegate.CommitAction != null || transactionDelegate.RollbackAction != null)) { } else if (controller.TransactionControl != null && (controller.TransactionControl.CommitAction != null || controller.TransactionControl.RollbackAction != null)) { transactionDelegate = controller.TransactionControl; transactionDelegate.RequestCommand = cmd; } if (transactionDelegate != null && transactionDelegate.CommitAction != null) { transactionDelegate.CommitAction(); } transactionDelegate = null; } finally { MicroServiceControllerBase.Current = null; controller?.OnUnLoad(); } }
public Bank(TransactionDelegate transactionDelegate, SavingDelegate savingDelegate, InvestmentDelegate investmentDelegate) { _transactionDelegate = transactionDelegate; _savingDelegate = savingDelegate; _investmentDelegate = investmentDelegate; }
public void Handle(NetClient netclient, InvokeCommand cmd) { TransactionDelegate transactionDelegate = null; MicroServiceControllerBase controller = null; object[] parameters = null; try { MicroServiceControllerBase.RequestingCommand.Value = cmd; var controllerTypeInfo = _MicroServiceProvider.ServiceNames[cmd.Service]; object userContent = null; if (controllerTypeInfo.NeedAuthorize) { var auth = _MicroServiceProvider.ServiceProvider.GetService <IAuthenticationHandler>(); if (auth != null) { userContent = auth.Authenticate(cmd.Header); } } controller = (MicroServiceControllerBase)_MicroServiceProvider.ServiceProvider.GetService(controllerTypeInfo.Type); controller.UserContent = userContent; controller.NetClient = netclient; controller._keyLocker = _MicroServiceProvider.ServiceProvider.GetService <IKeyLocker>(); _logger?.LogDebug("invoke service:{0} method:{1} parameters:{2}", cmd.Service, cmd.Method, cmd.Parameters); var methodInfo = controllerTypeInfo.Methods.FirstOrDefault(m => m.Method.Name == cmd.Method); if (methodInfo == null) { throw new Exception($"{cmd.Service}没有提供{cmd.Method}方法"); } if (methodInfo.NeedAuthorize && userContent == null) { var auth = _MicroServiceProvider.ServiceProvider.GetService <IAuthenticationHandler>(); if (auth != null) { userContent = auth.Authenticate(cmd.Header); } } MicroServiceControllerBase.Current = controller; var parameterInfos = methodInfo.Method.GetParameters(); object result = null; int startPIndex = 0; if (parameterInfos.Length > 0) { parameters = new object[parameterInfos.Length]; if (parameterInfos[0].ParameterType == typeof(TransactionDelegate)) { startPIndex = 1; parameters[0] = transactionDelegate = new TransactionDelegate(cmd.Header["TranId"]); transactionDelegate.RequestCommand = cmd; } } controller.BeforeAction(cmd.Method, parameters); if (parameterInfos.Length > 0) { for (int i = startPIndex, index = 0; i < parameters.Length && index < cmd.Parameters.Length; i++, index++) { string pvalue = cmd.Parameters[index]; if (pvalue == null) { continue; } try { parameters[i] = Newtonsoft.Json.JsonConvert.DeserializeObject(pvalue, parameterInfos[i].ParameterType); } catch (Exception) { _logger?.LogError("转换参数出错,name:{0} cmd:{1}", parameterInfos[i].Name, cmd.ToJsonString()); } } } result = methodInfo.Method.Invoke(controller, parameters); controller.AfterAction(cmd.Method, parameters); var supportTran = false; if (transactionDelegate != null && (transactionDelegate.CommitAction != null || transactionDelegate.RollbackAction != null)) { supportTran = true; } else if (controller.TransactionControl != null && (controller.TransactionControl.CommitAction != null || controller.TransactionControl.RollbackAction != null)) { transactionDelegate = controller.TransactionControl; transactionDelegate.RequestCommand = cmd; supportTran = true; } if (supportTran && cmd.Header.ContainsKey("Tran") && cmd.Header["Tran"] == "0") { //调用端不需要事务支持,所以,直接提交 if (transactionDelegate.CommitAction != null) { transactionDelegate.CommitAction(); } transactionDelegate = null; supportTran = false; } netclient.WriteServiceData(new InvokeResult { Success = true, SupportTransaction = supportTran, Data = result }); if (!supportTran) { return; } netclient.ReadTimeout = 0; while (true) { cmd = netclient.ReadServiceObject <InvokeCommand>(); if (cmd.Type == InvokeType.CommitTranaction) { var tran = transactionDelegate; transactionDelegate = null; if (tran != null && tran.CommitAction != null) { tran.CommitAction(); _loggerTran?.LogInformation("事务{0}提交完毕,请求数据:{1}", tran.TransactionId, tran.RequestCommand.ToJsonString()); } netclient.WriteServiceData(new InvokeResult() { Success = true }); return; } else if (cmd.Type == InvokeType.RollbackTranaction) { var tran = transactionDelegate; transactionDelegate = null; if (tran != null && tran.RollbackAction != null) { tran.RollbackAction(); _loggerTran?.LogInformation("事务{0}回滚完毕,请求数据:{1}", tran.TransactionId, tran.RequestCommand.ToJsonString()); } netclient.WriteServiceData(new InvokeResult() { Success = true }); return; } else if (cmd.Type == InvokeType.HealthyCheck) { netclient.WriteServiceData(new InvokeResult { Success = transactionDelegate.AgreeCommit }); } } } catch (SocketException) { if (transactionDelegate != null) { //连接意外中断,交给TransactionDelegateCenter事后处理 _logger?.LogInformation("连接意外中断,交给TransactionDelegateCenter事后处理,事务id:{0}", transactionDelegate.TransactionId); _transactionDelegateCenter.AddTransactionDelegate(transactionDelegate); transactionDelegate = null; } return; } catch (ResponseEndException) { return; } catch (Exception ex) { if (transactionDelegate != null) { try { if (transactionDelegate.RollbackAction != null) { transactionDelegate.RollbackAction(); _loggerTran?.LogInformation("事务{0}回滚完毕,请求数据:{1}", transactionDelegate.TransactionId, transactionDelegate.RequestCommand.ToJsonString()); } } catch (Exception rollex) { _logger?.LogError(rollex, rollex.Message); } transactionDelegate = null; } try { if (controller?.InvokeError(cmd.Method, parameters, ex) == false) { _logger?.LogError(ex, ex.Message); } } catch (ResponseEndException) { return; } while (ex.InnerException != null) { ex = ex.InnerException; } netclient.WriteServiceData(new InvokeResult { Success = false, Error = ex.Message }); return; } finally { MicroServiceControllerBase.Current = null; controller?.UnLoad(); } }
/// <summary> /// Create a new transaction. Any actions performed in the transaction will be committed atomically, and /// if the commit fails the datastore will be updated, and the actions will be retried until they succeed /// or the maximum number of retries is exceeded /// </summary> /// <param name="actions">The datastore operations to perform in the transaction. Note only synchronous operation /// should be performed within the actions delegate</param> /// <returns></returns> public Transaction Transaction(TransactionDelegate actions) { return(new Transaction(this, actions)); }
public static void CreateTransaction(Transaction pTran, ApplicationDbContext context) { if (pTran.Amount == 0) { throw new ForbiddenException("Transaction amount may not be '$0.00'. Trivial transactions are disallowed."); } Account account = Account.GetSingleAccount(pTran.AccountId, context); if (account == null) { throw new NotFoundException("Could not find account with Id: " + pTran.AccountId.ToString()); } // Bad Id passed // New tran can't be before the most recent tran on the account Transaction mostRecentTran = account.Transactions.OrderByDescending(tran => tran.Date).FirstOrDefault(); if (mostRecentTran != null && mostRecentTran.Date > pTran.Date) { throw new ForbiddenException("Transaction Date must not be before the most recent transaction on the Account."); } // TODO: Setup some kind of Guid key for the acct and check here if it matches // (if check fails, return 409 Conflict status code, since someone else has made a tran in the meantime...) decimal currentResaleTotal = account.Transactions.Sum(tran => tran.TransactionDistributions.Where(tranDist => tranDist.RevenueCodeId == RevenueCode.RESALE_ID).Sum(tranDist => tranDist.Amount)); decimal currentReturnTotal = account.Transactions.Sum(tran => tran.TransactionDistributions.Where(tranDist => tranDist.RevenueCodeId == RevenueCode.RETURN_ID).Sum(tranDist => tranDist.Amount)); TransactionDelegate tranHandler = null; switch (pTran.TransactionTypeId) { case TransactionType.RESALE_ID: tranHandler = CreateResale; break; case TransactionType.RETURN_ID: tranHandler = CreateReturn; break; case TransactionType.PURCHASE_ID: tranHandler = CreatePurchase; break; case TransactionType.CASHOUT_ID: if (currentResaleTotal <= 0) { throw new ForbiddenException("Cannot cashout an account with a 0 balance in resales--nothing to cashout."); } tranHandler = CreateCashout; break; default: throw new NotFoundException($"Could not find TransactionType with Id: {pTran.TransactionTypeId}."); // Bad transaction type Id! } if (pTran.Amount + currentResaleTotal + currentReturnTotal < 0) { throw new ForbiddenException("Transaction results in an Account balance less than $0.00."); } tranHandler(pTran.Amount, currentResaleTotal, currentReturnTotal, pTran.AccountId, pTran.Date, context); // Update total amount on the Account itself account.Total = pTran.Amount + currentResaleTotal + currentReturnTotal; context.SaveChanges(); }
private void InvokeTransactionRolledback(ITransaction transaction) { TransactionDelegate Delegate = TransactionRolledback; }
internal Transaction(TransactionDelegate transactionDelegate, RetryDelegate retryDelegate, TransactionOptions options) { Initialize(transactionDelegate, retryDelegate, options); }
public TransactionTableData() { DataSource = new TransactionDataSource(this); Delegate = new TransactionDelegate(this); TransactionDeltas = new List<Transaction.Delta>(); }
private void NewMethod(TransactionDelegate trd) { try { if (isHaveError) { return; } st1.Restart(); //SaveHelperStatus = string.Format("开始执行SQL"); if (trd != null && trd.isHaveError) { return; } temSql1.AppendFormat(" insert into MONOLINGUALSENTENCE{0}(ID,Content,Original,HW_Relevance) values(:ID,:Content,:Original,:HW_Relevance)", fromLang); temParam1.Add(new OracleParameter(":ID", OracleDbType.Varchar2, guidList1.ToArray(), System.Data.ParameterDirection.Input)); temParam1.Add(new OracleParameter(":Content", OracleDbType.Varchar2, contentList1.ToArray(), System.Data.ParameterDirection.Input)); temParam1.Add(new OracleParameter(":Original", OracleDbType.Varchar2, originalList.ToArray(), System.Data.ParameterDirection.Input)); temParam1.Add(new OracleParameter(":HW_Relevance", OracleDbType.Int32, HW_RelevanceList.ToArray(), System.Data.ParameterDirection.Input)); temSql2.AppendFormat(" insert into MONOLINGUALSENTENCE{0}(ID,Content,Original,HW_Relevance) values(:ID,:Content,:Original,:HW_Relevance)", toLang); temParam2.Add(new OracleParameter(":ID", OracleDbType.Varchar2, guidList2.ToArray(), System.Data.ParameterDirection.Input)); temParam2.Add(new OracleParameter(":Content", OracleDbType.Varchar2, contentList2.ToArray(), System.Data.ParameterDirection.Input)); temParam2.Add(new OracleParameter(":Original", OracleDbType.Varchar2, originalList.ToArray(), System.Data.ParameterDirection.Input)); temParam2.Add(new OracleParameter(":HW_Relevance", OracleDbType.Int32, HW_RelevanceList.ToArray(), System.Data.ParameterDirection.Input)); string temStr1 = string.Format(":{0}ID", fromLang); string temStr2 = string.Format(":{0}ID", toLang); temSql3.AppendFormat(" insert into BILINGUALSENTENCE{0}{1}(ID,{0}ID,{1}ID) values(:ID,{2},{3}) ", fromLang, toLang, temStr1, temStr2); temParam3.Add(new OracleParameter(":ID", OracleDbType.Varchar2, guidList.ToArray(), System.Data.ParameterDirection.Input)); temParam3.Add(new OracleParameter(temStr1, OracleDbType.Varchar2, guidList1.ToArray(), System.Data.ParameterDirection.Input)); temParam3.Add(new OracleParameter(temStr2, OracleDbType.Varchar2, guidList2.ToArray(), System.Data.ParameterDirection.Input)); SaveHelperStatus = string.Format("开始保存语言{0}:{1}", fromLang, guidList.ToArray()); re = OracleHelper.ExecuteNonQuery(trd.temTR, CommandType.Text, temSql1.ToString(), guidList.Count, temParam1.ToArray()); if (re > 0) { SaveHelperStatus = string.Format("保存语言{0}成功:{1}", fromLang, re); re = OracleHelper.ExecuteNonQuery(trd.temTR, CommandType.Text, temSql2.ToString(), guidList.Count, temParam2.ToArray()); if (re > 0) { SaveHelperStatus = string.Format("保存语言{0}成功:{1}", toLang, re); re = OracleHelper.ExecuteNonQuery(trd.temTR, CommandType.Text, temSql3.ToString(), guidList.Count, temParam3.ToArray()); if (re > 0) { SaveHelperStatus = string.Format("保存语言{0}_{1}成功:{2}", fromLang, toLang, re); if (trd.temTR != null) { try { trd.Commit(); lock (loc) { saveTatol -= re; } } catch (Exception ex) { SaveHelperStatus = string.Format("保存语言{0}_{1}失败:{2}", fromLang, toLang, guidList.Count); //MessageBox.Show("最后执行commit时出现错误了"+ex.Message); isHaveError = true; trd.Rollback(); } } else { isHaveError = true; trd.Rollback(); } } } else { SaveHelperStatus = string.Format("保存语言{0}失败:{1}", toLang, guidList.Count); isHaveError = true; trd.Rollback(); } } else { SaveHelperStatus = string.Format("保存语言{0}失败:{1}", fromLang, guidList.Count); isHaveError = true; trd.Rollback(); } } catch (Exception ex) { isHaveError = true; SaveHelperStatus = ex.Message; } if (!isHaveError) { SaveHelperStatus = string.Format("执行{0}:{1}s", guidList.Count().ToString(), (st1.ElapsedMilliseconds / (double)1000).ToString()); } else { SaveHelperStatus = string.Format("SQL执行出现了错误{0}:{1}s", SaveHelperStatus, (st1.ElapsedMilliseconds / (double)1000).ToString()); } ClearParam(); st2.Reset(); }
public StandardTransaction(TransactionDelegate onTransactionCommitted, TransactionDelegate onTransactionRolledback) { this.onTransactionCommitted = onTransactionCommitted; this.onTransactionRolledback = onTransactionRolledback; }
public static Transaction ExecuteTransaction(TransactionDelegate transactionDelegate, RetryDelegate retryDelegate) { return(ExecuteTransaction(transactionDelegate, retryDelegate, new TransactionOptions())); }
public TransactionTableData() { DataSource = new TransactionDataSource(this); Delegate = new TransactionDelegate(this); TransactionDeltas = new List <Transaction.Delta>(); }
private void InvokeTransactionCommitted(ITransaction transaction) { TransactionDelegate Delegate = TransactionCommitted; }
internal Transaction(TransactionDelegate transactionDelegate, RetryDelegate retryDelegate) { Initialize(transactionDelegate, retryDelegate, new TransactionOptions()); }
private void InvokeTransactionDisposed(ITransaction transaction) { TransactionDelegate Delegate = TransactionDisposed; }
/// <summary> /// Executes the the action specified by the given delegate callback within a transaction. /// </summary> /// <param name="transactionMethod">The delegate that specifies the transactional action.</param> /// <returns> /// A result object returned by the callback, or <code>null</code> if one /// </returns> /// <remarks>Allows for returning a result object created within the transaction, that is, /// a domain object or a collection of domain objects. An exception thrown by the callback /// is treated as a fatal exception that enforces a rollback. Such an exception gets /// propagated to the caller of the template. /// </remarks> /// <exception cref="Spring.Transaction.TransactionException"> /// In case of initialization or system errors. /// </exception> public object Execute( TransactionDelegate transactionMethod ) { ITransactionStatus status = _platformTransactionManager.GetTransaction( this ); object result; try { result = transactionMethod( status ); } catch ( Exception ex ) { rollbackOnException( status, ex ); throw; } _platformTransactionManager.Commit( status ); return result; }
public static Transaction ExecuteTransaction(TransactionDelegate transactionDelegate, TransactionOptions options) { return(ExecuteTransaction(transactionDelegate, null, options)); }
internal Transaction(Datastore store, TransactionDelegate actions) { _store = store; _actions = actions; }