Example #1
0
 internal static Exception OpenConnectionPropertySet(string property, ConnectionState state)
 {
     return(InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state))));
 }
Example #2
0
 internal static ArgumentException ParameterValueOutOfRange(Decimal value)
 {
     return(ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null))));
 }
Example #3
0
 //
 // SqlMetaData, SqlTypes, SqlClient
 //
 internal static Exception InvalidMetaDataValue()
 {
     return(ADP.Argument(SR.GetString(SR.ADP_InvalidMetaDataValue)));
 }
Example #4
0
 internal static Exception ConnectionAlreadyOpen(ConnectionState state)
 {
     return(InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state))));
 }
Example #5
0
 internal static Exception NonPooledOpenTimeout()
 {
     return(ADP.TimeoutException(SR.GetString(SR.ADP_NonPooledOpenTimeout)));
 }
Example #6
0
 internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state)
 {
     return(InvalidOperation(SR.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state))));
 }
Example #7
0
 //
 // DbConnectionOptions, DataAccess
 //
 internal static ArgumentException InvalidMinMaxPoolSizeValues()
 {
     return(ADP.Argument(SR.GetString(SR.ADP_InvalidMinMaxPoolSizeValues)));
 }
Example #8
0
        internal static int GetKeyValuePair(string connectionString, int currentPosition, StringBuilder buffer, bool useOdbcRules, out string keyname, out string keyvalue)
        {
            int startposition = currentPosition;

            buffer.Length = 0;
            keyname       = null;
            keyvalue      = null;

            char currentChar = '\0';

            ParserState parserState = ParserState.NothingYet;
            int         length      = connectionString.Length;

            for (; currentPosition < length; ++currentPosition)
            {
                currentChar = connectionString[currentPosition];

                switch (parserState)
                {
                case ParserState.NothingYet:     // [\\s;]*
                    if ((';' == currentChar) || char.IsWhiteSpace(currentChar))
                    {
                        continue;
                    }
                    if ('\0' == currentChar)
                    {
                        parserState = ParserState.NullTermination; continue;
                    }
                    if (char.IsControl(currentChar))
                    {
                        throw ADP.ConnectionStringSyntax(startposition);
                    }
                    startposition = currentPosition;
                    if ('=' != currentChar)
                    {
                        parserState = ParserState.Key;
                        break;
                    }
                    else
                    {
                        parserState = ParserState.KeyEqual;
                        continue;
                    }

                case ParserState.Key:     // (?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)
                    if ('=' == currentChar)
                    {
                        parserState = ParserState.KeyEqual; continue;
                    }
                    if (char.IsWhiteSpace(currentChar))
                    {
                        break;
                    }
                    if (char.IsControl(currentChar))
                    {
                        throw ADP.ConnectionStringSyntax(startposition);
                    }
                    break;

                case ParserState.KeyEqual:     // \\s*=(?!=)\\s*
                    if (!useOdbcRules && '=' == currentChar)
                    {
                        parserState = ParserState.Key; break;
                    }
                    keyname = GetKeyName(buffer);
                    if (ADP.IsEmpty(keyname))
                    {
                        throw ADP.ConnectionStringSyntax(startposition);
                    }
                    buffer.Length = 0;
                    parserState   = ParserState.KeyEnd;
                    goto case ParserState.KeyEnd;

                case ParserState.KeyEnd:
                    if (char.IsWhiteSpace(currentChar))
                    {
                        continue;
                    }
                    if (useOdbcRules)
                    {
                        if ('{' == currentChar)
                        {
                            parserState = ParserState.BraceQuoteValue; break;
                        }
                    }
                    else
                    {
                        if ('\'' == currentChar)
                        {
                            parserState = ParserState.SingleQuoteValue; continue;
                        }
                        if ('"' == currentChar)
                        {
                            parserState = ParserState.DoubleQuoteValue; continue;
                        }
                    }
                    if (';' == currentChar)
                    {
                        goto ParserExit;
                    }
                    if ('\0' == currentChar)
                    {
                        goto ParserExit;
                    }
                    if (char.IsControl(currentChar))
                    {
                        throw ADP.ConnectionStringSyntax(startposition);
                    }
                    parserState = ParserState.UnquotedValue;
                    break;

                case ParserState.UnquotedValue:     // "((?![\"'\\s])" + "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" + "(?<![\"']))"
                    if (char.IsWhiteSpace(currentChar))
                    {
                        break;
                    }
                    if (char.IsControl(currentChar) || ';' == currentChar)
                    {
                        goto ParserExit;
                    }
                    break;

                case ParserState.DoubleQuoteValue:     // "(\"([^\"\u0000]|\"\")*\")"
                    if ('"' == currentChar)
                    {
                        parserState = ParserState.DoubleQuoteValueQuote; continue;
                    }
                    if ('\0' == currentChar)
                    {
                        throw ADP.ConnectionStringSyntax(startposition);
                    }
                    break;

                case ParserState.DoubleQuoteValueQuote:
                    if ('"' == currentChar)
                    {
                        parserState = ParserState.DoubleQuoteValue; break;
                    }
                    keyvalue    = GetKeyValue(buffer, false);
                    parserState = ParserState.QuotedValueEnd;
                    goto case ParserState.QuotedValueEnd;

                case ParserState.SingleQuoteValue:     // "('([^'\u0000]|'')*')"
                    if ('\'' == currentChar)
                    {
                        parserState = ParserState.SingleQuoteValueQuote; continue;
                    }
                    if ('\0' == currentChar)
                    {
                        throw ADP.ConnectionStringSyntax(startposition);
                    }
                    break;

                case ParserState.SingleQuoteValueQuote:
                    if ('\'' == currentChar)
                    {
                        parserState = ParserState.SingleQuoteValue; break;
                    }
                    keyvalue    = GetKeyValue(buffer, false);
                    parserState = ParserState.QuotedValueEnd;
                    goto case ParserState.QuotedValueEnd;

                case ParserState.BraceQuoteValue:     // "(\\{([^\\}\u0000]|\\}\\})*\\})"
                    if ('}' == currentChar)
                    {
                        parserState = ParserState.BraceQuoteValueQuote; break;
                    }
                    if ('\0' == currentChar)
                    {
                        throw ADP.ConnectionStringSyntax(startposition);
                    }
                    break;

                case ParserState.BraceQuoteValueQuote:
                    if ('}' == currentChar)
                    {
                        parserState = ParserState.BraceQuoteValue; break;
                    }
                    keyvalue    = GetKeyValue(buffer, false);
                    parserState = ParserState.QuotedValueEnd;
                    goto case ParserState.QuotedValueEnd;

                case ParserState.QuotedValueEnd:
                    if (char.IsWhiteSpace(currentChar))
                    {
                        continue;
                    }
                    if (';' == currentChar)
                    {
                        goto ParserExit;
                    }
                    if ('\0' == currentChar)
                    {
                        parserState = ParserState.NullTermination; continue;
                    }
                    throw ADP.ConnectionStringSyntax(startposition); // unbalanced single quote

                case ParserState.NullTermination:                    // [\\s;\u0000]*
                    if ('\0' == currentChar)
                    {
                        continue;
                    }
                    if (char.IsWhiteSpace(currentChar))
                    {
                        continue;
                    }
                    throw ADP.ConnectionStringSyntax(currentPosition);

                default:
                    throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState1);
                }
                buffer.Append(currentChar);
            }
