Ejemplo n.º 1
0
        /// Function getParameterNameFromLine
        /// <summary>
        /// Gets a code line of a variable Declaration and gives back the node of the variable (name,type).
        /// </summary>
        /// <param name="line"> Code line type string.</param>
        /// <returns> returns type - ParametersType the variable that was being declared.</returns>
        static ParametersType GetParameterNameFromLine(string line)
        {
            string name;
            string type = line;
            int    lastIndex;

            //takes the substring that starts in the last space accurance and his length.
            name = line.Substring(line.LastIndexOf(GeneralConsts.SPACEBAR) + 1, (line.Length - (line.LastIndexOf(GeneralConsts.SPACEBAR) + 1)));
            //if there are no spaces in the line then it must be a '*', so doing the same thing with '*' instead of space.
            if (name == GeneralConsts.EMPTY_STRING)
            {
                name = line.Substring(line.LastIndexOf(GeneralConsts.ASTERIX), (line.Length - (line.LastIndexOf(GeneralConsts.ASTERIX) + 1)));
            }
            //last index of space
            lastIndex = line.LastIndexOf(GeneralConsts.SPACEBAR);
            if (lastIndex != GeneralConsts.NOT_FOUND_STRING)
            {
                //removes the variable name from the line to get the type
                type = line.Remove(lastIndex).Trim();
            }
            //all variables that does not matter to the checks are being removed.
            foreach (string var in ignoreVarialbesType)
            {
                if (type.IndexOf(var) != GeneralConsts.NOT_FOUND_STRING)
                {
                    type = type.Replace(var, GeneralConsts.EMPTY_STRING);
                    type = type.Trim();
                }
            }
            ParametersType result = new ParametersType(name, type);

            return(result);
        }
Ejemplo n.º 2
0
        public Parameter getParameter(string name, ParametersType type)
        {
            Parameter param = null;

            List <Parameter> paramList = null;

            if (type == ParametersType.IN)
            {
                paramList = this.parametersIn;
            }
            else
            {
                paramList = this.parametersOut;
            }

            foreach (var item in paramList)
            {
                if (item.Name.ToUpper().Equals(name.ToUpper()))
                {
                    param = item;
                    break;
                }
            }

            return(param);
        }
Ejemplo n.º 3
0
        /// Function - VariableEquationHandler
        /// <summary>
        /// Handling the variable equation part in the function "ChecksInSyntaxCheck" by
        /// make sure every variable is exist in the code and that their type of the equation
        /// is the same.
        /// </summary>
        /// <param name="threadNumber"> the number of the current thread.</param>
        /// <param name="sr"> buffer type MyStream.</param>
        /// <param name="codeLine"> the code line type string.</param>
        /// <param name="blocksAndNames"> ArrayList of variables.</param>
        /// <returns>returns if the variable equation is good.</returns>
        static bool VariableEquationHandler(MyStream sr, string codeLine, ArrayList blocksAndNames, int threadNumber)
        {
            char[] trimChars  = { '\t', ' ' };
            bool   isSameType = true;
            //splits the equation to 2 lines before the '=' and after it.
            string temp = Regex.Split(codeLine, GeneralConsts.EQUAL_SIGN)[0].Trim(trimChars);
            //takes the first param name.
            ParametersType result   = GetParameterNameFromLine(temp);
            string         varName1 = result.parameterName;

            temp = Regex.Split(codeLine, GeneralConsts.EQUAL_SIGN)[1];
            char[] searchingChars = { ';' };
            //takes the second param name.
            string varName2 = temp.Substring(0, temp.IndexOfAny(searchingChars));

            varName2 = varName2.Trim(trimChars);
            //takes the whole parameterType type by the function - "getVariableTypeParameterFromArrayList".
            ParametersType var1 = GetVariableTypeParameterFromArrayList(blocksAndNames, varName1.Trim(GeneralConsts.ASTERIX));
            ParametersType var2 = GetVariableTypeParameterFromArrayList(blocksAndNames, varName2.Trim(GeneralConsts.ASTERIX));

            //make sures the variable 2 is exist.
            if (var2 == null)
            {
                Server.ConnectionServer.CloseConnection(threadNumber, "There is no parameter named " + varName2 + " in row : " + sr.curRow, GeneralConsts.ERROR);
                CompileError = true;
                isSameType   = false;
            }
            //checks if their type is the same.
            if (isSameType && var1.parameterType != var2.parameterType)
            {
                isSameType = false;
            }
            return(isSameType);
        }
