Inheritance: System.CodeDom.CodeExpression
 internal static void AddCallbackImplementation(CodeTypeDeclaration codeClass, string callbackName, string handlerName, string handlerArgs, bool methodHasOutParameters)
 {
     CodeFlags[] parameterFlags = new CodeFlags[1];
     CodeMemberMethod method = AddMethod(codeClass, callbackName, parameterFlags, new string[] { typeof(object).FullName }, new string[] { "arg" }, typeof(void).FullName, null, (CodeFlags) 0);
     CodeEventReferenceExpression left = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), handlerName);
     CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));
     CodeStatement[] trueStatements = new CodeStatement[2];
     trueStatements[0] = new CodeVariableDeclarationStatement(typeof(InvokeCompletedEventArgs), "invokeArgs", new CodeCastExpression(typeof(InvokeCompletedEventArgs), new CodeArgumentReferenceExpression("arg")));
     CodeVariableReferenceExpression targetObject = new CodeVariableReferenceExpression("invokeArgs");
     CodeObjectCreateExpression expression4 = new CodeObjectCreateExpression();
     if (methodHasOutParameters)
     {
         expression4.CreateType = new CodeTypeReference(handlerArgs);
         expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "Results"));
     }
     else
     {
         expression4.CreateType = new CodeTypeReference(typeof(AsyncCompletedEventArgs));
     }
     expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "Error"));
     expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "Cancelled"));
     expression4.Parameters.Add(new CodePropertyReferenceExpression(targetObject, "UserState"));
     trueStatements[1] = new CodeExpressionStatement(new CodeDelegateInvokeExpression(new CodeEventReferenceExpression(new CodeThisReferenceExpression(), handlerName), new CodeExpression[] { new CodeThisReferenceExpression(), expression4 }));
     method.Statements.Add(new CodeConditionStatement(condition, trueStatements, new CodeStatement[0]));
 }
示例#2
0
		public override object Serialize (IDesignerSerializationManager manager, object value)
		{
			if (manager == null)
				throw new ArgumentNullException ("manager");
			if (value == null)
				throw new ArgumentNullException ("value");

			Enum[] enums = null;
			TypeConverter converter = TypeDescriptor.GetConverter (value);
			if (converter.CanConvertTo (typeof (Enum[])))
				enums = (Enum[]) converter.ConvertTo (value, typeof (Enum[]));
			else
				enums = new Enum[] { (Enum) value };
			CodeExpression left = null;
			CodeExpression right = null;
			foreach (Enum e in enums) {
				right = GetEnumExpression (e);
				if (left == null) // just the first time
					left = right;
				else
					left = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.BitwiseOr, right);
			}

			return left;
		}
        /// <summary>
        /// if (string.IsNullOrEmpty(APIKey) == false)
        ///    request = request.WithAPIKey(APIKey)
        /// </summary>
        /// <returns></returns>
        internal CodeConditionStatement CreateWithApiKey()
        {
            // !string.IsNullOrEmpty(Key)
            var condition = new CodeBinaryOperatorExpression(
                new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(string)), "IsNullOrEmpty",
                        new CodeVariableReferenceExpression(ApiKeyServiceDecorator.PropertyName)),
                CodeBinaryOperatorType.ValueEquality,
                new CodePrimitiveExpression(false));

            //var condition =
                //new CodeSnippetExpression("!string.IsNullOrEmpty(" + ApiKeyServiceDecorator.PropertyName + ")");

            // if (...) {
            var block = new CodeConditionStatement(condition);

            // request = request.WithKey(APIKey)
            var getProperty = new CodePropertyReferenceExpression(
                new CodeThisReferenceExpression(), ApiKeyServiceDecorator.PropertyName);
            var request = new CodeMethodInvokeExpression(
                new CodeVariableReferenceExpression("request"), "WithKey", getProperty);

            var trueCase = new CodeAssignStatement(new CodeVariableReferenceExpression("request"), request);

            // }
            block.TrueStatements.Add(trueCase);

            return block;
        }
		private static BinaryOperatorType CreateInstanceForType (Type l, CodeBinaryOperatorExpression code, object right, object left)
		{
			if (l == typeof (Int32))
				return new BinaryOperatorTypeInt32 (code, right, left);

			if (l == typeof (Int16))
				return new BinaryOperatorTypeInt16 (code, right, left);

			if (l == typeof (Int64))
				return new BinaryOperatorTypeInt64 (code, right, left);

			if (l == typeof (sbyte))
				return new BinaryOperatorTypeSbyte (code, right, left);

			if (l == typeof (float))
				return new BinaryOperatorTypeFloat (code, right, left);

			if (l == typeof (char))
				return new BinaryOperatorTypeChar (code, right, left);

			if (l == typeof (byte))
				return new BinaryOperatorTypeByte (code, right, left);

			throw new InvalidOperationException ("Type not suported as binary operator");
		}
 protected virtual void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpression e)
 {
     bool flag = false;
     this.Output.Write("(");
     this.GenerateExpression(e.Left);
     this.Output.Write(" ");
     if ((e.Left is CodeBinaryOperatorExpression) || (e.Right is CodeBinaryOperatorExpression))
     {
         if (!this.inNestedBinary)
         {
             flag = true;
             this.inNestedBinary = true;
             this.Indent += 3;
         }
         this.ContinueOnNewLine("");
     }
     this.OutputOperator(e.Operator);
     this.Output.Write(" ");
     this.GenerateExpression(e.Right);
     this.Output.Write(")");
     if (flag)
     {
         this.Indent -= 3;
         this.inNestedBinary = false;
     }
 }
