internal OleDbTransaction (OleDbConnection connection, int depth, IsolationLevel isolevel) 
		{
			this.connection = connection;

			gdaTransaction = libgda.gda_transaction_new (depth.ToString ());
			
			switch (isolevel) {
			case IsolationLevel.ReadCommitted :
				libgda.gda_transaction_set_isolation_level (gdaTransaction,
									    GdaTransactionIsolation.ReadCommitted);
				break;
			case IsolationLevel.ReadUncommitted :
				libgda.gda_transaction_set_isolation_level (gdaTransaction,
									    GdaTransactionIsolation.ReadUncommitted);
				break;
			case IsolationLevel.RepeatableRead :
				libgda.gda_transaction_set_isolation_level (gdaTransaction,
									    GdaTransactionIsolation.RepeatableRead);
				break;
			case IsolationLevel.Serializable :
				libgda.gda_transaction_set_isolation_level (gdaTransaction,
									    GdaTransactionIsolation.Serializable);
				break;
			}
			
			libgda.gda_connection_begin_transaction (connection.GdaConnection, gdaTransaction);
		}
Ejemplo n.º 2
0
        public DbContextScope(DbContextScopeOption joiningOption, bool readOnly, IsolationLevel? isolationLevel, IDbContextFactory dbContextFactory = null)
        {
            if (isolationLevel.HasValue && joiningOption == DbContextScopeOption.JoinExisting)
                throw new ArgumentException("Cannot join an ambient DbContextScope when an explicit database transaction is required. When requiring explicit database transactions to be used (i.e. when the 'isolationLevel' parameter is set), you must not also ask to join the ambient context (i.e. the 'joinAmbient' parameter must be set to false).");

            _disposed = false;
            _completed = false;
            _readOnly = readOnly;

            _parentScope = GetAmbientScope();
            if (_parentScope != null && joiningOption == DbContextScopeOption.JoinExisting)
            {
                if (_parentScope._readOnly && !this._readOnly)
                {
                    throw new InvalidOperationException("Cannot nest a read/write DbContextScope within a read-only DbContextScope.");
                }

                _nested = true;
                _dbContexts = _parentScope._dbContexts;
            }
            else
            {
                _nested = false;
                _dbContexts = new DbContextCollection(readOnly, isolationLevel, dbContextFactory);
            }

            SetAmbientScope(this);
        }
        public DistributedTransactionCoordinator(IsolationLevel isolationLevel)
        {
            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = isolationLevel;

            this.transactionScope = new TransactionScope(TransactionScopeOption.Required, options);
        }
 public IAdapterTransaction BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.Unspecified)
 {
     IDbConnection connection = CreateConnection();
     connection.OpenIfClosed();
     IDbTransaction transaction = connection.BeginTransaction(isolationLevel);
     return new AdoAdapterTransaction(transaction, _sharedConnection != null);
 }
Ejemplo n.º 5
0
 public SqlServerConnection(
     SqlConnection connection,
     IsolationLevel? isolationLevel,
     PersistentJobQueueProviderCollection queueProviders)
     : this(connection, isolationLevel, queueProviders, true)
 {
 }
Ejemplo n.º 6
0
    /// <summary>
    /// Constructs the transaction object, binding it to the supplied connection
    /// </summary>
    /// <param name="connection">The connection to open a transaction on</param>
    /// <param name="deferredLock">TRUE to defer the writelock, or FALSE to lock immediately</param>
    internal SQLiteTransaction(SQLiteConnection connection, bool deferredLock)
    {
      _cnn = connection;
      _version = _cnn._version;

      _level = (deferredLock == true) ? IsolationLevel.ReadCommitted : IsolationLevel.Serializable;

      if (_cnn._transactionLevel++ == 0)
      {
        try
        {
          using (SQLiteCommand cmd = _cnn.CreateCommand())
          {
            if (!deferredLock)
              cmd.CommandText = "BEGIN IMMEDIATE";
            else
              cmd.CommandText = "BEGIN";

            cmd.ExecuteNonQuery();
          }
        }
        catch (SQLiteException)
        {
          _cnn._transactionLevel--;
          _cnn = null;
          throw;
        }
      }
    }
 public static void Transaction(IsolationLevel level, Action transactional)
 {
     using (UnitOfWork.Start())
     {
         // If we are already in a transaction, don't start a new one
         if (UnitOfWork.Current.IsInActiveTransaction)
         {
             transactional();
         }
         else
         {
             IGenericTransaction tx = UnitOfWork.Current.BeginTransaction(level);
             try
             {
                 transactional();
                 tx.Commit();
             }
             catch
             {
                 tx.Rollback();
                 throw;
             }
             finally
             {
                 tx.Dispose();
             }
         }
     }
 }
