public override void Complete()
        {
            base.Complete();

            if (IsOuterMostUnitOfWork)
            {
                ConnectionHolder connectionHolder = GetConnectionHolder(DbProvider);
                if (connectionHolder == null)
                {
                    throw new InvalidConnectionHolderException(
                              "Can't complete the UnitOfWork, because the connHolder in current thread is null.");
                }
                if (connectionHolder.Transaction == null)
                {
                    throw new InvalidConnectionHolderException(
                              "Can't complete the UnitOfWork, because the Transaction of the connHolder in current thread is null");
                }
                connectionHolder.Transaction.Commit();
                Logger.Debug("[AdoNetUnitOfWork.Complete]:the transaction of the connectionHolder in current thread was commit over.");
            }
            else
            {
                Logger.DebugFormat(
                    "It's the inner UnitOfWork bound to the thread so don't commit the connHolder's transaction.Inner(deepth:{0})",
                    UnitOfWorkStackManager.Count);
            }
        }
示例#2
0
        /// <summary>
        /// Create the ConnHolder by DbProvider.
        /// </summary>
        /// <returns></returns>
        protected override ConnectionHolder CreateConnectionHolder()
        {
            IDbConnection dbConnection = null;

            try
            {
                dbConnection = DbProvider.CreateConnection();
                dbConnection.ConnectionString = DbProvider.ConnectionString;
                dbConnection.Open();

                var connectionHolder = new ConnectionHolder(dbConnection, null);

                int timeout = DetermineTimeout(Definition);
                if (timeout != DefaultUnitOfWorkDefinition.TIMEOUT_DEFAULT)
                {
                    connectionHolder.TimeoutInSeconds = timeout;
                }

                return(connectionHolder);
            }
            //TODO catch specific exception
            catch (Exception e)
            {
                ConnectionUtils.DisposeConnection(dbConnection, DbProvider);
                throw new CannotCreateConnectionHolderException("Could not create ADO.NET ConnectionHolder for transaction", e);
            }
        }
        /// <summary>
        /// Return the current transaction object.
        /// </summary>
        /// <returns>The current transaction object.</returns>
        /// <exception cref="Spring.Transaction.CannotCreateTransactionException">
        /// If transaction support is not available.
        /// </exception>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// In the case of lookup or system errors.
        /// </exception>
        protected override object DoGetTransaction()
        {
            HibernateTransactionObject txObject = new HibernateTransactionObject();

            txObject.SavepointAllowed = NestedTransactionsAllowed;
            if (TransactionSynchronizationManager.HasResource(SessionFactory))
            {
                SessionHolder sessionHolder =
                    (SessionHolder)TransactionSynchronizationManager.GetResource(SessionFactory);
                if (log.IsDebugEnabled)
                {
                    log.Debug("Found thread-bound Session [" + sessionHolder.Session +
                              "] for Hibernate transaction");
                }
                txObject.SetSessionHolder(sessionHolder, false);
                if (DbProvider != null)
                {
                    ConnectionHolder conHolder = (ConnectionHolder)
                                                 TransactionSynchronizationManager.GetResource(DbProvider);
                    txObject.ConnectionHolder = conHolder;
                }
            }
            txObject.PromotableTxScopeTransactionObject = new TxScopeTransactionManager.PromotableTxScopeTransactionObject();

            return(txObject);
        }