示例#6
0
        protected CodeStatementCollection GenerateSetMappedPropertyCode(CodeExpression targetObj, CodeExpression value)
        {
            CodeStatementCollection statements = new CodeStatementCollection();

            CodePropertyReferenceExpression property = new CodePropertyReferenceExpression(targetObj, MappedProperty.Name);

            if (_mappedProperty.PropertyType.IsArray)
            {
                statements.Add(new CodeAssignStatement(
                    new CodeIndexerExpression(property, new CodePrimitiveExpression(_index)), value));
                return statements;
            }

            if (IsCollection(_mappedProperty.PropertyType))
            {
                CodeBinaryOperatorExpression isNull =
                    new CodeBinaryOperatorExpression(property, CodeBinaryOperatorType.ValueEquality, new CodeSnippetExpression("null"));
                CodeAssignStatement create = new CodeAssignStatement(property, new CodeObjectCreateExpression(_mappedProperty.PropertyType));

                statements.Add(new CodeConditionStatement(isNull, create));
                statements.Add(new CodeMethodInvokeExpression(property, "Add", value));
                return statements;
            }

            statements.Add(new CodeAssignStatement(property, value));
            return statements;
        }
		public void TypeReferenceExpressionTest ()
		{
			StringBuilder sb = new StringBuilder();

			using (StringWriter sw = new StringWriter (sb)) {
				CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression();
				CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression();
				parentField.TargetObject = thisRef;
				parentField.FieldName = "Parent";

				CodeBinaryOperatorExpression expression = new CodeBinaryOperatorExpression(
					parentField,
					CodeBinaryOperatorType.IdentityInequality,
					new CodePrimitiveExpression(null));

				Assert.AreEqual ("(Not (Me.Parent) Is Nothing)", Generate (expression, sw), "#1");
				sw.Close ();
			}

			sb = new StringBuilder();
			using (StringWriter sw = new StringWriter (sb)) {
				CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression();
				CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression();
				parentField.TargetObject = thisRef;
				parentField.FieldName = "Parent";

				CodeBinaryOperatorExpression expression = new CodeBinaryOperatorExpression(
					new CodePrimitiveExpression(null),
					CodeBinaryOperatorType.IdentityInequality,
					parentField);

				Assert.AreEqual ("(Not (Me.Parent) Is Nothing)", Generate (expression, sw), "#2");
				sw.Close ();
			}
		}
 internal static CodeMemberMethod AddAsyncMethod(CodeTypeDeclaration codeClass, string methodName, string[] parameterTypeNames, string[] parameterNames, string callbackMember, string callbackName, string userState)
 {
     CodeMemberMethod method = AddMethod(codeClass, methodName, new CodeFlags[parameterNames.Length], parameterTypeNames, parameterNames, typeof(void).FullName, null, CodeFlags.IsPublic);
     method.Comments.Add(new CodeCommentStatement(Res.GetString("CodeRemarks"), true));
     CodeMethodInvokeExpression expression = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), methodName, new CodeExpression[0]);
     for (int i = 0; i < parameterNames.Length; i++)
     {
         expression.Parameters.Add(new CodeArgumentReferenceExpression(parameterNames[i]));
     }
     expression.Parameters.Add(new CodePrimitiveExpression(null));
     method.Statements.Add(expression);
     method = AddMethod(codeClass, methodName, new CodeFlags[parameterNames.Length], parameterTypeNames, parameterNames, typeof(void).FullName, null, CodeFlags.IsPublic);
     method.Comments.Add(new CodeCommentStatement(Res.GetString("CodeRemarks"), true));
     method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), userState));
     CodeFieldReferenceExpression left = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), callbackMember);
     CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
     CodeDelegateCreateExpression right = new CodeDelegateCreateExpression {
         DelegateType = new CodeTypeReference(typeof(SendOrPostCallback)),
         TargetObject = new CodeThisReferenceExpression(),
         MethodName = callbackName
     };
     CodeStatement[] trueStatements = new CodeStatement[] { new CodeAssignStatement(left, right) };
     method.Statements.Add(new CodeConditionStatement(condition, trueStatements, new CodeStatement[0]));
     return method;
 }
