Ejemplo n.º 1
0
 protected virtual void CacheOracleDbTypeEnumValues(DbCommand command) {
     var assembly = command.GetType().GetTypeInfo().Assembly;
     var typeEnum = assembly.GetType(OracleDbTypeEnumName);
     ReflectionCache.DbTypeRefCursor = Enum.Parse(typeEnum, "RefCursor");
     ReflectionCache.DbTypeBlob = Enum.Parse(typeEnum, "Blob");
     ReflectionCache.DbTypeDate = Enum.Parse(typeEnum, "Date");
 }
Ejemplo n.º 2
0
        ///// <summary>
        ///// 设置Oracle DbCommand  参数绑定的模式。
        ///// </summary>
        ///// <param name="db"></param>
        ///// <param name="dbCmd"></param>
        ///// <param name="byName"></param>
        public void SetDbCmdParamterBindByName(Database db, System.Data.Common.DbCommand dbCmd, bool byName)
        {
            var databaseType = MB.Orm.Persistence.DatabaseHelper.GetDatabaseType(db);

            if (databaseType == DatabaseType.Oracle)
            {
                //edit by  陈迪臣 修改Oracle 参数的顺序的问题,默认情况下通过名称来匹配
                if (dbCmd.GetType().FullName == "Oracle.DataAccess.Client.OracleCommand")  //
                {
                    PropertyInfo proInfo = dbCmd.GetType().GetProperty("BindByName");
                    if (proInfo != null)
                    {
                        proInfo.SetValue(dbCmd, true, null);
                    }
                }
            }
        }
 private static void EnsureOracleBindByName(DbCommand cmd)
 {
     //Oracle.DataAccess.Client only binds first parameter match unless BindByName=true
     //so we violate LiskovSP (in reflection to avoid dependency on ODP)
     if (cmd.GetType().GetProperty("BindByName") != null)
     {
         cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null);
     }
 }
Ejemplo n.º 4
0
 static internal Exception PrepareParameterScale(DbCommand cmd, string type)
 {
     return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterScale, cmd.GetType().Name, type));
 }
Ejemplo n.º 5
0
 static internal Exception PrepareParameterSize(DbCommand cmd)
 {
     return(InvalidOperation(Res.GetString(Res.ADP_PrepareParameterSize, cmd.GetType().Name)));
 }
Ejemplo n.º 6
0
        public DataTable Query( DbCommand cmd )
        {
            if ( cmd == null )
            {
                throw new ArgumentNullException( "cmd" );
            }

            SQLiteCommand sqliteCmd = cmd as SQLiteCommand;
            if ( cmd == null )
            {
                throw new ArgumentException( "command has invalid type: " + cmd.GetType() );
            }

            Open( false );

            if ( sqliteCmd.Connection != myConnection )
            {
                sqliteCmd.Connection = myConnection;
            }

            // TODO: use:
            // DbDataReader reader = cmd.ExecuteReader();
            // table.Load( reader );

            SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter( sqliteCmd );

            DataTable table = new DataTable();
            table.Locale = CultureInfo.InvariantCulture;
            dataAdapter.Fill( table );

            return table;
        }