Ejemplo n.º 8
0
        public MsmqScopeOptions(TimeSpan? requestedTimeout = null, IsolationLevel? requestedIsolationLevel = null)
        {
            var timeout = TransactionManager.DefaultTimeout;
            var isolationLevel = IsolationLevel.ReadCommitted;
            if (requestedTimeout.HasValue)
            {
                var maxTimeout = GetMaxTimeout();

                if (requestedTimeout.Value > maxTimeout)
                {
                    throw new ConfigurationErrorsException(
                        "Timeout requested is longer than the maximum value for this machine. Override using the maxTimeout setting of the system.transactions section in machine.config");
                }

                timeout = requestedTimeout.Value;
            }

            if (requestedIsolationLevel.HasValue)
            {
                isolationLevel = requestedIsolationLevel.Value;
            }

            TransactionOptions = new TransactionOptions
            {
                IsolationLevel = isolationLevel,
                Timeout = timeout
            };
        }
        internal NpgsqlTransaction(NpgsqlConnection conn, IsolationLevel isolation)
        {
            resman = new System.Resources.ResourceManager(this.GetType());

            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, CLASSNAME);
            if ((isolation != IsolationLevel.ReadCommitted) &&
                    (isolation != IsolationLevel.Serializable))
                throw new ArgumentOutOfRangeException(resman.GetString("Exception_UnsopportedIsolationLevel"), "isolation");

            _conn = conn;
            _isolation = isolation;

            StringBuilder commandText = new StringBuilder("SET TRANSACTION ISOLATION LEVEL ");

            if (isolation == IsolationLevel.ReadCommitted)
                commandText.Append("READ COMMITTED");
            else
                commandText.Append("SERIALIZABLE");

            commandText.Append("; BEGIN");

            NpgsqlCommand command = new NpgsqlCommand(commandText.ToString(), conn.Connector);
            command.ExecuteNonQuery();
            _conn.Connector.Transaction = this;
        }
