public static byte[] GetExportCookie(Transaction transaction, byte[] whereabouts) { if (null == transaction) { throw new ArgumentNullException(nameof(transaction)); } if (null == whereabouts) { throw new ArgumentNullException(nameof(whereabouts)); } if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceDistributed, "TransactionInterop.GetExportCookie"); } // Copy the whereabouts so that it cannot be modified later. var whereaboutsCopy = new byte[whereabouts.Length]; Buffer.BlockCopy(whereabouts, 0, whereaboutsCopy, 0, whereabouts.Length); DistributedTransaction dTx = ConvertToDistributedTransaction(transaction); byte[] cookie = dTx.GetExportCookie(whereaboutsCopy); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceDistributed, "TransactionInterop.GetExportCookie"); } return cookie; }
public TryLoadRunnableWorkflowAsyncResult(InstancePersistenceContext context, InstancePersistenceCommand command, SqlWorkflowInstanceStore store, SqlWorkflowInstanceStoreLock storeLock, Transaction currentTransaction, TimeSpan timeout, AsyncCallback callback, object state) : base(context, command, store, storeLock, currentTransaction, timeout, callback, state) { if (base.Store.WorkflowHostType == Guid.Empty) { throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(command.Name, System.Activities.DurableInstancing.SR.TryLoadRequiresWorkflowType, null)); } }
public DbConnection UseConnection(IConnectionUser user) { if (user == null) { throw Error.ArgumentNull("user"); } if (this.connection.State == ConnectionState.Closed) { this.connection.Open(); this.autoClose = true; this.AddInfoMessageHandler(); if (System.Transactions.Transaction.Current != null) { System.Transactions.Transaction.Current.TransactionCompleted += this.OnTransactionCompleted; } } if (this.transaction == null && System.Transactions.Transaction.Current != null && System.Transactions.Transaction.Current != systemTransaction) { this.ClearConnection(); systemTransaction = System.Transactions.Transaction.Current; this.connection.EnlistTransaction(System.Transactions.Transaction.Current); } if (this.users.Count == this.maxUsers) { this.BootUser(this.users[0]); } this.users.Add(user); return this.connection; }
internal SqlDelegatedTransaction(SqlInternalConnection connection, System.Transactions.Transaction tx) { this._connection = connection; this._atomicTransaction = tx; this._active = false; System.Transactions.IsolationLevel isolationLevel = tx.IsolationLevel; switch (isolationLevel) { case System.Transactions.IsolationLevel.Serializable: this._isolationLevel = System.Data.IsolationLevel.Serializable; return; case System.Transactions.IsolationLevel.RepeatableRead: this._isolationLevel = System.Data.IsolationLevel.RepeatableRead; return; case System.Transactions.IsolationLevel.ReadCommitted: this._isolationLevel = System.Data.IsolationLevel.ReadCommitted; return; case System.Transactions.IsolationLevel.ReadUncommitted: this._isolationLevel = System.Data.IsolationLevel.ReadUncommitted; return; case System.Transactions.IsolationLevel.Snapshot: this._isolationLevel = System.Data.IsolationLevel.Snapshot; return; } throw SQL.UnknownSysTxIsolationLevel(isolationLevel); }
internal PersistenceDBAccessor(DbResourceAllocator dbResourceAllocator, Transaction transaction, WorkflowCommitWorkBatchService transactionService) { this.dbResourceAllocator = dbResourceAllocator; this.localTransaction = DbResourceAllocator.GetLocalTransaction(transactionService, transaction); this.connection = this.dbResourceAllocator.GetEnlistedConnection(transactionService, transaction, out this.needToCloseConnection); this.dbRetry = new DbRetry(false); }
/// <summary> /// Called just after a transaction is created for this workbatch. /// </summary> /// <param name="transaction"> /// The transaction that was created. /// </param> protected override void TransactionCreated(Transaction transaction) { TraceHelper.Trace(); if (!connectionsByTransaction.ContainsKey(transaction)) connectionsByTransaction.Add(transaction, new Dictionary<String, DbConnection>()); }
/// <summary> /// Make the transacted changes permanent. /// </summary> void IEnlistmentNotification.Commit(Enlistment enlistment) { _value = new StringBuilder(_temporaryValue.ToString()); _temporaryValue = null; _enlistedTransaction = null; enlistment.Done(); }
/// <summary> /// Given a provider name locate the necessary /// <see cref="AdoTrackingResourceAccessor" /> in the configuration file. /// </summary> /// <returns> /// An <see cref="AdoTrackingResourceAccessor" />. /// </returns> public static AdoTrackingResourceAccessor Create( IAdoResourceProvider resourceProvider, ITrackingNameResolver nameResolver, IAdoValueReader valueReader, Transaction transaction, IStateProvider stateProvider) { // locate any mappings for the specified provider ProviderNameTypeMapping mapping = TrackingAdoProviderSettings.Get() .ResourceAccessors.FindByProviderName(resourceProvider.ProviderName); AdoTrackingResourceAccessor resourceAccessor; if (mapping != null) { resourceAccessor = TypeUtilities.CreateInstance<AdoTrackingResourceAccessor>( mapping.Type, new object[] { resourceProvider, nameResolver, valueReader, transaction, stateProvider }); } else { return new AdoTrackingResourceAccessor( resourceProvider, nameResolver, valueReader, transaction, stateProvider); } return resourceAccessor; }
/// <summary> /// Construct a new <see cref="AdoPersistenceResourceAccessor" /> with the /// specified <see cref="IAdoResourceProvider" />, /// <see cref="IPersistenceNameResolver" /> and <see cref="IAdoValueReader" /> /// All work should be performed in the specified <see cref="Transaction" />. /// </summary> /// <param name="resourceProvider"> /// An <see cref="IAdoResourceProvider" /> used to provide resources for /// accessing the tracking store. /// </param> /// <param name="nameResolver"> /// An <see cref="IPersistenceNameResolver" /> that resolves names /// of commands and parameters for the relevant tracking store. /// </param> /// <param name="valueReader"> /// An <see cref="IAdoValueReader" /> that reads values from /// <see cref="IDbCommand" /> and <see cref="IDataReader" /> implementations. /// </param> /// <param name="transaction"> /// An <see cref="Transaction" /> in which to perform the work. /// </param> public AdoPersistenceResourceAccessor(IAdoResourceProvider resourceProvider, IPersistenceNameResolver nameResolver, IAdoValueReader valueReader, Transaction transaction) { if (resourceProvider == null) throw new ArgumentNullException("resourceProvider"); if (nameResolver == null) throw new ArgumentNullException("nameResolver"); if (valueReader == null) throw new ArgumentNullException("valueReader"); this.resourceProvider = resourceProvider; this.nameResolver = nameResolver; this.valueReader = valueReader; if (transaction == null) { this.isConnectionOwner = true; this.dbConnection = resourceProvider.CreateConnection(); this.dbConnection.Open(); } else this.dbConnection = resourceProvider.CreateEnlistedConnection(transaction, out this.isConnectionOwner); }
public MySqlTransactionScope(MySqlConnection con, Transaction trans, MySqlTransaction simpleTransaction) { connection = con; baseTransaction = trans; this.simpleTransaction = simpleTransaction; }
private void Enlist(Transaction transaction) { if (transaction == null) { // no enlistment as we are not in a TransactionScope return; } // try to enlist as a PSPE if (!transaction.EnlistPromotableSinglePhase(this)) { // our enlistmente fail so we need to enlist ourselves as durable. // we create a transaction directly instead of using BeginTransaction that GraphClient // doesn't store it in its stack of scopes. var localTransaction = new Neo4jTransaction(_client); localTransaction.ForceKeepAlive(); _transactionId = localTransaction.Id; var resourceManager = GetResourceManager(); var propagationToken = TransactionInterop.GetTransmitterPropagationToken(transaction); var transactionExecutionEnvironment = new TransactionExecutionEnvironment(_client.ExecutionConfiguration) { TransactionId = localTransaction.Id, TransactionBaseEndpoint = _client.TransactionEndpoint }; resourceManager.Enlist(transactionExecutionEnvironment, propagationToken); localTransaction.Cancel(); } _enlistedInTransactions.Add(transaction); }
internal OracleInternalConnection(OracleConnectionString connectionOptions) { this._connectionOptions = connectionOptions; string userId = connectionOptions.UserId; string password = connectionOptions.Password; string dataSource = connectionOptions.DataSource; bool integratedSecurity = connectionOptions.IntegratedSecurity; bool unicode = connectionOptions.Unicode; bool omitOracleConnectionName = this._connectionOptions.OmitOracleConnectionName; this._connectionIsOpen = this.OpenOnLocalTransaction(userId, password, dataSource, integratedSecurity, unicode, omitOracleConnectionName); if (this.UnicodeEnabled) { this._encodingDatabase = Encoding.Unicode; } else if (this.ServerVersionAtLeastOracle8i) { this._encodingDatabase = new OracleEncoding(this); } else { this._encodingDatabase = Encoding.Default; } this._encodingNational = Encoding.Unicode; if (connectionOptions.Enlist && !connectionOptions.Pooling) { System.Transactions.Transaction currentTransaction = System.Data.Common.ADP.GetCurrentTransaction(); if (null != currentTransaction) { this.Enlist(userId, password, dataSource, currentTransaction, false); } } }
public override void EnlistTransaction(System.Transactions.Transaction transaction) { OracleConnectionString str = this._connectionOptions; this.RollbackDeadTransaction(); this.Enlist(str.UserId, str.Password, str.DataSource, transaction, true); }
private void Enlist(string userName, string password, string serverName, System.Transactions.Transaction transaction, bool manualEnlistment) { this.UnEnlist(); if (!OCI.ClientVersionAtLeastOracle9i) { throw System.Data.Common.ADP.DistribTxRequiresOracle9i(); } if (null != transaction) { if (this.HasTransaction) { throw System.Data.Common.ADP.TransactionPresent(); } byte[] buffer3 = this.StringToNullTerminatedBytes(password); byte[] buffer2 = this.StringToNullTerminatedBytes(userName); byte[] buffer = this.StringToNullTerminatedBytes(serverName); this._enlistContext = new OciEnlistContext(buffer2, buffer3, buffer, this.ServiceContextHandle, this.ErrorHandle); this._enlistContext.Join(this, transaction); this.TransactionState = System.Data.OracleClient.TransactionState.GlobalStarted; } else { this.TransactionState = System.Data.OracleClient.TransactionState.AutoCommit; } base.EnlistedTransaction = transaction; }
public void TransmitSucceeded(Transaction sendTransaction) { if (sendTransaction == null) { this.sent = true; } }
internal PersistenceContextEnlistment(PersistenceContext context, Transaction transaction) { this.transaction = transaction; this.enlistedContexts = new List<PersistenceContext>(); this.enlistedContexts.Add(context); }
internal SQLiteEnlistment(SQLiteConnection cnn, Transaction scope) { _transaction = cnn.BeginTransaction(); _scope = scope; _scope.EnlistVolatile(this, System.Transactions.EnlistmentOptions.None); }
public DeveelDbEnlistment(DeveelDbConnection connection, Transaction scope) { transaction = connection.BeginTransaction(); Scope = scope; Scope.EnlistVolatile(this, EnlistmentOptions.None); }
void IEnlistmentNotification.Commit(Enlistment enlistment) { this.m_Value = new StringBuilder(this.m_TemporaryValue.ToString()); this.m_TemporaryValue = null; this.enlistedTransaction = null; enlistment.Done(); }
internal void AddReference(ref MessageRpc rpc, Transaction tx, bool updateCallCount) { lock (this.mutex) { if (this.pending == null) { this.pending = new Dictionary<Transaction, RemoveReferenceRM>(); } if (tx != null) { RemoveReferenceRM erm; if (this.pending == null) { this.pending = new Dictionary<Transaction, RemoveReferenceRM>(); } if (!this.pending.TryGetValue(tx, out erm)) { RemoveReferenceRM erm2 = new RemoveReferenceRM(this.instanceContext, tx, rpc.Operation.Name) { CallCount = 1L }; this.pending.Add(tx, erm2); } else if (updateCallCount) { erm.CallCount += 1L; } } } }
public static Driver GetDriverInTransaction(Transaction transaction) { lock (driversInUse.SyncRoot) { return (Driver) driversInUse[transaction.GetHashCode()]; } }
// Detach transaction from connection. internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) { Bid.Trace("<prov.DbConnectionInternal.DetachTransaction|RES|CPOOL> %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount); // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new // transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should // be the exception, not the rule. lock (this) { // Detach if detach-on-end behavior, or if outer connection was closed DbConnection owner = (DbConnection)Owner; if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner) { SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction; if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction)) { EnlistedTransaction = null; if (IsTxRootWaitingForTxEnd) { DelegatedTransactionEnded(); } } } } }
private void SaveState(System.Transactions.Transaction transaction) { if (TransactionalFile.WriteStateFileTransacted(this.properties.StateFile, stateSerializer, atomState, transaction) == false) { throw new Exception(String.Format("State file {0} could not be written!", this.properties.StateFile)); } }
public static void Set(System.Transactions.Transaction transaction, Message message) { TransactionMessageProperty propertyAndThrowIfAlreadySet = GetPropertyAndThrowIfAlreadySet(message); propertyAndThrowIfAlreadySet.flowedTransaction = transaction; message.Properties.Add("TransactionMessageProperty", propertyAndThrowIfAlreadySet); }
//Releases the transaction lock and allows the next pending transaction to quire it. public void Unlock() { Debug.Assert(Locked); OwningTransaction = null; LinkedListNode<KeyValuePair<Transaction,ManualResetEvent>> node = null; lock(this) { if(m_PendingTransactions.Count > 0) { node = m_PendingTransactions.First; m_PendingTransactions.RemoveFirst(); } } if(node != null) { Transaction transaction = node.Value.Key; ManualResetEvent manualEvent = node.Value.Value; Lock(transaction); lock(manualEvent)//To deal with race condition of the handle closed between the check and the set { if(manualEvent.SafeWaitHandle.IsClosed == false) { manualEvent.Set(); } } } }
public static byte[] GetExportCookie(Transaction transaction, byte[] whereabouts) { if (null == transaction) { throw new ArgumentNullException(nameof(transaction)); } if (null == whereabouts) { throw new ArgumentNullException(nameof(whereabouts)); } TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetExportCookie"); } // Copy the whereabouts so that it cannot be modified later. var whereaboutsCopy = new byte[whereabouts.Length]; Buffer.BlockCopy(whereabouts, 0, whereaboutsCopy, 0, whereabouts.Length); DistributedTransaction dTx = ConvertToDistributedTransaction(transaction); byte[] cookie = dTx.GetExportCookie(whereaboutsCopy); if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetExportCookie"); } return cookie; }
public void Commit(Guid guid) { try { if (this.committableTx == null) { Marshal.ThrowExceptionForHR(-2147418113); } else if (this.owned) { if (guid == this.ownerGuid) { this.committableTx.Commit(); } else { Marshal.ThrowExceptionForHR(-2147418113); } } else { this.committableTx.Commit(); } } catch (TransactionException exception) { this.MapTxExceptionToHR(exception, true); } finally { this.committableTx.Dispose(); this.committableTx = null; this.systemTx = null; } }
protected override IEnumerator <IteratorAsyncResult <TIteratorAsyncResult> .AsyncStep> GetAsyncSteps() { if (this.Transaction == null) { this.wcfMessage = this.CreateWcfMessage(); } else { SbmpMessageCreator sbmpMessageCreator1 = (this.controlMessageCreator == null ? this.MessageCreator : this.controlMessageCreator.Value); SbmpTransactionalAsyncResult <TIteratorAsyncResult> sbmpTransactionalAsyncResult = this; IteratorAsyncResult <TIteratorAsyncResult> .BeginCall beginCall = (TIteratorAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => { SbmpResourceManager resourceManager = thisPtr.messagingFactory.ResourceManager; System.Transactions.Transaction transaction = thisPtr.Transaction; IRequestSessionChannel requestSessionChannel = thisPtr.channel; SbmpMessageCreator sbmpMessageCreator = sbmpMessageCreator1; object obj = thisPtr; return(resourceManager.BeginEnlist(transaction, requestSessionChannel, sbmpMessageCreator, new Action <RequestInfo>(obj.PartitionInfoSetter), t, c, s)); }; yield return(sbmpTransactionalAsyncResult.CallAsync(beginCall, (TIteratorAsyncResult thisPtr, IAsyncResult a) => thisPtr.txnSeqNumber = thisPtr.messagingFactory.ResourceManager.EndEnlist(a), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Transfer)); this.wcfMessage = this.CreateWcfMessage(); WorkUnitInfo.AddTo(this.wcfMessage.Headers, "TxnWorkUnit", this.Transaction.TransactionInformation.LocalIdentifier, this.txnSeqNumber); } SbmpTransactionalAsyncResult <TIteratorAsyncResult> sbmpTransactionalAsyncResult1 = this; IteratorAsyncResult <TIteratorAsyncResult> .BeginCall beginCall1 = (TIteratorAsyncResult thisPtr, TimeSpan t, AsyncCallback c, object s) => thisPtr.channel.BeginRequest(thisPtr.wcfMessage, SbmpProtocolDefaults.BufferTimeout(t, this.messagingFactory.GetSettings().EnableAdditionalClientTimeout), c, s); yield return(sbmpTransactionalAsyncResult1.CallAsync(beginCall1, (TIteratorAsyncResult thisPtr, IAsyncResult a) => thisPtr.Response = thisPtr.channel.EndRequest(a), IteratorAsyncResult <TIteratorAsyncResult> .ExceptionPolicy.Transfer)); }
internal void Commit(Transaction transaction) { lock (this.mutex) { this._pendingWorkCollection.Commit(transaction); } }
public SaveWorkflowAsyncResult(InstancePersistenceContext context, InstancePersistenceCommand command, SqlWorkflowInstanceStore store, SqlWorkflowInstanceStoreLock storeLock, Transaction currentTransaction, TimeSpan timeout, AsyncCallback callback, object state) : base(context, command, store, storeLock, currentTransaction, timeout, callback, state) { if (((SaveWorkflowCommand) command).InstanceKeyMetadataChanges.Count > 0) { throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(System.Activities.DurableInstancing.SR.InstanceKeyMetadataChangesNotSupported)); } }
/// <summary> /// Initializes a new instance of the TransactionScope class /// with the specified timeout value, and sets the specified /// transaction as the ambient transaction, so that transactional /// work done inside the scope uses this transDoFactory. /// </summary> /// <param name="transactionToUse">Represents a transaction.</param> /// <param name="scopeTimeout">The TimeSpan after which the transaction scope times out and aborts the transaction.</param> public TransactionDecorator(Transaction transactionToUse, TimeSpan scopeTimeout) { _transactionToUse = transactionToUse; _scopeTimeout = scopeTimeout; if (_dataProvider != "System.Data.OleDb") _scope = new TransactionScope(_transactionToUse, _scopeTimeout); }
/////////////////////////////////////////////////////////////////////////////////////////////// private /* protected virtual */ void Dispose(bool disposing) { if (!disposed) { if (disposing) { //////////////////////////////////// // dispose managed resources here... //////////////////////////////////// if (_transaction != null) { _transaction.Dispose(); _transaction = null; } if (_scope != null) { // _scope.Dispose(); // NOTE: Not "owned" by us. _scope = null; } } ////////////////////////////////////// // release unmanaged resources here... ////////////////////////////////////// disposed = true; } }
public static IDtcTransaction GetDtcTransaction(Transaction transaction) { if (!TransactionManager._platformValidated) { TransactionManager.ValidatePlatform(); } if (null == transaction) { throw new ArgumentNullException("transaction"); } if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), "TransactionInterop.GetDtcTransaction"); } IDtcTransaction transactionNative = null; OletxTransaction transaction2 = ConvertToOletxTransaction(transaction); try { transaction2.realOletxTransaction.TransactionShim.GetITransactionNative(out transactionNative); } catch (COMException exception) { OletxTransactionManager.ProxyException(exception); throw; } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceOletx"), "TransactionInterop.GetDtcTransaction"); } return transactionNative; }
/// <summary> /// Instantiate an opened connection enlisted to the Transaction /// if promotable is false, the Transaction wraps a local /// transaction inside and can never be promoted /// </summary> /// <param name="dbResourceAllocator"></param> /// <param name="transaction"></param> /// <param name="wantPromotable"></param> internal SharedConnectionInfo( DbResourceAllocator dbResourceAllocator, Transaction transaction, bool wantPromotable, ManualResetEvent handle) { Debug.Assert((transaction != null), "Null Transaction!"); if (null == handle) throw new ArgumentNullException("handle"); this.handle = handle; if (wantPromotable) { // Enlist a newly opened connection to this regular Transaction this.connection = dbResourceAllocator.OpenNewConnection(); this.connection.EnlistTransaction(transaction); } else { // Make this transaction no longer promotable by attaching our // IPromotableSinglePhaseNotification implementation (LocalTranscaction) // and track the DbConnection and DbTransaction associated with the LocalTranscaction LocalTransaction localTransaction = new LocalTransaction(dbResourceAllocator, handle); transaction.EnlistPromotableSinglePhase(localTransaction); this.connection = localTransaction.Connection; this.localTransaction = localTransaction.Transaction; } }
public static void RemoveDriverInTransaction(Transaction transaction) { lock (driversInUse.SyncRoot) { driversInUse.Remove(transaction.GetHashCode()); } }
internal void AutomaticEnlistment() { SysTx.Transaction currentSystemTransaction = ADP.GetCurrentTransaction(); // NOTE: Must be first to ensure _smiContext.ContextTransaction is set! SysTx.Transaction contextTransaction = _smiContext.ContextTransaction; // returns the transaction that was handed to SysTx that wraps the ContextTransactionId. long contextTransactionId = _smiContext.ContextTransactionId; SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.SqlInternalConnectionSmi.AutomaticEnlistment|ADV> {0}, contextTransactionId=0x{1}, contextTransaction={2}, currentSystemTransaction={3}.", ObjectID, contextTransactionId, (null != contextTransaction) ? contextTransaction.GetHashCode() : 0, (null != currentSystemTransaction) ? currentSystemTransaction.GetHashCode() : 0); if (SqlInternalTransaction.NullTransactionId != contextTransactionId) { if (null != currentSystemTransaction && contextTransaction != currentSystemTransaction) { throw SQL.NestedTransactionScopesNotSupported(); // can't use TransactionScope(RequiresNew) inside a Sql Transaction. } SqlClientEventSource.Log.TryTraceEvent("<sc.SqlInternalConnectionSmi.AutomaticEnlistment|ADV> {0}, using context transaction with transactionId=0x{1}", ObjectID, contextTransactionId); _currentTransaction = new SqlInternalTransaction(this, TransactionType.Context, null, contextTransactionId); ContextTransaction = contextTransaction; } else if (null == currentSystemTransaction) { _currentTransaction = null; // there really isn't a transaction. SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.SqlInternalConnectionSmi.AutomaticEnlistment|ADV> {0}, no transaction.", ObjectID); } else { SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.SqlInternalConnectionSmi.AutomaticEnlistment|ADV> {0}, using current System.Transaction.", ObjectID); base.Enlist(currentSystemTransaction); } }
internal static SafeTransactionHandle Create(Transaction managedTransaction) { if (managedTransaction == null) { throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_NeedTransaction); } // MSDTC is not available on WinPE machine. // CommitableTransaction will use DTC APIs under the covers to get KTM transaction manager interface. // KTM is kernel Transaction Manager to handle file, registry etc and MSDTC provides an integration support // with KTM to handle transaction across kernel resources and MSDTC resources like SQL, MSMQ etc. // We need KTMRM service as well. WinPE doesn’t have these services installed if (Utils.IsWinPEHost() || PsUtils.IsRunningOnProcessorArchitectureARM()) { throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions); } IDtcTransaction dtcTransaction = TransactionInterop.GetDtcTransaction(managedTransaction); IKernelTransaction ktmInterface = dtcTransaction as IKernelTransaction; if (null == ktmInterface) { throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions); } IntPtr ktmTxHandle; int hr = ktmInterface.GetHandle(out ktmTxHandle); HandleError(hr); return new SafeTransactionHandle(ktmTxHandle); }
// NOTE: This is just a private helper because OracleClient V1.1 shipped // with a different argument name and it's a breaking change to not use // the same argument names in V2.0 (VB Named Parameter Binding--Ick) private void EnlistDistributedTransactionHelper(System.EnterpriseServices.ITransaction transaction) { System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None); permissionSet.AddPermission(CONNECTIONOBJECTNAME.ExecutePermission); // MDAC 81476 permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)); permissionSet.Demand(); Bid.Trace("<prov.DbConnectionHelper.EnlistDistributedTransactionHelper|RES|TRAN> %d#, Connection enlisting in a transaction.\n", ObjectID); SysTx.Transaction indigoTransaction = null; if (null != transaction) { indigoTransaction = SysTx.TransactionInterop.GetTransactionFromDtcTransaction((SysTx.IDtcTransaction)transaction); } RepairInnerConnection(); // NOTE: since transaction enlistment involves round trips to the // server, we don't want to lock here, we'll handle the race conditions // elsewhere. InnerConnection.EnlistTransaction(indigoTransaction); // NOTE: If this outer connection were to be GC'd while we're // enlisting, the pooler would attempt to reclaim the inner connection // while we're attempting to enlist; not sure how likely that is but // we should consider a GC.KeepAlive(this) here. GC.KeepAlive(this); }
private bool _active; // Is the transaction active? internal SqlDelegatedTransaction(SqlInternalConnection connection, SysTx.Transaction tx) { Debug.Assert(null != connection, "null connection?"); _connection = connection; _atomicTransaction = tx; _active = false; SysTx.IsolationLevel systxIsolationLevel = tx.IsolationLevel; // We need to map the System.Transactions IsolationLevel to the one // that System.Data uses and communicates to SqlServer. We could // arguably do that in Initialize when the transaction is delegated, // however it is better to do this before we actually begin the process // of delegation, in case System.Transactions adds another isolation // level we don't know about -- we can throw the exception at a better // place. switch (systxIsolationLevel) { case SysTx.IsolationLevel.ReadCommitted: _isolationLevel = IsolationLevel.ReadCommitted; break; case SysTx.IsolationLevel.ReadUncommitted: _isolationLevel = IsolationLevel.ReadUncommitted; break; case SysTx.IsolationLevel.RepeatableRead: _isolationLevel = IsolationLevel.RepeatableRead; break; case SysTx.IsolationLevel.Serializable: _isolationLevel = IsolationLevel.Serializable; break; case SysTx.IsolationLevel.Snapshot: _isolationLevel = IsolationLevel.Snapshot; break; default: throw SQL.UnknownSysTxIsolationLevel(systxIsolationLevel); } }
internal void Open_EnlistTransaction(SysTx.Transaction transaction) { OdbcConnection.VerifyExecutePermission(); if ((null != this.weakTransaction) && this.weakTransaction.IsAlive) { throw ADP.LocalTransactionPresent(); } SysTx.IDtcTransaction oleTxTransaction = ADP.GetOletxTransaction(transaction); OdbcConnectionHandle connectionHandle = ConnectionHandle; ODBC32.RetCode retcode; if (null == oleTxTransaction) { retcode = connectionHandle.SetConnectionAttribute2(ODBC32.SQL_ATTR.SQL_COPT_SS_ENLIST_IN_DTC, (IntPtr)ODBC32.SQL_DTC_DONE, ODBC32.SQL_IS_PTR); } else { retcode = connectionHandle.SetConnectionAttribute4(ODBC32.SQL_ATTR.SQL_COPT_SS_ENLIST_IN_DTC, oleTxTransaction, ODBC32.SQL_IS_PTR); } if (retcode != ODBC32.RetCode.SUCCESS) { HandleError(connectionHandle, retcode); } // Tell the base class about our enlistment ((OdbcConnectionOpen)InnerConnection).EnlistedTransaction = transaction; }
protected SbmpTransactionalAsyncResult(SbmpMessagingFactory messagingFactory, SbmpMessageCreator messageCreator, Lazy <SbmpMessageCreator> controlMessageCreator, TimeSpan timeout, AsyncCallback callback, object state) : base(timeout, callback, state) { this.messagingFactory = messagingFactory; this.MessageCreator = messageCreator; this.channel = this.messagingFactory.Channel; this.controlMessageCreator = controlMessageCreator; this.Transaction = System.Transactions.Transaction.Current; }
internal VolatileResourceManager(NpgsqlConnection connection, [NotNull] System.Transactions.Transaction transaction) { _connector = connection.Connector; _transaction = transaction; // _tx gets disposed by System.Transactions at some point, but we want to be able to log its local ID _txId = transaction.TransactionInformation.LocalIdentifier; _localTx = connection.BeginTransaction(ConvertIsolationLevel(_transaction.IsolationLevel)); }
void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) { SysTx.Transaction transaction = e.Transaction; SqlClientEventSource.Log.PoolerTraceEvent("<prov.DbConnectionInternal.TransactionCompletedEvent|RES|CPOOL> {0}, Transaction Completed. (pooledCount = {1})", ObjectID, _pooledCount); CleanupTransactionOnCompletion(transaction); CleanupConnectionOnTransactionCompletion(transaction); }
public FbEnlistmentNotification(FbConnectionInternal connection, Transaction systemTransaction) { this.connection = connection; this.transaction = connection.BeginTransaction(systemTransaction.IsolationLevel); this.systemTransaction = systemTransaction; this.systemTransaction.EnlistVolatile(this, System.Transactions.EnlistmentOptions.None); }
private void Cleanup(SQLiteConnection cnn) { if (this._disposeConnection) { cnn.Dispose(); } this._transaction = null; this._scope = null; }
static private byte[] GetTransactionCookie(SysTx.Transaction transaction, byte[] whereAbouts) { byte[] transactionCookie = null; if (null != transaction) { transactionCookie = SysTx.TransactionInterop.GetExportCookie(transaction, whereAbouts); } return(transactionCookie); }
public DistributedTransactionContext(ISessionImplementor session, System.Transactions.Transaction transaction) { this.session = session; nhtx = session.ConnectionManager.Transaction; AmbientTransation = transaction; IsInActiveTransaction = true; }
void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) { SysTx.Transaction transaction = e.Transaction; Bid.Trace("<prov.DbConnectionInternal.TransactionCompletedEvent|RES|CPOOL> %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount); CleanupTransactionOnCompletion(transaction); CleanupConnectionOnTransactionCompletion(transaction); }
private bool Enlist(Db4oEnlist enlist) { System.Transactions.Transaction currentTx = System.Transactions.Transaction.Current; if (currentTx != null) { currentTx.EnlistVolatile(enlist, EnlistmentOptions.None); return(true); } return(false); }
public static void Display(System.Transactions.Transaction tr) { if (tr != null) { Console.WriteLine("Createtime:" + tr.TransactionInformation.CreationTime); Console.WriteLine("Status:" + tr.TransactionInformation.Status); Console.WriteLine("Local ID:" + tr.TransactionInformation.LocalIdentifier); Console.WriteLine("Distributed ID:" + tr.TransactionInformation.DistributedIdentifier); Console.WriteLine(); } }
internal void AddPendingEnlistedConnector(NpgsqlConnector connector, System.Transactions.Transaction transaction) { lock (_pendingEnlistedConnectors) { if (!_pendingEnlistedConnectors.TryGetValue(transaction, out var list)) { list = _pendingEnlistedConnectors[transaction] = new List <NpgsqlConnector>(); } list.Add(connector); } }
// Handle transaction detach, pool cleanup and other post-transaction cleanup tasks associated with internal void CleanupConnectionOnTransactionCompletion(SysTx.Transaction transaction) { DetachTransaction(transaction, false); DbConnectionPool pool = Pool; if (null != pool) { pool.TransactionEnded(transaction, this); } }
override protected void CleanupTransactionOnCompletion(SysTx.Transaction transaction) { // Note: unlocked, potentially multi-threaded code, so pull delegate to local to // ensure it doesn't change between test and call. SqlDelegatedTransaction delegatedTransaction = DelegatedTransaction; if (null != delegatedTransaction) { delegatedTransaction.TransactionEnded(transaction); } }
/// <summary> /// Default constructor. /// </summary> /// <param name="session">The session to enlist with the transaction.</param> /// <param name="transaction">The transaction into which the context will be enlisted.</param> /// <param name="systemTransactionCompletionLockTimeout">See <see cref="Cfg.Environment.SystemTransactionCompletionLockTimeout"/>.</param> /// <param name="useConnectionOnSystemTransactionPrepare">See <see cref="Cfg.Environment.UseConnectionOnSystemTransactionPrepare"/>.</param> public SystemTransactionContext( ISessionImplementor session, System.Transactions.Transaction transaction, int systemTransactionCompletionLockTimeout, bool useConnectionOnSystemTransactionPrepare) { _session = session ?? throw new ArgumentNullException(nameof(session)); _originalTransaction = transaction ?? throw new ArgumentNullException(nameof(transaction)); EnlistedTransaction = transaction.Clone(); _systemTransactionCompletionLockTimeout = systemTransactionCompletionLockTimeout; _useConnectionOnSystemTransactionPrepare = useConnectionOnSystemTransactionPrepare; }
override public void EnlistTransaction(SysTx.Transaction transaction) // MDAC 78997 { OleDbConnection.VerifyExecutePermission(); OleDbConnection outerConnection = Connection; if (null != LocalTransaction) { throw ADP.LocalTransactionPresent(); } EnlistTransactionInternal(transaction); }
internal void ActivateConnection(SysTx.Transaction transaction) { // Internal method called from the connection pooler so we don't expose // the Activate method publicly. #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); Debug.Assert(1 == activateCount, "activated multiple times?"); #endif // DEBUG Activate(transaction); PerformanceCounters.NumberOfActiveConnections.Increment(); }
private static TransactionStatus?FailsafeGetTransactionStatus(SysTran transaction) { try { return(transaction.TransactionInformation.Status); } catch (Exception ex) { // Only log exception message for avoid bloating the log for a minor case _log.InfoFormat("Failed getting transaction status, {0}", ex.Message); return(null); } }
internal void GetCurrentTransactionPair(out long transactionId, out SysTx.Transaction transaction) { // SQLBU 214740: Transaction state could change between obtaining tranid and transaction // due to background SqlDelegatedTransaction processing. Lock the connection to prevent that. lock (this) { transactionId = (null != CurrentTransaction) ? CurrentTransaction.TransactionId : 0; transaction = null; if (0 != transactionId) { transaction = InternalEnlistedTransaction; } } }
/// <summary> /// 获取数据库连接 /// </summary> /// <param name="db">数据库</param> /// <returns>数据库连接</returns> public static DatabaseConnectionWrapper GetConnection(Database db) { SystemTransaction currentTransaction = SystemTransaction.Current; if (currentTransaction == null) { return(null); } Dictionary <SystemTransaction, Dictionary <String, DatabaseConnectionWrapper> > obj; Monitor.Enter(obj = TransactionConnections); Dictionary <String, DatabaseConnectionWrapper> connectionList; try { if (!TransactionConnections.TryGetValue(currentTransaction, out connectionList)) { connectionList = new Dictionary <String, DatabaseConnectionWrapper>(); TransactionConnections.Add(currentTransaction, connectionList); currentTransaction.TransactionCompleted += new TransactionCompletedEventHandler(TransactionScopeConnections.OnTransactionCompleted); } } finally { Monitor.Exit(obj); } Dictionary <String, DatabaseConnectionWrapper> obj2; Monitor.Enter(obj2 = connectionList); DatabaseConnectionWrapper connection; try { if (!connectionList.TryGetValue(db.ConnectionString, out connection)) { connection = db.GetNewConnection(); connectionList.Add(db.ConnectionString, connection); } connection.AddRef(); } finally { Monitor.Exit(obj2); } return(connection); }
internal void ActivateConnection(SysTx.Transaction transaction) { // Internal method called from the connection pooler so we don't expose // the Activate method publicly. SqlClientEventSource.Log.PoolerTraceEvent("<prov.DbConnectionInternal.ActivateConnection|RES|INFO|CPOOL> {0}, Activating", ObjectID); #if DEBUG int activateCount = Interlocked.Increment(ref _activateCount); Debug.Assert(1 == activateCount, "activated multiple times?"); #endif // DEBUG Activate(transaction); PerformanceCounters.NumberOfActiveConnections.Increment(); }