示例#4
0
        public Listener([NotNull] ListenerConfiguration configuration,
                        [NotNull] ProcessingConfiguration processingConfiguration,
                        [NotNull] BufferManagerFactory bufferManagerFactory,
                        [NotNull] MessageTransportFactory messageTransportFactory)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }
            if (processingConfiguration == null)
            {
                throw new ArgumentNullException("processingConfiguration");
            }
            if (bufferManagerFactory == null)
            {
                throw new ArgumentNullException("bufferManagerFactory");
            }
            if (messageTransportFactory == null)
            {
                throw new ArgumentNullException("messageTransportFactory");
            }

            this._configuration        = configuration;
            this._bufferManagerFactory = bufferManagerFactory;

            this._clientConnectionInfoPool = new ObjectPool <ClientConnectionInfo>();
            this._disconnectSocketArgsPool = new ObjectPool <SocketAsyncEventArgs>();
            this._socketPool = new ObjectPool <Socket>();

            _connectionHolder         = new ConnectionHolder(configuration.ConnectionCapacity);
            _stoppedWaitHandle        = new ManualResetEvent(false);
            _messageTransport         = messageTransportFactory.GetMessageTransport(this);
            _compressionBufferManager = bufferManagerFactory.GetBufferManager(1024, 1024 * 8);
        }
        public void Should_shuffle_connections()
        {
            var actual = ConnectionHolder.Shuffle(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 });

            Assert.That(actual, Is.EquivalentTo(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }));
            Assert.That(actual, Is.Not.EqualTo(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }));
        }
示例#6
0
		public static void Initialize( frmMain Form ) {
			mForm = Form;

			ConnectionHolder con = new ConnectionHolder( "localhost", 3306, "eathena_test", "eathena_test", "eathena_test" );
			mSql = new FinalSoftware.MySql.MySqlWrapper();
			if( mSql.Init( con ) != MysqlError.None )
				throw mSql.LastError;
		}
 public void SetUp()
 {
     _connectionFactory1 = new Mock <IConnectionFactory>();
     _connectionFactory2 = new Mock <IConnectionFactory>();
     _connectionFactory3 = new Mock <IConnectionFactory>();
     _confirmStrategy    = new Mock <IConfirmStrategy>();
     _sut = new ConnectionHolder(new[] { _connectionFactory1.Object, _connectionFactory2.Object, _connectionFactory3.Object }, _confirmStrategy.Object);
 }
        /// <summary>
        /// Suspend the resources of the current transaction.
        /// </summary>
        /// <param name="transaction">Transaction object returned by
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
        /// <returns>
        /// An object that holds suspended resources (will be kept unexamined for passing it into
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoResume"/>.)
        /// </returns>
        /// <remarks>
        /// Transaction synchronization will already have been suspended.
        /// </remarks>
        /// <exception cref="Spring.Transaction.IllegalTransactionStateException">
        /// If suspending is not supported by the transaction manager implementation.
        /// </exception>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// in case of system errors.
        /// </exception>
        protected override object DoSuspend(object transaction)
        {
            DbProviderTransactionObject txMgrStateObject = (DbProviderTransactionObject)transaction;

            txMgrStateObject.ConnectionHolder = null;
            ConnectionHolder conHolder = (ConnectionHolder)TransactionSynchronizationManager.UnbindResource(DbProvider);

            return(conHolder);
        }
        public static IDisposable UseConnection(SqlConnection connection)
        {
            if (current?.Connection != null)
            {
                throw new InvalidOperationException("already set");
            }

            return(current = new ConnectionHolder(connection));
        }
        /// <summary>
        /// Return the current transaction object.
        /// </summary>
        /// <returns>The current transaction object.</returns>
        /// <exception cref="Spring.Transaction.CannotCreateTransactionException">
        /// If transaction support is not available.
        /// </exception>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// In the case of lookup or system errors.
        /// </exception>
        protected override object DoGetTransaction()
        {
            DbProviderTransactionObject txMgrStateObject =
                new DbProviderTransactionObject();

            txMgrStateObject.SavepointAllowed = NestedTransactionsAllowed;
            ConnectionHolder conHolder =
                (ConnectionHolder)TransactionSynchronizationManager.GetResource(DbProvider);

            txMgrStateObject.SetConnectionHolder(conHolder, false);
            return(txMgrStateObject);
        }
示例#11
0
        public static void Initialize(frmMain Form)
        {
            mForm = Form;

            ConnectionHolder con = new ConnectionHolder("localhost", 3306, "eathena_test", "eathena_test", "eathena_test");

            mSql = new FinalSoftware.MySql.MySqlWrapper();
            if (mSql.Init(con) != MysqlError.None)
            {
                throw mSql.LastError;
            }
        }