示例#9
0
 protected virtual CodeExpression BuildConditionalExpression(
     conditionalContainer container, ItemsChoiceType choiceType)
 {
     //grab the children
     List<CodeExpression> children = new List<CodeExpression>();
     for (int i = 0; i < container.Items.Length; i++)
     {
         if (container.Items[i] is conditionalContainer)
         {
             children.Add(BuildConditionalExpression((conditionalContainer)container.Items[i],
                 container.ItemsElementName[i]));
         }
         else if (container.Items[i] is actionEquals)
         {
             children.Add(BuildConditionalExpression((actionEquals)container.Items[i]));
         }
         else if (container.Items[i] is valueEquals)
         {
             children.Add(BuildConditionalExpression((valueEquals)container.Items[i],
                 container.ItemsElementName[i]));
         }
         else
         {
             throw new GatException("Unrecognized conditional item type: " +
                 container.Items[i].GetType());
         }
     }
     //get the full expression
     CodeExpression expr = null;
     if (choiceType == ItemsChoiceType.none)
     {
         expr = new CodeBinaryOperatorExpression(children[0],
             CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(false));
         for (int i = 1; i < children.Count; i++)
         {
             expr = new CodeBinaryOperatorExpression(expr,
                 CodeBinaryOperatorType.BooleanAnd,
                 new CodeBinaryOperatorExpression(children[i],
                     CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(false)));
         }
     }
     else if (choiceType == ItemsChoiceType.all ||
         choiceType == ItemsChoiceType.any)
     {
         CodeBinaryOperatorType opType = choiceType == ItemsChoiceType.all ?
             CodeBinaryOperatorType.BooleanAnd : CodeBinaryOperatorType.BooleanOr;
         expr = children[0];
         for (int i = 1; i < children.Count; i++)
         {
             expr = new CodeBinaryOperatorExpression(expr,
                 CodeBinaryOperatorType.BooleanOr, children[i]);
         }
     }
     else
     {
         throw new GatException("Unrecognized choice type: " + choiceType);
     }
     return expr;
 }
示例#10
0
	static CodeExpression BasePlusN (int n)
	{
	    CodeBinaryOperatorExpression idexpr = new CodeBinaryOperatorExpression ();
	    idexpr.Left = new CodeVariableReferenceExpression ("base_total");
	    idexpr.Operator = CodeBinaryOperatorType.Add;
	    idexpr.Right = new CodePrimitiveExpression (n);
	    return idexpr;
	}
示例#11
0
        public static void AddDisposalOfMember(CodeMemberMethod disposeMethod, string memberName)
        {
            CodeBinaryOperatorExpression isnull = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression(memberName), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));
            CodeExpressionStatement callDispose = new CodeExpressionStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression(memberName), "Dispose"));

            //add dispose code
            disposeMethod.Statements.Add(new CodeConditionStatement(isnull, callDispose));
        }
