Exemple #1
0
        CodeExpression OptimiseLoneExpression(CodeExpression expr)
        {
            if (IsVarAssignment(expr))
            {
                var assign = (CodeBinaryOperatorExpression)expr;
                assign.Right = OptimiseExpression(assign.Right);
                return assign;
            }

            if (!IsOptimisableExpression(expr))
                return expr;

            var invoke = (CodeMethodInvokeExpression)expr;

            for (int i = 1; i < 3; i++)
                invoke.Parameters[i] = OptimiseExpression(invoke.Parameters[i]);

            bool left = invoke.Parameters[1] is CodePrimitiveExpression, right = invoke.Parameters[2] is CodeExpression;

            if (!left && !right)
                return null;

            if (left)
                return invoke.Parameters[2];

            if (right)
                return invoke.Parameters[1];

            return expr;
        }
Exemple #2
0
 public static CodeMemberMethod CreateMethodThatChecksIfTheValueOfAMemberIsNotEqualToAnotherExpression(
    string name, CodeExpression expression)
 {
     return new CodeMemberMethod
     {
         ReturnType = new CodeTypeReference(typeof(bool)),
         Statements =
         {
             new CodeMethodReturnStatement()
             {
                 Expression = new CodeBinaryOperatorExpression()
                 {
                     Left = new CodeBinaryOperatorExpression()
                     {
                         Left = new CodeFieldReferenceExpression()
                         {
                             FieldName = "m_" + name.Substring(0, 1).ToLower() + name.Substring(1)
                         },
                     Operator = CodeBinaryOperatorType.ValueEquality,
                     Right = expression
                     },
                     Operator = CodeBinaryOperatorType.ValueEquality,
                     Right = new CodePrimitiveExpression(false)
                 }
             }
         },
         Attributes = MemberAttributes.Public | MemberAttributes.Final,
         Name = "ShouldSerialize" + name
     };
 }
        private void InitializeDialog(CodeExpression expression)
        {
            HelpRequested += new HelpEventHandler(OnHelpRequested);
            HelpButtonClicked += new CancelEventHandler(OnHelpClicked);

            if (expression != null)
            {
                this.ruleExpressionCondition.Expression = RuleExpressionWalker.Clone(expression);
                this.conditionTextBox.Text = ruleExpressionCondition.ToString().Replace("\n", "\r\n");
            }
            else
                this.conditionTextBox.Text = string.Empty;

            this.conditionTextBox.PopulateAutoCompleteList += new EventHandler<AutoCompletionEventArgs>(ConditionTextBox_PopulateAutoCompleteList);
            this.conditionTextBox.PopulateToolTipList += new EventHandler<AutoCompletionEventArgs>(ConditionTextBox_PopulateAutoCompleteList);

            try
            {
                this.ruleParser.ParseCondition(this.conditionTextBox.Text);
                conditionErrorProvider.SetError(this.conditionTextBox, string.Empty);
            }
            catch (RuleSyntaxException ex)
            {
                conditionErrorProvider.SetError(this.conditionTextBox, ex.Message);
            }
        }
		protected override void GeneratePropertySet (GeneratorContext ctx, CodeExpression var, PropertyDescriptor prop)
		{
			if (prop.Name == "Alpha" && Alpha == -1)
				return;
			else
				base.GeneratePropertySet (ctx, var, prop);
		}
 internal override void Analyze(RuleAnalysis analysis, MemberInfo member, CodeExpression targetExpression, RulePathQualifier targetQualifier, CodeExpressionCollection argumentExpressions, ParameterInfo[] parameters, List<CodeExpression> attributedExpressions)
 {
     if (!analysis.ForWrites)
     {
         base.AnalyzeReadWrite(analysis, targetExpression, targetQualifier, argumentExpressions, parameters, attributedExpressions);
     }
 }
Exemple #6
0
 private CodeStatement GenerateCallStatementC2J(GMethod method, CodeExpression invokeExpression)
 {
     CodeStatement call;
     if (method.IsConstructor || method.IsVoid)
     {
         call = new CodeExpressionStatement(invokeExpression);
     }
     else
     {
         if (method.ReturnType.IsPrimitive)
         {
             if (method.ReturnType.JVMSubst != null)
             {
                 invokeExpression = new CodeCastExpression(method.ReturnType.CLRReference, invokeExpression);
             }
             call = new CodeMethodReturnStatement(invokeExpression);
         }
         else
         {
             CodeMethodInvokeExpression conversionExpression = CreateConversionExpressionJ2CParam(method.ReturnType,
                                                                                             invokeExpression);
             call = new CodeMethodReturnStatement(conversionExpression);
         }
     }
     return call;
 }
 public CodeMethodReferenceExpression(CodeExpression targetObject, string methodName, params CodeTypeReference[] typeParameters) {
     TargetObject = targetObject;
     MethodName = methodName;
     if( typeParameters != null && typeParameters.Length > 0) {
         TypeArguments.AddRange(typeParameters);
     }
 }
 internal override RuleExpressionResult Evaluate(CodeExpression expression, RuleExecution execution)
 {
     CodeCastExpression expression2 = (CodeCastExpression) expression;
     object operandValue = RuleExpressionWalker.Evaluate(execution, expression2.Expression).Value;
     RuleExpressionInfo info = execution.Validation.ExpressionInfo(expression2);
     if (info == null)
     {
         InvalidOperationException exception = new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ExpressionNotValidated, new object[0]));
         exception.Data["ErrorObject"] = expression2;
         throw exception;
     }
     Type expressionType = info.ExpressionType;
     if (operandValue == null)
     {
         if (ConditionHelper.IsNonNullableValueType(expressionType))
         {
             RuleEvaluationException exception2 = new RuleEvaluationException(string.Format(CultureInfo.CurrentCulture, Messages.CastIncompatibleTypes, new object[] { Messages.NullValue, RuleDecompiler.DecompileType(expressionType) }));
             exception2.Data["ErrorObject"] = expression2;
             throw exception2;
         }
     }
     else
     {
         operandValue = Executor.AdjustTypeWithCast(execution.Validation.ExpressionInfo(expression2.Expression).ExpressionType, operandValue, expressionType);
     }
     return new RuleLiteralResult(operandValue);
 }