Ejemplo n.º 10
0
        public IDbTransaction BeginTransaction(IsolationLevel isolationLevel)
        {
            if (factory.AlwaysReturnTransaction != null)
                return factory.AlwaysReturnTransaction;

            return DbConnection.BeginTransaction(isolationLevel);
        }
        /// <summary>
        /// Begins a new, nested, isolation scope
        /// </summary>
        /// <param name="isolationScopeName">The name of the new isolation scope</param>
        /// <param name="initialize">A delegate to an action that is performed on initialization. If an exception occurs inside this 
        /// method, then the scope is automatically destroyed, calling any cleanup actions that were added during this method</param>
        public IDisposable BeginIsolationScope(string isolationScopeName, Action<IIsolationScope> initialize)
        {
            if (initialize == null)
                initialize = Functions.EmptyAction<IIsolationScope>();

            _currentState = State.Initialize;
            var lastIsolationLevel = _currentIsolationLevel;
            _currentIsolationLevel = new IsolationLevel(isolationScopeName);

            Logger.WriteLine("***************************** Initializing " + isolationScopeName + " *****************************");
            try
            {
                initialize(this);
                Logger.WriteLine("***************************** Initializing " + isolationScopeName + " Completed succesfully *****************************");
            }
            catch
            {
                _currentIsolationLevel.Cleanup();
                _currentIsolationLevel = lastIsolationLevel;
                throw;
            }

            _isolationLevels.Push(lastIsolationLevel);

            _currentState = State.Normal;

            return new IsolationScopeDisposer(this);
        }
 public static void AutoRollbackTransaction(IsolationLevel level, Proc transactional, UnitOfWorkNestingOptions nestingOptions)
 {
     using (UnitOfWork.Start(nestingOptions))
     {
         // If we are already in a transaction, don't start a new one
         if (UnitOfWork.Current.IsInActiveTransaction)
         {
             transactional();
         }
         else
         {
             RhinoTransaction tx = UnitOfWork.Current.BeginTransaction(level);
             try
             {
                 transactional();
                 tx.Rollback();
             }
             catch
             {
                 tx.Rollback();
                 throw;
             }
             finally
             {
                 tx.Dispose();
             }
         }
     }
 }
 public IDataContextReadOnlyScope CreateReadOnlyWithTransaction(IsolationLevel isolationLevel)
 {
     return new DataContextReadOnlyScope(
       joiningOption: DataContextScopeOption.ForceCreateNew,
       isolationLevel: isolationLevel,
       dataContextFactory: _dataContextFactory);
 }
Ejemplo n.º 14
0
        public Int32 executeNonQuery(MySqlCommand mySqlCommand, IsolationLevel isolationLevel)
        {
            using (MySqlTransaction transaccion = conexion.BeginTransaction(isolationLevel))
            {
                Int32 safectados = 0;
                try
                {

                    mySqlCommand.Connection = conexion;
                    mySqlCommand.Transaction = transaccion;
                    safectados = mySqlCommand.ExecuteNonQuery();

                    // Commit a la transacción
                    transaccion.Commit();

                }

                catch (Exception ex)
                {
                    ex.Source += " SQL: " + mySqlCommand.CommandText.ToString();
                    Log.Write(MethodBase.GetCurrentMethod().Name, ex);
                    throw ex;
                }
                return safectados;

            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SPOEmulationContext"/> class.
        /// </summary>
        /// <param name="isolationLevel">The level.</param>
        /// <param name="connectionInformation">The connection informations for the target web.</param>
        public SPOEmulationContext(IsolationLevel isolationLevel, ConnectionInformation connectionInformation)
        {
            this._isolationLevel = isolationLevel;

            switch (isolationLevel)
            {
                case IsolationLevel.Fake:
                    // create shim context
                    _shimsContext = ShimsContext.Create();

                    // initialize all simulated types
                    _clientContext = InitializeSimulatedAPI(connectionInformation.Url);
                    break;
                case IsolationLevel.Integration:
                    // create shim context
                    _shimsContext = ShimsContext.Create();
                    Connect(connectionInformation);
                    break;
                case IsolationLevel.None:
                    Connect(connectionInformation);
                    break;
                default:
                    throw new InvalidOperationException();
            }
        }
Ejemplo n.º 16
0
        internal NpgsqlTransaction(NpgsqlConnection conn, IsolationLevel isolation)
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, CLASSNAME);

            _conn = conn;
            _isolation = isolation;

            StringBuilder commandText = new StringBuilder("BEGIN; SET TRANSACTION ISOLATION LEVEL ");

            if ((isolation == IsolationLevel.RepeatableRead) ||
                (isolation == IsolationLevel.Serializable) ||
                (isolation == IsolationLevel.Snapshot))
            {
                commandText.Append("SERIALIZABLE");
            }
            else
            {
                // Set isolation level default to read committed.
                _isolation = IsolationLevel.ReadCommitted;
                commandText.Append("READ COMMITTED");
            }

            commandText.Append(";");

            NpgsqlCommand command = new NpgsqlCommand(commandText.ToString(), conn.Connector);
            command.ExecuteBlind();
            _conn.Connector.Transaction = this;
        }