示例#12
0
        public void BeginLoop()
        {
            var cond = new CodeBinaryOperatorExpression(_expr_memory_pointer, CodeBinaryOperatorType.IdentityInequality, _expr_value_zero);
            var loop = new CodeIterationStatement(new CodeSnippetStatement(), cond, new CodeSnippetStatement());
            _nest.Peek().Add(loop);
            _nest.Push(loop.Statements);

            IncrementInstructionPointer();
        }
 public static CodeBinaryOperatorExpression Clone(this CodeBinaryOperatorExpression expression)
 {
     if (expression == null) return null;
     CodeBinaryOperatorExpression e = new CodeBinaryOperatorExpression();
     e.Left = expression.Left.Clone();
     e.Operator = expression.Operator;
     e.Right = expression.Right.Clone();
     e.UserData.AddRange(expression.UserData);
     return e;
 }
 public static void ThrowWhenArgumentMatchesExpression(this CodeStatementCollection self, string argument, CodeBinaryOperatorExpression expression)
 {
     self.Add (
             new CodeConditionStatement (
                 expression,
                 new CodeThrowExceptionStatement (
                     new CodeObjectCreateExpression (
                         new CodeTypeReference ("System.ArgumentNullException"),
                         new CodePrimitiveExpression (argument)))));
 }
 public TypescriptBinaryOperatorExpression(
     IExpressionFactory expressionFactory,
     CodeBinaryOperatorExpression codeExpression, 
     CodeGeneratorOptions options)
 {
     _expressionFactory = expressionFactory;
     _codeExpression = codeExpression;
     _options = options;
     System.Diagnostics.Debug.WriteLine("TypescriptBinaryOperatorExpression Created");
 }
		public void Constructor0_Deny_Unrestricted ()
		{
			CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression ();
			Assert.IsNull (cboe.Left, "Left");
			cboe.Left = new CodeExpression ();
			Assert.IsNull (cboe.Right, "Right");
			cboe.Right = new CodeExpression ();
			Assert.AreEqual (CodeBinaryOperatorType.Add, cboe.Operator, "Operator");
			cboe.Operator = CodeBinaryOperatorType.Divide;
		}
		public void Constructor1_Deny_Unrestricted ()
		{
			CodeExpression left = new CodeExpression ();
			CodeExpression right = new CodeExpression ();
			CodeBinaryOperatorExpression cboe = new CodeBinaryOperatorExpression (left, CodeBinaryOperatorType.Subtract, right);
			Assert.AreSame (left, cboe.Left, "Left");
			cboe.Left = new CodeExpression ();
			Assert.AreSame (right, cboe.Right, "Right");
			cboe.Right = new CodeExpression ();
			Assert.AreEqual (CodeBinaryOperatorType.Subtract, cboe.Operator, "Operator");
			cboe.Operator = CodeBinaryOperatorType.Multiply;
		}
 internal static void GenerateConstructorStatements(CodeConstructor ctor, string url, string appSettingUrlKey, string appSettingBaseUrl, bool soap11)
 {
     bool flag = (url != null) && (url.Length > 0);
     bool flag2 = (appSettingUrlKey != null) && (appSettingUrlKey.Length > 0);
     CodeAssignStatement statement = null;
     if (flag || flag2)
     {
         CodeExpression expression;
         CodePropertyReferenceExpression left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "Url");
         if (flag)
         {
             expression = new CodePrimitiveExpression(url);
             statement = new CodeAssignStatement(left, expression);
         }
         if (flag && !flag2)
         {
             ctor.Statements.Add(statement);
         }
         else if (flag2)
         {
             CodeVariableReferenceExpression expression3 = new CodeVariableReferenceExpression("urlSetting");
             CodeTypeReferenceExpression targetObject = new CodeTypeReferenceExpression(typeof(ConfigurationManager));
             CodePropertyReferenceExpression expression5 = new CodePropertyReferenceExpression(targetObject, "AppSettings");
             expression = new CodeIndexerExpression(expression5, new CodeExpression[] { new CodePrimitiveExpression(appSettingUrlKey) });
             ctor.Statements.Add(new CodeVariableDeclarationStatement(typeof(string), "urlSetting", expression));
             if ((appSettingBaseUrl == null) || (appSettingBaseUrl.Length == 0))
             {
                 expression = expression3;
             }
             else
             {
                 if ((url == null) || (url.Length == 0))
                 {
                     throw new ArgumentException(Res.GetString("IfAppSettingBaseUrlArgumentIsSpecifiedThen0"));
                 }
                 string str = new Uri(appSettingBaseUrl).MakeRelative(new Uri(url));
                 CodeExpression[] parameters = new CodeExpression[] { expression3, new CodePrimitiveExpression(str) };
                 expression = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(string)), "Concat", parameters);
             }
             CodeStatement[] trueStatements = new CodeStatement[] { new CodeAssignStatement(left, expression) };
             CodeBinaryOperatorExpression condition = new CodeBinaryOperatorExpression(expression3, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));
             if (flag)
             {
                 ctor.Statements.Add(new CodeConditionStatement(condition, trueStatements, new CodeStatement[] { statement }));
             }
             else
             {
                 ctor.Statements.Add(new CodeConditionStatement(condition, trueStatements));
             }
         }
     }
 }