Exemple #9
0
        CodeExpression OptimiseExpression(CodeExpression expr)
        {
            if (!IsOptimisableExpression(expr))
                return expr;

            var invoke = (CodeMethodInvokeExpression)expr;

            for (int i = 1; i < 3; i++)
                invoke.Parameters[i] = OptimiseExpression(invoke.Parameters[i]);

            if (invoke.Parameters[1] is CodePrimitiveExpression && invoke.Parameters[2] is CodePrimitiveExpression)
            {
                object result = null;

                try
                {
                    result = Script.Operate((Script.Operator)invoke.Parameters[0].UserData[RawData],
                        ((CodePrimitiveExpression)invoke.Parameters[1]).Value,
                        ((CodePrimitiveExpression)invoke.Parameters[2]).Value);
                }
                catch (Exception) { }

                return new CodePrimitiveExpression(result);
            }

            return invoke;
        }
Exemple #10
0
	public static CodeConditionStatement IfTrueReturnTrue (CodeExpression condition)
	{
	    CodeConditionStatement cond = new CodeConditionStatement ();
	    cond.Condition = condition;
	    cond.TrueStatements.Add (new CodeMethodReturnStatement (True));
	    return cond;
	}
 /// <summary>
 /// Initializes a new instance of the CodeTypeOperationExpression class.
 /// </summary>
 /// <param name="source">The source expression.</param>
 /// <param name="targetType">The target type reference expression.</param>
 protected CodeTypeOperationExpression(CodeExpression source, CodeTypeReferenceExpression targetType)
 {
     ExceptionUtilities.CheckArgumentNotNull(source, "source");
     ExceptionUtilities.CheckArgumentNotNull(targetType, "targetType");
     this.Source = source;
     this.TargetType = targetType;
 }
 public static CodeMethodInvokeExpression XNameGetExpression(CodeExpression name, CodeExpression ns) {
     return new CodeMethodInvokeExpression(
         new CodeTypeReferenceExpression("XName"),
         "Get",
         name,
         ns);
 }
	public CodeVariableDeclarationStatement(Type type, String name,
											CodeExpression initExpression)
			{
				this.type = new CodeTypeReference(type);
				this.name = name;
				this.initExpression = initExpression;
			}
 internal override void Decompile(CodeExpression expression, StringBuilder stringBuilder, CodeExpression parentExpression)
 {
     CodeIndexerExpression expression2 = (CodeIndexerExpression) expression;
     CodeExpression targetObject = expression2.TargetObject;
     if (targetObject == null)
     {
         RuleEvaluationException exception = new RuleEvaluationException(string.Format(CultureInfo.CurrentCulture, Messages.NullIndexerTarget, new object[0]));
         exception.Data["ErrorObject"] = expression2;
         throw exception;
     }
     if ((expression2.Indices == null) || (expression2.Indices.Count == 0))
     {
         RuleEvaluationException exception2 = new RuleEvaluationException(string.Format(CultureInfo.CurrentCulture, Messages.MissingIndexExpressions, new object[0]));
         exception2.Data["ErrorObject"] = expression2;
         throw exception2;
     }
     RuleExpressionWalker.Decompile(stringBuilder, targetObject, expression2);
     stringBuilder.Append('[');
     RuleExpressionWalker.Decompile(stringBuilder, expression2.Indices[0], null);
     for (int i = 1; i < expression2.Indices.Count; i++)
     {
         stringBuilder.Append(", ");
         RuleExpressionWalker.Decompile(stringBuilder, expression2.Indices[i], null);
     }
     stringBuilder.Append(']');
 }
        private void ExplicitVisit_FunctionCall_SUBSTRING(FunctionCall node)
        {
            if (node.Parameters.Count != 3)
            {
                throw new NotSupportedException(node.AsText());
            }

            var invoke_ISNULL = new cs.CodeMethodInvokeExpression(new cs.CodeMethodReferenceExpression()
            {
                MethodName   = "SUBSTRING",
                TargetObject = new cs.CodeTypeReferenceExpression(new cs.CodeTypeReference("KnownSqlFunction"))
            });

            var prm_expression        = TryBuildFromNode(node.Parameters[0], ref lastHasError, ref lastError);
            var prm_starting_position = TryBuildFromNode(node.Parameters[1], ref lastHasError, ref lastError);
            var prm_length            = TryBuildFromNode(node.Parameters[2], ref lastHasError, ref lastError);

            if (!lastHasError)
            {
                invoke_ISNULL.Parameters.Add(prm_expression);
            }
            if (!lastHasError)
            {
                invoke_ISNULL.Parameters.Add(prm_starting_position);
            }
            if (!lastHasError)
            {
                invoke_ISNULL.Parameters.Add(prm_length);
            }

            lastExpression = invoke_ISNULL;
        }
		public void Constructor1 ()
		{
			CodeTypeReference type1 = new CodeTypeReference ("mono1");
			CodeExpression expression1 = new CodeExpression ();

			CodeCastExpression cce = new CodeCastExpression (type1, expression1);
			Assert.IsNotNull (cce.Expression, "#1");
			Assert.AreSame (expression1, cce.Expression, "#2");
			Assert.IsNotNull (cce.TargetType, "#3");
			Assert.AreSame (type1, cce.TargetType, "#4");

			cce.Expression = null;
			Assert.IsNull (cce.Expression, "#5");

			CodeExpression expression2 = new CodeExpression ();
			cce.Expression = expression2;
			Assert.IsNotNull (cce.Expression, "#6");
			Assert.AreSame (expression2, cce.Expression, "#7");

			cce.TargetType = null;
			Assert.IsNotNull (cce.TargetType, "#8");
			Assert.AreEqual (typeof (void).FullName, cce.TargetType.BaseType, "#9");

			CodeTypeReference type2 = new CodeTypeReference ("mono2");
			cce.TargetType = type2;
			Assert.IsNotNull (cce.TargetType, "#10");
			Assert.AreSame (type2, cce.TargetType, "#11");

			cce = new CodeCastExpression ((CodeTypeReference) null, (CodeExpression) null);
			Assert.IsNull (cce.Expression, "#12");
			Assert.IsNotNull (cce.TargetType, "#13");
			Assert.AreEqual (typeof (void).FullName, cce.TargetType.BaseType, "#14");
		}
        private void ExplicitVisit_FunctionCall_OBJECT_NAME(FunctionCall node)
        {
            if (node.Parameters.Count != 1)
            {
                throw new NotSupportedException(node.AsText());
            }

            var invoke_ISNULL = new cs.CodeMethodInvokeExpression(new cs.CodeMethodReferenceExpression()
            {
                MethodName   = "OBJECT_NAME",
                TargetObject = new cs.CodeTypeReferenceExpression(new cs.CodeTypeReference("KnownSqlFunction"))
            });

            var prm_string_expression = TryBuildFromNode(node.Parameters[0], ref lastHasError, ref lastError);

            if (!lastHasError)
            {
                invoke_ISNULL.Parameters.Add(prm_string_expression);
            }

            if (!lastHasError)
            {
                lastExpression = invoke_ISNULL;
            }
        }
        private void ExplicitVisit_FunctionCall_CONCAT(FunctionCall node)
        {
            //if (node.Parameters.Count != 1)
            //{
            //    throw new NotSupportedException(node.AsText());
            //}

            var invoke_ISNULL = new cs.CodeMethodInvokeExpression(new cs.CodeMethodReferenceExpression()
            {
                MethodName   = "CONCAT",
                TargetObject = new cs.CodeTypeReferenceExpression(new cs.CodeTypeReference("KnownSqlFunction"))
            });

            for (int idx = 0; idx < node.Parameters.Count; idx++)
            {
                var prm = TryBuildFromNode(node.Parameters[idx], ref lastHasError, ref lastError);
                if (!lastHasError)
                {
                    invoke_ISNULL.Parameters.Add(prm);
                }
            }
            if (!lastHasError)
            {
                lastExpression = invoke_ISNULL;
            }
        }
        private void ExplicitVisit_FunctionCall_DATEFROMPARTS(FunctionCall node)
        {
            if (node.Parameters.Count != 3)
            {
                throw new NotSupportedException(node.AsText());
            }

            var invoke_ISNULL = new cs.CodeMethodInvokeExpression(new cs.CodeMethodReferenceExpression()
            {
                MethodName   = "DATEFROMPARTS",
                TargetObject = new cs.CodeTypeReferenceExpression(new cs.CodeTypeReference("KnownSqlFunction"))
            });

            var prm_1 = TryBuildFromNode(node.Parameters[0], ref lastHasError, ref lastError);
            var prm_2 = TryBuildFromNode(node.Parameters[1], ref lastHasError, ref lastError);
            var prm_3 = TryBuildFromNode(node.Parameters[2], ref lastHasError, ref lastError);

            if (!lastHasError)
            {
                invoke_ISNULL.Parameters.Add(prm_1);
                invoke_ISNULL.Parameters.Add(prm_2);
                invoke_ISNULL.Parameters.Add(prm_3);

                lastExpression = invoke_ISNULL;
            }
        }
 internal override RuleExpressionInfo Validate(CodeExpression expression, RuleValidation validation, bool isWritten)
 {
     RuleExpressionInfo info;
     bool flag;
     CodeDirectionExpression expression2 = (CodeDirectionExpression) expression;
     if (isWritten)
     {
         ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CannotWriteToExpression, new object[] { typeof(CodeDirectionExpression).ToString() }), 0x17a);
         item.UserData["ErrorObject"] = expression2;
         validation.Errors.Add(item);
         return null;
     }
     if (expression2.Expression == null)
     {
         ValidationError error2 = new ValidationError(Messages.NullDirectionTarget, 0x53d);
         error2.UserData["ErrorObject"] = expression2;
         validation.Errors.Add(error2);
         return null;
     }
     if (expression2.Expression is CodeTypeReferenceExpression)
     {
         ValidationError error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.CodeExpressionNotHandled, new object[] { expression2.Expression.GetType().FullName }), 0x548);
         error.UserData["ErrorObject"] = expression2.Expression;
         validation.AddError(error);
         return null;
     }
     if (expression2.Direction == FieldDirection.Ref)
     {
         flag = true;
         if (RuleExpressionWalker.Validate(validation, expression2.Expression, false) == null)
         {
             return null;
         }
         info = RuleExpressionWalker.Validate(validation, expression2.Expression, true);
     }
     else if (expression2.Direction == FieldDirection.Out)
     {
         flag = true;
         info = RuleExpressionWalker.Validate(validation, expression2.Expression, true);
     }
     else
     {
         flag = false;
         info = RuleExpressionWalker.Validate(validation, expression2.Expression, false);
     }
     if (info == null)
     {
         return null;
     }
     Type expressionType = info.ExpressionType;
     if (expressionType == null)
     {
         return null;
     }
     if (((expressionType != typeof(NullLiteral)) && flag) && !expressionType.IsByRef)
     {
         expressionType = expressionType.MakeByRefType();
     }
     return new RuleExpressionInfo(expressionType);
 }