示例#12
0
        /// <summary>
        /// Create connection at handle set transaction if necessary
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        protected static ConnectionHolder CreateConnection(string connectionString)
        {
            var connection = new SqlConnection(connectionString);

            connection.Open();

            if (Transaction.Current == null)
            {
                var transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
                return(ConnectionHolder.ForTransactionalWork(connection, transaction));
            }
            return(ConnectionHolder.ForNonTransactionalWork(connection));
        }
示例#13
0
 /// <summary>
 /// Constructs the persister with the ability to create connections to SQL Server using the specified connection string.
 /// This also means that the persister will manage the connection by itself, closing it when it has stopped using it.
 /// </summary>
 public SqlServerSagaPersister(string connectionString, string sagaIndexTableName, string sagaTableName)
     : this(sagaIndexTableName, sagaTableName)
 {
     getConnection = () =>
     {
         var connection = new SqlConnection(connectionString);
         connection.Open();
         var transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
         return(ConnectionHolder.ForTransactionalWork(connection, transaction));
     };
     commitAction      = h => h.Commit();
     rollbackAction    = h => h.RollBack();
     releaseConnection = c => c.Dispose();
 }
示例#14
0
        public void ConfigureServices(IServiceCollection services)
        {
            string appConfig = File.ReadAllText("app.config");
            var    system    = ActorSystem.Create("reservieren", appConfig);

            var eventConnectionHolder = system.ActorOf(ConnectionHolder.props(), "event-connection-holder");
            var persistence           = system.ActorOf(Persistence.props(eventConnectionHolder), "persistence");

            services.AddTransient(typeof(IEventConnectionHolderActorRef),
                                  pServiceProvider => new EventConnectionHolderActorRef(eventConnectionHolder));
            services.AddTransient(typeof(IPersistenceActorRef),
                                  pServiceProvider => new PersistenceActorRef(persistence));
            services.AddMvc();
        }
示例#15
0
        /// <summary>
        /// Create connection at handle set transaction if necessary
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        protected static ConnectionHolder CreateConnection(string connectionStringOrConnectionStringName)
        {
            var connectionStringToUse = Rebus.Shared.ConnectionStringUtil.GetConnectionStringToUse(connectionStringOrConnectionStringName);
            var connection            = new SqlConnection(connectionStringToUse);

            connection.Open();

            if (Transaction.Current == null)
            {
                var transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
                return(ConnectionHolder.ForTransactionalWork(connection, transaction));
            }
            return(ConnectionHolder.ForNonTransactionalWork(connection));
        }
        ConnectionHolder GetOrCreateConnection()
        {
            if (currentConnection != null)
            {
                return(currentTransaction == null
                    ? ConnectionHolder.ForNonTransactionalWork(currentConnection)
                    : ConnectionHolder.ForTransactionalWork(currentConnection, currentTransaction));
            }

            var newConnection = new SqlConnection(ConnectionStrings.SqlServer);

            newConnection.Open();
            currentConnection = newConnection;
            return(ConnectionHolder.ForNonTransactionalWork(newConnection));
        }
        /// <summary>
        /// Suspend the resources of the current transaction.
        /// </summary>
        /// <param name="transaction">
        /// Transaction object returned by
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.
        /// </param>
        /// <returns>
        /// An object that holds suspended resources (will be kept unexamined for passing it into
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoResume"/>.)
        /// </returns>
        /// <remarks>
        /// Transaction synchronization will already have been suspended.
        /// </remarks>
        /// <exception cref="Spring.Transaction.IllegalTransactionStateException">
        /// If suspending is not supported by the transaction manager implementation.
        /// </exception>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// in case of system errors.
        /// </exception>
        protected override object DoSuspend(object transaction)
        {
            HibernateTransactionObject txObject = (HibernateTransactionObject)transaction;

            txObject.SetSessionHolder(null, false);
            SessionHolder sessionHolder =
                (SessionHolder)TransactionSynchronizationManager.UnbindResource(SessionFactory);
            ConnectionHolder connectionHolder = null;

            if (DbProvider != null)
            {
                connectionHolder = (ConnectionHolder)TransactionSynchronizationManager.UnbindResource(DbProvider);
            }
            return(new SuspendedResourcesHolder(sessionHolder, connectionHolder));
        }