Ejemplo n.º 4
0
        public Parameter getParameter(string name, ParametersType type )
        {
            Parameter param = null;

            List<Parameter> paramList = null;

            if (type == ParametersType.IN)
            {
                paramList = this.parametersIn;
            }
            else
            {
                paramList = this.parametersOut;
            }

            foreach (var item in paramList)
            {
                if (item.Name.ToUpper().Equals(name.ToUpper()))
                {
                    param = item;
                    break;
                }
            }

            return param;
        }
 /// Function - FindVariables
 /// <summary>
 /// Gets an arrayList and creates "ParametersType" array and attach all values of the arrayList to it (converts it from ArrayList to
 /// ParametersType Array).
 /// </summary>
 /// <param name="variables"> arrayList type "ParametersType".</param>
 /// <returns> array type "ParametersType".</returns>
 public static ParametersType[] FindVariables(ArrayList variables)
 {
     ParametersType[] parameterTypeVariables = new ParametersType[variables.Count];
     for (int i = 0; i < variables.Count; i++)
     {
         parameterTypeVariables[i] = (ParametersType)variables[i];
     }
     return(parameterTypeVariables);
 }
        /// <summary>
        /// Get underline DbParametes
        /// </summary>
        /// <param name="parametersType"></param>
        /// <returns></returns>
        public OracleParameter[] GetSpParameters(ParametersType parametersType)
        {
            if (_storedParametersType != parametersType)
                return CreateOracleParametersFromProperties(parametersType);

            if (_oracleParameters == null || _oracleParameters.Count < 1)
                return CreateOracleParametersFromProperties(parametersType);
            else
                return _oracleParameters.ToArray();
        }
 public frmParametersCreator(Capacity capacity, WSDLManager wsdlManager, ParametersType parametersType)
 {
     InitializeComponent();
     this.capacity       = capacity;
     this.bOs            = wsdlManager.BussinesObjects;
     this.wsdlManager    = wsdlManager;
     this.parametersType = parametersType;
     CargarBOs();
     LoadContainers();
 }
 public frmParametersCreator(Capacity capacity, WSDLManager wsdlManager, ParametersType parametersType)
 {
     InitializeComponent();
     this.capacity = capacity;
     this.bOs = wsdlManager.BussinesObjects;
     this.wsdlManager = wsdlManager;
     this.parametersType = parametersType;
     CargarBOs();
     LoadContainers();
 }
Ejemplo n.º 9
0
 public void DeleteParameter(string name, ParametersType type)
 {
     if (type == ParametersType.IN)
     {
         this.ParametersIn.Remove(this.getParameter(name, type));
     }
     else
     {
         this.ParametersOut.Remove(this.getParameter(name, type));
     }
 }
Ejemplo n.º 10
0
 public void DeleteParameter(string name, ParametersType type)
 {
     if(type == ParametersType.IN)
     {
         this.ParametersIn.Remove(this.getParameter(name, type));
     }
     else
     {
         this.ParametersOut.Remove(this.getParameter(name, type));
     }
 }