Exemple #21
0
 void EmitExpression(CodeExpression expr)
 {
     if (expr is CodeMethodInvokeExpression)
         EmitInvoke((CodeMethodInvokeExpression)expr);
     else if (expr is CodeArrayCreateExpression)
         EmitArray((CodeArrayCreateExpression)expr);
     else if (expr is CodePrimitiveExpression)
         EmitPrimitive((CodePrimitiveExpression)expr);
     else if (expr is CodeBinaryOperatorExpression)
         EmitBinary((CodeBinaryOperatorExpression)expr);
     else if (expr is CodeTernaryOperatorExpression)
         EmitTernary((CodeTernaryOperatorExpression)expr);
     else if (expr is CodeVariableReferenceExpression)
         EmitVariableReference((CodeVariableReferenceExpression)expr);
     else if (expr is CodeArgumentReferenceExpression)
         EmitArgumentReference((CodeArgumentReferenceExpression)expr);
     else if (expr is CodeFieldReferenceExpression)
         EmitFieldReference((CodeFieldReferenceExpression)expr);
     else if (expr is CodeTypeReferenceExpression)
         EmitTypeReference((CodeTypeReferenceExpression)expr);
     else if (expr is CodeArrayIndexerExpression)
         EmitArrayIndexer((CodeArrayIndexerExpression)expr);
     else if (expr is CodePropertyReferenceExpression)
         EmitPropertyReference((CodePropertyReferenceExpression)expr);
     else
         throw new ArgumentException("Unrecognised expression: " + expr.GetType());
 }
 internal override void AnalyzeUsage(CodeExpression expression, RuleAnalysis analysis, bool isRead, bool isWritten, RulePathQualifier qualifier)
 {
     CodeIndexerExpression expression2 = (CodeIndexerExpression) expression;
     CodeExpression targetObject = expression2.TargetObject;
     if (analysis.Validation.ExpressionInfo(targetObject) == null)
     {
         InvalidOperationException exception = new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ExpressionNotValidated, new object[0]));
         exception.Data["ErrorObject"] = targetObject;
         throw exception;
     }
     RulePropertyExpressionInfo info2 = analysis.Validation.ExpressionInfo(expression2) as RulePropertyExpressionInfo;
     if (info2 == null)
     {
         InvalidOperationException exception2 = new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ExpressionNotValidated, new object[0]));
         exception2.Data["ErrorObject"] = expression2;
         throw exception2;
     }
     PropertyInfo propertyInfo = info2.PropertyInfo;
     List<CodeExpression> attributedExprs = new List<CodeExpression>();
     analysis.AnalyzeRuleAttributes(propertyInfo, targetObject, qualifier, expression2.Indices, propertyInfo.GetIndexParameters(), attributedExprs);
     if (!attributedExprs.Contains(targetObject))
     {
         RuleExpressionWalker.AnalyzeUsage(analysis, targetObject, isRead, isWritten, qualifier);
     }
     for (int i = 0; i < expression2.Indices.Count; i++)
     {
         CodeExpression item = expression2.Indices[i];
         if (!attributedExprs.Contains(item))
         {
             RuleExpressionWalker.AnalyzeUsage(analysis, item, true, false, null);
         }
     }
 }
		public void Constructor1 ()
		{
			CodeEventReferenceExpression eventref = new CodeEventReferenceExpression ();
			CodeExpression listener = new CodeExpression ();

			CodeRemoveEventStatement caes = new CodeRemoveEventStatement (eventref, listener);
			Assert.AreSame (eventref, caes.Event, "#1");
			Assert.AreEqual (string.Empty, caes.Event.EventName, "#2");
			Assert.IsNull (caes.Event.TargetObject, "#3");
			Assert.AreSame (listener, caes.Listener, "#4");

			caes.Event = null;
			Assert.IsNotNull (caes.Event, "#5");
			Assert.AreEqual (string.Empty, caes.Event.EventName, "#6");
			Assert.IsNull (caes.Event.TargetObject, "#7");
			Assert.AreSame (listener, caes.Listener, "#8");

			caes.Listener = null;
			Assert.IsNull (caes.Listener, "#9");

			caes.Event = eventref;
			Assert.AreSame (eventref, caes.Event, "#10");

			caes.Listener = listener;
			Assert.AreSame (listener, caes.Listener, "#11");

			caes = new CodeRemoveEventStatement ((CodeEventReferenceExpression) null, (CodeExpression) null);
			Assert.IsNotNull (caes.Event, "#12");
			Assert.IsNull (caes.Listener, "#13");
			Assert.AreEqual (string.Empty, caes.Event.EventName, "#14");
			Assert.IsNull (caes.Event.TargetObject, "#15");
		}
 internal override void AnalyzeUsage(CodeExpression expression, RuleAnalysis analysis, bool isRead, bool isWritten, RulePathQualifier qualifier)
 {
     CodePropertyReferenceExpression expression2 = (CodePropertyReferenceExpression) expression;
     CodeExpression targetObject = expression2.TargetObject;
     if (analysis.Validation.ExpressionInfo(targetObject) == null)
     {
         InvalidOperationException exception = new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ExpressionNotValidated, new object[0]));
         exception.Data["ErrorObject"] = targetObject;
         throw exception;
     }
     RulePropertyExpressionInfo info2 = analysis.Validation.ExpressionInfo(expression2) as RulePropertyExpressionInfo;
     if (info2 == null)
     {
         InvalidOperationException exception2 = new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ExpressionNotValidated, new object[0]));
         exception2.Data["ErrorObject"] = expression2;
         throw exception2;
     }
     PropertyInfo propertyInfo = info2.PropertyInfo;
     List<CodeExpression> attributedExprs = new List<CodeExpression>();
     analysis.AnalyzeRuleAttributes(propertyInfo, targetObject, qualifier, null, null, attributedExprs);
     if (!attributedExprs.Contains(targetObject))
     {
         RuleExpressionWalker.AnalyzeUsage(analysis, targetObject, isRead, isWritten, new RulePathQualifier(propertyInfo.Name, qualifier));
     }
 }
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeExpression expression = new CodeExpression ();
			CodeMethodReturnStatement cmrs = new CodeMethodReturnStatement (expression);
			Assert.AreSame (expression, cmrs.Expression, "Expression");
			cmrs.Expression = new CodeExpression ();
		}
            /// <summary>
            /// Rewrites references to entities with dictionary provider specific CodeDom to do the correct lookup.
            /// </summary>
            /// <param name="source">the CodeDom Expression to rewrite</param>
            /// <param name="didRewrite">indicates whether or not the expression was rewritten</param>
            /// <returns>the CodeDom expression appropriate for the dictionary provider</returns>
            protected override CodeExpression Rewrite(CodeExpression source, ref bool didRewrite)
            {
                var propertyRef = source as CodePropertyReferenceExpression;
                if (propertyRef != null)
                {
                    return this.RewritePropertyReference(propertyRef, ref didRewrite);
                }

                var lambdaExpression = source as CodeLambdaExpression;
                if (lambdaExpression != null)
                {
                    return this.RewriteLambdaExpression(lambdaExpression, ref didRewrite);
                }

                var arrayExpression = source as CodeAnonymousArrayExpression;
                if (arrayExpression != null)
                {
                    return this.RewriteAnonymousArray(arrayExpression, ref didRewrite);
                }

                ExceptionUtilities.Assert(
                    source.GetType().Namespace == typeof(CodeObject).Namespace,
                    "Taupo-defined code expressions need to be explicitly handled or the base tree rewriter will lose them");

                return base.Rewrite(source, ref didRewrite);
            }
        private void ExplicitVisit_FunctionCall_DATEPART(FunctionCall node)
        {
            if (node.Parameters.Count != 2)
            {
                throw new NotSupportedException(node.AsText());
            }

            var invoke_ISNULL = new cs.CodeMethodInvokeExpression(new cs.CodeMethodReferenceExpression()
            {
                MethodName   = "DATEPART",
                TargetObject = new cs.CodeTypeReferenceExpression(new cs.CodeTypeReference("KnownSqlFunction"))
            });

            var prm_interval = TryBuildFromNode(node.Parameters[0], ref lastHasError, ref lastError);

            if (!lastHasError)
            {
                invoke_ISNULL.Parameters.Add(prm_interval);
            }
            var prm_datetimeoffset = TryBuildFromNode(node.Parameters[1], ref lastHasError, ref lastError);

            if (!lastHasError)
            {
                invoke_ISNULL.Parameters.Add(prm_datetimeoffset);
            }

            if (lastHasError)
            {
            }
            else
            {
                lastExpression = invoke_ISNULL;
            }
        }
