private void EndTransaction(object sender, TransactionEventArgs e) { SetSlim <IDisposable> set; if (registry.TryGetValue(Session.Transaction, out set)) { registry.Remove(Session.Transaction); foreach (var disposable in set) { disposable.DisposeSafely(); } } }
void RaiseTerminalTransactionEndedEvent() { EventHandler terminalTransactionEndedEvent = TerminalTransactionEndedEvent; TransactionEventArgs tranArg = new TransactionEventArgs(); tranArg.TransactionNumber = TransactionNumber; tranArg.TransactionAccepted = TransactionAccepted; if (terminalTransactionEndedEvent != null) { terminalTransactionEndedEvent(this, tranArg); } }
private async void HandleTransactionChanged(object sender, TransactionEventArgs e) { var transaction = e.Transaction; if ((PortfolioDateRange.FromDate == Date.MinValue) || !PortfolioDateRange.Contains(transaction.TransactionDate) || !OwnedStocks.Any(x => x.Value.Id == transaction.Stock.Id)) { await UpdatePortfolioProperties(); SelectedPage.Activate(); } }
/// <summary> /// Graze food add method. /// This style is not supported in GrazeFoodStoreType /// </summary> /// <param name="resourceAmount">Object to add. This object can be double or contain additional information (e.g. Nitrogen) of food being added</param> /// <param name="activity">Name of activity adding resource</param> /// <param name="reason">Name of individual adding resource</param> public new void Add(object resourceAmount, CLEMModel activity, string reason) { // expecting a GrazeFoodStoreResource (PastureManage) or FoodResourcePacket (CropManage) if (!(resourceAmount.GetType() == typeof(GrazeFoodStorePool) || resourceAmount.GetType() == typeof(FoodResourcePacket))) { throw new Exception(String.Format("ResourceAmount object of type {0} is not supported in Add method in {1}", resourceAmount.GetType().ToString(), this.Name)); } GrazeFoodStorePool pool; if (resourceAmount.GetType() == typeof(GrazeFoodStorePool)) { pool = resourceAmount as GrazeFoodStorePool; } else { pool = new GrazeFoodStorePool(); FoodResourcePacket packet = resourceAmount as FoodResourcePacket; pool.Set(packet.Amount); pool.Nitrogen = packet.PercentN; pool.DMD = packet.DMD; } if (pool.Amount > 0) { // allow decaying or no pools currently available if (PastureDecays || Pools.Count() == 0) { Pools.Insert(0, pool); } else { Pools[0].Add(pool); } // update biomass available biomassAddedThisYear += pool.Amount; ResourceTransaction details = new ResourceTransaction(); details.Gain = pool.Amount; details.Activity = activity.Name; details.ActivityType = activity.GetType().Name; details.Reason = reason; details.ResourceType = this.Name; LastTransaction = details; TransactionEventArgs te = new TransactionEventArgs() { Transaction = details }; OnTransactionOccurred(te); } }
void Current_TransactionCompleted(object sender, TransactionEventArgs e) { e.Transaction.TransactionCompleted -= this.transactionCompletedHandler; if (e.Transaction.TransactionInformation.Status == System.Transactions.TransactionStatus.Aborted) { List <long> transMsgs = null; lock (this.internalStateLock) { if (this.dtcTransMap.TryGetValue(e.Transaction.TransactionInformation.DistributedIdentifier, out transMsgs)) { // remove state about all messages locked in this dtc transaction // if we fail to relock the message, the message will simply go back to the // queue and any subsequent Complete() calls for the message will throw this.dtcTransMap.Remove(e.Transaction.TransactionInformation.DistributedIdentifier); } } if (transMsgs != null) { // relock all messages in this transaction foreach (long msgId in transMsgs) { TryRelockMessage(msgId); // not much we can do in case of failures } } } else if (e.Transaction.TransactionInformation.Status == System.Transactions.TransactionStatus.Committed) { List <long> transMsgs = null; lock (this.internalStateLock) { if (this.dtcTransMap.TryGetValue(e.Transaction.TransactionInformation.DistributedIdentifier, out transMsgs)) { // remove state about all messages locked in this dtc transaction this.dtcTransMap.Remove(e.Transaction.TransactionInformation.DistributedIdentifier); } if (transMsgs != null) { foreach (long msgId in transMsgs) { this.lockMap.Remove(msgId); } } } } }
/// <summary> /// 事务完成事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void OnTransactionCompleted(Object sender, TransactionEventArgs e) { connectionString = null; ConcurrentDictionary <String, DbConnection> connections; if (TransactionConnections.TryRemove(e.Transaction, out connections)) { foreach (var connection in connections.Values) { connection.Dispose(); } } }
private void BroadcastNewTransaction(object sender, TransactionEventArgs e) { if (e == null) { throw new ArgumentNullException(nameof(e)); } if (e.Data == null) { throw new ArgumentNullException(nameof(e.Data)); } Broadcast(e.Data); }
private void OnDtcTransactionCompleted(object sender, TransactionEventArgs args) { TransactionStatus aborted; try { aborted = args.Transaction.TransactionInformation.Status; } catch (ObjectDisposedException) { aborted = TransactionStatus.Aborted; } this.appender.DtcTransactionCompleted(this.connectionId, aborted); }
/// <summary> /// Eventhandler for TransactionScope.TransactionCompleted. /// Closes connections and removes transaction from observed connections. /// </summary> /// <param name="sender">sender</param> /// <param name="e">TransactionEventArgs</param> private static void OnTransactionCompleted(object sender, TransactionEventArgs e) { lock (transactedConnections) { IDictionary <string, DbConnection> connections = null; if (transactedConnections.TryGetValue(e.Transaction, out connections)) { foreach (DbConnection conn in connections.Values) { conn.Close(); } transactedConnections.Remove(e.Transaction); } } }
private void TransactionCompleted(object sender, TransactionEventArgs transactionEventArgs) { if (transactionEventArgs.Transaction.TransactionInformation.Status == TransactionStatus.Aborted) { Transaction.Current.Dispose(); Transaction.Current = null; int index = Operations.FindIndex( operation => operation.Inforamtion == transactionEventArgs.Transaction.TransactionInformation); for (int i = 0; i < index; i++) { Operations[i].DoRollBack(); } } }
/// <summary> /// Add to food store /// </summary> /// <param name="resourceAmount">Object to add. This object can be double or contain additional information (e.g. Nitrogen) of food being added</param> /// <param name="activity">Name of activity adding resource</param> /// <param name="relatesToResource"></param> /// <param name="category"></param> public new void Add(object resourceAmount, CLEMModel activity, string relatesToResource, string category) { HumanFoodStorePool pool; switch (resourceAmount.GetType().Name) { case "HumanFoodStorePool": pool = resourceAmount as HumanFoodStorePool; break; case "Double": pool = new HumanFoodStorePool((double)resourceAmount, 0); break; default: // expecting a HumanFoodStorePool or Double throw new Exception(String.Format("ResourceAmount object of type {0} is not supported in Add method in {1}", resourceAmount.GetType().ToString(), this.Name)); } if (pool.Amount > 0) { HumanFoodStorePool poolOfAge = Pools.Where(a => a.Age == pool.Age).FirstOrDefault(); if (poolOfAge is null) { Pools.Insert(0, pool); } else { poolOfAge.Add(pool.Amount); } ResourceTransaction details = new ResourceTransaction { TransactionType = TransactionType.Gain, Amount = pool.Amount, Activity = activity, RelatesToResource = relatesToResource, Category = category, ResourceType = this }; base.LastGain = pool.Amount; LastTransaction = details; TransactionEventArgs te = new TransactionEventArgs() { Transaction = details }; OnTransactionOccurred(te); } }
/// <summary> /// Add to food store /// </summary> /// <param name="resourceAmount">Object to add. This object can be double or contain additional information (e.g. Nitrogen) of food being added</param> /// <param name="activity">Name of activity adding resource</param> /// <param name="relatesToResource"></param> /// <param name="category"></param> public new void Add(object resourceAmount, CLEMModel activity, string relatesToResource, string category) { if (resourceAmount.GetType().ToString() != "System.Double") { throw new Exception(String.Format("ResourceAmount object of type [{0}] is not supported. Add method in [r={1}]", resourceAmount.GetType().ToString(), this.GetType().ToString())); } double addAmount = (double)resourceAmount; double amountAdded = addAmount; if (this.areaAvailable + addAmount > this.UsableArea) { amountAdded = this.UsableArea - this.areaAvailable; string message = "Tried to add more available land to [r=" + this.Name + "] than exists."; Summary.WriteWarning(this, message); this.areaAvailable = this.UsableArea; } else { this.areaAvailable += addAmount; } ResourceTransaction details = new ResourceTransaction { Style = TransactionStyle.Gain, Amount = amountAdded, Activity = activity, RelatesToResource = relatesToResource, Category = category, ResourceType = this }; LastGain = amountAdded; LastTransaction = details; TransactionEventArgs te = new TransactionEventArgs() { Transaction = details }; OnTransactionOccurred(te); if (category != "Initialise") { UpdateLandAllocatedList(activity, amountAdded, true); // adjust activity using all remaining land as well. if (ActivityRequestingRemainingLand != null && ActivityRequestingRemainingLand != activity) { UpdateLandAllocatedList(ActivityRequestingRemainingLand, amountAdded, true); } } }
/// <summary> /// 事务完成后,关闭数据库链接。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void OnTransactionCompleted(object sender, TransactionEventArgs e) { if (!_transConns.TryGetValue(e.Transaction, out SafetyDictionary <string, DbConnection> connDictionary)) { return; } Tracer.Debug($"Transaction completed."); foreach (var connection in connDictionary.Values) { connection.Dispose(); } _transConns.TryRemove(e.Transaction, out _); }
/// <summary> /// Fires when the command's transaction completes, or the Execute method fires when not within an ambient transaction /// </summary> private void OnCommandTransactionComplete(TransactionEventArgs args) { var handlers = new List <Action <TransactionEventArgs> >(); lock (_transactionCompletedHandlers) { handlers.AddRange(_transactionCompletedHandlers); _transactionCompletedHandlers.Clear(); } handlers.ForEach(handler => { handler(args); }); }
async void ConvertResource() { // Get the price of the source resource. var sourceResourcePredicate = PredicateBuilder.New <TradingResourceRateDto>(rate => rate.GameId == m_parentViewModel.CurrentGame.GameId); sourceResourcePredicate.And(rate => rate.MoveNumber == m_parentViewModel.CurrentGame.CurrentMoveNumber); sourceResourcePredicate.And(rate => rate.TradingResourceId == SourceResource.ResourceId); var sourceResourceRate = await m_resourceRateService.GetAsync(sourceResourcePredicate); // Get the price of the destination resource. var destResourcePredicate = PredicateBuilder.New <TradingResourceRateDto>(rate => rate.GameId == m_parentViewModel.CurrentGame.GameId); destResourcePredicate.And(rate => rate.MoveNumber == m_parentViewModel.CurrentGame.CurrentMoveNumber); destResourcePredicate.And(rate => rate.TradingResourceId == DestResource.ResourceId); var destResourceRate = await m_resourceRateService.GetAsync(destResourcePredicate); // Get source and destination wallets. var sourceWallet = m_parentViewModel.CurrentGameWallets.Find(w => w.ResourceId == SourceResource.ResourceId); var destWallet = m_parentViewModel.CurrentGameWallets.Find(w => w.ResourceId == DestResource.ResourceId); // Send resources to the destination wallet. double amountToSendToDestWallet = SourceResourceCount * sourceResourceRate.TradingResourcePrice / destResourceRate.TradingResourcePrice; try { await m_walletTransactionService.SendResourcesAsync(sourceWallet, destWallet, SourceResourceCount, amountToSendToDestWallet); var args = new TransactionEventArgs { SourceWallet = sourceWallet, AmountWithdrawnFromSourceWallet = SourceResourceCount, DestWallet = destWallet, AmountSentToDestWallet = amountToSendToDestWallet }; m_parentViewModel.RaiseTransactionFinished(this, args); LoggingHelper.Instance.Info($"The user has exchanged [{SourceResourceCount} {SourceResource.ResourceName}] for [{amountToSendToDestWallet} {DestResource.ResourceName}]"); } catch (Exception ex) { LoggingHelper.Instance.Info($"Can't exchange [{SourceResourceCount} {SourceResource.ResourceName}] for [{amountToSendToDestWallet} {DestResource.ResourceName}]", ex); } }
/// <summary> /// Add to food store /// </summary> /// <param name="resourceAmount">Object to add. This object can be double or contain additional information (e.g. Nitrogen) of food being added</param> /// <param name="activity">Name of activity adding resource</param> /// <param name="relatesToResource"></param> /// <param name="category"></param> public new void Add(object resourceAmount, CLEMModel activity, string relatesToResource, string category) { HumanFoodStorePool pool; switch (resourceAmount) { case HumanFoodStorePool _: pool = resourceAmount as HumanFoodStorePool; break; case double _: pool = new HumanFoodStorePool((double)resourceAmount, 0); break; default: throw new Exception($"ResourceAmount object of type [{resourceAmount.GetType().Name}] is not supported in [r={Name}]"); } if (pool.Amount > 0) { HumanFoodStorePool poolOfAge = Pools.Where(a => a.Age == pool.Age).FirstOrDefault(); if (poolOfAge is null) { Pools.Insert(0, pool); } else { poolOfAge.Add(pool.Amount); } ResourceTransaction details = new ResourceTransaction { TransactionType = TransactionType.Gain, Amount = pool.Amount, Activity = activity, RelatesToResource = relatesToResource, Category = category, ResourceType = this }; base.LastGain = pool.Amount; LastTransaction = details; TransactionEventArgs te = new TransactionEventArgs() { Transaction = details }; OnTransactionOccurred(te); } }
private void OnTransactionCompleted(object sender, TransactionEventArgs e) { e.Transaction.TransactionCompleted -= this.transactionCompletedHandler; lock (this.internalStateLock) { List <MsmqReceiveContext> list; if ((e.Transaction.TransactionInformation.Status == TransactionStatus.Committed) && this.transMessages.TryGetValue(e.Transaction.TransactionInformation.DistributedIdentifier, out list)) { foreach (MsmqReceiveContext context in list) { this.messageExpiryMap.Remove(context.LookupId); } } this.transMessages.Remove(e.Transaction.TransactionInformation.DistributedIdentifier); } }
void HandleTransactionCompleted(object sender, TransactionEventArgs e) { if (e.Transaction.TransactionInformation.Status != TransactionStatus.Committed) { return; } foreach (var counters in outboundCounters) { counters.Value.CommittTo(providerToCommitTo.GetOutboundCounters(counters.Key)); } foreach (var counters in inboundCounters) { counters.Value.CommittTo(providerToCommitTo.GetInboundCounters(counters.Key)); } }
private void TransactionDone(object sender, TransactionEventArgs e) { if (e.Transaction.Operations.Count == 0) { return; } var dirtying = e.Transaction.Operations.SelectMany(Presentation.Dirtiables.DirtiableManager.GetDirtyingOperations); var dirtiables = new HashSet <AssetViewModel>(dirtying.SelectMany(x => x.Dirtiables.OfType <AssetViewModel>())); if (dirtiables.Count > 0) { session.NotifyAssetPropertiesChanged(dirtiables); } Dispatcher.Invoke(() => transactions.Add(new TransactionViewModel(ServiceProvider, e.Transaction))); }
/// <summary> /// 事务完成后,关闭数据库链接。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void OnTransactionCompleted(object sender, TransactionEventArgs e) { if (!transConns.TryGetValue(e.Transaction, out ConcurrentDictionary <string, DbConnection> connDictionary)) { return; } Debug.WriteLine("Transaction completed."); foreach (var connection in connDictionary.Values) { connection.TryClose(); connection.Dispose(); } transConns.TryRemove(e.Transaction, out connDictionary); }
private void TransactionCompleted(object sender, [NotNull] TransactionEventArgs e) { var dirtiables = new HashSet <IDirtiable>(); foreach (var dirtyingOperation in e.Transaction.Operations.SelectMany(GetDirtyingOperations)) { allOperations.Add(dirtyingOperation); foreach (var dirtiable in dirtyingOperation.Dirtiables) { var dirtyingOperations = GetOrCreateOperationsMap(dirtyingOperationsMap, dirtiable); dirtyingOperations.Add(dirtyingOperation); dirtiables.Add(dirtiable); } } UpdateDirtiables(dirtiables); }
// Logs the transaction if rollbacked, given different details depending on logger level private static void LogTransactionIfAborted(TransactionEventArgs args) { if (args.Transaction.TransactionInformation.Status.Equals(TransactionStatus.Aborted)) { //Log any rollbacked transaction Logger.Error(TransactionRollbackedMessage); if (Logger.IsInfoEnabled) { Logger.Info( TransactionRollbackedDetailedMessage, args.Transaction.TransactionInformation.LocalIdentifier, args.Transaction.IsolationLevel, args.Transaction.TransactionInformation.CreationTime); } } }
private void KillStorage <T>(object sender, TransactionEventArgs e) { if (typeof(T) == typeof(TransactionPacketStorage)) { lock (_transactionResources) { var key = e.Transaction; if (!_transactionResources.ContainsKey(key)) { Debugger.Break(); } var t = _transactionResources[key]; t.Dispose(); _transactionResources.Remove(key); } } }
private static void OnTransactionCompleted(object sender, TransactionEventArgs e) { Dictionary <string, ConnectionWrapper> connWrappers; if (!tranConnections.TryRemove(e.Transaction, out connWrappers)) { return; } lock (connWrappers) { foreach (var connWrapper in connWrappers.Values) { connWrapper.Dispose(); } } }
private static void OnTransactionCompleted(object sender, TransactionEventArgs e) { Dictionary <string, DbConnection> dictionary; transactionConnections.TryGetValue(e.Transaction, out dictionary); if (dictionary != null) { lock (transactionConnections) { transactionConnections.Remove(e.Transaction); } foreach (DbConnection connection in dictionary.Values) { connection.Dispose(); } } }
/// <summary> /// Add to food store /// </summary> /// <param name="AddAmount">Amount to add to resource</param> /// <param name="ActivityName">Name of activity adding resource</param> /// <param name="UserName">Name of individual radding resource</param> public void Add(double AddAmount, string ActivityName, string UserName) { this.availableDays = this.availableDays + AddAmount; ResourceTransaction details = new ResourceTransaction(); details.Credit = AddAmount; details.Activity = ActivityName; details.Reason = UserName; details.ResourceType = this.Name; LastTransaction = details; TransactionEventArgs te = new TransactionEventArgs() { Transaction = details }; OnTransactionOccurred(te); }
/// <summary> /// Remove from human food store /// </summary> /// <param name="request">Resource request class with details.</param> public new void Remove(ResourceRequest request) { if (request.Required == 0) { return; } double amountRequired = request.Required; foreach (HumanFoodStorePool pool in Pools.OrderByDescending(a => a.Age)) { // take min of amount in pool, remaining intake needed double amountToRemove = Math.Min(pool.Amount, amountRequired); amountRequired -= amountToRemove; // remove resource from pool pool.Remove(amountToRemove, request.ActivityModel, "Consumed"); if (amountRequired <= 0) { break; } } double amountRemoved = request.Required - amountRequired; // avoid taking too much amountRemoved = Math.Min(this.Amount, amountRemoved); request.Provided = amountRemoved; ResourceTransaction details = new ResourceTransaction { ResourceType = this, Loss = amountRemoved, Activity = request.ActivityModel, Reason = request.Reason }; LastTransaction = details; TransactionEventArgs te = new TransactionEventArgs() { Transaction = details }; OnTransactionOccurred(te); }
public void recieveTransaction(object sender, TransactionEventArgs tArgs) { this.memPool.Add(new TransactionValidationObject(tArgs.transaction)); EventHandler handler = transactionVoteSubmitted; TransacionVoteEventArgs vArgs; if (this.validateTransaction(tArgs.transaction)) { vArgs = new TransacionVoteEventArgs(tArgs.transaction.Id, true); } else { vArgs = new TransacionVoteEventArgs(tArgs.transaction.Id, true); } handler?.Invoke(this, vArgs); }
private static void Current_TransactionCompleted(object sender, TransactionEventArgs e) { Dictionary <string, NpgsqlConnection> data = (Dictionary <string, NpgsqlConnection>)Thread.GetData(Thread.GetNamedDataSlot("ConnectionDictionary")); if (data != null) { foreach (NpgsqlConnection connection in data.Values) { if ((connection != null) && (connection.State != ConnectionState.Closed)) { connection.Close(); } } data.Clear(); } Thread.FreeNamedDataSlot("ConnectionDictionary"); }
/// <summary> /// Add to food store /// </summary> /// <param name="resourceAmount">Object to add. This object can be double or contain additional information (e.g. Nitrogen) of food being added</param> /// <param name="activity">Name of activity adding resource</param> /// <param name="relatesToResource"></param> /// <param name="category"></param> public new void Add(object resourceAmount, CLEMModel activity, string relatesToResource, string category) { double addAmount; double nAdded; switch (resourceAmount.GetType().ToString()) { case "System.Double": addAmount = (double)resourceAmount; nAdded = Nitrogen; break; case "Models.CLEM.Resources.FoodResourcePacket": addAmount = ((FoodResourcePacket)resourceAmount).Amount; nAdded = ((FoodResourcePacket)resourceAmount).PercentN; break; default: throw new Exception(String.Format("ResourceAmount object of type {0} is not supported Add method in {1}", resourceAmount.GetType().ToString(), this.Name)); } if (addAmount > 0) { // update N based on new input added CurrentStoreNitrogen = ((CurrentStoreNitrogen * Amount) + (nAdded * addAmount)) / (Amount + addAmount); this.amount += addAmount; ResourceTransaction details = new ResourceTransaction { TransactionType = TransactionType.Gain, Amount = addAmount, Activity = activity, RelatesToResource = relatesToResource, Category = category, ResourceType = this }; LastTransaction = details; LastGain = addAmount; TransactionEventArgs te = new TransactionEventArgs() { Transaction = details }; OnTransactionOccurred(te); } }
private void TransactionCompleted(object sender, TransactionEventArgs e) { transactionCompletion?.SetResult(0); transactionCompletion = null; }
void OnTransactionCompleted(object sender, TransactionEventArgs e) { Log("TransactionCompleted: " + e.productID + ", " + e.quantity); if (e.hasDownloads) { var srcFile = Application.persistentDataPath + "/downloads/" + e.productID; Log("has downloads at: " + srcFile); PrintFile(srcFile, srcFile); } }
private void TransactionStatusChanged(object sender, TransactionEventArgs e) { var dirtiables = e.Transaction.Operations.SelectMany(GetDirtyingOperations).SelectMany(x => x.Dirtiables); UpdateDirtiables(new HashSet<IDirtiable>(dirtiables)); }
private void TransactionCompleted(object sender, TransactionEventArgs e) { var dirtiables = new HashSet<IDirtiable>(); foreach (var dirtyingOperation in e.Transaction.Operations.SelectMany(GetDirtyingOperations)) { allOperations.Add(dirtyingOperation); foreach (var dirtiable in dirtyingOperation.Dirtiables) { var dirtyingOperations = GetOrCreateOperationsMap(dirtyingOperationsMap, dirtiable); dirtyingOperations.Add(dirtyingOperation); dirtiables.Add(dirtiable); } } UpdateDirtiables(dirtiables); }
void OnTransactionFailed(object sender, TransactionEventArgs e) { Log("TransactionFailed: " + e.productID + ", " + e.quantity + ", " + e.error.LocalizedDescription()); }