ParserExit:
            switch (parserState)
            {
            case ParserState.Key:
            case ParserState.DoubleQuoteValue:
            case ParserState.SingleQuoteValue:
            case ParserState.BraceQuoteValue:
                // keyword not found/unbalanced double/single quote
                throw ADP.ConnectionStringSyntax(startposition);

            case ParserState.KeyEqual:
                // equal sign at end of line
                keyname = GetKeyName(buffer);
                if (ADP.IsEmpty(keyname))
                {
                    throw ADP.ConnectionStringSyntax(startposition);
                }
                break;

            case ParserState.UnquotedValue:
                // unquoted value at end of line
                keyvalue = GetKeyValue(buffer, true);

                char tmpChar = keyvalue[keyvalue.Length - 1];
                if (!useOdbcRules && (('\'' == tmpChar) || ('"' == tmpChar)))
                {
                    throw ADP.ConnectionStringSyntax(startposition);        // unquoted value must not end in quote, except for odbc
                }
                break;

            case ParserState.DoubleQuoteValueQuote:
            case ParserState.SingleQuoteValueQuote:
            case ParserState.BraceQuoteValueQuote:
            case ParserState.QuotedValueEnd:
                // quoted value at end of line
                keyvalue = GetKeyValue(buffer, false);
                break;

            case ParserState.NothingYet:
            case ParserState.KeyEnd:
            case ParserState.NullTermination:
                // do nothing
                break;

            default:
                throw ADP.InternalError(ADP.InternalErrorCode.InvalidParserState2);
            }
            if ((';' == currentChar) && (currentPosition < connectionString.Length))
            {
                currentPosition++;
            }
            return(currentPosition);
        }