Exemple #28
0
		public ExpressionContext (CodeExpression expression, Type expressionType, object owner, object presetValue)
		{
			_expression = expression;
			_expressionType = expressionType;
			_owner = owner;
			_presetValue = presetValue;
		}
		public CodeMethodInvokeExpression (CodeExpression targetObject,
						   string methodName,
						   params CodeExpression [] parameters)
		{
			this.method = new CodeMethodReferenceExpression( targetObject, methodName );
			this.Parameters.AddRange (parameters);
		}
 /// <summary>
 /// Generates a test to determine if the given expressions are equal.
 /// </summary>
 /// <param name="clrType">The Type of the values being compared.</param>
 /// <param name="left">The left side of the test.</param>
 /// <param name="right">The right side of the test.</param>
 /// <param name="isCSharp">Indicates whether or not the output should be C# specific.</param>
 /// <returns>A new <see cref="CodeExpression"/>.</returns>
 public static CodeExpression MakeEqual(Type clrType, CodeExpression left, CodeExpression right, bool isCSharp)
 {
     if (isCSharp)
     {
         return new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.IdentityEquality, right);
     }
     else
     {
         CodeExpression eq;
         if (clrType != null && clrType.IsGenericType && clrType.GetGenericTypeDefinition() == typeof(Nullable<>))
         {
             eq = new CodeMethodInvokeExpression(left, "Equals", right);
         }
         else if (clrType != null && clrType.IsValueType)
         {
             eq = new CodeBinaryOperatorExpression(
                     left,
                     CodeBinaryOperatorType.ValueEquality,
                     right);
         }
         else if (clrType == typeof(string))
         {
             eq = new CodeMethodInvokeExpression(null, "String.Equals", left, right);
         }
         else
         {
             eq = new CodeMethodInvokeExpression(null, typeof(object).Name + ".Equals", left, right);
         }
         return eq;
     }
 }
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            if (!entry.Expression.Contains(","))
              {
            throw new ArgumentException("Must include two numbers separated by a comma.");
              }
              else
              {
            // get two numbers
            string[] numbers = entry.Expression.Split(',');
            if (numbers.Length != 2)
            {
              throw new ArgumentException("Only include two numbers");
            }
            else
            {
              int lowerLimit, upperLimit;
              if (Int32.TryParse(numbers[0], out lowerLimit) && Int32.TryParse(numbers[1], out upperLimit))
              {
            CodeTypeReferenceExpression typeRef = new CodeTypeReferenceExpression(this.GetType());
            CodeExpression[] methodParameters = new CodeExpression[2];
            methodParameters[0] = new CodePrimitiveExpression(lowerLimit);
            methodParameters[1] = new CodePrimitiveExpression(upperLimit);

            return new CodeMethodInvokeExpression(typeRef, "GetRandomNumber", methodParameters);
              }
              else
              {
            throw new ArgumentException("Use valid Integers");
              }
            }
              }
        }
		public override void Visit(ViewTreeNode node)
		{
			if (typeStack.Count == 0) return;

			var constructionArguments = new CodeExpression[]
			{
				new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), naming.ToMemberVariableName(serviceIdentifier)),
				new CodeTypeOfExpression(node.Controller.FullName),
				new CodePrimitiveExpression(node.Controller.Area),
				new CodePrimitiveExpression(naming.ToControllerName(node.Controller.Name)),
				new CodePrimitiveExpression(node.Name)
			};

			CodeExpression returnExpression =
				new CodeMethodInvokeExpression(
					new CodeMethodReferenceExpression(
						new CodePropertyReferenceExpression(
							new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), naming.ToMemberVariableName(serviceIdentifier)),
							"ControllerReferenceFactory"),
						"CreateViewReference"),
					constructionArguments);

			var propertyType = new CodeTypeReference(typeof (IControllerViewReference));
			typeStack.Peek().Members.Add(source.CreateReadOnlyProperty(node.Name, propertyType, returnExpression));

			base.Visit(node);
		}
        internal override void AnalyzeUsage(CodeExpression expression, RuleAnalysis analysis, bool isRead, bool isWritten, RulePathQualifier qualifier)
        {
            CodeDirectionExpression expression2 = (CodeDirectionExpression) expression;
            CodeExpression expression3 = expression2.Expression;
            bool flag = false;
            bool flag2 = true;
            RulePathQualifier qualifier2 = null;
            switch (expression2.Direction)
            {
                case FieldDirection.In:
                    flag = false;
                    flag2 = true;
                    qualifier2 = new RulePathQualifier("*", null);
                    break;

                case FieldDirection.Out:
                    flag = true;
                    flag2 = false;
                    qualifier2 = null;
                    break;

                case FieldDirection.Ref:
                    flag = true;
                    flag2 = true;
                    qualifier2 = analysis.ForWrites ? null : new RulePathQualifier("*", null);
                    break;
            }
            RuleExpressionWalker.AnalyzeUsage(analysis, expression3, flag2, flag, qualifier2);
        }
 internal override void Decompile(CodeExpression expression, StringBuilder stringBuilder, CodeExpression parentExpression)
 {
     CodeCastExpression childExpr = (CodeCastExpression) expression;
     CodeExpression expression3 = childExpr.Expression;
     if (expression3 == null)
     {
         RuleEvaluationException exception = new RuleEvaluationException(Messages.NullCastExpr);
         exception.Data["ErrorObject"] = childExpr;
         throw exception;
     }
     if (childExpr.TargetType == null)
     {
         RuleEvaluationException exception2 = new RuleEvaluationException(Messages.NullCastType);
         exception2.Data["ErrorObject"] = childExpr;
         throw exception2;
     }
     bool flag = RuleDecompiler.MustParenthesize(childExpr, parentExpression);
     if (flag)
     {
         stringBuilder.Append("(");
     }
     stringBuilder.Append("(");
     RuleDecompiler.DecompileType(stringBuilder, childExpr.TargetType);
     stringBuilder.Append(")");
     RuleExpressionWalker.Decompile(stringBuilder, expression3, childExpr);
     if (flag)
     {
         stringBuilder.Append(")");
     }
 }
        object SerializeCell(IDesignerSerializationManager manager, CodeExpression target, Cell cell)
        {
            object codeObject = null;
            ExpressionContext context = null;
            ExpressionContext context2 = manager.Context[typeof(ExpressionContext)] as ExpressionContext;
            if (context2 != null)
            {
                CodeMethodInvokeExpression codeIndexer = new CodeMethodInvokeExpression(target, "GetAt", new CodePrimitiveExpression(cell.Column.Index));
                context = new ExpressionContext(codeIndexer, typeof(RowCollection), context2.PresetValue, cell);
                manager.Context.Push(context);
            }
            try
            {
                CodeDomSerializer rowSerialzier = (CodeDomSerializer)manager.GetSerializer(cell.GetType(), typeof(CodeDomSerializer));

                //codeObject = rowSerialzier.Serialize(manager, row);
                codeObject = rowSerialzier.SerializeAbsolute(manager, cell);
            }
            finally
            {
                if (context != null)
                {
                    manager.Context.Pop();
                }
            }

            return codeObject;
        }
 public override void ExplicitVisit(BinaryLiteral node)
 {
     if (node.Value.StartsWith("0x") && node.Value.Length <= 10)
     {
         var value = Convert.ToUInt32(node.Value, 16);  //Using ToUInt32 not ToUInt64, as per OP comment
         lastExpression = new cs.CodePrimitiveExpression(value);
     }
     else
     {
         throw new NotImplementedException(node.AsText());
     }
 }
        public override void ExplicitVisit(BooleanNotExpression node)
        {
            var binaryOp = new cs.CodeBinaryOperatorExpression()
            {
                Operator = cs.CodeBinaryOperatorType.IdentityInequality,
                Left     = TryBuildFromNode(node.Expression, ref lastHasError, ref lastError),
                Right    = new cs.CodePrimitiveExpression(true)
            };

            if (!lastHasError)
            {
                lastExpression = binaryOp;
            }
        }
        public override void ExplicitVisit(BooleanBinaryExpression node)
        {
            // BinaryExpressionType + First + Second
            cs.CodeBinaryOperatorExpression binary = new cs.CodeBinaryOperatorExpression();
            binary.Operator = ConvertToBinaryOperatorType(node.BinaryExpressionType);
            binary.Left     = TryBuildFromNode(node.FirstExpression, ref lastHasError, ref lastError);
            binary.Right    = TryBuildFromNode(node.SecondExpression, ref lastHasError, ref lastError);

            if (lastHasError)
            {
            }
            else
            {
                this.lastExpression = binary;
            }
        }
        public override void ExplicitVisit(ColumnReferenceExpression node)
        {
            string columnName;

            if (node.MultiPartIdentifier.Count == 1)
            {
                columnName = node.MultiPartIdentifier[0].Value;
            }
            else
            {
                throw new NotImplementedException(node.AsText());
            }

            cs.CodeExpression targetObject = new cs.CodeThisReferenceExpression();

            this.lastExpression = new cs.CodeFieldReferenceExpression(targetObject, columnName);
        }
        public override void ExplicitVisit(BooleanIsNullExpression node)
        {
            cs.CodeBinaryOperatorExpression binary = new cs.CodeBinaryOperatorExpression();
            binary.Operator = node.IsNot
                ? cs.CodeBinaryOperatorType.IdentityInequality
                : cs.CodeBinaryOperatorType.ValueEquality;
            binary.Left  = TryBuildFromNode(node.Expression, ref lastHasError, ref lastError);
            binary.Right = new cs.CodePrimitiveExpression(null);

            if (lastHasError)
            {
            }
            else
            {
                this.lastExpression = binary;
            }
        }
        public override void ExplicitVisit(ParenthesisExpression node)
        {
            //Console.WriteLine(prefix + "(");
            //
            //using (new_PrefixScope())
            //{
            //    // the expression can result into: nothing, expression, literal or column
            //    //ParenthesisExpressionVisitor vstor = new ParenthesisExpressionVisitor();
            //    node.Expression.Accept(this);
            //    //if (vstor.result == null)
            //    //{
            //    //    throw new NotImplementedException(node.AsText());
            //    //}
            //}
            //
            //Console.WriteLine(prefix + ")");

            this.lastExpression = TryBuildFromNode(node.Expression, ref lastHasError, ref lastError);
        }
        public override void ExplicitVisit(BooleanComparisonExpression node)
        {
            // ComparisonType + First + Second
            cs.CodeBinaryOperatorExpression binary = new cs.CodeBinaryOperatorExpression();
            binary.Operator = ConvertToBinaryOperatorType(node.ComparisonType);
            binary.Left     = TryBuildFromNode(node.FirstExpression, ref lastHasError, ref lastError);
            binary.Right    = TryBuildFromNode(node.SecondExpression, ref lastHasError, ref lastError);

            if (lastHasError)
            {
                return;
            }

            // adjust left or right : boolean column - compare to int : true==1
            // try get left type
            // try  get right type

            this.lastExpression = binary;
        }
        private void ExplicitVisit_FunctionCall_CONVERT(FunctionCall node)
        {
            if (node.Parameters.Count != 2)
            {
                throw new NotSupportedException(node.AsText());
            }

            var invoke_ISNULL = new cs.CodeMethodInvokeExpression(new cs.CodeMethodReferenceExpression()
            {
                MethodName   = "CONVERT",
                TargetObject = new cs.CodeTypeReferenceExpression(new cs.CodeTypeReference("KnownSqlFunction"))
            });

            var prm_object_name = TryBuildFromNode(node.Parameters[0], ref lastHasError, ref lastError);
            var prm_object_part = TryBuildFromNode(node.Parameters[1], ref lastHasError, ref lastError);

            if (!lastHasError)
            {
                invoke_ISNULL.Parameters.Add(prm_object_name);
                invoke_ISNULL.Parameters.Add(prm_object_part);

                lastExpression = invoke_ISNULL;
            }
        }