示例#19
0
        private void MergeAssignmentAt(List<object> parts, int i)
        {
            int x = i - 1, y = i + 1;
            bool right = y < parts.Count;

            if (parts[i] as CodeBinaryOperatorType? != CodeBinaryOperatorType.Assign)
                return;

            if (i > 0 && IsJsonObject(parts[x]))
            {
                MergeObjectAssignmentAt(parts, i);
                return;
            }
            else if (i > 0 && IsArrayExtension(parts[x]))
            {
                var extend = (CodeMethodInvokeExpression) parts[x];
                extend.Parameters.Add(right ? VarMixedExpr(parts[y]) : new CodePrimitiveExpression(null));
                if (right)
                    parts.RemoveAt(y);
                parts.RemoveAt(i);
                return;
            }

            var assign = new CodeBinaryOperatorExpression
            {
                Operator = CodeBinaryOperatorType.Assign
            };
            parts[i] = assign;

            if (assign.Left != null)
                return;

            if (parts[x] is CodeBinaryOperatorExpression)
            {
                var binary = (CodeBinaryOperatorExpression) parts[x];
                assign.Left = (CodeArrayIndexerExpression) binary.Left;
            }
            else if (IsVarReference(parts[x]))
                assign.Left = (CodeArrayIndexerExpression) parts[x];
            else if (parts[x] is CodePropertyReferenceExpression)
                assign.Left = (CodePropertyReferenceExpression) parts[x];
            else
                assign.Left = VarId((CodeExpression) parts[x]);
            assign.Right = right ? VarMixedExpr(parts[y]) : new CodePrimitiveExpression(null);

            parts[x] = assign;

            if (right)
                parts.RemoveAt(y);
            parts.RemoveAt(i);
        }
        /// <summary>
        /// Formats an enum value to a code expression.
        /// </summary>
        /// <param name="value">The value to be formatted</param>
        /// <returns>A code expression representing one single enumeration value, or a collection of two or more values concatenated with the <c>Or</c> operator.</returns>
        public static CodeExpression FormatEnumValue(Enum value)
        {
            Type valueType = value.GetType();
            bool isFlags = valueType.HasCustomAttribute(typeof(FlagsAttribute));
            
            long enumValue = Convert.ToInt64(value);

            if (isFlags && enumValue > 0)
            {
                CodeExpression returnExpression = null;

                foreach (FieldInfo field in valueType.GetFields())
                {
                    if (field.IsLiteral)
                    {
                        long fieldValue = Convert.ToInt64(field.GetValue(null));

                        if ((enumValue & fieldValue) == fieldValue)
                        {
                            CodeFieldReferenceExpression fieldExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(valueType), field.Name);

                            if (returnExpression == null)
                                returnExpression = fieldExpression;
                            else
                                returnExpression = new CodeBinaryOperatorExpression(returnExpression, CodeBinaryOperatorType.BitwiseOr, fieldExpression);

                            enumValue ^= fieldValue;
                        }
                    }
                }

                if (enumValue == 0)
                    return returnExpression;
                else
                    return new CodeCastExpression(valueType, new CodePrimitiveExpression(Convert.ToInt64(value)));
            }
            else
            {
                foreach (FieldInfo field in valueType.GetFields())
                {
                    if (field.IsLiteral)
                    {
                        long fieldValue = Convert.ToInt64(field.GetValue(null));
                        if (fieldValue == enumValue)
                            return new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(valueType), field.Name);
                    }
                }
            }

            return new CodeCastExpression(valueType, new CodePrimitiveExpression(Convert.ToInt64(value)));
        }
        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 object Serialize(IDesignerSerializationManager manager, object value)
 {
     CodeExpression left = null;
     using (CodeDomSerializerBase.TraceScope("EnumCodeDomSerializer::Serialize"))
     {
         Enum[] enumArray;
         if (!(value is Enum))
         {
             return left;
         }
         bool flag = false;
         TypeConverter converter = TypeDescriptor.GetConverter(value);
         if ((converter != null) && converter.CanConvertTo(typeof(Enum[])))
         {
             enumArray = (Enum[]) converter.ConvertTo(value, typeof(Enum[]));
             flag = enumArray.Length > 1;
         }
         else
         {
             enumArray = new Enum[] { (Enum) value };
             flag = true;
         }
         CodeTypeReferenceExpression targetObject = new CodeTypeReferenceExpression(value.GetType());
         TypeConverter converter2 = new EnumConverter(value.GetType());
         foreach (Enum enum2 in enumArray)
         {
             string str = (converter2 != null) ? converter2.ConvertToString(enum2) : null;
             CodeExpression right = !string.IsNullOrEmpty(str) ? new CodeFieldReferenceExpression(targetObject, str) : null;
             if (right != null)
             {
                 if (left == null)
                 {
                     left = right;
                 }
                 else
                 {
                     left = new CodeBinaryOperatorExpression(left, CodeBinaryOperatorType.BitwiseOr, right);
                 }
             }
         }
         if ((left != null) && flag)
         {
             left = new CodeCastExpression(value.GetType(), left);
         }
     }
     return left;
 }
        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 CodeDoWhileStatement(CodeExpression testExpression, params CodeStatement[] statements)
        {
            string firstIterationFlagName = "firstIterationFlag" + (_firstIterationFlagCounter++);
            _testExpr = new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression(firstIterationFlagName),
                CodeBinaryOperatorType.BooleanOr,
                testExpression);
            Statements.AddRange(statements);

            base.InitStatement = new CodeVariableDeclarationStatement(
                typeof (bool),
                firstIterationFlagName,
                new CodePrimitiveExpression(true));
            base.TestExpression = _testExpr;
            base.IncrementStatement = new CodeAssignStatement(
                new CodeVariableReferenceExpression(firstIterationFlagName),
                new CodePrimitiveExpression(false));
        }
