/// <summary> /// Write a file with transaction /// </summary> /// <param name="data">Data to write</param> /// <param name="path">Path to file</param> /// <returns>Statut de l'opration</returns> public static bool WriteStateFileTransacted(string path, XmlSerializer stateSerializer, AtomState atomState, System.Transactions.Transaction transaction) { if (atomState == null) { return(false); } SafeTransactionHandle txHandle = null; SafeFileHandle fileHandle = null; bool response = true; try { IKernelTransaction kernelTx = (IKernelTransaction)TransactionInterop.GetDtcTransaction(transaction); kernelTx.GetHandle(out txHandle); fileHandle = CreateFileTransacted( path , SafeTransactionHandle.FileAccess.GENERIC_WRITE , SafeTransactionHandle.FileShare.FILE_SHARE_NONE , IntPtr.Zero , SafeTransactionHandle.FileMode.CREATE_ALWAYS , 0 , IntPtr.Zero , txHandle , IntPtr.Zero , IntPtr.Zero); if (fileHandle.IsInvalid) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } using (FileStream stateFile = new FileStream(fileHandle, FileAccess.Write, 1024, false)) { stateSerializer.Serialize(stateFile, atomState); } } catch { transaction.Rollback(); response = false; } finally { if (fileHandle != null && !fileHandle.IsInvalid) { fileHandle.Close(); fileHandle.Dispose(); } if (txHandle != null && !txHandle.IsInvalid) { txHandle.Close(); txHandle.Dispose(); } } return(response); }
public void Dispose() { if (disposed) { return; } disposed = true; if (parentScope != null) { parentScope.nested--; } if (nested > 0) { transaction.Rollback(); throw new InvalidOperationException("TransactionScope nested incorrectly"); } if (Transaction.CurrentInternal != transaction) { if (transaction != null) { transaction.Rollback(); } if (Transaction.CurrentInternal != null) { Transaction.CurrentInternal.Rollback(); } throw new InvalidOperationException("Transaction.Current has changed inside of the TransactionScope"); } if (Transaction.CurrentInternal == oldTransaction && oldTransaction != null) { oldTransaction.Scope = parentScope; } Transaction.CurrentInternal = oldTransaction; if (transaction == null) { /* scope was not in a transaction, (Suppress) */ return; } transaction.Scope = null; if (!IsComplete) { transaction.Rollback(); return; } if (!isRoot) { /* Non-root scope has completed+ended */ return; } transaction.CommitInternal(); }
public void ForceRollback(Exception e) { tx.Rollback(e, enlisted); /* See test RMFail2 */ ((ManualResetEvent)waitHandle).Set(); }
private void InternalDispose() { // Set this if it is called internally. _disposed = true; try { PopScope(); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (null == _expectedCurrent) { if (etwLog.IsEnabled()) { etwLog.TransactionScopeDisposed(TransactionTraceIdentifier.Empty); } } else { if (etwLog.IsEnabled()) { etwLog.TransactionScopeDisposed(_expectedCurrent.TransactionTraceId); } } // If Transaction.Current is not null, we have work to do. Otherwise, we don't, except to replace // the previous value. if (null != _expectedCurrent) { if (!_complete) { if (etwLog.IsEnabled()) { etwLog.TransactionScopeIncomplete(_expectedCurrent.TransactionTraceId); } // // Note: Rollback is not called on expected current because someone could conceiveably // dispose expectedCurrent out from under the transaction scope. // Transaction rollbackTransaction = _committableTransaction; if (rollbackTransaction == null) { rollbackTransaction = _dependentTransaction; } Debug.Assert(rollbackTransaction != null); rollbackTransaction.Rollback(); } else { // If we are supposed to commit on dispose, cast to CommittableTransaction and commit it. if (null != _committableTransaction) { _committableTransaction.Commit(); } else { Debug.Assert(null != _dependentTransaction, "null != this.dependentTransaction"); _dependentTransaction.Complete(); } } } } finally { if (null != _scopeTimer) { _scopeTimer.Dispose(); } if (null != _committableTransaction) { _committableTransaction.Dispose(); // If we created the committable transaction then we placed a clone in expectedCurrent // and it needs to be disposed as well. _expectedCurrent.Dispose(); } if (null != _dependentTransaction) { _dependentTransaction.Dispose(); } } }
// We don't have a finalizer (~TransactionScope) because all it would be able to do is try to // operate on other managed objects (the transaction), which is not safe to do because they may // already have been finalized. public void Dispose() { bool successful = false; TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.MethodEnter(TraceSourceType.TraceSourceBase, this); } if (_disposed) { if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceBase, this); } return; } // Dispose for a scope can only be called on the thread where the scope was created. if ((_scopeThread != Thread.CurrentThread) && !AsyncFlowEnabled) { if (etwLog.IsEnabled()) { etwLog.InvalidOperation("TransactionScope", "InvalidScopeThread"); } throw new InvalidOperationException(SR.InvalidScopeThread); } Exception exToThrow = null; try { // Single threaded from this point _disposed = true; // First, lets pop the "stack" of TransactionScopes and dispose each one that is above us in // the stack, making sure they are NOT consistent before disposing them. // Optimize the first lookup by getting both the actual current scope and actual current // transaction at the same time. TransactionScope actualCurrentScope = _threadContextData.CurrentScope; Transaction contextTransaction = null; Transaction current = Transaction.FastGetTransaction(actualCurrentScope, _threadContextData, out contextTransaction); if (!Equals(actualCurrentScope)) { // Ok this is bad. But just how bad is it. The worst case scenario is that someone is // poping scopes out of order and has placed a new transaction in the top level scope. // Check for that now. if (actualCurrentScope == null) { // Something must have gone wrong trying to clean up a bad scope // stack previously. // Make a best effort to abort the active transaction. Transaction rollbackTransaction = _committableTransaction; if (rollbackTransaction == null) { rollbackTransaction = _dependentTransaction; } Debug.Assert(rollbackTransaction != null); rollbackTransaction.Rollback(); successful = true; throw TransactionException.CreateInvalidOperationException( TraceSourceType.TraceSourceBase, SR.TransactionScopeInvalidNesting, null, rollbackTransaction.DistributedTxId); } // Verify that expectedCurrent is the same as the "current" current if we the interopOption value is None. else if (EnterpriseServicesInteropOption.None == actualCurrentScope._interopOption) { if (((null != actualCurrentScope._expectedCurrent) && (!actualCurrentScope._expectedCurrent.Equals(current))) || ((null != current) && (null == actualCurrentScope._expectedCurrent)) ) { TransactionTraceIdentifier myId; TransactionTraceIdentifier currentId; if (null == current) { currentId = TransactionTraceIdentifier.Empty; } else { currentId = current.TransactionTraceId; } if (null == _expectedCurrent) { myId = TransactionTraceIdentifier.Empty; } else { myId = _expectedCurrent.TransactionTraceId; } if (etwLog.IsEnabled()) { etwLog.TransactionScopeCurrentChanged(currentId, myId); } exToThrow = TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceBase, SR.TransactionScopeIncorrectCurrent, null, current == null ? Guid.Empty : current.DistributedTxId); // If there is a current transaction, abort it. if (null != current) { try { current.Rollback(); } catch (TransactionException) { // we are already going to throw and exception, so just ignore this one. } catch (ObjectDisposedException) { // Dito } } } } // Now fix up the scopes while (!Equals(actualCurrentScope)) { if (null == exToThrow) { exToThrow = TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceBase, SR.TransactionScopeInvalidNesting, null, current == null ? Guid.Empty : current.DistributedTxId); } if (null == actualCurrentScope._expectedCurrent) { if (etwLog.IsEnabled()) { etwLog.TransactionScopeNestedIncorrectly(TransactionTraceIdentifier.Empty); } } else { if (etwLog.IsEnabled()) { etwLog.TransactionScopeNestedIncorrectly(actualCurrentScope._expectedCurrent.TransactionTraceId); } } actualCurrentScope._complete = false; try { actualCurrentScope.InternalDispose(); } catch (TransactionException) { // we are already going to throw an exception, so just ignore this one. } actualCurrentScope = _threadContextData.CurrentScope; // We want to fail this scope, too, because work may have been done in one of these other // nested scopes that really should have been done in my scope. _complete = false; } } else { // Verify that expectedCurrent is the same as the "current" current if we the interopOption value is None. // If we got here, actualCurrentScope is the same as "this". if (EnterpriseServicesInteropOption.None == _interopOption) { if (((null != _expectedCurrent) && (!_expectedCurrent.Equals(current))) || ((null != current) && (null == _expectedCurrent)) ) { TransactionTraceIdentifier myId; TransactionTraceIdentifier currentId; if (null == current) { currentId = TransactionTraceIdentifier.Empty; } else { currentId = current.TransactionTraceId; } if (null == _expectedCurrent) { myId = TransactionTraceIdentifier.Empty; } else { myId = _expectedCurrent.TransactionTraceId; } if (etwLog.IsEnabled()) { etwLog.TransactionScopeCurrentChanged(currentId, myId); } if (null == exToThrow) { exToThrow = TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceBase, SR.TransactionScopeIncorrectCurrent, null, current == null ? Guid.Empty : current.DistributedTxId); } // If there is a current transaction, abort it. if (null != current) { try { current.Rollback(); } catch (TransactionException) { // we are already going to throw and exception, so just ignore this one. } catch (ObjectDisposedException) { // Dito } } // Set consistent to false so that the subsequent call to // InternalDispose below will rollback this.expectedCurrent. _complete = false; } } } successful = true; } finally { if (!successful) { PopScope(); } } // No try..catch here. Just let any exception thrown by InternalDispose go out. InternalDispose(); if (null != exToThrow) { throw exToThrow; } if (etwLog.IsEnabled()) { etwLog.MethodExit(TraceSourceType.TraceSourceBase, this); } }
public void Dispose() { bool flag = false; if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceBase"), "TransactionScope.Dispose"); } if (this.disposed) { if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceBase"), "TransactionScope.Dispose"); } } else { if (this.scopeThread != Thread.CurrentThread) { if (DiagnosticTrace.Error) { InvalidOperationExceptionTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceBase"), System.Transactions.SR.GetString("InvalidScopeThread")); } throw new InvalidOperationException(System.Transactions.SR.GetString("InvalidScopeThread")); } Exception exception = null; try { this.disposed = true; TransactionScope currentScope = this.threadContextData.CurrentScope; Transaction contextTransaction = null; Transaction transaction = Transaction.FastGetTransaction(currentScope, this.threadContextData, out contextTransaction); if (!this.Equals(currentScope)) { if (currentScope == null) { Transaction committableTransaction = this.committableTransaction; if (committableTransaction == null) { committableTransaction = this.dependentTransaction; } committableTransaction.Rollback(); flag = true; throw TransactionException.CreateInvalidOperationException(System.Transactions.SR.GetString("TraceSourceBase"), System.Transactions.SR.GetString("TransactionScopeInvalidNesting"), null); } if ((currentScope.interopOption == EnterpriseServicesInteropOption.None) && (((null != currentScope.expectedCurrent) && !currentScope.expectedCurrent.Equals(transaction)) || ((null != transaction) && (null == currentScope.expectedCurrent)))) { if (DiagnosticTrace.Warning) { TransactionTraceIdentifier transactionTraceId; TransactionTraceIdentifier empty; if (null == transaction) { empty = TransactionTraceIdentifier.Empty; } else { empty = transaction.TransactionTraceId; } if (null == this.expectedCurrent) { transactionTraceId = TransactionTraceIdentifier.Empty; } else { transactionTraceId = this.expectedCurrent.TransactionTraceId; } TransactionScopeCurrentChangedTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceBase"), transactionTraceId, empty); } exception = TransactionException.CreateInvalidOperationException(System.Transactions.SR.GetString("TraceSourceBase"), System.Transactions.SR.GetString("TransactionScopeIncorrectCurrent"), null); if (null != transaction) { try { transaction.Rollback(); } catch (TransactionException) { } catch (ObjectDisposedException) { } } } while (!this.Equals(currentScope)) { if (exception == null) { exception = TransactionException.CreateInvalidOperationException(System.Transactions.SR.GetString("TraceSourceBase"), System.Transactions.SR.GetString("TransactionScopeInvalidNesting"), null); } if (DiagnosticTrace.Warning) { if (null == currentScope.expectedCurrent) { TransactionScopeNestedIncorrectlyTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceBase"), TransactionTraceIdentifier.Empty); } else { TransactionScopeNestedIncorrectlyTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceBase"), currentScope.expectedCurrent.TransactionTraceId); } } currentScope.complete = false; try { currentScope.InternalDispose(); } catch (TransactionException) { } currentScope = this.threadContextData.CurrentScope; this.complete = false; } } else if ((this.interopOption == EnterpriseServicesInteropOption.None) && (((null != this.expectedCurrent) && !this.expectedCurrent.Equals(transaction)) || ((null != transaction) && (null == this.expectedCurrent)))) { if (DiagnosticTrace.Warning) { TransactionTraceIdentifier identifier; TransactionTraceIdentifier identifier2; if (null == transaction) { identifier2 = TransactionTraceIdentifier.Empty; } else { identifier2 = transaction.TransactionTraceId; } if (null == this.expectedCurrent) { identifier = TransactionTraceIdentifier.Empty; } else { identifier = this.expectedCurrent.TransactionTraceId; } TransactionScopeCurrentChangedTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceBase"), identifier, identifier2); } if (exception == null) { exception = TransactionException.CreateInvalidOperationException(System.Transactions.SR.GetString("TraceSourceBase"), System.Transactions.SR.GetString("TransactionScopeIncorrectCurrent"), null); } if (null != transaction) { try { transaction.Rollback(); } catch (TransactionException) { } catch (ObjectDisposedException) { } } this.complete = false; } flag = true; } finally { if (!flag) { this.PopScope(); } } this.InternalDispose(); if (exception != null) { throw exception; } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(System.Transactions.SR.GetString("TraceSourceBase"), "TransactionScope.Dispose"); } } }
private bool TransactedAccept(out Transaction tx) { tx = null; try { tx = TransactionBehavior.CreateTransaction(this.ChannelDispatcher.TransactionIsolationLevel, this.ChannelDispatcher.TransactionTimeout); IChannelBinder channelBinder = null; using (TransactionScope scope = new TransactionScope(tx)) { TimeSpan timeout = TimeoutHelper.Min(this.ChannelDispatcher.TransactionTimeout, this.ChannelDispatcher.DefaultCommunicationTimeouts.ReceiveTimeout); if (!this.acceptor.TryAccept(TransactionBehavior.NormalizeTimeout(timeout), out channelBinder)) { return false; } scope.Complete(); } if (channelBinder != null) { this.channel = new ListenerChannel(channelBinder); this.idleManager = ServiceChannel.SessionIdleManager.CreateIfNeeded(this.channel.Binder, this.channelDispatcher.DefaultCommunicationTimeouts.ReceiveTimeout); return true; } this.AcceptedNull(); tx = null; return false; } catch (CommunicationException exception) { if (null != tx) { try { tx.Rollback(); } catch (TransactionException exception2) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information); } } } tx = null; if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information); } return false; } catch (TransactionException exception3) { tx = null; if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Information); } return false; } }
internal static void Complete(Transaction transaction, Exception error) { try { if (error == null) { CommittableTransaction transaction2 = transaction as CommittableTransaction; if (transaction2 != null) { transaction2.Commit(); } else { DependentTransaction transaction3 = transaction as DependentTransaction; if (transaction3 != null) { transaction3.Complete(); } } } else { transaction.Rollback(); } } catch (TransactionException exception) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Error); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TransactionBehavior.CreateFault(System.ServiceModel.SR.GetString("SFxTransactionAsyncAborted"), "TransactionAborted", true)); } }
// ........................................................................................................ internal static void Complete(Transaction transaction, Exception error) { try { if (error == null) { CommittableTransaction commit = (transaction as CommittableTransaction); if (commit != null) { commit.Commit(); } else { DependentTransaction complete = (transaction as DependentTransaction); if (complete != null) { complete.Complete(); } } } else { transaction.Rollback(); } } catch (TransactionException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Error); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TransactionBehavior.CreateFault(SR.GetString(SR.SFxTransactionAsyncAborted), FaultCodeConstants.Codes.TransactionAborted, true)); } }
public void Dispose() { if (disposed) { return; } disposed = true; if (parentScope != null) { parentScope.nested--; } if (nested > 0) { transaction.Rollback(); throw new InvalidOperationException("TransactionScope nested incorrectly"); } if (Transaction.CurrentInternal != transaction && !asyncFlowEnabled) { if (transaction != null) { transaction.Rollback(); } if (Transaction.CurrentInternal != null) { Transaction.CurrentInternal.Rollback(); } throw new InvalidOperationException("Transaction.Current has changed inside of the TransactionScope"); } if (scopeTimer != null) { scopeTimer.Dispose(); } if (asyncFlowEnabled) { if (oldTransaction != null) { oldTransaction.Scope = parentScope; } var variedTransaction = Transaction.CurrentInternal; if (transaction == null && variedTransaction == null) { /* scope was not in a transaction, (Suppress) */ return; } variedTransaction.Scope = parentScope; Transaction.CurrentInternal = oldTransaction; transaction.Scope = null; if (IsAborted) { throw new TransactionAbortedException("Transaction has aborted"); } else if (!IsComplete) { transaction.Rollback(); variedTransaction.Rollback(); return; } if (!isRoot) { /* Non-root scope has completed+ended */ return; } variedTransaction.CommitInternal(); transaction.CommitInternal(); } else { if (Transaction.CurrentInternal == oldTransaction && oldTransaction != null) { oldTransaction.Scope = parentScope; } Transaction.CurrentInternal = oldTransaction; if (transaction == null) { /* scope was not in a transaction, (Suppress) */ return; } if (IsAborted) { transaction.Scope = null; throw new TransactionAbortedException("Transaction has aborted"); } else if (!IsComplete) { transaction.Rollback(); return; } if (!isRoot) { /* Non-root scope has completed+ended */ return; } transaction.CommitInternal(); transaction.Scope = null; } }
public XmlDocument ExecuteXml(SqlCommand cmd, Transaction ts) { XmlDocument xd = null; XmlReader xr = null; try { if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); } if (ts != null) { cmd.Connection.EnlistTransaction(ts); } xr = cmd.ExecuteXmlReader(); } catch (Exception err) { Exceptions.LogOnly(err); if (ts != null) { ts.Rollback(); } } finally { cmd.Connection.Close(); } xd = new XmlDocument(); xd.AppendChild(xd.CreateElement("root")); //xr.ReadStartElement("row"); xd.Load(xr); xr.Close(); return xd; }
public ExecuteResult Execute(string Sql, DbConnection Connection, Transaction Tst) { int RowCount; if (Connection == null) { Connection = GetConnection(); } try { if (Connection.State == ConnectionState.Closed) { Connection.Open(); } if (Tst != null) { Connection.EnlistTransaction(Tst); } DbCommand cm = GetCommand(Sql, Connection); RowCount = cm.ExecuteNonQuery(); return new ExecuteResult(RowCount, null); } catch (TransactionException err) { if (Tst != null) { Tst.Rollback(err); } Exceptions.LogOnly(err); return new ExecuteResult(null, err); } catch (Exception err) { if (Tst != null) { Tst.Rollback(err); } Exceptions.LogOnly(err); return new ExecuteResult(null, err); } finally { Connection.Close(); } }
public ExecuteResult ExecuteReader(string Sql, DbConnection Connection, Transaction Tst) { IDataReader rlt; if (Connection == null) { Connection = GetConnection(); } try { if (Connection.State == ConnectionState.Closed) { Connection.Open(); } if (Tst != null) { Connection.EnlistTransaction(Tst); } DbCommand cm = GetCommand(Sql, Connection); rlt = cm.ExecuteReader(CommandBehavior.CloseConnection); return new ExecuteResult(rlt, null); } catch (TransactionException err) { if (Tst != null) { Tst.Rollback(err); } Exceptions.LogOnly(err); return new ExecuteResult(null, err); } catch (Exception err) { if (Tst != null) { Tst.Rollback(err); } Exceptions.LogOnly(err); return new ExecuteResult(null, err); } finally { Connection.Close(); } }