示例#18
0
        /// <summary>
        /// 根据当前线程中的ConnHolder来验证是否是最外层事务标识
        /// </summary>
        protected void CheckUnitOfWorkOutMostFlag(IDbProvider dbProvider)
        {
            ConnectionHolder connectionHolder = GetConnectionHolder(dbProvider);

            //当前线程中存在ConnHolder,理论上此事务应为嵌套事务,但是标识为最外层事务,冲突!
            if (connectionHolder != null && IsOuterMostUnitOfWork)
            {
                throw new InValidUnitOfWorkException("当前线程中存在ConnHolder,理论上此事务应为嵌套事务,但是IsOuterMostUnitOfWork标识为最外层事务,冲突!");
            }
            //当前线程中不存在ConnHolder,理论上此事务应为最外层事务,但是IsOuterMostUnitOfWork标识为非外层事务,冲突!
            if (connectionHolder == null && !IsOuterMostUnitOfWork)
            {
                throw new InValidUnitOfWorkException("当前线程中不存在ConnHolder,理论上此事务应为最外层事务,但是IsOuterMostUnitOfWork标识为非外层事务,冲突!");
            }
        }
示例#19
0
        /// <summary>
        /// Constructs the storage with the ability to create connections to SQL Server using the specified connection string.
        /// This also means that the storage will manage the connection by itself, closing it when it has stopped using it.
        /// </summary>
        public SqlServerSubscriptionStorage(string connectionString, string subscriptionsTableName)
        {
            this.subscriptionsTableName = subscriptionsTableName;

            getConnection = () =>
            {
                var connection = new SqlConnection(connectionString);
                connection.Open();
                var transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
                return(ConnectionHolder.ForTransactionalWork(connection, transaction));
            };
            commitAction      = h => h.Commit();
            rollbackAction    = h => h.RollBack();
            releaseConnection = c => c.Dispose();
        }
示例#20
0
        /// <summary>
        /// 事务开始
        /// </summary>
        protected void BeginTransaction(IDbProvider dbProvider, IUnitOfWorkDefinition definition)
        {
            CheckUnitOfWorkOutMostFlag(dbProvider);

            //从当前线程中获取
            ConnectionHolder conHolder = GetConnectionHolder(dbProvider);

            //如果当前线程中存在ConnectionHolder,则此事务为嵌套事务,外层事务已存在多年;
            if (conHolder != null)
            {
                Logger.Debug(m => m("[AbstractUnitOfWork.BeginTransaction]:Inner(deepth:{0}) unit of work initiates with definition({1})!",
                                    UnitOfWorkStackManager.Count, definition));
            }
            else             //外层事务
            {
                Logger.Debug(m => m("[AbstractUnitOfWork.BeginTransaction]:Outer most unit of work initiates with definition({0})!", definition));
                ConnectionHolder connectionHolder = CreateConnectionHolder();
                TransactionSynchronizationManager.BindResource(dbProvider, connectionHolder);
                Logger.Debug(m => m("[AbstractUnitOfWork.BeginTransaction]:UnitOfWork created with(connstring:{0})", connectionHolder.Connection.ConnectionString));
            }
        }