Example #9
0
        internal DBConnectionString Intersect(DBConnectionString entry)
        {
            KeyRestrictionBehavior behavior = _behavior;

            string[] restrictionValues = null;

            if (null == entry)
            {
                //Debug.WriteLine("0 entry AllowNothing");
                behavior = KeyRestrictionBehavior.AllowOnly;
            }
            else if (_behavior != entry._behavior)
            { // subset of the AllowOnly array
                behavior = KeyRestrictionBehavior.AllowOnly;

                if (KeyRestrictionBehavior.AllowOnly == entry._behavior)
                { // this PreventUsage and entry AllowOnly
                    if (!ADP.IsEmptyArray(_restrictionValues))
                    {
                        if (!ADP.IsEmptyArray(entry._restrictionValues))
                        {
                            //Debug.WriteLine("1 this PreventUsage with restrictions and entry AllowOnly with restrictions");
                            restrictionValues = NewRestrictionAllowOnly(entry._restrictionValues, _restrictionValues);
                        }
                        else
                        {
                            //Debug.WriteLine("2 this PreventUsage with restrictions and entry AllowOnly with no restrictions");
                        }
                    }
                    else
                    {
                        //Debug.WriteLine("3/4 this PreventUsage with no restrictions and entry AllowOnly");
                        restrictionValues = entry._restrictionValues;
                    }
                }
                else if (!ADP.IsEmptyArray(_restrictionValues))
                { // this AllowOnly and entry PreventUsage
                    if (!ADP.IsEmptyArray(entry._restrictionValues))
                    {
                        //Debug.WriteLine("5 this AllowOnly with restrictions and entry PreventUsage with restrictions");
                        restrictionValues = NewRestrictionAllowOnly(_restrictionValues, entry._restrictionValues);
                    }
                    else
                    {
                        //Debug.WriteLine("6 this AllowOnly and entry PreventUsage with no restrictions");
                        restrictionValues = _restrictionValues;
                    }
                }
                else
                {
                    //Debug.WriteLine("7/8 this AllowOnly with no restrictions and entry PreventUsage");
                }
            }
            else if (KeyRestrictionBehavior.PreventUsage == _behavior)
            { // both PreventUsage
                if (ADP.IsEmptyArray(_restrictionValues))
                {
                    //Debug.WriteLine("9/10 both PreventUsage and this with no restrictions");
                    restrictionValues = entry._restrictionValues;
                }
                else if (ADP.IsEmptyArray(entry._restrictionValues))
                {
                    //Debug.WriteLine("11 both PreventUsage and entry with no restrictions");
                    restrictionValues = _restrictionValues;
                }
                else
                {
                    //Debug.WriteLine("12 both PreventUsage with restrictions");
                    restrictionValues = NoDuplicateUnion(_restrictionValues, entry._restrictionValues);
                }
            }
            else if (!ADP.IsEmptyArray(_restrictionValues) && !ADP.IsEmptyArray(entry._restrictionValues))
            { // both AllowOnly with restrictions
                if (_restrictionValues.Length <= entry._restrictionValues.Length)
                {
                    //Debug.WriteLine("13a this AllowOnly with restrictions and entry AllowOnly with restrictions");
                    restrictionValues = NewRestrictionIntersect(_restrictionValues, entry._restrictionValues);
                }
                else
                {
                    //Debug.WriteLine("13b this AllowOnly with restrictions and entry AllowOnly with restrictions");
                    restrictionValues = NewRestrictionIntersect(entry._restrictionValues, _restrictionValues);
                }
            }
            else
            { // both AllowOnly
              //Debug.WriteLine("14/15/16 this AllowOnly and entry AllowOnly but no restrictions");
            }

            // verify _hasPassword & _parsetable are in [....] between Everett/Whidbey
            Debug.Assert(!_hasPassword || ContainsKey(KEY.Password) || ContainsKey(KEY.Pwd), "OnDeserialized password mismatch this");
            Debug.Assert(null == entry || !entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry");

            DBConnectionString value = new DBConnectionString(this, restrictionValues, behavior);

            ValidateCombinedSet(this, value);
            ValidateCombinedSet(entry, value);

            return(value);
        }
        /// <summary>
        /// This method attempts to convert the given value to a PoolBlockingPeriod enum. The algorithm is:
        /// * if the value is from type string, it will be matched against PoolBlockingPeriod enum names only, using ordinal, case-insensitive comparer
        /// * if the value is from type PoolBlockingPeriod, it will be used as is
        /// * if the value is from integral type (SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64), it will be converted to enum
        /// * if the value is another enum or any other type, it will be blocked with an appropriate ArgumentException
        /// 
        /// in any case above, if the conerted value is out of valid range, the method raises ArgumentOutOfRangeException.
        /// </summary>
        /// <returns>PoolBlockingPeriod value in the valid range</returns>
        internal static PoolBlockingPeriod ConvertToPoolBlockingPeriod(string keyword, object value)
        {
            Debug.Assert(null != value, "ConvertToPoolBlockingPeriod(null)");
            string sValue = (value as string);
            PoolBlockingPeriod result;
            if (null != sValue)
            {
                // We could use Enum.TryParse<PoolBlockingPeriod> here, but it accepts value combinations like
                // "ReadOnly, ReadWrite" which are unwelcome here
                // Also, Enum.TryParse is 100x slower than plain StringComparer.OrdinalIgnoreCase.Equals method.
                if (TryConvertToPoolBlockingPeriod(sValue, out result))
                {
                    return result;
                }

                // try again after remove leading & trailing whitespaces.
                sValue = sValue.Trim();
                if (TryConvertToPoolBlockingPeriod(sValue, out result))
                {
                    return result;
                }

                // string values must be valid
                throw ADP.InvalidConnectionOptionValue(keyword);
            }
            else
            {
                // the value is not string, try other options
                PoolBlockingPeriod eValue;

                if (value is PoolBlockingPeriod)
                {
                    // quick path for the most common case
                    eValue = (PoolBlockingPeriod)value;
                }
                else if (value.GetType().IsEnum)
                {
                    // explicitly block scenarios in which user tries to use wrong enum types, like:
                    // builder["PoolBlockingPeriod"] = EnvironmentVariableTarget.Process;
                    // workaround: explicitly cast non-PoolBlockingPeriod enums to int
                    throw ADP.ConvertFailed(value.GetType(), typeof(PoolBlockingPeriod), null);
                }
                else
                {
                    try
                    {
                        // Enum.ToObject allows only integral and enum values (enums are blocked above), rasing ArgumentException for the rest
                        eValue = (PoolBlockingPeriod)Enum.ToObject(typeof(PoolBlockingPeriod), value);
                    }
                    catch (ArgumentException e)
                    {
                        // to be consistent with the messages we send in case of wrong type usage, replace 
                        // the error with our exception, and keep the original one as inner one for troubleshooting
                        throw ADP.ConvertFailed(value.GetType(), typeof(PoolBlockingPeriod), e);
                    }
                }

                // ensure value is in valid range
                if (IsValidPoolBlockingPeriodValue(eValue))
                {
                    return eValue;
                }
                else
                {
                    throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)eValue);
                }
            }
        }
 internal static void TraceExceptionWithoutRethrow(Exception e)
 {
     Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
     TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
 }
