public void ReleaseConnection(Tds connection)
        {
            if (connection == null)
            {
                return;
            }
            if (no_pooling)
            {
                connection.Disconnect();
                return;
            }

            if (connection.poolStatus == 2 || connection.Expired)
            {
                lock (conns)
                    conns.Remove(connection);
                connection.Disconnect();
                connection = null;
            }
            lock (available) {
                if (connection != null)                 // connection is still open
                {
                    available.Enqueue(connection);
                }
                // We pulse even if we don't queue, because null means that there's a slot
                // available in 'conns'
                Monitor.Pulse(available);
            }
        }
示例#2
0
        public void LifeTimeIsTakenInAccount()
        {
            var SMALLEST_LIFETIME_TO_TEST    = 1;
            var WAIT_TO_MAKE_LIFETIME_PASSED = 2;

            TdsConnectionPoolManager sqlConnectionPools = new FakeConnectionPoolManager();
            TdsConnectionInfo        info = new TdsConnectionInfo("dummy", 0, 0, 0,
                                                                  1 /*minpoolsize*/,
                                                                  1 /*maxpoolsize*/,
                                                                  SMALLEST_LIFETIME_TO_TEST /*lifetime*/);

            TdsConnectionPool pool = sqlConnectionPools.GetConnectionPool("test", info);

            Mono.Data.Tds.Protocol.Tds tds, tds2 = null;

            tds = pool.GetConnection();

            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(WAIT_TO_MAKE_LIFETIME_PASSED));
            pool.ReleaseConnection(tds);

            tds2 = pool.GetConnection();


            Assert.IsFalse(object.ReferenceEquals(tds, tds2));
            pool.ReleaseConnection(tds2);
        }
示例#3
0
        void Open()
        {
            string serverName = "";

            if (connectionString == null || connectionString.Equals(""))
            {
                throw new InvalidOperationException("Connection string has not been initialized.");
            }

            try {
                if (!pooling)
                {
                    ParseDataSource(dataSource, out port, out serverName);
                    tds = new Tds50(serverName, port, PacketSize, ConnectionTimeout);
                }
                else
                {
                    ParseDataSource(dataSource, out port, out serverName);
                    TdsConnectionInfo info = new TdsConnectionInfo(serverName, port, packetSize, ConnectionTimeout, minPoolSize, maxPoolSize);
                    pool = sybaseConnectionPools.GetConnectionPool(connectionString, info);
                    tds  = pool.GetConnection();
                }
            }
            catch (TdsTimeoutException e) {
                throw SybaseException.FromTdsInternalException((TdsInternalException)e);
            }

            tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler(ErrorHandler);
            tds.TdsInfoMessage  += new TdsInternalInfoMessageEventHandler(MessageHandler);

            if (!tds.IsConnected)
            {
                try {
                    tds.Connect(parms);
                    ChangeState(ConnectionState.Open);
                    ChangeDatabase(parms.Database);
                }
                catch {
                    if (pooling)
                    {
                        pool.ReleaseConnection(tds);
                    }
                    throw;
                }
            }
            else if (connectionReset)
            {
                // tds.ExecuteNonQuery ("EXEC sp_reset_connection"); FIXME
                ChangeState(ConnectionState.Open);
            }
        }
 void InitializePool()
 {
     /* conns.Count might not be 0 when we are resetting the connection pool */
     for (int i = conns.Count; i < info.PoolMinSize; i++)
     {
         try {
             Tds t = manager.CreateConnection(info);
             conns.Add(t);
             available.Enqueue(t);
         } catch {
             // Ignore. GetConnection will throw again.
         }
     }
 }