Ejemplo n.º 7
0
 protected virtual bool DatabaseEngineIs(DbCommand command, params System.String[] flavors)
 {
     return DatabaseEngineIs(command.GetType().FullName, flavors);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the format of the parameter, to avoid query the schema the parameter
        /// format is cached with the type of the parameter. This version is used 
        /// for the old interface of DataAccess based on anonimous function.
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        private static String GetParameterFormat(DbCommand command)
        {
            String typeName = command.GetType().FullName;
            if (!mParametersFormat.ContainsKey(typeName))
            {

                    mParametersFormat.Add(typeName,
                    command.Connection.GetSchema("DataSourceInformation")
                        .Rows[0]["ParameterMarkerFormat"].ToString());

            }
            return mParametersFormat[typeName];
        }
Ejemplo n.º 9
0
 internal static Exception PrepareParameterSize(DbCommand cmd)
 {
     return InvalidOperation(Res.GetString(Res.ADP_PrepareParameterSize, cmd.GetType().Name));
 }
Ejemplo n.º 10
0
 private void ConfigureCommandForSelect(DbCommand command, ViewPage page, SelectClauseDictionary expressions, string fromClause, string whereClause, string orderByClause, CommandConfigurationType commandConfiguration)
 {
     bool useServerPaging = ((commandConfiguration != CommandConfigurationType.SelectDistinct && !(_serverRules.EnableResultSet)) && (commandConfiguration != CommandConfigurationType.SelectAggregates && commandConfiguration != CommandConfigurationType.SelectFirstLetters));
     bool useLimit = SupportsLimitInSelect(command);
     bool useSkip = SupportsSkipInSelect(command);
     if (useServerPaging)
         page.AcceptAllRows();
     StringBuilder sb = new StringBuilder();
     if (useLimit || useSkip)
         useServerPaging = false;
     bool countUsingHierarchy = false;
     if ((commandConfiguration == CommandConfigurationType.SelectCount) && (useServerPaging && RequiresHierarchy(page)))
     {
         countUsingHierarchy = true;
         commandConfiguration = CommandConfigurationType.Select;
     }
     if (commandConfiguration == CommandConfigurationType.SelectExisting)
         useServerPaging = false;
     if (commandConfiguration == CommandConfigurationType.SelectCount)
         sb.AppendLine("select count(*)");
     else
     {
         if (useServerPaging)
             sb.AppendLine("with page_cte__ as (");
         else
             if ((commandConfiguration == CommandConfigurationType.Sync) && useLimit)
                 sb.Append("select * from (select @row_num := @row_num+1 row_number__,cte__.* from (select @r" +
                         "ow_num:=0) r,(");
         sb.AppendLine("select");
         if (useServerPaging)
             AppendRowNumberExpression(sb, page, expressions, orderByClause);
         if (commandConfiguration == CommandConfigurationType.SelectDistinct)
         {
             DataField distinctField = page.FindField(page.DistinctValueFieldName);
             string distinctExpression = expressions[distinctField.ExpressionName()];
             if (distinctField.Type.StartsWith("Date"))
             {
                 string commandType = command.GetType().ToString();
                 if (commandType == "System.Data.SqlClient.SqlCommand")
                     distinctExpression = String.Format("DATEADD(dd, 0, DATEDIFF(dd, 0, {0}))", distinctExpression);
                 if (commandType == "MySql.Data.MySqlClient.MySqlCommand")
                     distinctExpression = String.Format("cast({0} as date)", distinctExpression);
             }
             sb.AppendFormat("distinct {0} \"{1}\"\r\n", distinctExpression, page.DistinctValueFieldName);
         }
         else
             if (commandConfiguration == CommandConfigurationType.SelectAggregates)
                 AppendAggregateExpressions(sb, page, expressions);
             else
                 if (commandConfiguration == CommandConfigurationType.SelectFirstLetters)
                 {
                     string substringFunction = "substring";
                     if (DatabaseEngineIs(command, "Oracle", "DB2"))
                         substringFunction = "substr";
                     AppendFirstLetterExpressions(sb, page, expressions, substringFunction);
                 }
                 else
                 {
                     if ((commandConfiguration == CommandConfigurationType.Select) && useSkip)
                         sb.AppendFormat(" first {0} skip {1}\r\n", page.PageSize, (page.PageSize * page.PageIndex));
                     if ((commandConfiguration == CommandConfigurationType.Sync) && useSkip)
                     {
                         // Only select the primary key.
                         foreach (DataField field in page.Fields)
                             if (field.IsPrimaryKey)
                             {
                                 sb.Append(expressions[field.ExpressionName()]);
                                 break;
                             }
                     }
                     else
                         if (commandConfiguration == CommandConfigurationType.SelectExisting)
                             sb.AppendLine("*");
                         else
                             AppendSelectExpressions(sb, page, expressions, !(useServerPaging));
                 }
     }
     sb.AppendLine("from");
     sb.AppendLine(fromClause);
     _hasWhere = false;
     if (String.IsNullOrEmpty(_viewFilter))
     {
         _viewFilter = _view.GetAttribute("filter", String.Empty);
         if (String.IsNullOrEmpty(_viewFilter) && ((_viewType == "Form") && !(String.IsNullOrEmpty(page.LastView))))
         {
             XPathNavigator lastView = _config.SelectSingleNode("/c:dataController/c:views/c:view[@id=\'{0}\']", page.LastView);
             if (lastView != null)
                 _viewFilter = lastView.GetAttribute("filter", String.Empty);
         }
     }
     if (!(String.IsNullOrEmpty(_viewFilter)))
         _viewFilter = String.Format("({0})", _viewFilter);
     if (commandConfiguration == CommandConfigurationType.SelectExisting)
     {
         EnsureWhereKeyword(sb);
         sb.Append(expressions[page.InnerJoinForeignKey.ToLower()]);
         sb.Append("=");
         sb.Append(page.InnerJoinPrimaryKey);
         sb.AppendLine(" and ");
     }
     AppendSystemFilter(command, page, expressions);
     AppendAccessControlRules(command, page, expressions);
     if (((page.Filter != null) && (page.Filter.Length > 0)) || !(String.IsNullOrEmpty(_viewFilter)))
         AppendFilterExpressionsToWhere(sb, page, command, expressions, whereClause);
     else
         if (!(String.IsNullOrEmpty(whereClause)))
         {
             EnsureWhereKeyword(sb);
             sb.AppendLine(whereClause);
         }
     if (commandConfiguration == CommandConfigurationType.Select)
     {
         bool preFetch = RequiresPreFetching(page);
         if (useServerPaging)
         {
             if (!(ConfigureCTE(sb, page, command, expressions, countUsingHierarchy)))
                 sb.Append(")\r\nselect * from page_cte__ ");
             if (!(countUsingHierarchy))
             {
                 sb.AppendFormat("where row_number__ > {0}PageRangeFirstRowNumber and row_number__ <= {0}PageRangeL" +
                         "astRowNumber order by row_number__", _parameterMarker);
                 DbParameter p = command.CreateParameter();
                 p.ParameterName = (_parameterMarker + "PageRangeFirstRowNumber");
                 p.Value = ((page.PageSize * page.PageIndex)
                             + page.PageOffset);
                 if (preFetch)
                     p.Value = (((int)(p.Value)) - page.PageSize);
                 command.Parameters.Add(p);
                 DbParameter p2 = command.CreateParameter();
                 p2.ParameterName = (_parameterMarker + "PageRangeLastRowNumber");
                 p2.Value = ((page.PageSize
                             * (page.PageIndex + 1))
                             + page.PageOffset);
                 if (preFetch)
                     p2.Value = (((int)(p2.Value)) + page.PageSize);
                 command.Parameters.Add(p2);
             }
         }
         else
         {
             AppendOrderByExpression(sb, page, expressions, orderByClause);
             if (useLimit)
             {
                 sb.AppendFormat("\r\nlimit {0}Limit_PageOffset, {0}Limit_PageSize", _parameterMarker);
                 DbParameter p = command.CreateParameter();
                 p.ParameterName = (_parameterMarker + "Limit_PageOffset");
                 p.Value = ((page.PageSize * page.PageIndex)
                             + page.PageOffset);
                 if (preFetch && (((int)(p.Value)) > page.PageSize))
                     p.Value = (((int)(p.Value)) - page.PageSize);
                 command.Parameters.Add(p);
                 DbParameter p2 = command.CreateParameter();
                 p2.ParameterName = (_parameterMarker + "Limit_PageSize");
                 p2.Value = page.PageSize;
                 if (preFetch)
                 {
                     int pagesToFetch = 2;
                     if (((int)(p.Value)) > page.PageSize)
                         pagesToFetch = 3;
                     p2.Value = (page.PageSize * pagesToFetch);
                 }
                 command.Parameters.Add(p2);
             }
         }
     }
     else
         if (commandConfiguration == CommandConfigurationType.Sync)
         {
             if (useServerPaging)
             {
                 if (!(ConfigureCTE(sb, page, command, expressions, false)))
                     sb.Append(")\r\nselect * from page_cte__ ");
                 sb.Append("where ");
             }
             else
             {
                 if (useLimit || useSkip)
                     AppendOrderByExpression(sb, page, expressions, orderByClause);
                 if (!(useSkip))
                     sb.Append(") cte__)cte2__ where ");
             }
             bool first = true;
             if (!(useSkip))
                 foreach (DataField field in page.Fields)
                     if (field.IsPrimaryKey)
                     {
                         if (first)
                             first = false;
                         else
                             sb.AppendFormat(" and ");
                         sb.AppendFormat("{2}{1}{3}={0}PrimaryKey_{1}", _parameterMarker, field.Name, _leftQuote, _rightQuote);
                     }
         }
         else
             if ((commandConfiguration == CommandConfigurationType.SelectDistinct) || (commandConfiguration == CommandConfigurationType.SelectFirstLetters))
                 sb.Append("order by 1");
     command.CommandText = sb.ToString();
     _viewFilter = null;
 }
Ejemplo n.º 11
0
 private static MethodInfo InitSetBindByName(DbCommand command)
 {
     return command.GetType().GetMethod("set_BindByName", BindingFlags.Public | BindingFlags.Instance);
 }
Ejemplo n.º 12
0
 public static string EscapePattern(DbCommand command, string s)
 {
     if (String.IsNullOrEmpty(s))
         return s;
     if (command.GetType().FullName == "System.Data.SqlClient.SqlCommand")
         return _sqlClientPatternEscape.Replace(s, "[$1]");
     return s;
 }
Ejemplo n.º 13
0
		private void AddDbCommandStatements (CodeMemberMethod m, 
		                                     CodeExpression expr, 
		                                     DbCommand cmd)
		{
			if (cmd == null)
				return;
			
			CodeExpression expr1;
			CodeStatement stmt = Let (expr, New (cmd.GetType ()));
			m.Statements.Add (stmt);
			
			stmt = Let (PropRef (expr,"Connection"), PropRef ("Connection"));
			m.Statements.Add (stmt);
			stmt = Let (PropRef (expr, "CommandText"), Const (cmd.CommandText));
			m.Statements.Add (stmt);
			expr1 = PropRef (Local(typeof (CommandType).FullName), cmd.CommandType.ToString ());
			stmt = Let (PropRef (expr, "CommandType"), expr1);
			m.Statements.Add (stmt);
			
			expr1 = PropRef (expr, "Parameters");
			foreach (DbParameter param in cmd.Parameters) {
				AddDbParameterStatements (m, expr1, param);
			}
		}
Ejemplo n.º 14
0
		private void CreateDBCommandCollectionFieldAndProperty (CodeTypeDeclaration t, DbCommand cmd)
		{
			CodeExpression expr;
			CodeStatement setStmt;
			CodeStatement stmt;
			CodeMemberField f = new CodeMemberField ();
			f.Name = "_commandCollection";
			f.Type = TypeRefArray (cmd.GetType (), 1);
			t.Members.Add (f);
			
			CodeMemberProperty p = new CodeMemberProperty ();
			p.Name = "CommandCollection";
			p.Attributes = MemberAttributes.Family;
			p.Type = f.Type;
			p.HasSet = false;

			expr = FieldRef ("_commandCollection");
			setStmt = Eval (MethodInvoke ("InitCommandCollection"));
			stmt = new CodeConditionStatement (Equals (expr, Const (null)),
			                                   new CodeStatement [] {setStmt},
			                                   new CodeStatement [] {});
			p.GetStatements.Add (stmt);
			p.GetStatements.Add (Return (expr));
			t.Members.Add (p);
		}
Ejemplo n.º 15
0
 protected virtual void AppendFilterExpressionsToWhere(StringBuilder sb, ViewPage page, DbCommand command, SelectClauseDictionary expressions, string whereClause)
 {
     string quickFindHint = page.QuickFindHint;
     bool firstCriteria = String.IsNullOrEmpty(_viewFilter);
     if (!(firstCriteria))
     {
         EnsureWhereKeyword(sb);
         sb.AppendLine("(");
         sb.Append(ProcessViewFilter(page, command, expressions));
     }
     int matchListCount = 0;
     bool firstDoNotMatch = true;
     string logicalConcat = "and ";
     if (page.Filter != null)
         foreach (string filterExpression in page.Filter)
         {
             Match matchingMode = MatchingModeRegex.Match(filterExpression);
             if (matchingMode.Success)
             {
                 bool doNotMatch = (matchingMode.Groups["Match"].Value == "_donotmatch_");
                 if (doNotMatch)
                 {
                     if (firstDoNotMatch)
                     {
                         firstDoNotMatch = false;
                         EnsureWhereKeyword(sb);
                         if (!(firstCriteria))
                             sb.AppendLine(")");
                         if (matchListCount > 0)
                             sb.AppendLine(")");
                         if (!(firstCriteria) || (matchListCount > 0))
                             sb.AppendLine("and");
                         matchListCount = 0;
                         sb.AppendLine(" not");
                         firstCriteria = true;
                     }
                 }
                 if (matchListCount == 0)
                 {
                     EnsureWhereKeyword(sb);
                     if (!(firstCriteria))
                         sb.Append(") and");
                     // the list of matches begins
                     sb.AppendLine("(");
                 }
                 else
                 {
                     sb.AppendLine(")");
                     sb.AppendLine("or");
                 }
                 // begin a list of conditions for the next match
                 if (matchingMode.Groups["Scope"].Value == "$all$")
                     logicalConcat = " and ";
                 else
                     logicalConcat = " or ";
                 matchListCount++;
                 firstCriteria = true;
             }
             Match filterMatch = FilterExpressionRegex.Match(filterExpression);
             if (filterMatch.Success)
             {
                 // "ProductName:?g", "CategoryCategoryName:=Condiments\x00=Seafood"
                 bool firstValue = true;
                 string fieldOperator = " or ";
                 if (Regex.IsMatch(filterMatch.Groups["Values"].Value, ">|<"))
                     fieldOperator = " and ";
                 Match valueMatch = FilterValueRegex.Match(filterMatch.Groups["Values"].Value);
                 while (valueMatch.Success)
                 {
                     string alias = filterMatch.Groups["Alias"].Value;
                     string operation = valueMatch.Groups["Operation"].Value;
                     string paramValue = valueMatch.Groups["Value"].Value;
                     if ((operation == "~") && (alias == "_quickfind_"))
                         alias = page.Fields[0].Name;
                     bool deepSearching = alias.Contains(",");
                     DataField field = page.FindField(alias);
                     if (((((field != null) && field.AllowQBE) || (operation == "~")) && (((page.DistinctValueFieldName != field.Name || (matchListCount > 0)) || (operation == "~")) || (page.AllowDistinctFieldInFilter || page.CustomFilteredBy(field.Name)))) || deepSearching)
                     {
                         if (firstValue)
                         {
                             if (firstCriteria)
                             {
                                 EnsureWhereKeyword(sb);
                                 sb.AppendLine("(");
                                 firstCriteria = false;
                             }
                             else
                                 sb.Append(logicalConcat);
                             sb.Append("(");
                             firstValue = false;
                         }
                         else
                             sb.Append(fieldOperator);
                         if (deepSearching)
                         {
                             string deepSearchFieldName = alias.Substring(0, alias.IndexOf(','));
                             string hint = alias.Substring((deepSearchFieldName.Length + 1));
                             string deepFilterExpression = (deepSearchFieldName + filterExpression.Substring(filterExpression.IndexOf(':')));
                             AppendDeepFilter(hint, page, command, sb, deepFilterExpression);
                         }
                         else
                             if (operation == "~")
                             {
                                 paramValue = Convert.ToString(StringToValue(paramValue));
                                 List<string> words = new List<string>();
                                 List<List<string>> phrases = new List<List<string>>();
                                 phrases.Add(words);
                                 CultureInfo currentCulture = CultureInfo.CurrentCulture;
                                 string textDateNumber = ("\\p{L}\\d" + Regex.Escape((currentCulture.DateTimeFormat.DateSeparator
                                                 + (currentCulture.DateTimeFormat.TimeSeparator + currentCulture.NumberFormat.NumberDecimalSeparator))));
                                 string[] removableNumericCharacters = new string[] {
                                         currentCulture.NumberFormat.NumberGroupSeparator,
                                         currentCulture.NumberFormat.CurrencyGroupSeparator,
                                         currentCulture.NumberFormat.CurrencySymbol};
                                 Match m = Regex.Match(paramValue, String.Format("\\s*(?\'Token\'((?\'Quote\'\")(?\'Value\'.+?)\")|((?\'Quote\'\\\')(?\'Value\'.+?)\\\')|(,|;|(^|\\s+" +
                                             ")-)|(?\'Value\'[{0}]+))", textDateNumber));
                                 bool negativeSample = false;
                                 while (m.Success)
                                 {
                                     string token = m.Groups["Token"].Value.Trim();
                                     if ((token == ",") || (token == ";"))
                                     {
                                         words = new List<string>();
                                         phrases.Add(words);
                                         negativeSample = false;
                                     }
                                     else
                                         if (token == "-")
                                             negativeSample = true;
                                         else
                                         {
                                             string exactFlag = "=";
                                             if (String.IsNullOrEmpty(m.Groups["Quote"].Value))
                                                 exactFlag = " ";
                                             string negativeFlag = " ";
                                             if (negativeSample)
                                             {
                                                 negativeFlag = "-";
                                                 negativeSample = false;
                                             }
                                             words.Add(String.Format("{0}{1}{2}", negativeFlag, exactFlag, m.Groups["Value"].Value));
                                         }
                                     m = m.NextMatch();
                                 }
                                 bool firstPhrase = true;
                                 foreach (List<String> phrase in phrases)
                                     if (phrase.Count > 0)
                                     {
                                         if (firstPhrase)
                                             firstPhrase = false;
                                         else
                                             sb.AppendLine("or");
                                         sb.AppendLine("(");
                                         bool firstWord = true;
                                         System.DateTime paramValueAsDate;
                                         foreach (string paramValueWord in phrase)
                                         {
                                             bool negativeFlag = (paramValueWord[0] == '-');
                                             bool exactFlag = (paramValueWord[1] == '=');
                                             string comparisonOperator = "like";
                                             if (exactFlag)
                                                 comparisonOperator = "=";
                                             string pv = paramValueWord.Substring(2);
                                             bool paramValueIsDate = SqlStatement.TryParseDate(command.GetType(), pv, out paramValueAsDate);
                                             bool firstTry = true;
                                             DbParameter parameter = null;
                                             if (!(paramValueIsDate))
                                                 pv = SqlStatement.EscapePattern(command, pv);
                                             double paramValueAsNumber;
                                             string testNumber = pv;
                                             foreach (string s in removableNumericCharacters)
                                                 testNumber = testNumber.Replace(s, string.Empty);
                                             bool paramValueIsNumber = double.TryParse(testNumber, out paramValueAsNumber);
                                             if (!(exactFlag) && !(pv.Contains("%")))
                                                 pv = String.Format("%{0}%", pv);
                                             if (firstWord)
                                                 firstWord = false;
                                             else
                                                 sb.Append("and");
                                             if (negativeFlag)
                                                 sb.Append(" not");
                                             sb.Append("(");
                                             bool hasTests = false;
                                             DbParameter originalParameter = null;
                                             if (String.IsNullOrEmpty(quickFindHint) || !(quickFindHint.StartsWith(";")))
                                                 foreach (DataField tf in page.Fields)
                                                     if ((tf.AllowQBE && String.IsNullOrEmpty(tf.AliasName)) && (!((tf.IsPrimaryKey && tf.Hidden)) && (!(tf.Type.StartsWith("Date")) || paramValueIsDate)))
                                                     {
                                                         hasTests = true;
                                                         if ((parameter == null) || command.GetType().FullName.Contains("ManagedDataAccess"))
                                                         {
                                                             parameter = command.CreateParameter();
                                                             parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
                                                             parameter.DbType = DbType.String;
                                                             command.Parameters.Add(parameter);
                                                             parameter.Value = pv;
                                                             if (exactFlag && paramValueIsNumber)
                                                             {
                                                                 parameter.DbType = DbType.Double;
                                                                 parameter.Value = paramValueAsNumber;
                                                             }
                                                         }
                                                         if (!((exactFlag && ((!(tf.Type.Contains("String")) && !(paramValueIsNumber)) || (tf.Type.Contains("String") && paramValueIsNumber)))))
                                                         {
                                                             if (firstTry)
                                                                 firstTry = false;
                                                             else
                                                                 sb.Append(" or ");
                                                             if (tf.Type.StartsWith("Date"))
                                                             {
                                                                 DbParameter dateParameter = command.CreateParameter();
                                                                 dateParameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
                                                                 dateParameter.DbType = DbType.DateTime;
                                                                 command.Parameters.Add(dateParameter);
                                                                 dateParameter.Value = paramValueAsDate;
                                                                 if (negativeFlag)
                                                                     sb.AppendFormat("({0} is not null)and", expressions[tf.ExpressionName()]);
                                                                 sb.AppendFormat("({0} = {1})", expressions[tf.ExpressionName()], dateParameter.ParameterName);
                                                             }
                                                             else
                                                             {
                                                                 bool skipLike = false;
                                                                 if (!((comparisonOperator == "=")) && ((tf.Type == "String") && ((tf.Len > 0) && (tf.Len < pv.Length))))
                                                                 {
                                                                     string pv2 = pv;
                                                                     pv2 = pv2.Substring(1);
                                                                     if (tf.Len < pv2.Length)
                                                                         pv2 = pv2.Substring(0, (pv2.Length - 1));
                                                                     if (pv2.Length > tf.Len)
                                                                         skipLike = true;
                                                                     else
                                                                     {
                                                                         originalParameter = parameter;
                                                                         parameter = command.CreateParameter();
                                                                         parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
                                                                         parameter.DbType = DbType.String;
                                                                         command.Parameters.Add(parameter);
                                                                         parameter.Value = pv2;
                                                                     }
                                                                 }
                                                                 if (_serverRules.EnableResultSet)
                                                                 {
                                                                     string fieldNameExpression = expressions[tf.ExpressionName()];
                                                                     if ((tf.Type != "String" && !(exactFlag)) || (tf.Type == "Boolean"))
                                                                         fieldNameExpression = String.Format("convert({0}, \'System.String\')", fieldNameExpression);
                                                                     if (negativeFlag)
                                                                         sb.AppendFormat("({0} is not null)and", fieldNameExpression);
                                                                     sb.AppendFormat("({0} {2} {1})", fieldNameExpression, parameter.ParameterName, comparisonOperator);
                                                                 }
                                                                 else
                                                                     if (skipLike)
                                                                         sb.Append("1=0");
                                                                     else
                                                                     {
                                                                         if (negativeFlag)
                                                                             sb.AppendFormat("({0} is not null)and", expressions[tf.ExpressionName()]);
                                                                         if (DatabaseEngineIs(command, "Oracle", "DB2", "Firebird"))
                                                                         {
                                                                             sb.AppendFormat("(upper({0}) {2} {1})", expressions[tf.ExpressionName()], parameter.ParameterName, comparisonOperator);
                                                                             parameter.Value = Convert.ToString(parameter.Value).ToUpper();
                                                                         }
                                                                         else
                                                                             sb.AppendFormat("({0} {2} {1})", expressions[tf.ExpressionName()], parameter.ParameterName, comparisonOperator);
                                                                     }
                                                             }
                                                         }
                                                         if (originalParameter != null)
                                                         {
                                                             parameter = originalParameter;
                                                             originalParameter = null;
                                                         }
                                                     }
                                             if (!(String.IsNullOrEmpty(quickFindHint)) && quickFindHint.Contains(";"))
                                             {
                                                 sb.AppendLine();
                                                 if (hasTests)
                                                     sb.AppendLine("or");
                                                 else
                                                     hasTests = true;
                                                 sb.AppendLine("(");
                                                 bool firstHint = true;
                                                 foreach (string hint in quickFindHint.Substring((quickFindHint.IndexOf(';') + 1)).Split(new char[] {
                                                             ';'}))
                                                 {
                                                     if (firstHint)
                                                         firstHint = false;
                                                     else
                                                     {
                                                         sb.AppendLine();
                                                         sb.AppendLine("or");
                                                     }
                                                     sb.AppendLine("(");
                                                     string newFilterExpression = filterExpression;
                                                     StringBuilder reversedFilterExpression = new StringBuilder();
                                                     if (negativeFlag)
                                                     {
                                                         bool firstExpressionPhrase = true;
                                                         foreach (List<string> ph in phrases)
                                                         {
                                                             if (firstExpressionPhrase)
                                                                 firstExpressionPhrase = false;
                                                             else
                                                                 reversedFilterExpression.Append(",");
                                                             bool firstExpressionWord = true;
                                                             foreach (string w in ph)
                                                             {
                                                                 if (firstExpressionWord)
                                                                     firstExpressionWord = false;
                                                                 else
                                                                     reversedFilterExpression.Append(" ");
                                                                 if (!((w[0] == '-')))
                                                                     reversedFilterExpression.Append("-");
                                                                 if (w[1] == '=')
                                                                     reversedFilterExpression.Append("\"");
                                                                 reversedFilterExpression.Append(w.Substring(2));
                                                                 if (w[1] == '=')
                                                                     reversedFilterExpression.Append("\"");
                                                             }
                                                         }
                                                         newFilterExpression = ("_quickfind_:~" + ValueToString(reversedFilterExpression.ToString()));
                                                     }
                                                     AppendDeepFilter(hint, page, command, sb, newFilterExpression);
                                                     sb.AppendLine(")");
                                                 }
                                                 sb.AppendLine(")");
                                             }
                                             if (!(hasTests))
                                                 if (negativeFlag && quickFindHint.StartsWith(";"))
                                                     sb.Append("1=1");
                                                 else
                                                     sb.Append("1=0");
                                             sb.Append(")");
                                         }
                                         sb.AppendLine(")");
                                     }
                                 if (firstPhrase)
                                     sb.Append("1=1");
                             }
                             else
                                 if (operation.StartsWith("$"))
                                     sb.Append(FilterFunctions.Replace(command, expressions, String.Format("{0}({1}$comma${2})", operation.TrimEnd('$'), alias, Convert.ToBase64String(Encoding.UTF8.GetBytes(paramValue)))));
                                 else
                                 {
                                     DbParameter parameter = command.CreateParameter();
                                     parameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
                                     AssignParameterDbType(parameter, field.Type);
                                     sb.Append(expressions[field.ExpressionName()]);
                                     bool requiresRangeAdjustment = ((operation == "=") && (field.Type.StartsWith("DateTime") && !(StringIsNull(paramValue))));
                                     if ((operation == "<>") && StringIsNull(paramValue))
                                         sb.Append(" is not null ");
                                     else
                                         if ((operation == "=") && StringIsNull(paramValue))
                                             sb.Append(" is null ");
                                         else
                                         {
                                             if (operation == "*")
                                             {
                                                 sb.Append(" like ");
                                                 parameter.DbType = DbType.String;
                                                 if (!(paramValue.Contains("%")))
                                                     paramValue = (SqlStatement.EscapePattern(command, paramValue) + "%");
                                             }
                                             else
                                                 if (requiresRangeAdjustment)
                                                     sb.Append(">=");
                                                 else
                                                     sb.Append(operation);
                                             try
                                             {
                                                 parameter.Value = StringToValue(field, paramValue);
                                                 if ((parameter.DbType == DbType.Binary) && (parameter.Value is Guid))
                                                     parameter.Value = ((Guid)(parameter.Value)).ToByteArray();
                                             }
                                             catch (Exception )
                                             {
                                                 parameter.Value = DBNull.Value;
                                             }
                                             sb.Append(parameter.ParameterName);
                                             command.Parameters.Add(parameter);
                                             if (requiresRangeAdjustment)
                                             {
                                                 DbParameter rangeParameter = command.CreateParameter();
                                                 AssignParameterDbType(rangeParameter, field.Type);
                                                 rangeParameter.ParameterName = String.Format("{0}p{1}", _parameterMarker, command.Parameters.Count);
                                                 sb.Append(String.Format(" and {0} < {1}", expressions[field.ExpressionName()], rangeParameter.ParameterName));
                                                 if (field.Type == "DateTimeOffset")
                                                 {
                                                     DateTime dt = Convert.ToDateTime(parameter.Value);
                                                     parameter.Value = new DateTimeOffset(dt).AddHours(-14);
                                                     rangeParameter.Value = new DateTimeOffset(dt).AddDays(1).AddHours(14);
                                                 }
                                                 else
                                                     rangeParameter.Value = Convert.ToDateTime(parameter.Value).AddDays(1);
                                                 command.Parameters.Add(rangeParameter);
                                             }
                                         }
                                 }
                     }
                     valueMatch = valueMatch.NextMatch();
                 }
                 if (!(firstValue))
                     sb.AppendLine(")");
             }
         }
     if (matchListCount > 0)
     {
         sb.AppendLine(")");
         // the end of the "match" list
         sb.AppendLine(")");
         firstCriteria = true;
     }
     if (!(firstCriteria))
     {
         sb.AppendLine(")");
         if (!(String.IsNullOrEmpty(whereClause)))
             sb.Append("and ");
     }
     if (!(String.IsNullOrEmpty(whereClause)))
     {
         sb.AppendLine("(");
         sb.AppendLine(whereClause);
         sb.AppendLine(")");
     }
 }
Ejemplo n.º 16
0
 internal static Exception PrepareParameterScale(DbCommand cmd, string type)
 {
     return(InvalidOperation(SR.GetString(SR.ADP_PrepareParameterScale, cmd.GetType().Name, type)));
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Gets the format of the parameter, to avoid query the schema the parameter
        /// format is cached with the type of the parameter
        /// </summary>
        /// <param name="command"></param>
        /// <param name="connectionStringName">Connection String name is needed because if 
        /// we did not already get the format of the parameter we need the connection to 
        /// retrieve the format from the schema.</param>
        /// <returns></returns>
        private static String GetParameterFormat(DbCommand command, String connectionStringName)
        {
            String typeName = command.GetType().FullName;
            if (!mParametersFormat.ContainsKey(typeName))
            {

                    ConnectionStringSettings cn;
                    if (String.IsNullOrEmpty(connectionStringName))
                        cn = ConfigurationRegistry.MainConnectionString;
                    else
                        cn = ConfigurationRegistry.ConnectionString(connectionStringName);
                    DbProviderFactory Factory = DbProviderFactories.GetFactory(cn.ProviderName);
                    using (DbConnection conn = Factory.CreateConnection())
                    {
                        conn.ConnectionString = cn.ConnectionString;
                        conn.Open();
                        mParametersFormat.Add(
                            typeName,
                            conn.GetSchema("DataSourceInformation")
                                .Rows[0]["ParameterMarkerFormat"].ToString());
                    }

            }
            return mParametersFormat[typeName];
        }
Ejemplo n.º 18
0
 protected virtual void CacheCommandProperties(DbCommand command) {
     var oracleDbCommandType = command.GetType().GetTypeInfo();
     ReflectionCache.PropBindByName = oracleDbCommandType.GetDeclaredProperty("BindByName");
     ReflectionCache.PropArrayBindCount = oracleDbCommandType.GetDeclaredProperty("ArrayBindCount");
 }