Ejemplo n.º 17
0
		public void BeginTrans(IsolationLevel isoLevel)
		{
			if (this.Transaction == null)
			{
				this.Transaction = this.Connection.BeginTransaction(isoLevel);
			}
		}
		internal OracleTransaction (OracleConnection connection, IsolationLevel isolevel, OciTransactionHandle transaction)
		{
			this.connection = connection;
			this.isolationLevel = isolevel;
			this.transaction = transaction;
			isOpen = true;
		}
Ejemplo n.º 19
0
 internal OdbcTransaction(OdbcConnection connection, IsolationLevel isolevel, OdbcConnectionHandle handle) {
     OdbcConnection.VerifyExecutePermission();
     
     _connection = connection;
     _isolevel   = isolevel;
     _handle = handle;
 }
Ejemplo n.º 20
0
        public RhinoQueuesTransport(
            Uri endpoint,
            IEndpointRouter endpointRouter,
            IMessageSerializer messageSerializer,
            int threadCount,
            string path,
            IsolationLevel queueIsolationLevel,
            int numberOfRetries)
        {
            this.endpoint = endpoint;
            this.queueIsolationLevel = queueIsolationLevel;
            this.numberOfRetries = numberOfRetries;
            this.endpointRouter = endpointRouter;
            this.messageSerializer = messageSerializer;
            this.threadCount = threadCount;
            this.path = path;

            queueName = endpoint.GetQueueName();

            threads = new Thread[threadCount];

            // This has to be the first subscriber to the transport events
            // in order to successfuly handle the errors semantics
            new ErrorAction(numberOfRetries).Init(this);
        }