Example #12
0
        internal static void AppendKeyValuePairBuilder(StringBuilder builder, string keyName, string?keyValue, bool useOdbcRules)
        {
            ADP.CheckArgumentNull(builder, nameof(builder));
            ADP.CheckArgumentLength(keyName, nameof(keyName));

            if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName))
            {
                throw ADP.InvalidKeyname(keyName);
            }
            if ((null != keyValue) && !IsValueValidInternal(keyValue))
            {
                throw ADP.InvalidValue(keyName);
            }

            if ((0 < builder.Length) && (';' != builder[builder.Length - 1]))
            {
                builder.Append(';');
            }

            if (useOdbcRules)
            {
                builder.Append(keyName);
            }
            else
            {
                builder.Append(keyName.Replace("=", "=="));
            }
            builder.Append('=');

            if (null != keyValue)
            {
                // else <keyword>=;
                if (useOdbcRules)
                {
                    if ((0 < keyValue.Length) &&
                        // string.Contains(char) is .NetCore2.1+ specific
                        (('{' == keyValue[0]) || (0 <= keyValue.IndexOf(';')) || string.Equals(DbConnectionStringKeywords.Driver, keyName, StringComparison.OrdinalIgnoreCase)) &&
                        !s_connectionStringQuoteOdbcValueRegex.IsMatch(keyValue))
                    {
                        // always quote Driver value (required for ODBC Version 2.65 and earlier)
                        // always quote values that contain a ';'
                        builder.Append('{').Append(keyValue.Replace("}", "}}")).Append('}');
                    }
                    else
                    {
                        builder.Append(keyValue);
                    }
                }
                else if (s_connectionStringQuoteValueRegex.IsMatch(keyValue))
                {
                    // <value> -> <value>
                    builder.Append(keyValue);
                }
                else if ((keyValue.Contains('\"')) && (!keyValue.Contains('\'')))
                {
                    // <val"ue> -> <'val"ue'>
                    builder.Append('\'');
                    builder.Append(keyValue);
                    builder.Append('\'');
                }
                else
                {
                    // <val'ue> -> <"val'ue">
                    // <=value> -> <"=value">
                    // <;value> -> <";value">
                    // < value> -> <" value">
                    // <va lue> -> <"va lue">
                    // <va'"lue> -> <"va'""lue">
                    builder.Append('\"');
                    builder.Append(keyValue.Replace("\"", "\"\""));
                    builder.Append('\"');
                }
            }
        }