示例#26
0
 public NumericExpression(
     string numericProperty,
     NumericOperand numericOperand,
     double value,
     Conditional conditional)
     : base(numericProperty, value, numericOperand, conditional)
 {
     this._binaryExpression =
         new CodeBinaryOperatorExpression(
             new CodeCastExpression(
                 "System.Double",
                 new CodePropertyReferenceExpression(
                     new CodeThisReferenceExpression(),
                     numericProperty)),
             (CodeBinaryOperatorType)
             Enum.Parse(typeof(CodeBinaryOperatorType), numericOperand.ToString(), true),
             new CodePrimitiveExpression(value));
 }
示例#27
0
        internal static CodeStatement CreateNullHandlingStatement(bool replaceNullValue, bool hasReturnType, bool useNullInsteadOfDefault)
        {
            string retValue = "";
            CodeStatement[] trueStatements = new CodeStatement[1];
            if(hasReturnType)
            {
                retValue = replaceNullValue ? "nullValue" : (useNullInsteadOfDefault ? "null" : "default(T)");
            }

            trueStatements[0] = CreateReturnStatement(retValue);

            CodeExpression ifExpression = new CodeBinaryOperatorExpression(
                new CodeSnippetExpression("source"),
                CodeBinaryOperatorType.ValueEquality,
                new CodeSnippetExpression("null"));
            CodeConditionStatement st = new CodeConditionStatement(ifExpression, trueStatements, new CodeStatement[0]);

            return st;
        }
示例#28
0
        protected override PropertyDeclaration CreateForeignKey(ClassDeclaration classDeclaration, ForeignKeyColumnSchema foreignKey)
        {
            string columnName = foreignKey.PrimaryKeyTable.Name;

            string fkname = this.NameProvider.GetPropertyName(columnName);
            string fkfieldname = this.NameProvider.GetFieldName(columnName);
            string fkdatatype = this.NameProvider.GetClassName(foreignKey.PrimaryKeyTable);

            //add the field
            var field = new CodeMemberField(fkdatatype, fkfieldname);
            classDeclaration.Members.Add(field);

            //add the prop
            var prop = new CodeMemberProperty();
            prop.Name = fkname;
            prop.Type = new CodeTypeReference(fkdatatype);
            prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
            prop.GetStatements.Add(
                new CodeMethodReturnStatement(
                    new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fkfieldname)));

            //if (value == null || this._stateCode == null || (value.ID != this._stateCode.ID))
            var ifValueNull = new CodeBinaryOperatorExpression(new CodeSnippetExpression("value"), CodeBinaryOperatorType.IdentityEquality, new CodeSnippetExpression("null"));
            var ifFieldNull = new CodeBinaryOperatorExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fkfieldname), CodeBinaryOperatorType.IdentityEquality, new CodeSnippetExpression("null"));
            var valueIdExpression = new CodePropertyReferenceExpression(new CodeSnippetExpression("value"), "ID");
            var fieldIdExpression = new CodePropertyReferenceExpression(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fkfieldname), "ID");
            var ifValueIdDoesNotEqualFieldId = new CodeBinaryOperatorExpression(valueIdExpression, CodeBinaryOperatorType.IdentityInequality, fieldIdExpression);

            prop.SetStatements.Add(
                new CodeConditionStatement(
                    new CodeBinaryOperatorExpression(
                        new CodeBinaryOperatorExpression(ifValueNull, CodeBinaryOperatorType.BooleanOr, ifFieldNull),
                        CodeBinaryOperatorType.BooleanOr,
                        ifValueIdDoesNotEqualFieldId),
                    new CodeSnippetStatement(String.Format("{1}((EightyProofSolutions.BlogEngine.Core.Models.ITrackPropertyChanges)this).OnPropertyChanged(\"{0}\", this.{2}, value);", fkname, new String('\t', 5), fkfieldname)),
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), fkfieldname),
                        new CodeSnippetExpression("value"))));
            classDeclaration.Members.Add(prop);
            return null;
            //PropertyDeclaration result = classDeclaration.AddProperty(fkname, fkfieldname, fkdatatype);
            //return result;
        }
        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;
        }
        public void Visit(WhenLiteralStatement statement)
        {
            CodeStatementCollection collection = new CodeStatementCollection();
            var arg = VisitChild(statement.Literal);

            var condition = new CodeConditionStatement();
            if (arg.Tag != null) //this is a null literal
            {
                condition.Condition = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("var"), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(null));
            }
            else
            {
                var preCondition = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("var"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null));
                condition.Condition = new CodeBinaryOperatorExpression(preCondition, CodeBinaryOperatorType.BooleanAnd, new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("var"), "Equals", arg.CodeExpression));
            }

            var then = VisitChild(statement.Then);
            condition.TrueStatements.Add(new CodeMethodReturnStatement(then.CodeExpression));
            _codeStack.Peek().Tag = then.Tag;
            _codeStack.Peek().ParentStatements.Add(condition);
        }