Ejemplo n.º 21
0
        public static ITransaction CreateTransaction(this IDatabase database, IsolationLevel isolation)
        {
            if (!database.IsOpen)
                throw new InvalidOperationException(String.Format("Database '{0}' is not open.", database.Name));

            return database.CreateSafeTransaction(isolation);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Registers openning of a workspace
 /// </summary>
 /// <param name="workspaceId">Workspace ID</param>
 /// <param name="snapshotId">Opened snapshot ID</param>
 /// <param name="isolationLevel">Isolation level</param>
 /// <param name="timeout">Workspace timeout</param>
 public void AddWorkspace(Guid workspaceId, Guid snapshotId, IsolationLevel isolationLevel, TimeSpan timeout)
 {
     lock (workspaceStates)
     {
         workspaceStates.Add(workspaceId, new WorkspaceStateElement(snapshotId, isolationLevel, DateTime.UtcNow, timeout));
     }
 }
        public ServiceBusTransactionScope(string name, IsolationLevel isolationLevel, TimeSpan timeout)
        {
            this.name = name;
            log = Log.For(this);

            ignore = Transaction.Current != null;

            if (ignore)
            {
                if (log.IsVerboseEnabled)
                {
                    log.Verbose(string.Format(ESBResources.QueueTransactionScopeAmbient, name,
                                              Thread.CurrentThread.ManagedThreadId));
                }

                return;
            }

            scope = new TransactionScope(TransactionScopeOption.RequiresNew,
                                             new TransactionOptions
                                             	{
                                             		IsolationLevel = isolationLevel,
                                             		Timeout = timeout
                                             	});

            if (log.IsVerboseEnabled)
            {
                log.Verbose(string.Format(ESBResources.QueueTransactionScopeCreated, name, isolationLevel, timeout,
                                          Thread.CurrentThread.ManagedThreadId));
            }
        }
Ejemplo n.º 24
0
		internal SqlTransaction (SqlConnection connection, IsolationLevel isolevel)
		{
			this.connection = connection;
			this.isolationLevel = isolevel;
			isOpen = true;
			isRolledBack = false;
		}
Ejemplo n.º 25
0
 public IDbTransaction BeginTransaction(IsolationLevel il)
 {
     using (ExecuteHelper.Begin(dur => context.FireExecuteEvent(this, String.Format("BeginTransaction({0})", il), dur)))
     {
         return new DbTransactionProxy(connection.BeginTransaction(il), context);
     }
 }
Ejemplo n.º 26
0
        internal NpgsqlTransaction(NpgsqlConnection conn, IsolationLevel isolationLevel)
        {
            Contract.Requires(conn != null);
            Contract.Requires(isolationLevel != IsolationLevel.Chaos);

            Connection = conn;
            Connector.Transaction = this;
            Connector.TransactionStatus = TransactionStatus.Pending;

            switch (isolationLevel) {
                case IsolationLevel.RepeatableRead:
                    Connector.PrependInternalMessage(PregeneratedMessage.BeginTransRepeatableRead);
                    break;
                case IsolationLevel.Serializable:
                case IsolationLevel.Snapshot:
                    Connector.PrependInternalMessage(PregeneratedMessage.BeginTransSerializable);
                    break;
                case IsolationLevel.ReadUncommitted:
                    // PG doesn't really support ReadUncommitted, it's the same as ReadCommitted. But we still
                    // send as if.
                    Connector.PrependInternalMessage(PregeneratedMessage.BeginTransReadUncommitted);
                    break;
                case IsolationLevel.ReadCommitted:
                    Connector.PrependInternalMessage(PregeneratedMessage.BeginTransReadCommitted);
                    break;
                case IsolationLevel.Unspecified:
                    isolationLevel = DefaultIsolationLevel;
                    goto case DefaultIsolationLevel;
                default:
                    throw PGUtil.ThrowIfReached("Isolation level not supported: " + isolationLevel);
            }

            _isolationLevel = isolationLevel;
        }
Ejemplo n.º 27
0
        public void BeginTransaction(IsolationLevel level)
        {
            if (mConnection.State == ConnectionState.Closed)
                mConnection.Open();

            mTransaction = mConnection.BeginTransaction(level);
        }
        private TestAdapterService(IsolationLevel isolationLevelToUse, Func<IDataAccessAdapter> adapterFunc)
        {
            _AdapterFunc = adapterFunc;
            _IsolationLevel = isolationLevelToUse;

            ResetActionsOnceCalled = true;
        }
Ejemplo n.º 29
0
		public override IUnitOfWork GetUnitOfWork(IsolationLevel isolationLevel = IsolationLevel.Unspecified)
		{
			if ((object)this.DictionaryUnitOfWorkCallback != null)
				return this.DictionaryUnitOfWorkCallback();
			else
				return null;
		}
Ejemplo n.º 30
0
        public static ISession CreateSession(this IDatabase database, string userName, string password, IsolationLevel isolation)
        {
            if (!database.Authenticate(userName, password))
                throw new InvalidOperationException(String.Format("Unable to create a session for user '{0}': not authenticated.", userName));

            return database.CreateSession(userName, isolation);
        }
Ejemplo n.º 31
0
 public IDbTransaction BeginTransaction(IsolationLevel il) => throw new NotSupportedException();
 /// <summary>启动事务</summary>
 /// <param name="isolationLevel">事务隔离级别</param>
 public void BeginTransaction(IsolationLevel isolationLevel)
 {
     this.ibatisMapper.BeginTransaction(isolationLevel);
 }
Ejemplo n.º 33
0
 public void BeginTransaction(IsolationLevel isolation = IsolationLevel.ReadCommitted)
 {
     transaction = connection.BeginTransaction(isolation);
 }
        /// <summary>
        /// Method that allows multiple process in the database in a single transaction
        /// </summary>
        /// <typeparam name="TResult">Type of data to return if the process is succesful</typeparam>
        /// <param name="process">Process to execute in the transaction flow</param>
        /// <param name="isolation">Specifies the transaction locking behavior for the connection.</param>
        /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
        /// <returns>Represents an asynchronous operation that can return a value.</returns>
        public async Task <TResult> TransactionAsync <TResult>(Func <DbContext, Task <TResult> > process, IsolationLevel isolation = IsolationLevel.ReadUncommitted, CancellationToken cancellationToken = default)
        {
            var strategy = this.Context.Database.CreateExecutionStrategy();

            return(await strategy.ExecuteAsync(async (cancellation) =>
            {
                using var transaction = await this.Context.Database.BeginTransactionAsync(isolation, cancellation);

                var result = await process(this.Context);

                await transaction.CommitAsync();

                return result;
            }, cancellationToken));
        }
Ejemplo n.º 35
0
 public void Initialize(IServiceBus bus)
 {
     _enabled        = bus.Configuration.TransactionScope.Enabled;
     _isolationLevel = bus.Configuration.TransactionScope.IsolationLevel;
     _timeout        = TimeSpan.FromSeconds(bus.Configuration.TransactionScope.TimeoutSeconds);
 }
Ejemplo n.º 36
0
 protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 37
0
 public ITransaction BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.Snapshot)
 {
     return(new DbTransaction(_context.Database.BeginTransaction(isolationLevel)));
 }