Example #13
0
        private static Hashtable SplitConnectionString(string connectionString, Hashtable synonyms, bool firstKey)
        {
            Hashtable parsetable = new Hashtable();
            Regex     parser     = (firstKey ? ConnectionStringRegexOdbc : ConnectionStringRegex);

            const int KeyIndex = 1, ValueIndex = 2;

            Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index");
            Debug.Assert(ValueIndex == parser.GroupNumberFromName("value"), "wrong value index");

            if (null != connectionString)
            {
                Match match = parser.Match(connectionString);
                if (!match.Success || (match.Length != connectionString.Length))
                {
                    throw ADP.ConnectionStringSyntax(match.Length);
                }
                int indexValue = 0;
                CaptureCollection keyvalues = match.Groups[ValueIndex].Captures;
                foreach (Capture keypair in match.Groups[KeyIndex].Captures)
                {
                    string keyname  = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLowerInvariant();
                    string keyvalue = keyvalues[indexValue++].Value;
                    if (0 < keyvalue.Length)
                    {
                        if (!firstKey)
                        {
                            switch (keyvalue[0])
                            {
                            case '\"':
                                keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\"\"", "\"");
                                break;

                            case '\'':
                                keyvalue = keyvalue.Substring(1, keyvalue.Length - 2).Replace("\'\'", "\'");
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    else
                    {
                        keyvalue = null;
                    }
                    DebugTraceKeyValuePair(keyname, keyvalue, synonyms);

                    string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname);
                    if (!IsKeyNameValid(realkeyname))
                    {
                        throw ADP.KeywordNotSupported(keyname);
                    }
                    if (!firstKey || !parsetable.ContainsKey(realkeyname))
                    {
                        parsetable[realkeyname] = keyvalue; // last key-value pair wins (or first)
                    }
                }
            }
            return(parsetable);
        }
Example #14
0
 internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value)
 {
     return(ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString())));
 }
Example #15
0
 //
 // DbConnectionPool and related
 //
 internal static Exception PooledOpenTimeout()
 {
     return(ADP.InvalidOperation(SR.GetString(SR.ADP_PooledOpenTimeout)));
 }
Example #16
0
 protected virtual DbDataReader GetDbDataReader(int i)
 {
     throw ADP.NotSupported();
 }
Example #17
0
 public void Reset()
 {
     throw ADP.NotSupported();
 }