示例#31
0
 /// <summary>
 /// string content functions
 /// </summary>
 /// <example>
 /// "abcdefg".StartsWith("abc") ?
 /// </example>
 public StringExpression(
     string stringProperty,
     StringOperand operand,
     string value,
     Conditional conditional)
     : base(stringProperty, value, operand, conditional)
 {
     this._binaryExpression = new CodeBinaryOperatorExpression
         {
             Left =
                 new CodeMethodInvokeExpression(
                     CodeTypeReferenceExpression, "StringFunction",
                     new CodeExpression[]
                         {
                             new CodePropertyReferenceExpression(new CodeThisReferenceExpression(),
                                                                 stringProperty),
                             new CodePrimitiveExpression(value),
                             new CodePrimitiveExpression(operand),
                         }),
             Operator = CodeBinaryOperatorType.ValueEquality,
             Right = CodePrimitiveExpressionTrue
         };
 }
示例#32
0
        void EmitBinary(CodeBinaryOperatorExpression binary)
        {
            bool stmt = this.stmt;

            if (stmt)
                this.stmt = false;
            else
                writer.Write(Parser.ParenOpen);

            depth++;
            EmitExpression(binary.Left);
            depth--;

            writer.Write(Parser.SingleSpace);
            writer.Write(Operator(binary.Operator));
            writer.Write(Parser.SingleSpace);

            depth++;
            EmitExpression(binary.Right);
            depth--;

            if (!stmt)
                writer.Write(Parser.ParenClose);
        }
        private CodeTypeMember GetCompositeClassEqualsMethod(string className, List<CodeMemberField> fields)
        {
            //public override bool Equals( object obj )
            //{
            //    if( obj == this ) return true;
            //    if( obj == null || obj.GetType() != this.GetType() ) return false;
            //    MyCompositeKey test = ( MyCompositeKey ) obj;
            //    return ( _keyA == test.KeyA || (_keyA != null && _keyA.Equals( test.KeyA ) ) ) &&
            //      ( _keyB == test.KeyB || ( _keyB != null && _keyB.Equals( test.KeyB ) ) );
            //}
            CodeMemberMethod equals = new CodeMemberMethod();
            equals.Attributes = MemberAttributes.Public | MemberAttributes.Override;
            equals.ReturnType = new CodeTypeReference(typeof(Boolean));
            equals.Name = "Equals";

            CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(Object), "obj");
            equals.Parameters.Add(param);

            equals.Statements.Add(new CodeConditionStatement(
                                      new CodeBinaryOperatorExpression(
                                          new CodeFieldReferenceExpression(null, "obj"),
                                          CodeBinaryOperatorType.ValueEquality, new CodeThisReferenceExpression()
                                          ), new CodeMethodReturnStatement(new CodePrimitiveExpression(true))
                                      )
                );

            equals.Statements.Add(new CodeConditionStatement
                                      (
                                      new CodeBinaryOperatorExpression
                                          (
                                          new CodeBinaryOperatorExpression(
                                              new CodeFieldReferenceExpression(null, "obj"),
                                              CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(null)),
                                          CodeBinaryOperatorType.BooleanOr,
                                          new CodeBinaryOperatorExpression(
                                              new CodeMethodInvokeExpression(
                                                  new CodeFieldReferenceExpression(null, "obj"), "GetType"),
                                              CodeBinaryOperatorType.IdentityInequality,
                                              new CodeMethodInvokeExpression(new CodeThisReferenceExpression(),
                                                                             "GetType"))
                                          )
                                      , new CodeMethodReturnStatement(new CodePrimitiveExpression(false))
                                      )
                );

            equals.Statements.Add(
                new CodeVariableDeclarationStatement(new CodeTypeReference(className), "test",
                                                     new CodeCastExpression(new CodeTypeReference(className),
                                                                            new CodeFieldReferenceExpression(null, "obj"))));

            List<CodeExpression> expressions = new List<CodeExpression>();
            foreach (CodeMemberField field in fields)
            {
                expressions.Add(
                    new CodeBinaryOperatorExpression(
                    //_keyA == test.KeyA
                        new CodeBinaryOperatorExpression(
                            new CodeFieldReferenceExpression(null, field.Name),
                            CodeBinaryOperatorType.ValueEquality,
                            new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(null, "test"), field.Name)),
                        CodeBinaryOperatorType.BooleanOr, // ||
                        new CodeBinaryOperatorExpression(
                    //_keyA != null
                            new CodeBinaryOperatorExpression(
                                new CodeFieldReferenceExpression(null, field.Name),
                                CodeBinaryOperatorType.IdentityInequality,
                                new CodePrimitiveExpression(null)
                                ),
                            CodeBinaryOperatorType.BooleanAnd, // &&
                    // _keyA.Equals( test.KeyA )   
                            new CodeMethodInvokeExpression(
                                new CodeFieldReferenceExpression(null, field.Name), "Equals",
                                new CodeFieldReferenceExpression(
                                    new CodeFieldReferenceExpression(null, "test"), field.Name))
                            )
                        )
                    );
            }

            CodeExpression expression;
            if (expressions.Count > 2)
                expression =
                    new CodeBinaryOperatorExpression(expressions[0], CodeBinaryOperatorType.BooleanAnd,
                                                     GetBooleanAnd(expressions, 1));
            else
                expression =
                    new CodeBinaryOperatorExpression(expressions[0], CodeBinaryOperatorType.BooleanAnd, expressions[1]);


            equals.Statements.Add(new CodeMethodReturnStatement(expression));

            return equals;
        }