示例#21
0
        public void CanPublishWithinTransactionScopeWhenProvidingTransactionLessConnectionHolder()
        {
            // arrange
            var subscriptionStorage = new SqlServerSubscriptionStorage(() =>
            {
                var sqlConnection = new SqlConnection(ConnectionString);
                sqlConnection.Open();
                return(ConnectionHolder.ForNonTransactionalWork(sqlConnection));
            }, SubscriptionsTableName);

            subscriptionStorage.EnsureTableIsCreated();

            var publisher = CreateBus(PublisherInputQueueName, subscriptionStorage);

            var subReceivedEvents = new List <int>();

            var sub = CreateBus(SubscriberInputQueueName, subscriptionStorage)
                      .Handle <SomeEvent>(e => subReceivedEvents.Add(e.EventNumber));

            sub.Bus.Subscribe <SomeEvent>();

            // act
            Thread.Sleep(1.Seconds());

            using (var scope = new TransactionScope())
            {
                publisher.Bus.Publish(new SomeEvent {
                    EventNumber = 1
                });

                scope.Complete();
            }

            Thread.Sleep(1.Seconds());

            // assert
            subReceivedEvents.ShouldBe(new[] { 1 }.ToList());
        }
示例#22
0
        /// <summary>
        /// 释放当前线程中的ConnectionHolder,并从当前线程中清空此资源。
        /// </summary>
        /// <param name="dbProvider">the DbProvider.</param>
        protected void DisposeConnHolderBoundThread(IDbProvider dbProvider)
        {
            //从当前线程中获取ConnectionHolder
            ConnectionHolder connHolder = GetConnectionHolder(dbProvider);

            if (connHolder == null)
            {
                Logger.Debug("[AbstractUnitOfWork.DisposeConnHolderBoundThread]:Dispose UnitOfWork failed, because the connHolder bound current thread is null");
                TransactionSynchronizationManager.UnbindResource(dbProvider);
                return;
            }
            //如果是最外层事务,则进行Dispose
            if (IsOuterMostUnitOfWork)
            {
                if (connHolder.Connection != null)
                {
                    connHolder.Connection.Dispose();
                }
                if (connHolder.Transaction != null)
                {
                    connHolder.Transaction.Dispose();
                }
                TransactionSynchronizationManager.UnbindResource(dbProvider);

                Logger.Debug("[AbstractUnitOfWork.DisposeConnHolderBoundThread]:Outer most unit of work disposing, disposing connHolder, unbindResource connHolder in thread.");
            }
            else
            {
                //It's the transactional connection bound to the thread so don't close it.
                Logger.Debug(
                    m =>
                    m(
                        "[AbstractUnitOfWork.DisposeConnHolderBoundThread]:It's the transactional connHolder bound to the thread so don't close it. Inner UnitOfWork(deepth:{0}) disposing, keep connHolder in thread.",
                        UnitOfWorkStackManager.Count + 1));
            }
        }
