Exemple #1
0
 private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, SqlConnection owningObject)
 {
     if (serverInfo.ExtendedServerName == null)
     {
         string userServerName = serverInfo.UserServerName;
         string userProtocol   = serverInfo.UserProtocol;
         if (aliasLookup)
         {
             TdsParserStaticMethods.AliasRegistryLookup(ref userServerName, ref userProtocol);
             if ((owningObject != null) && ((SqlConnectionString)owningObject.UserConnectionOptions).EnforceLocalHost)
             {
                 SqlConnectionString.VerifyLocalHostAndFixup(ref userServerName, true, true);
             }
         }
         serverInfo.SetDerivedNames(userProtocol, userServerName);
     }
 }
        internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms(), false)
        {
            bool runningInProc = InOutOfProcHelper.InProc;

            _integratedSecurity = ConvertValueToIntegratedSecurity();

            ConvertValueToBoolean(KEY.AsynchronousProcessing, DEFAULT.Asynchronous); // while we don't use it anymore, we still need to verify it is true/false

            // SQLPT 41700: Ignore ResetConnection=False (still validate the keyword/value)
            _connectionReset   = ConvertValueToBoolean(KEY.Connection_Reset, DEFAULT.Connection_Reset);
            _contextConnection = ConvertValueToBoolean(KEY.Context_Connection, DEFAULT.Context_Connection);
            _encrypt           = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt);
            _enlist            = ConvertValueToBoolean(KEY.Enlist, ADP.IsWindowsNT);
            _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS);
            _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info);
            _pooling             = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling);
            _replication         = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication);
            _userInstance        = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance);
            _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover);

            _connectTimeout       = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout);
            _loadBalanceTimeout   = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout);
            _maxPoolSize          = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size);
            _minPoolSize          = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size);
            _packetSize           = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size);
            _connectRetryCount    = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count);
            _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval);

            _applicationIntent      = ConvertValueToApplicationIntent();
            _applicationName        = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name);
            _attachDBFileName       = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename);
            _currentLanguage        = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language);
            _dataSource             = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source);
            _localDBInstance        = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
            _failoverPartner        = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner);
            _initialCatalog         = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog);
            _networkLibrary         = ConvertValueToString(KEY.Network_Library, null);
            _password               = ConvertValueToString(KEY.Password, DEFAULT.Password);
            _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate);

            // Temporary string - this value is stored internally as an enum.
            string typeSystemVersionString  = ConvertValueToString(KEY.Type_System_Version, null);
            string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null);

            _userID        = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID);
            _workstationId = ConvertValueToString(KEY.Workstation_Id, null);

            if (_contextConnection)
            {
                // We have to be running in the engine for you to request a
                // context connection.

                if (!runningInProc)
                {
                    throw SQL.ContextUnavailableOutOfProc();
                }

                // When using a context connection, we need to ensure that no
                // other connection string keywords are specified.

                foreach (DictionaryEntry entry in Parsetable)
                {
                    if ((string)entry.Key != KEY.Context_Connection &&
                        (string)entry.Key != KEY.Type_System_Version)
                    {
                        throw SQL.ContextAllowsLimitedKeywords();
                    }
                }
            }

            if (!_encrypt)      // Support legacy registry encryption settings
            {
                const string folder = "Software\\Microsoft\\MSSQLServer\\Client\\SuperSocketNetLib";
                const string value  = "Encrypt";

                Object obj = ADP.LocalMachineRegistryValue(folder, value);
                if ((obj is Int32) && (1 == (int)obj))           // If the registry key exists
                {
                    _encrypt = true;
                }
            }


            if (_loadBalanceTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout);
            }

            if (_connectTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout);
            }

            if (_maxPoolSize < 1)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size);
            }

            if (_minPoolSize < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size);
            }
            if (_maxPoolSize < _minPoolSize)
            {
                throw ADP.InvalidMinMaxPoolSizeValues();
            }

            if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize))
            {
                throw SQL.InvalidPacketSizeValue();
            }

            if (null != _networkLibrary)   // MDAC 83525
            {
                string    networkLibrary = _networkLibrary.Trim().ToLower(CultureInfo.InvariantCulture);
                Hashtable netlib         = NetlibMapping();
                if (!netlib.ContainsKey(networkLibrary))
                {
                    throw ADP.InvalidConnectionOptionValue(KEY.Network_Library);
                }
                _networkLibrary = (string)netlib[networkLibrary];
            }
            else
            {
                _networkLibrary = DEFAULT.Network_Library;
            }

            ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name);
            ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language);
            ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
            ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner);
            ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog);
            ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password);
            ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID);
            if (null != _workstationId)
            {
                ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
            }

            if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase))
            {
                // fail-over partner is set

                if (_multiSubnetFailover)
                {
                    throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null);
                }

                if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase))
                {
                    throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog);
                }
            }

            // expand during construction so that CreatePermissionSet and Expand are consistent
            string datadir = null;

            _expandedAttachDBFilename = ExpandDataDirectory(KEY.AttachDBFilename, _attachDBFileName, ref datadir);
            if (null != _expandedAttachDBFilename)
            {
                if (0 <= _expandedAttachDBFilename.IndexOf('|'))
                {
                    throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
                }
                ValidateValueLength(_expandedAttachDBFilename, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
                if (_localDBInstance == null)
                {
                    // fail fast to verify LocalHost when using |DataDirectory|
                    // still must check again at connect time
                    string host     = _dataSource;
                    string protocol = _networkLibrary;
                    TdsParserStaticMethods.AliasRegistryLookup(ref host, ref protocol);
                    VerifyLocalHostAndFixup(ref host, true, false /*don't fix-up*/);
                }
            }
            else if (0 <= _attachDBFileName.IndexOf('|'))
            {
                throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
            }
            else
            {
                ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
            }

            _typeSystemAssemblyVersion = constTypeSystemAsmVersion10;

            if (true == _userInstance && !ADP.IsEmpty(_failoverPartner))
            {
                throw SQL.UserInstanceFailoverNotCompatible();
            }

            if (ADP.IsEmpty(typeSystemVersionString))
            {
                typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion;
            }

            if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.Latest;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase))
            {
                if (_contextConnection)
                {
                    throw SQL.ContextAllowsOnlyTypeSystem2005();
                }
                _typeSystemVersion = TypeSystem.SQLServer2000;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2005;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2008;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion         = TypeSystem.SQLServer2012;
                _typeSystemAssemblyVersion = constTypeSystemAsmVersion11;
            }
            else
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version);
            }

            if (ADP.IsEmpty(transactionBindingString))
            {
                transactionBindingString = DbConnectionStringDefaults.TransactionBinding;
            }

            if (transactionBindingString.Equals(TRANSACIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase))
            {
                _transactionBinding = TransactionBindingEnum.ImplicitUnbind;
            }
            else if (transactionBindingString.Equals(TRANSACIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase))
            {
                _transactionBinding = TransactionBindingEnum.ExplicitUnbind;
            }
            else
            {
                throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding);
            }

            if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner))
            {
                throw SQL.ROR_FailoverNotSupportedConnString();
            }

            if ((_connectRetryCount < 0) || (_connectRetryCount > 255))
            {
                throw ADP.InvalidConnectRetryCountValue();
            }

            if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60))
            {
                throw ADP.InvalidConnectRetryIntervalValue();
            }
        }
        internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms(), false)
        {
            bool inProc = InOutOfProcHelper.InProc;

            this._integratedSecurity = base.ConvertValueToIntegratedSecurity();
            this._async             = base.ConvertValueToBoolean("asynchronous processing", false);
            this._connectionReset   = base.ConvertValueToBoolean("connection reset", true);
            this._contextConnection = base.ConvertValueToBoolean("context connection", false);
            this._encrypt           = base.ConvertValueToBoolean("encrypt", false);
            this._enlist            = base.ConvertValueToBoolean("enlist", ADP.IsWindowsNT);
            this._mars = base.ConvertValueToBoolean("multipleactiveresultsets", false);
            this._persistSecurityInfo    = base.ConvertValueToBoolean("persist security info", false);
            this._pooling                = base.ConvertValueToBoolean("pooling", true);
            this._replication            = base.ConvertValueToBoolean("replication", false);
            this._userInstance           = base.ConvertValueToBoolean("user instance", false);
            this._multiSubnetFailover    = base.ConvertValueToBoolean("multisubnetfailover", false);
            this._connectTimeout         = base.ConvertValueToInt32("connect timeout", 15);
            this._loadBalanceTimeout     = base.ConvertValueToInt32("load balance timeout", 0);
            this._maxPoolSize            = base.ConvertValueToInt32("max pool size", 100);
            this._minPoolSize            = base.ConvertValueToInt32("min pool size", 0);
            this._packetSize             = base.ConvertValueToInt32("packet size", 0x1f40);
            this._applicationIntent      = this.ConvertValueToApplicationIntent();
            this._applicationName        = base.ConvertValueToString("application name", ".Net SqlClient Data Provider");
            this._attachDBFileName       = base.ConvertValueToString("attachdbfilename", "");
            this._currentLanguage        = base.ConvertValueToString("current language", "");
            this._dataSource             = base.ConvertValueToString("data source", "");
            this._localDBInstance        = LocalDBAPI.GetLocalDbInstanceNameFromServerName(this._dataSource);
            this._failoverPartner        = base.ConvertValueToString("failover partner", "");
            this._initialCatalog         = base.ConvertValueToString("initial catalog", "");
            this._networkLibrary         = base.ConvertValueToString("network library", null);
            this._password               = base.ConvertValueToString("password", "");
            this._trustServerCertificate = base.ConvertValueToBoolean("trustservercertificate", false);
            string str  = base.ConvertValueToString("type system version", null);
            string str2 = base.ConvertValueToString("transaction binding", null);

            this._userID        = base.ConvertValueToString("user id", "");
            this._workstationId = base.ConvertValueToString("workstation id", null);
            if (this._contextConnection)
            {
                if (!inProc)
                {
                    throw SQL.ContextUnavailableOutOfProc();
                }
                foreach (DictionaryEntry entry in base.Parsetable)
                {
                    if ((((string)entry.Key) != "context connection") && (((string)entry.Key) != "type system version"))
                    {
                        throw SQL.ContextAllowsLimitedKeywords();
                    }
                }
            }
            if (!this._encrypt)
            {
                object obj2 = ADP.LocalMachineRegistryValue(@"Software\Microsoft\MSSQLServer\Client\SuperSocketNetLib", "Encrypt");
                if ((obj2 is int) && (1 == ((int)obj2)))
                {
                    this._encrypt = true;
                }
            }
            if (this._loadBalanceTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue("load balance timeout");
            }
            if (this._connectTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue("connect timeout");
            }
            if (this._maxPoolSize < 1)
            {
                throw ADP.InvalidConnectionOptionValue("max pool size");
            }
            if (this._minPoolSize < 0)
            {
                throw ADP.InvalidConnectionOptionValue("min pool size");
            }
            if (this._maxPoolSize < this._minPoolSize)
            {
                throw ADP.InvalidMinMaxPoolSizeValues();
            }
            if ((this._packetSize < 0x200) || (0x8000 < this._packetSize))
            {
                throw SQL.InvalidPacketSizeValue();
            }
            if (this._networkLibrary != null)
            {
                string    key       = this._networkLibrary.Trim().ToLower(CultureInfo.InvariantCulture);
                Hashtable hashtable = NetlibMapping();
                if (!hashtable.ContainsKey(key))
                {
                    throw ADP.InvalidConnectionOptionValue("network library");
                }
                this._networkLibrary = (string)hashtable[key];
            }
            else
            {
                this._networkLibrary = "";
            }
            this.ValidateValueLength(this._applicationName, 0x80, "application name");
            this.ValidateValueLength(this._currentLanguage, 0x80, "current language");
            this.ValidateValueLength(this._dataSource, 0x80, "data source");
            this.ValidateValueLength(this._failoverPartner, 0x80, "failover partner");
            this.ValidateValueLength(this._initialCatalog, 0x80, "initial catalog");
            this.ValidateValueLength(this._password, 0x80, "password");
            this.ValidateValueLength(this._userID, 0x80, "user id");
            if (this._workstationId != null)
            {
                this.ValidateValueLength(this._workstationId, 0x80, "workstation id");
            }
            if (!string.Equals("", this._failoverPartner, StringComparison.OrdinalIgnoreCase))
            {
                if (this._multiSubnetFailover)
                {
                    bool serverProvidedFailoverPartner = false;
                    throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner);
                }
                if (string.Equals("", this._initialCatalog, StringComparison.OrdinalIgnoreCase))
                {
                    throw ADP.MissingConnectionOptionValue("failover partner", "initial catalog");
                }
            }
            string datadir = null;

            this._expandedAttachDBFilename = DbConnectionOptions.ExpandDataDirectory("attachdbfilename", this._attachDBFileName, ref datadir);
            if (this._expandedAttachDBFilename != null)
            {
                if (0 <= this._expandedAttachDBFilename.IndexOf('|'))
                {
                    throw ADP.InvalidConnectionOptionValue("attachdbfilename");
                }
                this.ValidateValueLength(this._expandedAttachDBFilename, 260, "attachdbfilename");
                if (this._localDBInstance == null)
                {
                    string host     = this._dataSource;
                    string protocol = this._networkLibrary;
                    TdsParserStaticMethods.AliasRegistryLookup(ref host, ref protocol);
                    VerifyLocalHostAndFixup(ref host, true, false);
                }
            }
            else
            {
                if (0 <= this._attachDBFileName.IndexOf('|'))
                {
                    throw ADP.InvalidConnectionOptionValue("attachdbfilename");
                }
                this.ValidateValueLength(this._attachDBFileName, 260, "attachdbfilename");
            }
            if (this._async && inProc)
            {
                throw SQL.AsyncInProcNotSupported();
            }
            if (this._userInstance && !ADP.IsEmpty(this._failoverPartner))
            {
                throw SQL.UserInstanceFailoverNotCompatible();
            }
            if (ADP.IsEmpty(str))
            {
                str = "Latest";
            }
            if (str.Equals("Latest", StringComparison.OrdinalIgnoreCase))
            {
                this._typeSystemVersion = TypeSystem.Latest;
            }
            else if (str.Equals("SQL Server 2000", StringComparison.OrdinalIgnoreCase))
            {
                if (this._contextConnection)
                {
                    throw SQL.ContextAllowsOnlyTypeSystem2005();
                }
                this._typeSystemVersion = TypeSystem.SQLServer2000;
            }
            else if (str.Equals("SQL Server 2005", StringComparison.OrdinalIgnoreCase))
            {
                this._typeSystemVersion = TypeSystem.SQLServer2005;
            }
            else
            {
                if (!str.Equals("SQL Server 2008", StringComparison.OrdinalIgnoreCase))
                {
                    throw ADP.InvalidConnectionOptionValue("type system version");
                }
                this._typeSystemVersion = TypeSystem.Latest;
            }
            if (ADP.IsEmpty(str2))
            {
                str2 = "Implicit Unbind";
            }
            if (str2.Equals("Implicit Unbind", StringComparison.OrdinalIgnoreCase))
            {
                this._transactionBinding = TransactionBindingEnum.ImplicitUnbind;
            }
            else
            {
                if (!str2.Equals("Explicit Unbind", StringComparison.OrdinalIgnoreCase))
                {
                    throw ADP.InvalidConnectionOptionValue("transaction binding");
                }
                this._transactionBinding = TransactionBindingEnum.ExplicitUnbind;
            }
            if ((this._applicationIntent == System.Data.SqlClient.ApplicationIntent.ReadOnly) && !string.IsNullOrEmpty(this._failoverPartner))
            {
                throw SQL.ROR_FailoverNotSupportedConnString();
            }
        }