Ejemplo n.º 38
0
 public static IDbTransaction OpenTransaction(this IDbConnection dbConn, IsolationLevel isolationLevel)
 {
     return(new OrmLiteTransaction(dbConn, dbConn.BeginTransaction(isolationLevel)));
 }
Ejemplo n.º 39
0
 public new SqlTransaction BeginTransaction(IsolationLevel isolationLevel)
 {
     return(BeginTransaction(isolationLevel, "Transaction"));
 }
Ejemplo n.º 40
0
 public SqlTransaction BeginTransaction(IsolationLevel isolationLevel, string transactionName)
 {
     return(new SqlTransaction(isolationLevel, this, transactionName));
 }
 /// <summary>Creates a new transaction object</summary>
 /// <param name="levelOfIsolation">The level of isolation.</param>
 /// <param name="name">The name.</param>
 protected override ITransaction CreateTransaction(IsolationLevel levelOfIsolation, string name)
 {
     return(new Transaction(levelOfIsolation, name));
 }
Ejemplo n.º 42
0
 protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
 {
     return(BeginTransaction(isolationLevel));
 }
Ejemplo n.º 43
0
 override public DbTransaction BeginTransaction(IsolationLevel iso)
 {
     return BeginSqlTransaction(iso, null, false);
 }
Ejemplo n.º 44
0
 abstract internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso, SqlInternalTransaction internalTransaction);
 public async Task BeginTransactionAsync(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, CancellationToken cancellationToken = default)
 {
     _dbContextTransaction = await Database.BeginTransactionAsync(isolationLevel, cancellationToken);
 }
Ejemplo n.º 46
0
 public void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.Unspecified)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 47
0
 public IDbTransaction BeginTransaction(IsolationLevel il)
 {
     throw new NotImplementedException();
 }
 public void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
 {
     _dbContextTransaction = Database.BeginTransaction(isolationLevel);
 }
Ejemplo n.º 49
0
 /// <summary>
 ///  지정된 함수를 현재 UnitOfWork의 Transaction 하에서 수행합니다.
 /// </summary>
 /// <typeparam name="T">Return Type of Function to execute</typeparam>
 /// <param name="transactionalFunc">Function to execute under Transaction</param>
 /// <param name="isolationLevel">격리수준</param>
 /// <returns>함수 수행 결과</returns>
 public static T Transaction <T>(Func <T> transactionalFunc, IsolationLevel isolationLevel)
 {
     return(Transaction(transactionalFunc, isolationLevel, UnitOfWorkNestingOptions.ReturnExistingOrCreateUnitOfWork));
 }