示例#5
0
		void Open ()
		{
			string serverName = string.Empty;
			if (state == ConnectionState.Open)
				throw new InvalidOperationException ("The Connection is already Open (State=Open)");

			if (connectionString == null || connectionString.Trim().Length == 0)
				throw new InvalidOperationException ("Connection string has not been initialized.");

			try {
				if (!pooling) {
					if(!ParseDataSource (dataSource, out port, out serverName))
						throw new SqlException(20, 0, "SQL Server does not exist or access denied.",  17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
					tds = new Tds80 (serverName, port, PacketSize, ConnectionTimeout, 0);
					tds.Pooling = false;
				}
				else {
					if(!ParseDataSource (dataSource, out port, out serverName))
						throw new SqlException(20, 0, "SQL Server does not exist or access denied.",  17, "ConnectionOpen (Connect()).", dataSource, parms.ApplicationName, 0);
					
					TdsConnectionInfo info = new TdsConnectionInfo (serverName, port, packetSize, ConnectionTimeout, minPoolSize, maxPoolSize, connectionLifeTime);
					pool = sqlConnectionPools.GetConnectionPool (connectionString, info);
					tds = pool.GetConnection ();
				}
			} catch (TdsTimeoutException e) {
				throw SqlException.FromTdsInternalException ((TdsInternalException) e);
			} catch (TdsInternalException e) {
				throw SqlException.FromTdsInternalException (e);
			}

			tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler (ErrorHandler);
			tds.TdsInfoMessage += new TdsInternalInfoMessageEventHandler (MessageHandler);

			if (!tds.IsConnected) {
				try {
					if (Credentials != null) {
						if (parms.User != String.Empty)
							throw new ArgumentException("UserID already specified");
						if (parms.PasswordSet)
							throw new ArgumentException("Password already specified");
						if (parms.DomainLogin != false)
							throw new ArgumentException("Cannot use credentials with DomainLogin");
						parms.User = Credentials.UserId;
						parms.Password = Credentials.Password;
					}
					tds.Connect (parms);
				} catch {
					if (pooling)
						pool.ReleaseConnection (tds);
					throw;
				}
			}

			disposed = false; // reset this, so using () would call Close ().
			ChangeState (ConnectionState.Open);
		}
        public Tds GetConnection()
        {
            if (no_pooling)
            {
                return(manager.CreateConnection(info));
            }

            Tds  result = null;
            bool create_new;
            int  retries = info.PoolMaxSize * 2;

retry:
            while (result == null)
            {
                create_new = false;
                lock (available) {
                    if (available.Count > 0)
                    {
                        result = (Tds)available.Dequeue();
                        break;                         // .. and do the reset out of the loop
                    }
                    Monitor.Enter(conns);
                    try {
                        if (conns.Count >= info.PoolMaxSize - in_progress)
                        {
                            Monitor.Exit(conns);
                            bool got_lock = Monitor.Wait(available, info.Timeout * 1000);
                            if (!got_lock)
                            {
                                throw new InvalidOperationException(
                                          "Timeout expired. The timeout period elapsed before a " +
                                          "connection could be obtained. A possible explanation " +
                                          "is that all the connections in the pool are in use, " +
                                          "and the maximum pool size is reached.");
                            }
                            else if (available.Count > 0)
                            {
                                result = (Tds)available.Dequeue();
                                break;                                 // .. and do the reset out of the loop
                            }
                            continue;
                        }
                        else
                        {
                            create_new = true;
                            in_progress++;
                        }
                    } finally {
                        Monitor.Exit(conns);                          // Exiting if not owned is ok < 2.x
                    }
                }
                if (create_new)
                {
                    try {
                        result = manager.CreateConnection(info);
                        lock (conns)
                            conns.Add(result);
                        return(result);
                    } finally {
                        lock (available)
                            in_progress--;
                    }
                }
            }

            bool      remove_cnc = true;
            Exception exc        = null;

            try {
                remove_cnc = (!result.IsConnected || !result.Reset());
            } catch (Exception e) {
                remove_cnc = true;
                exc        = e;
            }
            if (remove_cnc)
            {
                lock (conns)
                    conns.Remove(result);
                result.Disconnect();
                retries--;
                if (retries == 0)
                {
                    throw exc;
                }
                result = null;
                goto retry;
            }
            return(result);
        }
示例#7
0
 public TdsBulkCopy(Tds tds)
 {
     this.tds = tds;
 }
示例#8
0
		public void ReleaseConnection (Tds connection)
		{
			if (connection == null)
				return;
			if (no_pooling) {
				connection.Disconnect ();
				return;
			}

			if (connection.poolStatus == 2) {
				lock (conns)
					conns.Remove (connection);
				connection.Disconnect ();
				connection = null;
			}
			lock (available) {
				if (connection != null) // connection is still open
 					available.Enqueue (connection);
				// We pulse even if we don't queue, because null means that there's a slot
				// available in 'conns'
 				Monitor.Pulse (available);
			}
		}
示例#9
0
        public TdsComm(string dataSource, int port, int packetSize, int timeout, TdsVersion tdsVersion)
        {
            this.packetSize = packetSize;
            this.tdsVersion = tdsVersion;
            this.dataSource = dataSource;

            outBuffer = new byte[packetSize];
            inBuffer  = new byte[packetSize];

            outBufferLength = packetSize;
            inBufferLength  = packetSize;

            lsb = true;

            IPEndPoint endPoint;
            bool       have_exception = false;

            try {
                IPAddress ip;
                if (IPAddress.TryParse(this.dataSource, out ip))
                {
                    endPoint = new IPEndPoint(ip, port);
                }
                else
                {
                    IPHostEntry hostEntry = Dns.GetHostEntry(this.dataSource);
                    endPoint = new IPEndPoint(hostEntry.AddressList [0], port);
                }
            } catch (SocketException e) {
                throw new TdsInternalException("Server does not exist or connection refused.", e);
            }

            try {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IAsyncResult ares       = socket.BeginConnect(endPoint, null, null);
                int          timeout_ms = timeout * 1000;
                if (timeout > 0 && !ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne(timeout_ms, false))
                {
                    throw Tds.CreateTimeoutException(dataSource, "Open()");
                }
                socket.EndConnect(ares);
                try {
                    // MS sets these socket option
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                } catch (SocketException) {
                    // Some platform may throw an exception, so
                    // eat all socket exception, yeaowww!
                }

                try {
                    socket.NoDelay = true;
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout_ms);
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout_ms);
                } catch {
                    // Ignore exceptions here for systems that do not support these options.
                }
                // Let the stream own the socket and take the pleasure of closing it
                stream = new NetworkStream(socket, true);
            } catch (SocketException e) {
                have_exception = true;
                throw new TdsInternalException("Server does not exist or connection refused.", e);
            } catch (Exception) {
                have_exception = true;
                throw;
            } finally {
                if (have_exception && socket != null)
                {
                    try {
                        Socket s = socket;
                        socket = null;
                        s.Close();
                    } catch {}
                }
            }
            if (!socket.Connected)
            {
                throw new TdsInternalException("Server does not exist or connection refused.", null);
            }
            packetsSent = 1;
        }