Ejemplo n.º 11
0
        public static ParametersType[] findParameters2(string s)
        {
            string[] tempSplit;
            string[] finalSplit;
            string   tempSplit2;
            string   finalType;
            int      i, j;

            tempSplit  = Regex.Split(s, @"\(");
            tempSplit2 = tempSplit[1];
            tempSplit  = Regex.Split(tempSplit2, @"\,|\)");
            ParametersType[] finalParameters = new ParametersType[tempSplit.Length - 1];
            char[]           charsToTrim     = { '*', '&' };
            if (tempSplit2.Length > 2)
            {
                for (i = 0; i < tempSplit.Length - 1; i++)
                {
                    tempSplit2 = tempSplit[i];
                    if (tempSplit2.IndexOf("*") != -1)
                    {
                        finalSplit = Regex.Split(tempSplit2, @"\*");
                    }
                    else
                    {
                        finalSplit = Regex.Split(tempSplit2, @"\s");
                    }

                    if (finalSplit.Length == 1)
                    {
                        tempSplit2 = finalSplit[0];
                    }
                    else
                    {
                        tempSplit2 = takeSecondNotNullString(finalSplit);
                    }
                    if (tempSplit2.IndexOf("&") != -1 || tempSplit2.IndexOf("*") != -1)
                    {
                        tempSplit2 = tempSplit2.Trim(charsToTrim);
                    }
                    //trimEnd
                    tempSplit[i]       = tempSplit[i].Substring(0, tempSplit[i].Length - (tempSplit2.Length));
                    finalType          = tempSplit[i].Replace(" ", "");
                    tempSplit2         = tempSplit2.Replace(" ", "");
                    finalParameters[i] = new ParametersType(tempSplit2, finalType);
                }
            }
            else
            {
                finalParameters = new ParametersType[0];
            }
            return(finalParameters);
        }
        /// Function - FindParameters
        /// <summary>
        /// get a string of a function and returns all the parameters of the function in a parameter type array.
        /// </summary>
        /// <param name="codeLine"> function line type string.</param>
        /// <returns> returns all of the parameters in an array type ParemetrsType.</returns>
        public static ParametersType[] FindParameters(string codeLine)
        {
            string[] tempSplit;
            string[] finalSplit;
            string   tempSplit2;
            string   finalType;
            int      i;

            tempSplit  = Regex.Split(codeLine, @"\(");
            tempSplit2 = tempSplit[1];
            tempSplit  = Regex.Split(tempSplit2, @"\,|\)");
            ParametersType[] finalParameters = new ParametersType[tempSplit.Length - 1];
            char[]           charsToTrim     = { '*', '&' };
            if (tempSplit2.Length > 2)
            {
                for (i = 0; i < tempSplit.Length - 1; i++)
                {
                    tempSplit2 = tempSplit[i];
                    if (tempSplit2.IndexOf("*") != NOT_FOUND_STRING)
                    {
                        finalSplit = Regex.Split(tempSplit2, @"\*");
                    }
                    else
                    {
                        finalSplit = Regex.Split(tempSplit2, @"\s");
                    }

                    if (finalSplit.Length == 1)
                    {
                        tempSplit2 = finalSplit[0];
                    }
                    else
                    {
                        tempSplit2 = takeSecondNotNullString(finalSplit);
                    }
                    if (tempSplit2.IndexOf("&") != NOT_FOUND_STRING || tempSplit2.IndexOf("*") != NOT_FOUND_STRING)
                    {
                        tempSplit2 = tempSplit2.Trim(charsToTrim);
                    }
                    //trimEnd
                    tempSplit[i]       = tempSplit[i].Substring(0, tempSplit[i].Length - (tempSplit2.Length));
                    finalType          = tempSplit[i].Replace(GeneralConsts.SPACEBAR, GeneralConsts.EMPTY_STRING);
                    tempSplit2         = tempSplit2.Replace(GeneralConsts.SPACEBAR, GeneralConsts.EMPTY_STRING);
                    finalParameters[i] = new ParametersType(tempSplit2, finalType);
                }
            }
            else
            {
                finalParameters = new ParametersType[0];
            }
            return(finalParameters);
        }
Ejemplo n.º 13
0
        /// Function - getVariableTypeParameterFromArrayList
        /// <summary>
        /// Get the whole parameterType node out of the ArrayList.
        /// </summary>
        /// <param name="blocksAndNames"> ArrayList type.</param>
        /// <param name="name"> the name to get the whole node from.</param>
        /// <returns> returns parameterType type of the node named like "name".</returns>
        static ParametersType GetVariableTypeParameterFromArrayList(ArrayList blocksAndNames, string name)
        {
            bool           endLoop = false;
            ParametersType result  = null;

            for (int i = blocksAndNames.Count; i > 0 && !endLoop; i--)
            {
                if ((result = IsExistInArrayList((ArrayList)blocksAndNames[i - 1], name)) != null)
                {
                    endLoop = true;
                }
            }
            return(result);
        }
        /// <summary>
        /// Create paramters from object properties
        /// </summary>
        /// <param name="parametersType"></param>
        /// <returns></returns>
        public OracleParameter[] CreateOracleParametersFromProperties(ParametersType parametersType)
        {
            _outParameterPropertyInfoCollection = new List<PropertyInfo>();
            _spOutParameters = new List<OracleParameter>();

            var procedureType = this.GetType();
            var propertiesForSqlParams = procedureType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Default);

            _oracleParameters =
                propertiesForSqlParams.Select(propertyInfo => CreateOracleParameter(propertyInfo, parametersType, propertiesForSqlParams))
                    .Where<OracleParameter>(p => p != null).ToList();

            _storedParametersType = parametersType;
            return _oracleParameters.ToArray();
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Create paramters from object properties
        /// </summary>
        /// <param name="parametersType"></param>
        /// <returns></returns>
        public OracleParameter[] CreateOracleParametersFromProperties(ParametersType parametersType)
        {
            _outParameterPropertyInfoCollection = new List <PropertyInfo>();
            _spOutParameters = new List <OracleParameter>();

            var procedureType          = this.GetType();
            var propertiesForSqlParams = procedureType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Default);

            _oracleParameters =
                propertiesForSqlParams.Select(propertyInfo => CreateOracleParameter(propertyInfo, parametersType, propertiesForSqlParams))
                .Where <OracleParameter>(p => p != null).ToList();

            _storedParametersType = parametersType;
            return(_oracleParameters.ToArray());
        }