Ejemplo n.º 50
0
        /// <summary>
        ///  지정된 함수를 현재 UnitOfWork의 Transaction 하에서 수행합니다.
        /// </summary>
        /// <typeparam name="T">Return Type of Function to execute</typeparam>
        /// <param name="transactionalFunc">Function to execute under Transaction</param>
        /// <param name="isolationLevel">격리수준</param>
        /// <param name="nestingOptions">UnitOfWork Nesting option.</param>
        /// <returns>함수 수행 결과</returns>
        public static T Transaction <T>(Func <T> transactionalFunc, IsolationLevel isolationLevel, UnitOfWorkNestingOptions nestingOptions)
        {
            transactionalFunc.ShouldNotBeNull("transactionalFunc");

            if (IsDebugEnabled)
            {
                log.Debug("Execute the specified action under transaction... " +
                          "transactionalFunc=[{0}], isolationLevel=[{1}], nestingOptions=[{2}]",
                          transactionalFunc, isolationLevel, nestingOptions);
            }

            // 기존 UnitOfWork에 참여할 수도 있고, 새로운 UnitOfWork를 생성할 수도 있습니다.
            //
            using (UnitOfWork.Start(nestingOptions)) {
                // 기존 Transaction 이 없다면, 새로운 Transaction 에서 작업합니다.
                //
                if (UnitOfWork.Current.IsInActiveTransaction == false)
                {
                    if (IsDebugEnabled)
                    {
                        log.Debug("새로운 NHibernate.ITransaction을 생성합니다.");
                    }

                    var tx = UnitOfWork.Current.BeginTransaction(isolationLevel);

                    try {
                        var result = transactionalFunc();
                        tx.Commit();

                        if (IsDebugEnabled)
                        {
                            log.Debug("Transactional Function을 수행하고, Transaction.Commit을 수행하였습니다!!!");
                        }

                        return(result);
                    }
                    catch (Exception ex) {
                        if (log.IsErrorEnabled)
                        {
                            log.Error("Fail to execute transactional action. rollback transaction.");
                            log.Error(ex);
                        }

                        tx.Rollback();
                        throw;
                    }
                    finally {
                        if (tx != null)
                        {
                            tx.Dispose();

                            if (IsDebugEnabled)
                            {
                                log.Debug("Dispose current transaction.");
                            }
                        }
                    }
                }

                if (IsDebugEnabled)
                {
                    log.Debug("활성화된 기존 Transaction에 참여하여, 실행합니다.");
                }

                return(transactionalFunc.Invoke());
            }
        }
 public EntityFrameworkSagaRepository(SagaDbContextFactory sagaDbContextFactory, IsolationLevel isolationLevel = IsolationLevel.Serializable)
 {
     _sagaDbContextFactory = sagaDbContextFactory;
     _isolationLevel       = isolationLevel;
 }