示例#23
0
 bool AuthenticateCore(ConnectionHolder holder)
 {
     try
     {
         holder.Connection.Bind();
         return true;
     }
     catch (LdapException ex)
     {
         if (ex.ErrorCode == 49) // LDAP_INVALID_CREDENTIALS
             return false;
         throw;
     }
 }
        /// <summary>
        /// Begin a new transaction with the given transaction definition.
        /// </summary>
        /// <param name="transaction">
        /// Transaction object returned by
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.
        /// </param>
        /// <param name="definition">
        /// <see cref="Spring.Transaction.ITransactionDefinition"/> instance, describing
        /// propagation behavior, isolation level, timeout etc.
        /// </param>
        /// <remarks>
        /// Does not have to care about applying the propagation behavior,
        /// as this has already been handled by this abstract manager.
        /// </remarks>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// In the case of creation or system errors.
        /// </exception>
        protected override void DoBegin(object transaction, ITransactionDefinition definition)
        {
            TxScopeTransactionManager.PromotableTxScopeTransactionObject promotableTxScopeTransactionObject =
                ((HibernateTransactionObject)transaction).PromotableTxScopeTransactionObject;
            try
            {
                DoTxScopeBegin(promotableTxScopeTransactionObject, definition);
            }
            catch (Exception e)
            {
                throw new CannotCreateTransactionException("Transaction Scope failure on begin", e);
            }

            HibernateTransactionObject txObject = (HibernateTransactionObject)transaction;

            if (DbProvider != null && TransactionSynchronizationManager.HasResource(DbProvider) &&
                !txObject.ConnectionHolder.SynchronizedWithTransaction)
            {
                throw new IllegalTransactionStateException(
                          "Pre-bound ADO.NET Connection found - HibernateTransactionManager does not support " +
                          "running within AdoTransactionManager if told to manage the DbProvider itself. " +
                          "It is recommended to use a single HibernateTransactionManager for all transactions " +
                          "on a single DbProvider, no matter whether Hibernate or ADO.NET access.");
            }
            ISession session = null;

            try
            {
                if (txObject.SessionHolder == null || txObject.SessionHolder.SynchronizedWithTransaction)
                {
                    IInterceptor interceptor = EntityInterceptor;
                    ISession     newSession  = (interceptor != null ?
                                                SessionFactory.OpenSession(interceptor) : SessionFactory.OpenSession());

                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Opened new Session [" + newSession + "] for Hibernate transaction");
                    }
                    txObject.SetSessionHolder(new SessionHolder(newSession), true);
                }
                txObject.SessionHolder.SynchronizedWithTransaction = true;
                session = txObject.SessionHolder.Session;

                IDbConnection con = session.Connection;
                //TODO isolation level mgmt
                //IsolationLevel previousIsolationLevel =

                if (definition.ReadOnly && txObject.NewSessionHolder)
                {
                    // Just set to NEVER in case of a new Session for this transaction.
                    session.FlushMode = FlushMode.Never;
                }

                if (!definition.ReadOnly && !txObject.NewSessionHolder)
                {
                    // We need AUTO or COMMIT for a non-read-only transaction.
                    FlushMode flushMode = session.FlushMode;
                    if (FlushMode.Never == flushMode)
                    {
                        session.FlushMode = FlushMode.Auto;
                        txObject.SessionHolder.PreviousFlushMode = flushMode;
                    }
                }

                // Add the Hibernate transaction to the session holder.
                // for now pass in tx options isolation level.
                ITransaction   hibernateTx = session.BeginTransaction(definition.TransactionIsolationLevel);
                IDbTransaction adoTx       = GetIDbTransaction(hibernateTx);

                // Add the Hibernate transaction to the session holder.
                txObject.SessionHolder.Transaction = hibernateTx;

                // Register transaction timeout.
                int timeout = DetermineTimeout(definition);
                if (timeout != DefaultTransactionDefinition.TIMEOUT_DEFAULT)
                {
                    txObject.SessionHolder.TimeoutInSeconds = timeout;
                }

                // Register the Hibernate Session's ADO.NET Connection/TX pair for the DbProvider, if set.
                if (DbProvider != null)
                {
                    //investigate passing null for tx.
                    ConnectionHolder conHolder = new ConnectionHolder(con, adoTx);
                    if (timeout != DefaultTransactionDefinition.TIMEOUT_DEFAULT)
                    {
                        conHolder.TimeoutInMillis = definition.TransactionTimeout;
                    }
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Exposing Hibernate transaction as ADO transaction [" + con + "]");
                    }
                    TransactionSynchronizationManager.BindResource(DbProvider, conHolder);
                    txObject.ConnectionHolder = conHolder;
                }

                // Bind the session holder to the thread.
                if (txObject.NewSessionHolder)
                {
                    TransactionSynchronizationManager.BindResource(SessionFactory, txObject.SessionHolder);
                }
            }
            catch (Exception ex)
            {
                SessionFactoryUtils.CloseSession(session);
                throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);
            }
        }
        /// <summary>
        /// Resume the resources of the current transaction.
        /// </summary>
        /// <param name="transaction">Transaction object returned by
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
        /// <param name="suspendedResources">The object that holds suspended resources as returned by
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoSuspend"/>.</param>
        /// <remarks>
        /// Transaction synchronization will be resumed afterwards.
        /// </remarks>
        /// <exception cref="Spring.Transaction.IllegalTransactionStateException">
        /// If suspending is not supported by the transaction manager implementation.
        /// </exception>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// In the case of system errors.
        /// </exception>
        protected override void DoResume(object transaction, object suspendedResources)
        {
            ConnectionHolder conHolder = (ConnectionHolder)suspendedResources;

            TransactionSynchronizationManager.BindResource(DbProvider, conHolder);
        }
 public SuspendedResourcesHolder(SessionHolder sessionHolder, ConnectionHolder conHolder)
 {
     this.sessionHolder    = sessionHolder;
     this.connectionHolder = conHolder;
 }
 public void SetConnectionHolder(ConnectionHolder connectionHolder,
                                 bool newConnection)
 {
     ConnectionHolder    = connectionHolder;
     newConnectionHolder = newConnection;
 }