Ejemplo n.º 16
0
        //the checks that are being mad in syntax Check are being written here.
        /// Function - IsExistInArrayList
        /// <summary>
        /// Checks if the string can be found in the ArrayList.
        /// </summary>
        /// <param name="a"> ArrayList </param>
        /// <param name="name"> the string that is being checked.</param>
        /// <returns> returns the ArrayList Node.</returns>
        public static ParametersType IsExistInArrayList(ArrayList a, string name)
        {
            ParametersType result = null;
            bool           found  = false;

            for (int i = 0; i < a.Count && !found; i++)
            {
                if (((ParametersType)a[i]).parameterName == name)
                {
                    result = (ParametersType)a[i];
                    found  = true;
                }
            }
            return(result);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Get underline DbParametes
        /// </summary>
        /// <param name="parametersType"></param>
        /// <returns></returns>
        public OracleParameter[] GetSpParameters(ParametersType parametersType)
        {
            if (_storedParametersType != parametersType)
            {
                return(CreateOracleParametersFromProperties(parametersType));
            }

            if (_oracleParameters == null || _oracleParameters.Count < 1)
            {
                return(CreateOracleParametersFromProperties(parametersType));
            }
            else
            {
                return(_oracleParameters.ToArray());
            }
        }
Ejemplo n.º 18
0
        public PropertyBasedMethodMock(MocklisTypesForSymbols typesForSymbols, INamedTypeSymbol classSymbol, INamedTypeSymbol interfaceSymbol,
                                       IMethodSymbol symbol, string mockMemberName, bool strict, bool veryStrict) : base(typesForSymbols, classSymbol, interfaceSymbol, symbol,
                                                                                                                         mockMemberName, strict, veryStrict)
        {
            var parametersBuilder   = new SingleTypeOrValueTupleBuilder(TypesForSymbols);
            var returnValuesBuilder = new SingleTypeOrValueTupleBuilder(TypesForSymbols);

            if (!symbol.ReturnsVoid)
            {
                returnValuesBuilder.AddReturnValue(symbol.ReturnType, symbol.ReturnTypeIsNullableOrOblivious());
            }

            foreach (var parameter in symbol.Parameters)
            {
                switch (parameter.RefKind)
                {
                case RefKind.Ref:
                {
                    parametersBuilder.AddParameter(parameter);
                    returnValuesBuilder.AddParameter(parameter);
                    break;
                }

                case RefKind.Out:
                {
                    returnValuesBuilder.AddParameter(parameter);
                    break;
                }

                case RefKind.In:
                {
                    parametersBuilder.AddParameter(parameter);
                    break;
                }

                case RefKind.None:
                {
                    parametersBuilder.AddParameter(parameter);
                    break;
                }
                }
            }

            ParametersType   = parametersBuilder.Build();
            ReturnValuesType = returnValuesBuilder.Build();

            var parameterTypeSyntax = ParametersType.BuildTypeSyntax();

            var returnValueTypeSyntax = ReturnValuesType.BuildTypeSyntax();

            if (returnValueTypeSyntax == null)
            {
                MockMemberType = parameterTypeSyntax == null
                    ? TypesForSymbols.ActionMethodMock()
                    : TypesForSymbols.ActionMethodMock(parameterTypeSyntax);
            }
            else
            {
                MockMemberType = parameterTypeSyntax == null
                    ? TypesForSymbols.FuncMethodMock(returnValueTypeSyntax)
                    : TypesForSymbols.FuncMethodMock(parameterTypeSyntax, returnValueTypeSyntax);
            }
        }
Ejemplo n.º 19
0
        protected MemberDeclarationSyntax ExplicitInterfaceMember()
        {
            var baseReturnType = Symbol.ReturnsVoid
                ? F.PredefinedType(F.Token(SyntaxKind.VoidKeyword))
                : TypesForSymbols.ParseTypeName(Symbol.ReturnType, Symbol.ReturnTypeIsNullableOrOblivious());
            var returnType = baseReturnType;

            if (Symbol.ReturnsByRef)
            {
                returnType = F.RefType(returnType);
            }
            else if (Symbol.ReturnsByRefReadonly)
            {
                returnType = F.RefType(returnType).WithReadOnlyKeyword(F.Token(SyntaxKind.ReadOnlyKeyword));
            }

            var mockedMethod = ExplicitInterfaceMemberMethodDeclaration(returnType);

            var memberMockInstance = ExplicitInterfaceMemberMemberMockInstance();

            ExpressionSyntax invocation = F.InvocationExpression(
                F.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
                                         memberMockInstance, F.IdentifierName("Call")))
                                          .WithExpressionsAsArgumentList(ParametersType.BuildArgumentListWithOriginalNames());

            // look at the return parameters. If we don't have any we can just make the call.
            // if we only have one and that's the return value, we can just return it.
            if (ReturnValuesType.Count == 0 ||
                ReturnValuesType.Count == 1 && ReturnValuesType[0].IsReturnValue)
            {
                if (Symbol.ReturnsByRef || Symbol.ReturnsByRefReadonly)
                {
                    invocation = TypesForSymbols.WrapByRef(invocation, baseReturnType);
                }

                mockedMethod = mockedMethod.WithExpressionBody(F.ArrowExpressionClause(invocation))
                               .WithSemicolonToken(F.Token(SyntaxKind.SemicolonToken));
            }
            // if we only have one and that's not a return value, we can just assign it to the out or ref parameter it corresponds to.
            else if (ReturnValuesType.Count == 1)
            {
                mockedMethod = mockedMethod.WithBody(F.Block(F.ExpressionStatement(F.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                                                                                          F.IdentifierName(ReturnValuesType[0].OriginalName), invocation))));
            }
            else
            {
                // if we have more than one, put it in a temporary variable. (consider name clashes with method parameter names)
                var    x   = new Uniquifier(Symbol.Parameters.Select(m => m.Name));
                string tmp = x.GetUniqueName("tmp");

                var statements = new List <StatementSyntax>
                {
                    F.LocalDeclarationStatement(F.VariableDeclaration(F.IdentifierName("var")).WithVariables(
                                                    F.SingletonSeparatedList(F.VariableDeclarator(F.Identifier(tmp)).WithInitializer(F.EqualsValueClause(invocation)))))
                };

                // then for any out or ref parameters, set their values from the temporary variable.
                foreach (var rv in ReturnValuesType.Where(a => !a.IsReturnValue))
                {
                    statements.Add(F.ExpressionStatement(F.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                                                                F.IdentifierName(rv.OriginalName),
                                                                                F.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, F.IdentifierName(tmp),
                                                                                                         F.IdentifierName(rv.TupleSafeName)))));
                }

                // finally, if there is a 'proper' return type, return the corresponding value from the temporary variable.
                foreach (var rv in ReturnValuesType.Where(a => a.IsReturnValue))
                {
                    ExpressionSyntax memberAccess = F.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, F.IdentifierName(tmp),
                                                                             F.IdentifierName(rv.TupleSafeName));

                    if (Symbol.ReturnsByRef || Symbol.ReturnsByRefReadonly)
                    {
                        memberAccess = TypesForSymbols.WrapByRef(memberAccess, baseReturnType);
                    }

                    statements.Add(F.ReturnStatement(memberAccess));
                }

                mockedMethod = mockedMethod.WithBody(F.Block(statements));
            }

            return(mockedMethod);
        }