Ejemplo n.º 52
0
        /// <summary>
        /// 지정된 <see cref="Action"/>를 지정된 격리수준의 Transaction 하에서 수행한다.
        /// </summary>
        /// <param name="isolationLevel">격리수준</param>
        /// <param name="transactionalAction">Action to execute under Transaction</param>
        /// <param name="nestingOptions">UnitOfWork Nesting option.</param>
        public static void Transaction(IsolationLevel isolationLevel,
                                       Action transactionalAction,
                                       UnitOfWorkNestingOptions nestingOptions)
        {
            transactionalAction.ShouldNotBeNull("transactionalAction");

            if (IsDebugEnabled)
            {
                log.Debug("Execute the specified action under transaction... " +
                          "isolationLevel=[{0}], transactionalAction=[{1}], nestingOptions=[{2}]",
                          isolationLevel, transactionalAction, nestingOptions);
            }

            using (UnitOfWork.Start(nestingOptions)) {
                // if we are already in a transaction, don't start a new one
                if (UnitOfWork.Current.IsInActiveTransaction)
                {
                    if (IsDebugEnabled)
                    {
                        log.Debug("활성화된 기존 Transaction에 참여합니다.");
                    }

                    transactionalAction();
                }
                else
                {
                    if (IsDebugEnabled)
                    {
                        log.Debug("새로운 NHibernate.ITransaction을 생성합니다.");
                    }

                    var tx = UnitOfWork.Current.BeginTransaction(isolationLevel);

                    try {
                        transactionalAction();

                        tx.Commit();

                        if (IsDebugEnabled)
                        {
                            log.Debug("Transactional Action을 수행하고, Transaction.Commit을 수행하였습니다.");
                        }
                    }
                    catch (Exception ex) {
                        if (log.IsErrorEnabled)
                        {
                            log.Error("Fail to execute transactional action. rollback transaction.");
                            log.Error(ex);
                        }

                        tx.Rollback();
                        throw;
                    }
                    finally {
                        if (tx != null)
                        {
                            tx.Dispose();

                            if (IsDebugEnabled)
                            {
                                log.Debug("Dispose current transaction.");
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 53
0
 public IUnitOfWork Begin(IsolationLevel isolationLevel)
 {
     return(Current);
 }
Ejemplo n.º 54
0
 protected DbUnitTestBase(SqlConnection connection, IsolationLevel isolationLevel)
 {
     _isolationLevel = isolationLevel;
     Db = new SqlDbHelper(connection);
 }
        /// <summary>
        /// Begins a database transaction with the specified isolation level.
        /// </summary>
        /// <param name="level">The <see cref="System.Data.IsolationLevel">isolation level</see> under which the transaction should run.</param>
        /// <returns>An <see cref="System.Data.IDbTransaction">IDbTransaction</see>
        /// object representing the new transaction.</returns>
        /// <remarks>
        /// Currently the IsolationLevel ReadCommitted and Serializable are supported by the PostgreSQL backend.
        /// There's no support for nested transactions.
        /// </remarks>
        IDbTransaction IDbConnection.BeginTransaction(IsolationLevel level)
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "IDbConnection.BeginTransaction", level);

            return(BeginTransaction(level));
        }
        public static UnitOfWorkScopeTransaction GetTransactionForScope(IUnitOfWorkFactory factory, UnitOfWorkScope scope, IsolationLevel isolationLevel, UoWScopeOptions options)
        {
            var useCompatibleTx = (options & UoWScopeOptions.UseCompatible) == UoWScopeOptions.UseCompatible;
            var createNewTx     = (options & UoWScopeOptions.CreateNew) == UoWScopeOptions.CreateNew;

            //вот нельзя одновременно создавать новую транзакцию и использовать существующую
            if (useCompatibleTx && createNewTx)
            {
                throw new InvalidOperationException("Несовместимые опции запуска транзакции");
            }

            if (options == UoWScopeOptions.UseCompatible)
            {
                var transaction = (from t in CurrentTransactions where t.IsolationLevel == isolationLevel select t).FirstOrDefault();
                if (transaction != null)
                {
                    transaction.AttachScope(scope);
                    return(transaction);
                }
            }

            var newTransaction = new UnitOfWorkScopeTransaction(factory, isolationLevel);

            newTransaction.AttachScope(scope);
            CurrentTransactions.AddFirst(newTransaction);
            return(newTransaction);
        }
 public ITransaction BeginTransaction(IsolationLevel level)
 {
     return(_session.BeginTransaction(level));
 }
Ejemplo n.º 58
0
 public ScimoreDbTransaction(ScimoreDb database, ScimoreConnection connection, IsolationLevel level)
 {
     _database    = database;
     _connection  = connection;
     _transaction = new ScimoreTransaction(level, connection);
 }
Ejemplo n.º 59
0
 /// <summary>
 /// Only SqlServer
 /// </summary>
 /// <param name="iso"></param>
 /// <param name="transactionName"></param>
 public override void BeginTran(IsolationLevel iso, string transactionName)
 {
     base.BeginTran(iso);
 }
 public static UnitOfWorkScopeTransaction GetTransactionForScope(IUnitOfWorkFactory factory, UnitOfWorkScope scope, IsolationLevel isolationLevel)
 {
     return(GetTransactionForScope(factory, scope, isolationLevel, UoWScopeOptions.UseCompatible));
 }