示例#28
0
        void CreateIndex(IEnumerable <KeyValuePair <string, string> > propertiesToIndex, ConnectionHolder connection, ISagaData sagaData)
        {
            var sagaTypeName = GetSagaTypeName(sagaData.GetType());
            var parameters   = propertiesToIndex
                               .Select((p, i) => new
            {
                PropertyName           = p.Key,
                PropertyValue          = p.Value ?? "",
                PropertyNameParameter  = string.Format("@n{0}", i),
                PropertyValueParameter = string.Format("@v{0}", i)
            })
                               .ToList();

            // lastly, generate new index
            using (var command = connection.CreateCommand())
            {
                // generate batch insert with SQL for each entry in the index
                var inserts = parameters
                              .Select(a => string.Format(
                                          @"                      insert into [{0}]
                                                            ([saga_type], [key], [value], [saga_id]) 
                                                        values 
                                                            (@saga_type, {1}, {2}, @saga_id)",
                                          sagaIndexTableName, a.PropertyNameParameter, a.PropertyValueParameter))
                              .ToList();

                var sql = string.Join(";" + Environment.NewLine, inserts);

                command.CommandText = sql;

                foreach (var parameter in parameters)
                {
                    command.Parameters.Add(parameter.PropertyNameParameter, SqlDbType.NVarChar).Value  = parameter.PropertyName;
                    command.Parameters.Add(parameter.PropertyValueParameter, SqlDbType.NVarChar).Value = parameter.PropertyValue;
                }

                command.Parameters.Add("saga_type", SqlDbType.NVarChar).Value       = sagaTypeName;
                command.Parameters.Add("saga_id", SqlDbType.UniqueIdentifier).Value = sagaData.Id;

                try
                {
                    command.ExecuteNonQuery();
                }
                catch (SqlException sqlException)
                {
                    if (sqlException.Number == SqlServerMagic.PrimaryKeyViolationNumber)
                    {
                        throw new OptimisticLockingException(sagaData, sqlException);
                    }

                    throw;
                }
            }
        }
示例#29
0
        protected IEnumerable<IDirectoryAttributes> LookupUserEntries(ConnectionHolder holder)
        {
            var query = holder.DirectoryContext
                .Query(Directory.BaseDn, objectClass: Directory.UserObjectClass, objectCategory: Directory.UserObjectCategory);

            if (!string.IsNullOrEmpty(Directory.UserFilter))
                query = query.Where(Directory.UserFilter);

            IEnumerable<IDirectoryAttributes> result = query.ToList();

            return result;
        }
示例#30
0
 public App()
 {
     ConnectionHolder.SetConnection("database.db");
 }
示例#31
0
        protected IDirectoryAttributes LookupUserEntry(ConnectionHolder holder, string userName)
        {
            var query = holder.DirectoryContext
                .Query(Directory.BaseDn, objectClass: Directory.UserObjectClass)
                .Where(Directory.UserNameAttribute + '=' + userName);

            if (!string.IsNullOrEmpty(Directory.UserFilter))
                query = query.Where(Directory.UserFilter);

            IDirectoryAttributes result;
            try
            {
                result = query.SingleOrDefault();
            }
            catch (InvalidOperationException)
            {
                throw new ApplicationException(string.Format("More objects were found with the user name {0}.", userName));
            }

            return result;
        }