示例#10
0
		public TdsBulkCopy (Tds tds)
		{
			this.tds = tds;
		}
		public void Open () 
		{
			string serverName = "";
			if (connectionString == null)
				throw new InvalidOperationException ("Connection string has not been initialized.");

			try {
				if (!pooling) {
					ParseDataSource (dataSource, out port, out serverName);
					tds = new Tds42 (serverName, port, PacketSize, ConnectionTimeout);
				}
				else {
					ParseDataSource (dataSource, out port, out serverName);
 					TdsConnectionInfo info = new TdsConnectionInfo (serverName, port, packetSize, ConnectionTimeout, minPoolSize, maxPoolSize);
					pool = tdsConnectionPools.GetConnectionPool (connectionString, info);
					tds = pool.GetConnection ();
				}
			}
			catch (TdsTimeoutException e) {
				throw TdsException.FromTdsInternalException ((TdsInternalException) e);
			}

			tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler (ErrorHandler);
			tds.TdsInfoMessage += new TdsInternalInfoMessageEventHandler (MessageHandler);

			if (!tds.IsConnected) {
				try {
					tds.Connect (parms);
					ChangeState (ConnectionState.Open);
					ChangeDatabase (parms.Database);
				}
				catch {
					if (pooling)
						pool.ReleaseConnection (tds);
					throw;
				}
			}
			else if (connectionReset) {
				// tds.ExecuteNonQuery ("EXEC sp_reset_connection"); FIXME
				ChangeState (ConnectionState.Open);
			}
		}