示例#34
0
        /// <summary>
        /// Creates the property changed method.
        /// </summary>
        /// <returns>CodeMemberMethod on Property Change handler</returns>
        /// <remarks>
        /// <code>
        ///  protected virtual  void OnPropertyChanged(string info) {
        ///      PropertyChangedEventHandler handler = PropertyChanged;
        ///      if (handler != null) {
        ///          handler(this, new PropertyChangedEventArgs(info));
        ///      }
        ///  }
        /// </code>
        /// </remarks>
        internal static CodeMemberMethod CreatePropertyChangedMethod()
        {
            const string paramName = "propertyName";
            const string variableName = "handler";

            var propertyChangedMethod = new CodeMemberMethod
            {
                Name = "OnPropertyChanged",
                Attributes = MemberAttributes.Public
            };
            propertyChangedMethod.Parameters.Add(new CodeParameterDeclarationExpression(
                new CodeTypeReference(typeof(String)), paramName));

            if (GeneratorContext.GeneratorParams.TrackingChanges.Enabled && GeneratorContext.GeneratorParams.Language == GenerationLanguage.CSharp)
            {
                propertyChangedMethod.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "value"));
                // this.ChangeTracker.RecordCurrentValue(info, value);
                var changeTrackerParams = new CodeExpression[] { new CodeArgumentReferenceExpression(paramName), new CodeArgumentReferenceExpression(("value")) };
                var changeTrackerInvokeExpression = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), "ChangeTracker.RecordCurrentValue"), changeTrackerParams);
                propertyChangedMethod.Statements.Add(changeTrackerInvokeExpression);
            }

            //Declare temp variable holding the event
            var vardec = new CodeVariableDeclarationStatement(
                new CodeTypeReference(typeof(PropertyChangedEventHandler)), variableName);

            vardec.InitExpression = new CodeEventReferenceExpression(
                new CodeThisReferenceExpression(), "PropertyChanged");

            propertyChangedMethod.Statements.Add(vardec);

            //The part of the true, create the event and invoke it

            //var createArgs = new CodeObjectCreateExpression(
            //    new CodeTypeReference(typeof(PropertyChangedEventArgs)),
            //    new CodeArgumentReferenceExpression(paramName));

            var createArgs = CodeDomHelper.CreateInstance(typeof(PropertyChangedEventArgs), paramName);

            var raiseEvent = new CodeDelegateInvokeExpression(
                new CodeVariableReferenceExpression(variableName),
                new CodeThisReferenceExpression(), createArgs);

            //The Condition
            CodeExpression condition = new CodeBinaryOperatorExpression(
                new CodeVariableReferenceExpression(variableName),
                    CodeBinaryOperatorType.IdentityInequality,
                new CodePrimitiveExpression(null));

            //The if condition
            var ifTempIsNull = new CodeConditionStatement();
            ifTempIsNull.Condition = condition;
            ifTempIsNull.TrueStatements.Add(raiseEvent);

            propertyChangedMethod.Statements.Add(ifTempIsNull);
            return propertyChangedMethod;
        }