Exemple #44
0
 public CodeExpressionStatement(CodeExpression expression)
 {
     Expression = expression;
 }
Exemple #45
0
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public CodeArrayIndexerExpression(CodeExpression targetObject, params CodeExpression[] indices)
 {
     this.targetObject = targetObject;
     this.indices      = new CodeExpressionCollection();
     this.indices.AddRange(indices);
 }
Exemple #46
0
 public CodeThrowExceptionStatement(CodeExpression toThrow)
 {
     this.ToThrow = toThrow;
 }
Exemple #47
0
        //System.CodeDom.CodeVariableDeclarationStatement mVecVariableDeclaration = new System.CodeDom.CodeVariableDeclarationStatement();
        public override async System.Threading.Tasks.Task GCode_CodeDom_GenerateCode(CodeTypeDeclaration codeClass, CodeStatementCollection codeStatementCollection, CodeGenerateSystem.Base.LinkPinControl element, CodeGenerateSystem.Base.GenerateCodeContext_Method context)
        {
            var strValueName = GCode_GetValueName(null, context);

            if (!context.Method.Statements.Contains(mVarDec))
            {
                mVarDec = new CodeAssignStatement(new CodeSnippetExpression(mValueType.FullName + " " + strValueName), CodeGenerateSystem.Program.GetDefaultValueExpressionFromType(mValueType));//, paramCodeName, CodeGenerateSystem.Program.GetDefaultValueExpressionFromType(ParamType));
                context.Method.Statements.Insert(0, mVarDec);
            }
            if (mCtrlvalue_VectorIn.HasLink)
            {
                if (!mCtrlvalue_VectorIn.GetLinkedObject(0, true).IsOnlyReturnValue)
                {
                    await mCtrlvalue_VectorIn.GetLinkedObject(0, true).GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, mCtrlvalue_VectorIn.GetLinkedPinControl(0, true), context);
                }


                if (!codeStatementCollection.Contains(mAssignCode))
                {
                    mAssignCode = new CodeAssignStatement(new System.CodeDom.CodeVariableReferenceExpression(strValueName), mCtrlvalue_VectorIn.GetLinkedObject(0, true).GCode_CodeDom_GetValue(mCtrlvalue_VectorIn.GetLinkedPinControl(0, true), context));
                    codeStatementCollection.Add(mAssignCode);
                }
            }
            else
            {
                if (!codeStatementCollection.Contains(mAssignCode))
                {
                    mAssignCode      = new CodeAssignStatement();
                    mAssignCode.Left = new System.CodeDom.CodeVariableReferenceExpression(strValueName);
                    var paramExp = new System.CodeDom.CodeExpression[mLinkInDic.Count];
                    var param    = CSParam as AixConstructionParams;
                    if (param != null)
                    {
                        for (int i = 0; i < mLinkInDic.Count; i++)
                        {
                            paramExp[i] = new System.CodeDom.CodePrimitiveExpression(param.Value[i]);
                        }
                    }
                    mAssignCode.Right = new CodeObjectCreateExpression(mValueType, paramExp);
                    codeStatementCollection.Add(mAssignCode);
                }
            }

            foreach (var data in mLinkInDic)
            {
                var linkOI = data.Element;
                if (linkOI.HasLink)
                {
                    if (!linkOI.GetLinkedObject(0, true).IsOnlyReturnValue)
                    {
                        await linkOI.GetLinkedObject(0, true).GCode_CodeDom_GenerateCode(codeClass, codeStatementCollection, linkOI.GetLinkedPinControl(0, true), context);
                    }

                    var fieldRef = new System.CodeDom.CodeFieldReferenceExpression();
                    fieldRef.TargetObject = new CodeVariableReferenceExpression(strValueName);
                    fieldRef.FieldName    = data.KeyName;
                    var statValAss = new System.CodeDom.CodeAssignStatement();
                    statValAss.Left  = fieldRef;
                    statValAss.Right = new CodeGenerateSystem.CodeDom.CodeCastExpression(typeof(float), linkOI.GetLinkedObject(0, true).GCode_CodeDom_GetValue(linkOI.GetLinkedPinControl(0, true), context));
                    codeStatementCollection.Add(statValAss);
                }
            }
        }
 public override void ExplicitVisit(FunctionCall node)
 {
     /*if (string.Equals(node.FunctionName.Value, "ISNULL", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_ISNULL(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "DATEPART", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_DATEPART(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "LEN", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_LEN(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "REPLACE", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_REPLACE(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "RTRIM", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_RTRIM(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "SUBSTRING", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_SUBSTRING(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "PARSENAME", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_PARSENAME(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "CONVERT", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_CONVERT(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "REPLICATE", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_REPLICATE(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "DATALENGTH", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_DATALENGTH(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "EOMONTH", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_EOMONTH(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "DATEDIFF", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_DATEDIFF(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "CHARINDEX", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_CHARINDEX(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "COL_NAME", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_COL_NAME(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "OBJECT_NAME", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_OBJECT_NAME(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "CONCAT", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_CONCAT(node);
      * }
      * else if (string.Equals(node.FunctionName.Value, "DATEFROMPARTS", StringComparison.OrdinalIgnoreCase))
      * {
      *  ExplicitVisit_FunctionCall_DATEFROMPARTS(node);
      * }
      * else*/
     {
         lastExpression = null;
         lastError      = "FunctionCall:" + node.FunctionName.Value;
         //throw new NotImplementedException(node.AsText());
     }
 }
 /// <include file='doc\CodeBinaryOperatorExpression.uex' path='docs/doc[@for="CodeBinaryOperatorExpression.CodeBinaryOperatorExpression1"]/*' />
 /// <devdoc>
 ///    <para>
 ///       Initializes a new instance of <see cref='System.CodeDom.CodeBinaryOperatorExpression'/>
 ///       using the specified
 ///       parameters.
 ///    </para>
 /// </devdoc>
 public CodeBinaryOperatorExpression(CodeExpression left, CodeBinaryOperatorType op, CodeExpression right)
 {
     Right    = right;
     Operator = op;
     Left     = left;
 }
        public override void ExplicitVisit(IntegerLiteral node)
        {
            int value = int.Parse(node.Value);

            lastExpression = new cs.CodePrimitiveExpression(value);
        }
 public CodeAssignStatement(CodeExpression left, CodeExpression right)
 {
     this.Left  = left;
     this.Right = right;
 }
 public override void ExplicitVisit(StringLiteral node)
 {
     lastExpression = new cs.CodePrimitiveExpression(node.Value);
 }
 public CodeAttributeArgument(string name, CodeExpression value)
 {
     throw new NotImplementedException();
 }