Ejemplo n.º 20
0
 public IDataParameter[] CreateSqlParametersFromProperties(ParametersType parametersType)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 21
0
        ///// <summary>
        ///// Create paramters from object properties
        ///// </summary>
        ///// <param name="parametersType"></param>
        ///// <returns></returns>
        //public IDataParameter[] CreateSqlParametersFromProperties(object entity)
        //{
        //    var entityParameters = new EntityParameters();

        //    var procedureType = entity.GetType();
        //    var propertiesForDataParams = procedureType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Default);

        //    DataParameters =
        //        propertiesForDataParams.Select(propertyInfo => CreateDataParameter(propertyInfo, parametersType, propertiesForDataParams, OutParameterPropertyInfoCollection, OutParameters))
        //            .Where(p => p != null).ToList();

        //    return DataParameters.ToArray();
        //}


        /// <summary>
        ///
        /// </summary>
        /// <param name="propertyInfo"></param>
        /// <param name="parametesType"></param>
        /// <param name="propertyInfos"></param>
        /// <returns></returns>
        public IDataParameter CreateDataParameter(PropertyInfo propertyInfo, ParametersType parametesType,
                                                  IEnumerable <PropertyInfo> propertyInfos, IList <PropertyInfo> outParameterPropertyInfoCollection, List <IDataParameter> outDataParameters)
        {
            object value = propertyInfo.GetValue(this, new object[] { });

            var sqlParam = new MySqlParameter(string.Format("@{0}", propertyInfo.Name), value);

            if (propertyInfo.PropertyType.Name == "String" && value != null)
            {
                value = SafeSqlLiteral(value.ToString());
            }

            if ((propertyInfo.PropertyType.IsGenericType ||
                 propertyInfo.PropertyType.Name == "String") & value == null)
            {
                sqlParam.IsNullable = true;
                sqlParam.Value      = DBNull.Value;
            }

            var attrbutes = propertyInfo.GetCustomAttributes(true);

            if (propertyInfo.GetGetMethod().IsVirtual)
            {
                return(null);
            }

            if (attrbutes.FirstOrDefault(a => a is NotASpParameterAttribute) != null)
            {
                return(null);
            }


            var dbColumnAttribute =
                attrbutes.FirstOrDefault(a => a is DbColumnAttribute) as DbColumnAttribute;

            if (dbColumnAttribute != null)
            {
                sqlParam.ParameterName = string.Format("@{0}", dbColumnAttribute.DbColumn);
            }



            if (parametesType == ParametersType.Insert)
            {
                //var propertyDataType = propertyInfo.DeclaringType;

                var outParaAttr = attrbutes.FirstOrDefault(a => a is ParameterDirectionAttribute) as ParameterDirectionAttribute;
                if (outParaAttr != null)
                {
                    sqlParam.Direction = outParaAttr.SpParameterDirection;
                    outParameterPropertyInfoCollection.Add(propertyInfo);
                    outDataParameters.Add(sqlParam);
                }

                //if (propertyInfo.PropertyType.GetType() is DateTime
                //    || propertyInfo.PropertyType.GetType() is DateTime?)
                //{
                //    value = value == null || (DateTime)value == DateTime.MinValue ? new DateTime(2000, 1, 1) : value;
                //}
            }

            Debug.WriteLine(sqlParam.ParameterName);
            return(sqlParam);
        }
