public void Commit(Enlistment enlistment)
        {
            if (_transaction != null && !_transaction.IsUpdated)
            {
                _transaction.Commit();
                _transaction = null;

                if (Completed != null)
                {
                    Completed(this, new EventArgs());
                }

                if (_connection != null)
                {
                    if (!_connection.Options.Pooling && (_connection.OwningConnection == null || _connection.OwningConnection.IsClosed))
                    {
                        _connection.Disconnect();
                    }
                }
                _connection        = null;
                _systemTransaction = null;

                // Declare done on the enlistment
                enlistment.Done();
            }
        }
            static FbConnectionInternal CreateNewConnection(FbConnectionString connectionString)
            {
                var result = new FbConnectionInternal(connectionString);

                result.Connect();
                return(result);
            }
        public void CheckIn(FbConnectionInternal connection)
        {
            connection.OwningConnection = null;
            connection.Created          = System.DateTime.Now.Ticks;

            this.MoveConnection(connection, MoveType.LockedToUnlocked);
        }
Ejemplo n.º 4
0
        protected override void Dispose(bool disposing)
        {
            lock (this)
            {
                if (!this.disposed)
                {
                    try
                    {
                        // release any unmanaged resources
                        this.Close();

                        if (disposing)
                        {
                            // release any managed resources
                            this.innerConnection  = null;
                            this.options          = null;
                            this.connectionString = null;
                        }

                        this.disposed = true;
                    }
                    catch
                    {
                    }
                    finally
                    {
                        base.Dispose(disposing);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public FbEnlistmentNotification(FbConnectionInternal connection, Transaction systemTransaction)
        {
            _connection        = connection;
            _transaction       = connection.BeginTransaction(systemTransaction.IsolationLevel);
            _systemTransaction = systemTransaction;

            _systemTransaction.EnlistVolatile(this, System.Transactions.EnlistmentOptions.None);
        }
        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);
        }
        public FbEnlistmentNotification(FbConnectionInternal connection, Transaction systemTransaction)
        {
            _connection        = connection;
            _transaction       = connection.BeginTransaction(systemTransaction.IsolationLevel, new AsyncWrappingCommonArgs(false)).GetAwaiter().GetResult();
            _systemTransaction = systemTransaction;

            _systemTransaction.EnlistVolatile(this, EnlistmentOptions.None);
        }
Ejemplo n.º 8
0
            static FbConnectionInternal CreateNewConnection(FbConnectionString connectionString, FbConnection owner)
            {
                var result = new FbConnectionInternal(connectionString);

                result.SetOwningConnection(owner);
                result.Connect();
                return(result);
            }
Ejemplo n.º 9
0
        public override void Close()
        {
            if (!this.IsClosed && this.innerConnection != null)
            {
                lock (this)
                {
                    try
                    {
                        lock (this.innerConnection)
                        {
                            // Close the Remote	Event Manager
                            this.innerConnection.CloseEventManager();

                            // Unbind Warning messages event
                            if (this.innerConnection.Database != null)
                            {
                                this.innerConnection.Database.WarningMessage = null;
                            }

                            // Dispose Transaction
                            this.innerConnection.DisposeTransaction();

                            // Dispose all active statemenets
                            this.innerConnection.ReleasePreparedCommands();

                            // Close connection	or send	it back	to the pool
                            if (this.innerConnection.Pooled)
                            {
                                if (this.innerConnection.CancelDisabled)
                                {
                                    // Enable fb_cancel_operation if going into pool
                                    this.innerConnection.EnableCancel();
                                }

                                // Send	connection to the Pool
                                FbPoolManager.Instance.GetPool(this.connectionString).CheckIn(this.innerConnection);
                            }
                            else
                            {
                                if (!this.innerConnection.IsEnlisted)
                                {
                                    this.innerConnection.Dispose();
                                }
                                this.innerConnection = null;
                            }
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        // Update connection state
                        this.OnStateChange(this.state, ConnectionState.Closed);
                    }
                }
            }
        }
				public void Dispose()
				{
					if (_disposed)
						return;
					_disposed = true;
					Created = default(DateTimeOffset);
					Connection.Dispose();
					Connection = null;
				}
Ejemplo n.º 11
0
 public FbRemoteEvent(string connectionString)
 {
     _connection = new FbConnectionInternal(new FbConnectionString(connectionString));
     _connection.Connect();
     _revent = new RemoteEvent(_connection.Database);
     _revent.EventCountsCallback = OnRemoteEventCounts;
     _revent.EventErrorCallback  = OnRemoteEventError;
     _synchronizationContext     = SynchronizationContext.Current ?? new SynchronizationContext();
 }
Ejemplo n.º 12
0
        internal void Release(FbConnectionInternal connection, bool returnToAvailable)
        {
            CheckDisposed();

            if (_pools.TryGetValue(connection.Options.NormalizedConnectionString, out var pool))
            {
                pool.ReleaseConnection(connection, returnToAvailable);
            }
        }
        private FbConnectionInternal GetConnection()
        {
            FbConnectionInternal result = null;
            long check = -1;

            lock (this.unlocked.SyncRoot)
            {
                FbConnectionInternal[] connections = (FbConnectionInternal[])this.unlocked.ToArray(typeof(FbConnectionInternal));

                for (int i = connections.Length - 1; i >= 0; i--)
                {
                    if (connections[i].Verify())
                    {
                        if (this.lifeTime != 0)
                        {
                            long now    = DateTime.Now.Ticks;
                            long expire = connections[i].Created + this.lifeTime;

                            if (now >= expire)
                            {
                                if (this.CheckMinPoolSize())
                                {
                                    this.unlocked.Remove(connections[i]);
                                    this.Expire(connections[i]);
                                }
                            }
                            else
                            {
                                if (expire > check)
                                {
                                    check  = expire;
                                    result = connections[i];
                                }
                            }
                        }
                        else
                        {
                            result = connections[i];
                            break;
                        }
                    }
                    else
                    {
                        this.unlocked.Remove(connections[i]);
                        this.Expire(connections[i]);
                    }
                }

                if (result != null)
                {
                    this.MoveConnection(result, MoveType.UnlockedToLocked);
                }
            }

            return(result);
        }
        private FbConnectionInternal Create()
        {
            FbConnectionInternal connection = new FbConnectionInternal(this.options);

            connection.Connect();

            connection.Pooled  = true;
            connection.Created = DateTime.Now.Ticks;

            return(connection);
        }
Ejemplo n.º 15
0
 public void Dispose()
 {
     if (_disposed)
     {
         return;
     }
     _disposed = true;
     Created   = default(long);
     Connection.Dispose();
     Connection = null;
 }
Ejemplo n.º 16
0
        public override async Task CloseAsync()
#endif
        {
            if (!IsClosed && _innerConnection != null)
            {
                try
                {
                    await _innerConnection.CloseEventManagerAsync(CancellationToken.None).ConfigureAwait(false);

                    if (_innerConnection.Database != null)
                    {
                        _innerConnection.Database.WarningMessage = null;
                    }

                    await _innerConnection.DisposeTransactionAsync(CancellationToken.None).ConfigureAwait(false);

                    await _innerConnection.ReleasePreparedCommandsAsync(CancellationToken.None).ConfigureAwait(false);

                    if (_options.Pooling)
                    {
                        if (_innerConnection.CancelDisabled)
                        {
                            await _innerConnection.EnableCancelAsync(CancellationToken.None).ConfigureAwait(false);
                        }

                        var broken = _innerConnection.Database.ConnectionBroken;
                        FbConnectionPoolManager.Instance.Release(_innerConnection, !broken);
                        if (broken)
                        {
                            await DisconnectEnlistedHelper().ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        await DisconnectEnlistedHelper().ConfigureAwait(false);
                    }
                }
                catch
                { }
                finally
                {
                    OnStateChange(_state, ConnectionState.Closed);
                }
            }

            async Task DisconnectEnlistedHelper()
            {
                if (!_innerConnection.IsEnlisted)
                {
                    await _innerConnection.DisconnectAsync(CancellationToken.None).ConfigureAwait(false);
                }
                _innerConnection = null;
            }
        }
 public void Dispose()
 {
     if (_disposed)
     {
         return;
     }
     _disposed = true;
     Created   = default(DateTimeOffset);
     Connection.Dispose();
     Connection = null;
 }
Ejemplo n.º 18
0
        public override void Close()
        {
            if (!IsClosed && _innerConnection != null)
            {
                try
                {
                    _innerConnection.CloseEventManager();

                    if (_innerConnection.Database != null)
                    {
                        _innerConnection.Database.WarningMessage = null;
                    }

                    _innerConnection.DisposeTransaction();

                    _innerConnection.ReleasePreparedCommands();

                    if (_options.Pooling)
                    {
                        if (_innerConnection.CancelDisabled)
                        {
                            _innerConnection.EnableCancel();
                        }

                        if (!_innerConnection.Database.ConnectionBroken)
                        {
                            FbConnectionPoolManager.Instance.Release(_innerConnection);
                        }
                        else
                        {
                            if (!_innerConnection.IsEnlisted)
                            {
                                _innerConnection.Dispose();
                            }
                            _innerConnection = null;
                        }
                    }
                    else
                    {
                        if (!_innerConnection.IsEnlisted)
                        {
                            _innerConnection.Dispose();
                        }
                        _innerConnection = null;
                    }
                }
                catch
                { }
                finally
                {
                    OnStateChange(_state, ConnectionState.Closed);
                }
            }
        }
Ejemplo n.º 19
0
        private async Task DisposeHelper(AsyncWrappingCommonArgs async)
        {
            if (!_disposed)
            {
                _disposed = true;
                await CloseImpl(async).ConfigureAwait(false);

                _innerConnection  = null;
                _options          = null;
                _connectionString = null;
            }
        }
Ejemplo n.º 20
0
        internal async Task CloseImpl(AsyncWrappingCommonArgs async)
        {
            if (!IsClosed && _innerConnection != null)
            {
                try
                {
                    await _innerConnection.CloseEventManager(async).ConfigureAwait(false);

                    if (_innerConnection.Database != null)
                    {
                        _innerConnection.Database.WarningMessage = null;
                    }

                    await _innerConnection.DisposeTransaction(async).ConfigureAwait(false);

                    await _innerConnection.ReleasePreparedCommands(async).ConfigureAwait(false);

                    if (_options.Pooling)
                    {
                        if (_innerConnection.CancelDisabled)
                        {
                            await _innerConnection.EnableCancel(async).ConfigureAwait(false);
                        }

                        var broken = _innerConnection.Database.ConnectionBroken;
                        FbConnectionPoolManager.Instance.Release(_innerConnection, !broken);
                        if (broken)
                        {
                            await DisconnectEnlistedHelper().ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        await DisconnectEnlistedHelper().ConfigureAwait(false);
                    }
                }
                catch
                { }
                finally
                {
                    OnStateChange(_state, ConnectionState.Closed);
                }
            }

            async Task DisconnectEnlistedHelper()
            {
                if (!_innerConnection.IsEnlisted)
                {
                    await _innerConnection.Disconnect(async).ConfigureAwait(false);
                }
                _innerConnection = null;
            }
        }
 private void Expire(FbConnectionInternal connection)
 {
     try
     {
         connection.Dispose();
         connection = null;
     }
     catch (Exception)
     {
         // Do not raise an exception as the connection could be invalid due to several reasons
         // ( network problems, server shutdown, ... )
     }
 }
Ejemplo n.º 22
0
            public void ReleaseConnection(FbConnectionInternal connection)
            {
                lock (_syncRoot)
                {
                    CheckDisposedImpl();

                    var removed = _busy.Remove(connection);
                    if (removed)
                    {
                        _available.Enqueue(new Item(DateTimeOffset.UtcNow, connection));
                    }
                }
            }
Ejemplo n.º 23
0
        public override async ValueTask DisposeAsync()
        {
            if (!_disposed)
            {
                _disposed = true;
                await CloseAsync().ConfigureAwait(false);

                _innerConnection  = null;
                _options          = null;
                _connectionString = null;
            }
            await base.DisposeAsync().ConfigureAwait(false);
        }
Ejemplo n.º 24
0
            public void ReleaseConnection(FbConnectionInternal connection)
            {
                lock (_syncRoot)
                {
                    CheckDisposedImpl();

                    var removed = _busy.Remove(connection);
                    if (removed)
                    {
                        _available.Push(new Item(GetTicks(), connection));
                    }
                }
            }
Ejemplo n.º 25
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (!_disposed)
         {
             _disposed = true;
             Close();
             _innerConnection  = null;
             _options          = null;
             _connectionString = null;
         }
     }
     base.Dispose(disposing);
 }
Ejemplo n.º 26
0
        public static void DropDatabase(string connectionString)
        {
            FbConnectionString options = new FbConnectionString(connectionString);

            options.Validate();

            try
            {
                FbConnectionInternal db = new FbConnectionInternal(options);
                db.DropDatabase();
            }
            catch (IscException ex)
            {
                throw new FbException(ex.Message, ex);
            }
        }
Ejemplo n.º 27
0
        private static void CreateDatabaseImpl(string connectionString, int pageSize = 4096, bool forcedWrites = true, bool overwrite = false)
        {
            FbConnectionString options = new FbConnectionString(connectionString);

            options.Validate();

            try
            {
                DatabaseParameterBuffer dpb = new DatabaseParameterBuffer();

                dpb.Append(IscCodes.isc_dpb_version1);
                dpb.Append(IscCodes.isc_dpb_dummy_packet_interval, new byte[] { 120, 10, 0, 0 });
                dpb.Append(IscCodes.isc_dpb_sql_dialect, new byte[] { options.Dialect, 0, 0, 0 });
                if (!string.IsNullOrEmpty(options.UserID))
                {
                    dpb.Append(IscCodes.isc_dpb_user_name, options.UserID);
                }
                if (options.Charset.Length > 0)
                {
                    Charset charset = Charset.GetCharset(options.Charset);
                    if (charset == null)
                    {
                        throw new ArgumentException("Character set is not valid.");
                    }
                    else
                    {
                        dpb.Append(IscCodes.isc_dpb_set_db_charset, charset.Name);
                    }
                }
                dpb.Append(IscCodes.isc_dpb_force_write, (short)(forcedWrites ? 1 : 0));
                dpb.Append(IscCodes.isc_dpb_overwrite, (overwrite ? 1 : 0));
                if (pageSize > 0)
                {
                    dpb.Append(IscCodes.isc_dpb_page_size, pageSize);
                }

                using (FbConnectionInternal db = new FbConnectionInternal(options))
                {
                    db.CreateDatabase(dpb);
                }
            }
            catch (IscException ex)
            {
                throw new FbException(ex.Message, ex);
            }
        }
        public static void CreateDatabase(string connectionString, int pageSize = 4096, bool forcedWrites = true, bool overwrite = false)
        {
            var options = new ConnectionString(connectionString);

            options.Validate();

            try
            {
                using (var db = new FbConnectionInternal(options))
                {
                    db.CreateDatabase(pageSize, forcedWrites, overwrite);
                }
            }
            catch (IscException ex)
            {
                throw new FbException(ex.Message, ex);
            }
        }
        private void MoveConnection(FbConnectionInternal connection, MoveType moveType)
        {
            if (connection != null)
            {
                lock (this.unlocked.SyncRoot)
                {
                    switch (moveType)
                    {
                    case MoveType.LockedToUnlocked:
                        this.locked.Remove(connection);
                        this.unlocked.Add(connection);
                        break;

                    case MoveType.UnlockedToLocked:
                        this.unlocked.Remove(connection);
                        this.locked.Add(connection);
                        break;
                    }
                }
            }
        }
Ejemplo n.º 30
0
        public static async Task CreateDatabaseAsync(string connectionString, int pageSize = 4096, bool forcedWrites = true, bool overwrite = false, CancellationToken cancellationToken = default)
        {
            var options = new ConnectionString(connectionString);

            options.Validate();

            try
            {
                var db = new FbConnectionInternal(options);
                try
                {
                    await db.CreateDatabaseAsync(pageSize, forcedWrites, overwrite, cancellationToken).ConfigureAwait(false);
                }
                finally
                {
                    await db.DisconnectAsync(cancellationToken).ConfigureAwait(false);
                }
            }
            catch (IscException ex)
            {
                throw FbException.Create(ex);
            }
        }
Ejemplo n.º 31
0
        public static async Task DropDatabaseAsync(string connectionString, CancellationToken cancellationToken = default)
        {
            var options = new ConnectionString(connectionString);

            options.Validate();

            try
            {
                var db = new FbConnectionInternal(options);
                try
                {
                    await db.DropDatabaseAsync(cancellationToken).ConfigureAwait(false);
                }
                finally
                {
                    await db.DisconnectAsync(cancellationToken).ConfigureAwait(false);
                }
            }
            catch (IscException ex)
            {
                throw FbException.Create(ex);
            }
        }
Ejemplo n.º 32
0
        public void Rollback(Enlistment enlistment)
        {
            if (_transaction != null && !_transaction.IsCompleted)
            {
                _transaction.Rollback();
                _transaction = null;

                Completed?.Invoke(this, new EventArgs());

                if (_connection != null)
                {
                    if (!_connection.Options.Pooling && (_connection.OwningConnection == null || _connection.OwningConnection.IsClosed))
                    {
                        _connection.Disconnect();
                    }
                }
                _connection        = null;
                _systemTransaction = null;

                // Declare done on the enlistment
                enlistment.Done();
            }
        }
        public override void Close()
        {
            if (!this.IsClosed && this.innerConnection != null)
            {
                lock (this)
                {
                    try
                    {
                        lock (this.innerConnection)
                        {
                            // Close the Remote	Event Manager
                            this.innerConnection.CloseEventManager();

                            // Unbind Warning messages event
                            if (this.innerConnection.Database != null)
                            {
                                this.innerConnection.Database.WarningMessage = null;
                            }

                            // Dispose Transaction
                            this.innerConnection.DisposeTransaction();

                            // Dispose all active statemenets
                            this.innerConnection.ReleasePreparedCommands();

                            // Close connection	or send	it back	to the pool
                            if (this.innerConnection.Pooled)
                            {
								if (this.innerConnection.CancelDisabled)
								{
									// Enable fb_cancel_operation if going into pool
									this.innerConnection.EnableCancel();
								}

                                // Send	connection to the Pool
                                FbPoolManager.Instance.GetPool(this.connectionString).CheckIn(this.innerConnection);
                            }
                            else
                            {
                                if (!this.innerConnection.IsEnlisted)
                                {
                                    this.innerConnection.Dispose();
                                }
                                this.innerConnection = null;
                            }
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        // Update connection state
                        this.OnStateChange(this.state, ConnectionState.Closed);
                    }
                }
            }
        }
        public override void Open()
        {
            lock (this)
            {
                if (string.IsNullOrEmpty(this.connectionString))
                {
                    throw new InvalidOperationException("Connection String is not initialized.");
                }
                if (!this.IsClosed && this.state != ConnectionState.Connecting)
                {
                    throw new InvalidOperationException("Connection already Open.");
                }
#if (!NET_CF)
                if (this.options.Enlist && System.Transactions.Transaction.Current == null)
                {
                    throw new InvalidOperationException("There is no active TransactionScope to enlist transactions.");
                }
#endif

                this.DemandPermission();

                try
                {
                    this.OnStateChange(this.state, ConnectionState.Connecting);

                    if (this.options.Pooling)
                    {
                        this.innerConnection = FbPoolManager.Instance.GetPool(this.connectionString).CheckOut();
                        this.innerConnection.OwningConnection = this;
                    }
                    else
                    {
                        // Do not use Connection Pooling
                        this.innerConnection = new FbConnectionInternal(this.options, this);
                        this.innerConnection.Connect();
                    }

#if (!NET_CF)
                    try
                    {
                        this.innerConnection.EnlistTransaction(System.Transactions.Transaction.Current);
                    }
                    catch
                    {
                        // if enlistment fails clean up innerConnection
                        this.innerConnection.DisposeTransaction();

                        if (this.innerConnection.Pooled)
                        {
                            // Send connection return back to the Pool
                            FbPoolManager.Instance.GetPool(this.connectionString).CheckIn(this.innerConnection);
                        }
                        else
                        {
                            this.innerConnection.Dispose();
                            this.innerConnection = null;
                        }

                        throw;
                    }
#endif

                    // Bind	Warning	messages event
                    this.innerConnection.Database.WarningMessage = new WarningMessageCallback(this.OnWarningMessage);

                    // Update the connection state
                    this.OnStateChange(this.state, ConnectionState.Open);
                }
                catch (IscException ex)
                {
                    this.OnStateChange(this.state, ConnectionState.Closed);
                    throw new FbException(ex.Message, ex);
                }
                catch
                {
                    this.OnStateChange(this.state, ConnectionState.Closed);
                    throw;
                }
            }
        }
        protected override void Dispose(bool disposing)
        {
            lock (this)
            {
                if (!this.disposed)
                {
                    try
                    {
                        // release any unmanaged resources
                        this.Close();

                        if (disposing)
                        {
                            // release any managed resources
                            this.innerConnection = null;
                            this.options = null;
                            this.connectionString = null;
                        }

                        this.disposed = true;
                    }
                    catch
                    {
                    }
                    finally
                    {
                        base.Dispose(disposing);
                    }
                }
            }
        }
        public static void DropDatabase(string connectionString)
        {
            // Configure Attachment
            FbConnectionString options = new FbConnectionString(connectionString);
            options.Validate();

            try
            {
                // Drop	the	database	
                FbConnectionInternal db = new FbConnectionInternal(options);
                db.DropDatabase();
            }
            catch (IscException ex)
            {
                throw new FbException(ex.Message, ex);
            }
        }
        public void Commit(Enlistment enlistment)
        {
            if (this.transaction != null && !this.transaction.IsUpdated)
            {
                this.transaction.Commit();
                this.transaction = null;

                if (this.Completed != null)
                {
                    this.Completed(this, new EventArgs());
                }

                if (this.connection != null)
                {
                    if (!this.connection.Pooled && (this.connection.OwningConnection == null || this.connection.OwningConnection.IsClosed))
                    {
                        this.connection.Disconnect();
                    }
                }
                this.connection         = null;
                this.systemTransaction  = null;

                // Declare done on the enlistment
                enlistment.Done();
            }
        }
		public override void Open()
		{
			lock (this)
			{
				if (string.IsNullOrEmpty(_connectionString))
				{
					throw new InvalidOperationException("Connection String is not initialized.");
				}
				if (!IsClosed && _state != ConnectionState.Connecting)
				{
					throw new InvalidOperationException("Connection already Open.");
				}
				if (_options.Enlist && System.Transactions.Transaction.Current == null)
				{
					throw new InvalidOperationException("There is no active TransactionScope to enlist transactions.");
				}

				DemandPermission();

				try
				{
					OnStateChange(_state, ConnectionState.Connecting);

					if (_options.Pooling)
					{
						_innerConnection = FbConnectionPoolManager.Instance.Get(_options, this);
					}
					else
					{
						// Do not use Connection Pooling
						_innerConnection = new FbConnectionInternal(_options);
						_innerConnection.SetOwningConnection(this);
						_innerConnection.Connect();
					}

					try
					{
						_innerConnection.EnlistTransaction(System.Transactions.Transaction.Current);
					}
					catch
					{
						// if enlistment fails clean up innerConnection
						_innerConnection.DisposeTransaction();

						if (_options.Pooling)
						{
							// Send connection return back to the Pool
							FbConnectionPoolManager.Instance.Release(_innerConnection);
						}
						else
						{
							_innerConnection.Dispose();
							_innerConnection = null;
						}

						throw;
					}

					// Bind	Warning	messages event
					_innerConnection.Database.WarningMessage = new WarningMessageCallback(OnWarningMessage);

					// Update the connection state
					OnStateChange(_state, ConnectionState.Open);
				}
				catch (IscException ex)
				{
					OnStateChange(_state, ConnectionState.Closed);
					throw new FbException(ex.Message, ex);
				}
				catch
				{
					OnStateChange(_state, ConnectionState.Closed);
					throw;
				}
			}
		}
		public void Commit(Enlistment enlistment)
		{
			if (_transaction != null && !_transaction.IsUpdated)
			{
				_transaction.Commit();
				_transaction = null;

				if (Completed != null)
				{
					Completed(this, new EventArgs());
				}

				if (_connection != null)
				{
					if (!_connection.Options.Pooling && (_connection.OwningConnection == null || _connection.OwningConnection.IsClosed))
					{
						_connection.Disconnect();
					}
				}
				_connection = null;
				_systemTransaction = null;

				// Declare done on the enlistment
				enlistment.Done();
			}
		}
		private void Expire(FbConnectionInternal connection)
		{
			try
			{
				connection.Dispose();
                connection = null;
			}
			catch
			{
                // Do not raise an exception as the connection could be invalid due to several reasons
                // ( network problems, server shutdown, ... )
			}
		}
        private FbConnectionInternal Create()
        {
            FbConnectionInternal connection = new FbConnectionInternal(this.options);
            connection.Connect();

            connection.Pooled = true;
            connection.Created = DateTime.Now.Ticks;

            return connection;
        }
			static FbConnectionInternal CreateNewConnection(FbConnectionString connectionString, FbConnection owner)
			{
				var result = new FbConnectionInternal(connectionString);
				result.SetOwningConnection(owner);
				result.Connect();
				return result;
			}
			static FbConnectionInternal CreateNewConnection(FbConnectionString connectionString)
			{
				var result = new FbConnectionInternal(connectionString);
				result.Connect();
				return result;
			}
		internal void Release(FbConnectionInternal connection)
		{
			CheckDisposed();

			_pools.GetOrAdd(connection.Options.NormalizedConnectionString, _ => new Pool(connection.Options)).ReleaseConnection(connection);
		}
        public static void CreateDatabase(string connectionString, int pageSize, bool forcedWrites, bool overwrite)
        {
            FbConnectionString options = new FbConnectionString(connectionString);
            options.Validate();

            try
            {
                // DPB configuration
                DatabaseParameterBuffer dpb = new DatabaseParameterBuffer();

                // Dpb version
                dpb.Append(IscCodes.isc_dpb_version1);

                // Dummy packet	interval
                dpb.Append(IscCodes.isc_dpb_dummy_packet_interval, new byte[] { 120, 10, 0, 0 });

                // User	name
                dpb.Append(IscCodes.isc_dpb_user_name, options.UserID);

                // User	password
                dpb.Append(IscCodes.isc_dpb_password, options.Password);

                // Database	dialect
                dpb.Append(IscCodes.isc_dpb_sql_dialect, new byte[] { options.Dialect, 0, 0, 0 });

                // Character set
                if (options.Charset.Length > 0)
                {
                    Charset charset = Charset.GetCharset(options.Charset);

                    if (charset == null)
                    {
                        throw new ArgumentException("Character set is not valid.");
                    }
                    else
                    {
                        dpb.Append(IscCodes.isc_dpb_set_db_charset, charset.Name);
                    }
                }

                // Forced writes
                dpb.Append(IscCodes.isc_dpb_force_write, (short)(forcedWrites ? 1 : 0));

                // Database overwrite
                dpb.Append(IscCodes.isc_dpb_overwrite, (overwrite ? 1 : 0));

                // Page	Size
                if (pageSize > 0)
                {
                    dpb.Append(IscCodes.isc_dpb_page_size, pageSize);
                }

                // Create the new database
                FbConnectionInternal db = new FbConnectionInternal(options);
                db.CreateDatabase(dpb);
            }
            catch (IscException ex)
            {
                throw new FbException(ex.Message, ex);
            }
        }
        private void MoveConnection(FbConnectionInternal connection, MoveType moveType)
        {
            if (connection != null)
            {
                lock (this.unlocked.SyncRoot)
                {
                    switch (moveType)
                    {
                        case MoveType.LockedToUnlocked:
                            this.locked.Remove(connection);
                            this.unlocked.Add(connection);
                            break;

                        case MoveType.UnlockedToLocked:
                            this.unlocked.Remove(connection);
                            this.locked.Add(connection);
                            break;
                    }
                }
            }
        }
			public void ReleaseConnection(FbConnectionInternal connection)
			{
				lock (_syncRoot)
				{
					CheckDisposedImpl();

					var removed = _busy.Remove(connection);
					if (removed)
						_available.Enqueue(new Item(DateTimeOffset.UtcNow, connection));
				}
			}
			public void ReleaseConnection(FbConnectionInternal connection)
			{
				lock (_syncRoot)
				{
					CheckDisposedImpl();

					var removed = _busy.Remove(connection);
					if (removed && _available.Count < _connectionString.MaxPoolSize)
					{
						_available.Push(new Item(DateTimeOffset.UtcNow, connection));
					}
                    else
                    {
                        connection.Dispose();
                    }
                }
			}
		public void CheckIn(FbConnectionInternal connection)
		{
            connection.OwningConnection = null;
            connection.Created = System.DateTime.Now.Ticks;

            this.MoveConnection(connection, MoveType.LockedToUnlocked);
        }
				public Item(DateTimeOffset created, FbConnectionInternal connection)
					: this()
				{
					Created = created;
					Connection = connection;
				}