Exemple #54
0
 public System.CodeDom.CodeExpression GetWriterExpression(CodeExpression writer, System.CodeDom.CodeExpression obj)
 {
     return(_baseWriter.GetWriterExpression(writer, obj));
 }
 /// <include file='doc\CodeRemoveEventStatement.uex' path='docs/doc[@for="CodeRemoveEventStatement.CodeRemoveEventStatement1"]/*' />
 /// <devdoc>
 ///    <para>
 ///       Initializes a new instance of the <see cref='System.CodeDom.CodeRemoveEventStatement'/> class using the specified arguments.
 ///    </para>
 /// </devdoc>
 public CodeRemoveEventStatement(CodeEventReferenceExpression eventRef, CodeExpression listener)
 {
     this.eventRef = eventRef;
     this.listener = listener;
 }
Exemple #56
0
 public int Add(CodeExpression value)
 {
     return(Add(new CodeExpressionStatement(value)));
 }
Exemple #57
0
 public void Insert(int index, CodeExpression value)
 {
     throw new NotImplementedException();
 }
 /// <include file='doc\CodeRemoveEventStatement.uex' path='docs/doc[@for="CodeRemoveEventStatement.CodeRemoveEventStatement2"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public CodeRemoveEventStatement(CodeExpression targetObject, string eventName, CodeExpression listener)
 {
     this.eventRef = new CodeEventReferenceExpression(targetObject, eventName);
     this.listener = listener;
 }
Exemple #59
0
 public int IndexOf(CodeExpression value)
 {
     throw new NotImplementedException();
 }
Exemple #60
0
 public void Remove(CodeExpression value)
 {
     throw new NotImplementedException();
 }