Ejemplo n.º 22
0
 public ParametersParser(ParametersType type = ParametersType.Standard) => this.type = type;
        private OracleParameter CreateOracleParameter(PropertyInfo propertyInfo, ParametersType parametesType, IEnumerable<PropertyInfo> propertyInfos)
        {
            object value = propertyInfo.GetValue(this, new object[] { });

            var sqlParam = new OracleParameter(string.Format("@{0}", propertyInfo.Name), value);

            if (propertyInfo.PropertyType.Name == "String" && value != null)
            {
                value = SafeSqlLiteral(value.ToString());
            }

            if ((propertyInfo.PropertyType.IsGenericType
                || propertyInfo.PropertyType.Name == "String") & value == null)
            {
                sqlParam.IsNullable = true;
                sqlParam.Value = DBNull.Value;
            }

            var attrbutes = propertyInfo.GetCustomAttributes(true);

            /*
            if (propertyInfo.PropertyType.IsGenericType)
            {
                if (propertyInfo.PropertyType.GetGenericArguments()[0].IsEnum)
                {
                    sqlParam.Value = value.ToString();
                }
            }
            if (propertyInfo.PropertyType.IsEnum)
                sqlParam.Value = value.ToString();
            */
            var getMethodInfo = propertyInfo.GetGetMethod();

            if (getMethodInfo.IsVirtual && !getMethodInfo.IsFinal)
                return null;

            if (attrbutes.FirstOrDefault(a => a is NotASpParameterAttribute) != null)
                return null;

            //var dbColumnPropertyAttribute =
            //    attrbutes.FirstOrDefault(a => a is DbColumnPropertyAttribute) as DbColumnPropertyAttribute;

            //if (dbColumnPropertyAttribute != null)
            //{
            //    var dbColumnPropertyPropertyInfo =
            //        propertyInfos.FirstOrDefault(p => p.Name == dbColumnPropertyAttribute.DbColumnProperty);

            //    value = dbColumnPropertyPropertyInfo.GetValue(this, new object[] { });
            //    sqlParam.Value = value;
            //}

            var dbColumnAttribute =
                attrbutes.FirstOrDefault(a => a is DbColumnAttribute) as DbColumnAttribute;

            if (dbColumnAttribute != null)
            {
                sqlParam.ParameterName = string.Format("@{0}", dbColumnAttribute.DbColumn);
            }

            if (parametesType == ParametersType.Insert)
            {
                //var propertyDataType = propertyInfo.DeclaringType;

                var outParaAttr = attrbutes.FirstOrDefault(a => a is ParameterDirectionAttribute) as ParameterDirectionAttribute;
                if (outParaAttr != null)
                {
                    sqlParam.Direction = outParaAttr.SpParameterDirection;
                    _outParameterPropertyInfoCollection.Add(propertyInfo);
                    _spOutParameters.Add(sqlParam);
                }

                //if (propertyInfo.PropertyType.GetType() is DateTime
                //    || propertyInfo.PropertyType.GetType() is DateTime?)
                //{
                //    value = value == null || (DateTime)value == DateTime.MinValue ? new DateTime(2000, 1, 1) : value;
                //}
            }

            Debug.WriteLine(sqlParam.ParameterName);
            return sqlParam;
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Builds the internal.
        /// </summary>
        /// <param name="commandContext">The command context.</param>
        protected virtual void BuildInternal(CommandContext commandContext)
        {
            var properties = ParametersType
                             .GetProperties(
                BindingFlags.Instance
                | BindingFlags.Public
                | BindingFlags.NonPublic
                )
                             .Where(prop => prop.IsDefined(typeof(FilterOptionAttribute), false));

            string output = null;

            var howSearchProp = properties.FirstOrDefault(pr => pr is HowSearchFilterOptionAttribute);
            var pro           = properties.FirstOrDefault(pr => pr is SearchStringFilterOptionAttribute);

            if (pro != null)
            {
                var context = new FilterOptionAttributeContext {
                    Context  = commandContext,
                    Property = pro,
                    Value    = pro.GetValue(commandContext.Parameters, null)
                };

                if (!string.IsNullOrEmpty((string)context.Value))
                {
                    if (!commandContext.HowSearchDefined && howSearchProp != null)
                    {
                        commandContext.Declarations.Add(@"
							DECLARE @ГдеИскать INT SET @ГдеИскать = {0}
							"                            .FormatWith(context.Value is int?context.Value.ToString() : "0"));
                        commandContext.HowSearchDefined = true;
                    }
                }
            }

            foreach (var property in properties)
            {
                var option  = property.GetCustomAttributes(typeof(FilterOptionAttribute), false).FirstOrDefault() as FilterOptionAttribute;
                var context = new FilterOptionAttributeContext {
                    Context  = commandContext,
                    Property = property,
                    Value    = property.GetValue(commandContext.Parameters, null)
                };

                output = option.BuildPrecode(context);
                if (!String.IsNullOrEmpty(output))
                {
                    commandContext.Sql.AppendLine(sqlPreprocessor(this, output));
                }

                output = option.BuildPredicate(context);
                if (!String.IsNullOrEmpty(output))
                {
                    commandContext.Predicates.Add(sqlPreprocessor(this, output));
                }
            }

            if (commandContext.RowStartIndex > 0)
            {
                commandContext.Declarations.Add(@"
					;-- Определим таблицу для результатов поиска	
					DECLARE @РезультатПоиска TABLE(Код INT, Порядок BIGINT IDENTITY(0,1))
					"                    );
            }

            if (commandContext.Declarations.Count > 0)
            {
                commandContext.Sql.Insert(0, String.Join(";", commandContext.Declarations));
            }

            int top = 0;

            if (commandContext.PageSize > 0)
            {
                top += commandContext.PageSize;
                if (commandContext.RowStartIndex > 0)
                {
                    top += commandContext.RowStartIndex;
                }
            }

            if (commandContext.RowStartIndex > 0)
            {
                commandContext.Sql.AppendFormat(@"
					INSERT INTO @РезультатПоиска(Код)
					"                    , this.UniqueIdField, commandContext.RowStartIndex, commandContext.PageSize);
            }

            commandContext.Sql.AppendFormat(@"
					SELECT {2} {1} FROM {0} T0 {3}
					"                    , TableOrViewName,
                                            (commandContext.RowStartIndex > 0)
                                                        ? UniqueIdField
                                                        : (String.IsNullOrEmpty(FieldList) ? " * " : FieldList),
                                            (top > 0) ? " TOP {0} ".FormatWith(top) : String.Empty,
                                            Joins ?? String.Empty
                                            );

            commandContext.Sql.AppendFormatIfTrue(commandContext.Predicates.Count > 0,
                                                  @"WHERE {0}
					"                    , String.Join(@"
						AND	"                            , commandContext.Predicates));

            commandContext.Sql.AppendFormatIfTrue(commandContext.OrderBy != null && commandContext.OrderBy.Count > 0,
                                                  @"ORDER BY {0}
					"                    , String.Join(@"
						, "                        , commandContext.OrderBy));

            if (commandContext.RowStartIndex > 0)
            {
                commandContext.Sql.AppendFormat(@"
					;-- Вернём результат
					SELECT {1}
					FROM @РезультатПоиска РП 
						INNER JOIN {0} T0 ON РП.Код = T0.{2}
					WHERE	РП.Порядок >= {3}{4}
					ORDER BY РП.Порядок
					"                    , TableOrViewName
                                                , String.IsNullOrEmpty(FieldList) ? " * " : FieldList
                                                , UniqueIdField
                                                , commandContext.RowStartIndex
                                                , (commandContext.PageSize > 0) ? @" AND РП.Порядок < {0} ".FormatWith(top) : String.Empty);
            }
        }
Ejemplo n.º 25
0
        private OracleParameter CreateOracleParameter(PropertyInfo propertyInfo, ParametersType parametesType, IEnumerable <PropertyInfo> propertyInfos)
        {
            object value = propertyInfo.GetValue(this, new object[] { });

            var sqlParam = new OracleParameter(string.Format("@{0}", propertyInfo.Name), value);

            if (propertyInfo.PropertyType.Name == "String" && value != null)
            {
                value = SafeSqlLiteral(value.ToString());
            }

            if ((propertyInfo.PropertyType.IsGenericType ||
                 propertyInfo.PropertyType.Name == "String") & value == null)
            {
                sqlParam.IsNullable = true;
                sqlParam.Value      = DBNull.Value;
            }

            var attrbutes = propertyInfo.GetCustomAttributes(true);

            /*
             * if (propertyInfo.PropertyType.IsGenericType)
             * {
             *  if (propertyInfo.PropertyType.GetGenericArguments()[0].IsEnum)
             *  {
             *      sqlParam.Value = value.ToString();
             *  }
             * }
             * if (propertyInfo.PropertyType.IsEnum)
             *  sqlParam.Value = value.ToString();
             */
            var getMethodInfo = propertyInfo.GetGetMethod();


            if (getMethodInfo.IsVirtual && !getMethodInfo.IsFinal)
            {
                return(null);
            }

            if (attrbutes.FirstOrDefault(a => a is NotASpParameterAttribute) != null)
            {
                return(null);
            }

            //var dbColumnPropertyAttribute =
            //    attrbutes.FirstOrDefault(a => a is DbColumnPropertyAttribute) as DbColumnPropertyAttribute;

            //if (dbColumnPropertyAttribute != null)
            //{
            //    var dbColumnPropertyPropertyInfo =
            //        propertyInfos.FirstOrDefault(p => p.Name == dbColumnPropertyAttribute.DbColumnProperty);

            //    value = dbColumnPropertyPropertyInfo.GetValue(this, new object[] { });
            //    sqlParam.Value = value;
            //}

            var dbColumnAttribute =
                attrbutes.FirstOrDefault(a => a is DbColumnAttribute) as DbColumnAttribute;

            if (dbColumnAttribute != null)
            {
                sqlParam.ParameterName = string.Format("@{0}", dbColumnAttribute.DbColumn);
            }



            if (parametesType == ParametersType.Insert)
            {
                //var propertyDataType = propertyInfo.DeclaringType;

                var outParaAttr = attrbutes.FirstOrDefault(a => a is ParameterDirectionAttribute) as ParameterDirectionAttribute;
                if (outParaAttr != null)
                {
                    sqlParam.Direction = outParaAttr.SpParameterDirection;
                    _outParameterPropertyInfoCollection.Add(propertyInfo);
                    _spOutParameters.Add(sqlParam);
                }

                //if (propertyInfo.PropertyType.GetType() is DateTime
                //    || propertyInfo.PropertyType.GetType() is DateTime?)
                //{
                //    value = value == null || (DateTime)value == DateTime.MinValue ? new DateTime(2000, 1, 1) : value;
                //}
            }

            Debug.WriteLine(sqlParam.ParameterName);
            return(sqlParam);
        }